optionally allow live ranges to be reordered
[ppcg.git] / gpu.c
blobd2c179b1e61e239869e2b5cc870e04e64bbf2c64
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/band.h>
23 #include <isl/schedule.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "schedule.h"
30 #include "ppcg_options.h"
31 #include "print.h"
33 /* The fields stride, shift and shift_map only contain valid information
34 * if shift != NULL.
35 * If so, they express that current index is such that if you add shift,
36 * then the result is always a multiple of stride.
37 * shift_map contains the mapping
39 * i -> (i + shift)/stride
41 * Let D represent the initial shared_len dimensions of the computed schedule.
42 * The spaces of "lb" and "shift" are of the form
44 * D -> [b]
46 * "shift_map" is of the form
48 * [D -> i] -> [D -> (i + shift(D))/stride]
50 struct gpu_array_bound {
51 isl_val *size;
52 isl_aff *lb;
54 isl_val *stride;
55 isl_aff *shift;
56 isl_basic_map *shift_map;
59 /* A tile of an array.
61 * n is the dimension of the array.
62 * bound is an array of size "n" representing the lower bound
63 * and size for each index.
65 * tiling maps a tile in the global array to the corresponding
66 * shared/private memory tile and is of the form
68 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
70 * where D represents the initial shared_len dimensions
71 * of the computed schedule.
73 struct gpu_array_tile {
74 int n;
75 struct gpu_array_bound *bound;
76 isl_multi_aff *tiling;
79 struct gpu_array_info;
81 /* A group of array references in a kernel that should be handled together.
82 * If private_tile is not NULL, then it is mapped to registers.
83 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
84 * Otherwise, it is accessed from global memory.
86 struct gpu_array_ref_group {
87 /* The references in this group access this array. */
88 struct gpu_array_info *array;
89 /* Position of this group in the list of reference groups of array. */
90 int nr;
92 /* The following fields are use during the construction of the groups.
93 * access is the combined access relation relative to the shared
94 * memory tiling. In particular, the domain of the map corresponds
95 * to the first shared_len dimensions of the computed schedule.
96 * write is set if any access in the group is a write.
97 * exact_write is set if all writes are definite writes.
99 isl_map *access;
100 int write;
101 int exact_write;
103 /* The shared memory tile, NULL if none. */
104 struct gpu_array_tile *shared_tile;
106 /* The private memory tile, NULL if none. */
107 struct gpu_array_tile *private_tile;
109 /* References in this group; point to elements of a linked list. */
110 int n_ref;
111 struct gpu_stmt_access **refs;
113 /* Last shared memory tile dimension that affects tile of this group. */
114 int last_shared;
117 struct gpu_gen {
118 isl_ctx *ctx;
119 struct ppcg_options *options;
121 /* Callback for printing of AST in appropriate format. */
122 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
123 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
124 struct gpu_types *types, void *user);
125 void *print_user;
127 struct gpu_prog *prog;
128 /* The generated AST. */
129 isl_ast_node *tree;
131 /* The sequence of types for which a definition has been printed. */
132 struct gpu_types types;
134 /* tile, grid and block sizes for each kernel */
135 isl_union_map *sizes;
137 /* Identifier of current kernel. */
138 int kernel_id;
139 /* Pointer to the current kernel. */
140 struct ppcg_kernel *kernel;
141 /* Does the computed schedule exhibit any parallelism? */
142 int any_parallelism;
144 /* First tile dimension. */
145 int tile_first;
146 /* Number of tile dimensions. */
147 int tile_len;
148 /* Number of initial parallel loops among tile dimensions. */
149 int n_parallel;
151 /* Number of dimensions determining shared memory. */
152 int shared_len;
154 /* Number of rows in the untiled schedule. */
155 int untiled_len;
156 /* Number of rows in the tiled schedule. */
157 int tiled_len;
158 /* Number of rows in schedule after tiling/wrapping over threads. */
159 int thread_tiled_len;
161 /* Global untiled schedule. */
162 isl_union_map *sched;
163 /* Local (per kernel launch) tiled schedule. */
164 isl_union_map *tiled_sched;
165 /* Local schedule per shared memory tile loop iteration. */
166 isl_union_map *local_sched;
168 /* Local tiled schedule projected onto the shared tile loops and
169 * the loops that will be wrapped over the threads,
170 * with all shared tile loops parametrized.
172 isl_union_map *shared_sched;
173 /* Projects out the loops that will be wrapped over the threads
174 * from shared_sched.
176 isl_union_map *shared_proj;
178 /* A map that takes the range of shared_sched as input,
179 * wraps the appropriate loops over the threads and then projects
180 * out these loops.
182 isl_map *privatization;
184 /* A map from the shared memory tile loops and the thread indices
185 * (as parameters) to the set of accessed memory elements that
186 * will be accessed through private copies.
188 isl_union_map *private_access;
190 /* The schedule for the current private/shared access
191 * (within print_private_access or print_shared_access).
193 isl_map *copy_sched;
194 /* The array reference group corresponding to copy_sched. */
195 struct gpu_array_ref_group *copy_group;
197 /* Is any array in the current kernel marked force_private? */
198 int any_force_private;
200 /* First loop to unroll (or -1 if none) in the current part of the
201 * schedule.
203 int first_unroll;
205 int n_grid;
206 int n_block;
207 /* Note: in the input file, the sizes of the grid and the blocks
208 * are specified in the order x, y, z, but internally, the sizes
209 * are stored in reverse order, so that the last element always
210 * refers to the x dimension.
212 int grid_dim[2];
213 int block_dim[3];
214 int *tile_size;
217 /* Print the name of the local copy of a given group of array references.
219 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
220 struct gpu_array_ref_group *group)
222 int global = 0;
224 if (group->private_tile)
225 p = isl_printer_print_str(p, "private_");
226 else if (group->shared_tile)
227 p = isl_printer_print_str(p, "shared_");
228 else
229 global = 1;
230 p = isl_printer_print_str(p, group->array->name);
231 if (!global && group->array->n_group > 1) {
232 p = isl_printer_print_str(p, "_");
233 p = isl_printer_print_int(p, group->nr);
236 return p;
239 /* Collect all references to the given array and store pointers to them
240 * in array->refs.
242 * If the array contains structures, then there is no need to collect
243 * the references since we will not be computing any reference groups.
245 static void collect_references(struct gpu_prog *prog,
246 struct gpu_array_info *array)
248 int i;
249 int n;
251 if (array->has_compound_element)
252 return;
254 n = 0;
255 for (i = 0; i < prog->n_stmts; ++i) {
256 struct gpu_stmt *stmt = &prog->stmts[i];
257 struct gpu_stmt_access *access;
259 for (access = stmt->accesses; access; access = access->next) {
260 const char *name;
261 name = isl_map_get_tuple_name(access->access,
262 isl_dim_out);
263 if (name && !strcmp(array->name, name))
264 n++;
268 array->n_ref = n;
269 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
270 assert(array->refs);
272 n = 0;
273 for (i = 0; i < prog->n_stmts; ++i) {
274 struct gpu_stmt *stmt = &prog->stmts[i];
275 struct gpu_stmt_access *access;
277 for (access = stmt->accesses; access; access = access->next) {
278 const char *name;
279 name = isl_map_get_tuple_name(access->access,
280 isl_dim_out);
281 if (!name || strcmp(array->name, name))
282 continue;
284 array->refs[n++] = access;
289 /* Create a gpu_array_tile for an array of dimension "n_index".
291 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
293 int i;
294 struct gpu_array_tile *tile;
296 tile = isl_calloc_type(ctx, struct gpu_array_tile);
297 assert(tile);
299 tile->n = n_index;
301 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
302 assert(tile->bound);
304 for (i = 0; i < n_index; ++i) {
305 tile->bound[i].size = NULL;
306 tile->bound[i].lb = NULL;
307 tile->bound[i].stride = NULL;
308 tile->bound[i].shift = NULL;
309 tile->bound[i].shift_map = NULL;
312 return tile;
315 static void *free_tile(struct gpu_array_tile *tile)
317 int j;
319 if (!tile)
320 return NULL;
322 for (j = 0; j < tile->n; ++j) {
323 isl_val_free(tile->bound[j].size);
324 isl_val_free(tile->bound[j].stride);
325 isl_aff_free(tile->bound[j].lb);
326 isl_aff_free(tile->bound[j].shift);
327 isl_basic_map_free(tile->bound[j].shift_map);
329 free(tile->bound);
330 isl_multi_aff_free(tile->tiling);
331 free(tile);
333 return NULL;
336 static struct pet_array *find_array(struct ppcg_scop *scop,
337 __isl_keep isl_set *accessed)
339 int i;
340 isl_id *id;
342 id = isl_set_get_tuple_id(accessed);
344 for (i = 0; i < scop->n_array; ++i) {
345 isl_id *id_i;
347 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
348 isl_id_free(id_i);
349 if (id == id_i)
350 break;
352 isl_id_free(id);
354 return i < scop->n_array ? scop->arrays[i] : NULL;
357 /* Compute and return the extent of "array", taking into account the set of
358 * accessed elements.
360 * In particular, the extent in the outer dimension is taken
361 * from "accessed", while then extent in the remaing dimensions
362 * are taken from array->extent.
364 * The extent in the outer dimension cannot be taken from array->extent
365 * because that may be unbounded. Furthermore, even if it is bounded,
366 * it may be larger than the piece of the array that is being accessed.
368 static __isl_give isl_set *compute_extent(struct pet_array *array,
369 __isl_keep isl_set *accessed)
371 int n_index;
372 isl_id *id;
373 isl_set *outer;
374 isl_set *extent;
376 extent = isl_set_copy(array->extent);
378 n_index = isl_set_dim(accessed, isl_dim_set);
379 if (n_index == 0)
380 return extent;
382 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
383 outer = isl_set_copy(accessed);
384 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
385 extent = isl_set_flat_product(outer, extent);
386 id = isl_set_get_tuple_id(accessed);
387 extent = isl_set_set_tuple_id(extent, id);
389 return extent;
392 /* Is the array "array" being extracted a read-only scalar?
394 * That is, is "array" a scalar that is never possibly written to.
395 * An array containing structures is never considered to be a scalar.
397 static int is_read_only_scalar(struct gpu_array_info *array,
398 struct gpu_prog *prog)
400 isl_set *space;
401 isl_union_map *write;
402 int empty;
404 if (array->has_compound_element)
405 return 0;
406 if (array->n_index != 0)
407 return 0;
409 write = isl_union_map_copy(prog->may_write);
410 space = isl_set_universe(isl_space_copy(array->space));
411 write = isl_union_map_intersect_range(write,
412 isl_union_set_from_set(space));
413 empty = isl_union_map_is_empty(write);
414 isl_union_map_free(write);
416 return empty;
419 /* Compute bounds on the host arrays based on the accessed elements
420 * and collect all references to the array.
422 * If the array is zero-dimensional and does not contain structures,
423 * i.e., if the array is a scalar, we check whether it is read-only.
425 static int extract_array_info(__isl_take isl_set *array, void *user)
427 int i;
428 struct gpu_prog *prog = (struct gpu_prog *)user;
429 const char *name;
430 int n_index;
431 isl_pw_aff **bounds;
432 struct pet_array *pa;
433 struct gpu_array_info *info;
434 isl_set *extent;
436 info = &prog->array[prog->n_array];
437 prog->n_array++;
439 n_index = isl_set_dim(array, isl_dim_set);
440 name = isl_set_get_tuple_name(array);
441 bounds = isl_alloc_array(isl_set_get_ctx(array),
442 isl_pw_aff *, n_index);
443 if (!bounds)
444 goto error;
446 info->space = isl_set_get_space(array);
447 info->name = strdup(name);
448 info->n_index = n_index;
449 info->bound = bounds;
450 info->linearize = prog->scop->options->linearize_device_arrays;
452 pa = find_array(prog->scop, array);
453 if (!pa)
454 isl_die(isl_set_get_ctx(array), isl_error_internal,
455 "unable to find array in scop", goto error);
457 info->type = strdup(pa->element_type);
458 info->size = pa->element_size;
459 info->local = pa->declared && !pa->exposed;
460 info->has_compound_element = pa->element_is_record;
461 info->read_only_scalar = is_read_only_scalar(info, prog);
463 extent = compute_extent(pa, array);
464 for (i = 0; i < n_index; ++i) {
465 isl_set *dom;
466 isl_local_space *ls;
467 isl_aff *one;
468 isl_pw_aff *bound;
470 bound = isl_set_dim_max(isl_set_copy(extent), i);
471 assert(bound);
472 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
473 ls = isl_local_space_from_space(isl_set_get_space(dom));
474 one = isl_aff_zero_on_domain(ls);
475 one = isl_aff_add_constant_si(one, 1);
476 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
477 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
479 bounds[i] = bound;
480 if (!isl_pw_aff_is_cst(bound))
481 info->linearize = 1;
483 info->extent = extent;
485 collect_references(prog, info);
487 isl_set_free(array);
488 return 0;
489 error:
490 isl_set_free(array);
491 return -1;
494 /* Compute a mapping from all outer arrays (of structs) in scop
495 * to their innermost arrays.
497 * In particular, for each array of a primitive type, the result
498 * contains the identity mapping on that array.
499 * For each array involving member accesses, the result
500 * contains a mapping from the elements of the outer array of structs
501 * to all corresponding elements of the innermost nested arrays.
503 static __isl_give isl_union_map *compute_to_inner(struct ppcg_scop *scop)
505 int i;
506 isl_union_map *to_inner;
508 to_inner = isl_union_map_empty(isl_set_get_space(scop->context));
510 for (i = 0; i < scop->n_array; ++i) {
511 struct pet_array *array = scop->arrays[i];
512 isl_set *set;
513 isl_map *map;
515 if (array->element_is_record)
516 continue;
518 set = isl_set_copy(array->extent);
519 map = isl_set_identity(isl_set_copy(set));
521 while (set && isl_set_is_wrapping(set)) {
522 isl_id *id;
523 isl_map *wrapped;
525 id = isl_set_get_tuple_id(set);
526 wrapped = isl_set_unwrap(set);
527 wrapped = isl_map_domain_map(wrapped);
528 wrapped = isl_map_set_tuple_id(wrapped, isl_dim_in, id);
529 map = isl_map_apply_domain(map, wrapped);
530 set = isl_map_domain(isl_map_copy(map));
533 map = isl_map_gist_domain(map, set);
535 to_inner = isl_union_map_add_map(to_inner, map);
538 return to_inner;
541 /* For each array in "prog", store the (untagged) order dependences
542 * derived from the array in array->dep_order.
543 * In particular, consider all references that access the given array
544 * and take the order dependences that have one of these references
545 * as source. (Since an order dependence relates two references to
546 * the same array, the target of these order dependences will also
547 * be one of these references.)
548 * Additionally, store the union of these array->dep_order relations
549 * for all non-scalar arrays in prog->array_order.
551 void collect_order_dependences(struct gpu_prog *prog)
553 int i;
554 isl_space *space;
555 isl_union_map *accesses;
557 space = isl_union_map_get_space(prog->read);
558 prog->array_order = isl_union_map_empty(space);
560 accesses = isl_union_map_copy(prog->scop->tagged_reads);
561 accesses = isl_union_map_union(accesses,
562 isl_union_map_copy(prog->scop->tagged_may_writes));
563 accesses = isl_union_map_universe(accesses);
564 accesses = isl_union_map_apply_range(accesses,
565 isl_union_map_copy(prog->to_outer));
567 for (i = 0; i < prog->n_array; ++i) {
568 struct gpu_array_info *array = &prog->array[i];
569 isl_set *set;
570 isl_union_set *uset;
571 isl_union_map *order;
573 set = isl_set_universe(isl_space_copy(array->space));
574 uset = isl_union_set_from_set(set);
575 uset = isl_union_map_domain(
576 isl_union_map_intersect_range(isl_union_map_copy(accesses),
577 uset));
578 order = isl_union_map_copy(prog->scop->tagged_dep_order);
579 order = isl_union_map_intersect_domain(order, uset);
580 order = isl_union_map_zip(order);
581 order = isl_union_set_unwrap(isl_union_map_domain(order));
582 array->dep_order = order;
584 if (gpu_array_is_scalar(array))
585 continue;
587 prog->array_order = isl_union_map_union(prog->array_order,
588 isl_union_map_copy(array->dep_order));
591 isl_union_map_free(accesses);
594 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
595 * collect them in prog->array.
597 * If there are any member accesses involved, then they are first mapped
598 * to the outer arrays of structs.
600 * If we are allowing live range reordering, then also set
601 * the dep_order field. Otherwise leave it NULL.
603 static int collect_array_info(struct gpu_prog *prog)
605 int r;
606 isl_union_set *arrays;
608 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
609 arrays = isl_union_set_union(arrays,
610 isl_union_map_range(isl_union_map_copy(prog->may_write)));
612 arrays = isl_union_set_apply(arrays,
613 isl_union_map_copy(prog->to_outer));
615 arrays = isl_union_set_coalesce(arrays);
617 prog->n_array = isl_union_set_n_set(arrays);
618 prog->array = isl_calloc_array(prog->ctx,
619 struct gpu_array_info, prog->n_array);
620 assert(prog->array);
621 prog->n_array = 0;
622 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
623 isl_union_set_free(arrays);
625 if (prog->scop->options->live_range_reordering)
626 collect_order_dependences(prog);
628 return r;
631 static void free_array_info(struct gpu_prog *prog)
633 int i, j;
635 for (i = 0; i < prog->n_array; ++i) {
636 int n_index = prog->array[i].n_index;
637 free(prog->array[i].type);
638 free(prog->array[i].name);
639 for (j = 0; j < n_index; ++j)
640 isl_pw_aff_free(prog->array[i].bound[j]);
641 isl_space_free(prog->array[i].space);
642 isl_set_free(prog->array[i].extent);
643 free(prog->array[i].bound);
644 free(prog->array[i].refs);
645 isl_union_map_free(prog->array[i].dep_order);
647 free(prog->array);
650 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
651 * as an array or through a pointer reference, but as a single data element.
652 * At the moment, scalars are represented as zero-dimensional arrays.
653 * A zero-dimensional array containing structures is not considered
654 * to be a scalar.
656 int gpu_array_is_scalar(struct gpu_array_info *array)
658 return !array->has_compound_element && array->n_index == 0;
661 /* Is "array" a read-only scalar?
663 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
665 return array->read_only_scalar;
668 /* Internal data structure for extract_size_of_type.
669 * "type" specifies the name of the space that we want to extract.
670 * "res" is used to store the subset of that space.
672 struct ppcg_extract_size_data {
673 const char *type;
674 isl_set *res;
677 /* This function is called for each set in a union_set.
678 * If the name of the set matches data->type, we store the
679 * set in data->res.
681 static int extract_size_of_type(__isl_take isl_set *size, void *user)
683 struct ppcg_extract_size_data *data = user;
684 const char *name;
686 name = isl_set_get_tuple_name(size);
687 if (name && !strcmp(name, data->type)) {
688 data->res = size;
689 return -1;
692 isl_set_free(size);
693 return 0;
696 /* Given a union map { kernel[i] -> *[...] },
697 * return the range in the space called "type" for the kernel with
698 * sequence number "id".
700 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
701 const char *type, int id)
703 isl_space *space;
704 isl_set *dom;
705 isl_union_set *local_sizes;
706 struct ppcg_extract_size_data data = { type, NULL };
708 if (!sizes)
709 return NULL;
711 space = isl_union_map_get_space(sizes);
712 space = isl_space_set_from_params(space);
713 space = isl_space_add_dims(space, isl_dim_set, 1);
714 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
715 dom = isl_set_universe(space);
716 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
718 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
719 isl_union_map_copy(sizes));
720 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
721 isl_union_set_free(local_sizes);
722 return data.res;
725 /* Given a singleton set, extract the first (at most *len) elements
726 * of the single integer tuple into *sizes and update *len if needed.
728 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
730 int i;
731 int dim;
733 if (!set)
734 return;
736 dim = isl_set_dim(set, isl_dim_set);
737 if (dim < *len)
738 *len = dim;
740 for (i = 0; i < *len; ++i) {
741 isl_val *v;
743 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
744 assert(v);
746 sizes[i] = isl_val_get_num_si(v);
747 isl_val_free(v);
750 isl_set_free(set);
753 /* Extract user specified "tile" sizes from the "sizes" command line option,
754 * defaulting to option->tile_size in each dimension.
756 static void read_tile_sizes(struct gpu_gen *gen)
758 int n;
759 isl_set *size;
761 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
762 assert(gen->tile_size);
763 for (n = 0; n < gen->tile_len; ++n)
764 gen->tile_size[n] = gen->options->tile_size;
766 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
767 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
769 if (gen->n_parallel > gen->tile_len)
770 gen->n_parallel = gen->tile_len;
773 /* Extract user specified "block" sizes from the "sizes" command line option,
774 * after filling in some potentially useful defaults.
776 static void read_block_sizes(struct gpu_gen *gen)
778 int n;
779 isl_set *size;
781 n = gen->n_parallel;
782 gen->n_block = (n <= 3) ? n : 3;
783 switch (gen->n_block) {
784 case 1:
785 gen->block_dim[0] = 512;
786 break;
787 case 2:
788 gen->block_dim[0] = 32;
789 gen->block_dim[1] = 16;
790 break;
791 default:
792 gen->block_dim[0] = 32;
793 gen->block_dim[1] = 4;
794 gen->block_dim[2] = 4;
795 break;
798 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
799 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
802 /* Extract user specified "grid" sizes from the "sizes" command line option,
803 * after filling in some potentially useful defaults.
805 static void read_grid_sizes(struct gpu_gen *gen)
807 int n = gen->n_parallel;
808 isl_set *size;
810 gen->n_grid = (n <= 2) ? n : 2;
811 switch (gen->n_grid) {
812 case 1:
813 gen->grid_dim[0] = 32768;
814 break;
815 default:
816 gen->grid_dim[0] = 256;
817 gen->grid_dim[1] = 256;
818 break;
821 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
822 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
825 /* Extract user specified sizes from the "sizes" command line option
826 * after filling in some potentially useful defaults.
828 static void read_sizes(struct gpu_gen *gen)
830 read_tile_sizes(gen);
831 read_block_sizes(gen);
832 read_grid_sizes(gen);
835 static void *free_stmts(struct gpu_stmt *stmts, int n)
837 int i;
839 if (!stmts)
840 return NULL;
842 for (i = 0; i < n; ++i) {
843 struct gpu_stmt_access *access, *next;
845 for (access = stmts[i].accesses; access; access = next) {
846 next = access->next;
847 isl_id_free(access->ref_id);
848 isl_map_free(access->access);
849 isl_map_free(access->tagged_access);
850 free(access);
853 isl_id_free(stmts[i].id);
855 free(stmts);
857 return NULL;
860 /* Construct a map from a domain of dimensionality "len"
861 * to a domain of dimensionality "len" + "tile_len" that tiles
862 * the "tile_len" coordinates starting at "first".
863 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
864 * "dim" prescribes the parameters.
866 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
867 int first, int tile_len, int *tile_size)
869 int i;
870 isl_basic_map *bmap;
871 isl_constraint *c;
872 isl_local_space *ls;
874 dim = isl_space_add_dims(dim, isl_dim_in, len);
875 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
876 bmap = isl_basic_map_universe(isl_space_copy(dim));
877 ls = isl_local_space_from_space(dim);
879 for (i = 0; i < len - tile_len; ++i) {
880 int j = i < first ? i : i + tile_len;
881 int k = i < first ? i : i + 2 * tile_len;
883 c = isl_equality_alloc(isl_local_space_copy(ls));
884 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
885 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
886 bmap = isl_basic_map_add_constraint(bmap, c);
889 for (i = 0; i < tile_len; ++i) {
890 c = isl_equality_alloc(isl_local_space_copy(ls));
891 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
892 first + i, -1);
893 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
894 first + i, tile_size[i]);
895 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
896 first + i + tile_len, 1);
897 bmap = isl_basic_map_add_constraint(bmap, c);
899 c = isl_inequality_alloc(isl_local_space_copy(ls));
900 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
901 first + i + tile_len, 1);
902 bmap = isl_basic_map_add_constraint(bmap, c);
904 c = isl_inequality_alloc(isl_local_space_copy(ls));
905 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
906 first + i + tile_len, -1);
907 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
908 bmap = isl_basic_map_add_constraint(bmap, c);
911 isl_local_space_free(ls);
913 return isl_map_from_basic_map(bmap);
916 /* Construct a map from a domain of dimensionality "len"
917 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
918 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
919 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
920 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
921 * that are projected out at the end.
922 * "dim" prescribes the parameters.
924 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
925 int first, int wrap_len, int *wrap_size)
927 int i;
928 isl_basic_map *bmap;
929 isl_constraint *c;
930 isl_local_space *ls;
932 dim = isl_space_add_dims(dim, isl_dim_in, len);
933 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
934 bmap = isl_basic_map_universe(isl_space_copy(dim));
935 ls = isl_local_space_from_space(dim);
937 for (i = 0; i < len; ++i) {
938 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
940 c = isl_equality_alloc(isl_local_space_copy(ls));
941 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
942 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
943 bmap = isl_basic_map_add_constraint(bmap, c);
946 for (i = 0; i < wrap_len; ++i) {
947 c = isl_equality_alloc(isl_local_space_copy(ls));
948 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
949 first + i, -1);
950 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
951 first + wrap_len + i, 1);
952 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
953 first + 2 * wrap_len + i, wrap_size[i]);
954 bmap = isl_basic_map_add_constraint(bmap, c);
956 c = isl_inequality_alloc(isl_local_space_copy(ls));
957 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
958 first + wrap_len + i, 1);
959 bmap = isl_basic_map_add_constraint(bmap, c);
961 c = isl_inequality_alloc(isl_local_space_copy(ls));
962 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
963 first + wrap_len + i, -1);
964 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
965 bmap = isl_basic_map_add_constraint(bmap, c);
968 isl_local_space_free(ls);
970 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
971 first + 2 * wrap_len, wrap_len);
973 return isl_map_from_basic_map(bmap);
976 /* Add "n" parameters named prefix%d.
978 static __isl_give isl_set *add_params( __isl_take isl_set *set,
979 int n, const char *prefix)
981 int i;
982 unsigned nparam;
983 char name[20];
985 nparam = isl_set_dim(set, isl_dim_param);
986 set = isl_set_add_dims(set, isl_dim_param, n);
988 for (i = 0; i < n; ++i) {
989 snprintf(name, sizeof(name), "%s%d", prefix, i);
990 set = isl_set_set_dim_name(set, isl_dim_param,
991 nparam + i, name);
994 return set;
997 /* Equate the "n" dimensions of "set" starting at "first" to
998 * freshly created parameters named prefix%d.
1000 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1001 int first, int n, const char *prefix)
1003 int i;
1004 unsigned nparam;
1006 nparam = isl_set_dim(set, isl_dim_param);
1008 set = add_params(set, n, prefix);
1010 for (i = 0; i < n; ++i)
1011 set = isl_set_equate(set, isl_dim_param, nparam + i,
1012 isl_dim_set, first + i);
1014 return set;
1017 /* Given a parameter space "space", create a set of dimension "len"
1018 * of which the "n" dimensions starting at "first" are equated to
1019 * freshly created parameters named prefix%d.
1021 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1022 int len, int first, int n, const char *prefix)
1024 isl_set *set;
1026 space = isl_space_set_from_params(space);
1027 space = isl_space_add_dims(space, isl_dim_set, len);
1028 set = isl_set_universe(space);
1030 return parametrize(set, first, n, prefix);
1033 /* Tile the B loops over the tile sizes and then tile/wrap
1034 * the T1 loops over the blocks.
1036 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1037 __isl_take isl_union_map *sched)
1039 isl_space *dim;
1040 isl_map *tiling, *block_tiling;
1042 dim = isl_union_map_get_space(sched);
1043 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1044 gen->tile_first, gen->tile_len, gen->tile_size);
1046 if (gen->options->wrap)
1047 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1048 gen->tile_first, gen->n_grid, gen->grid_dim);
1049 else
1050 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1051 gen->tile_first, gen->n_grid, gen->grid_dim);
1053 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1055 tiling = isl_map_apply_range(tiling, block_tiling);
1057 sched = isl_union_map_apply_range(sched,
1058 isl_union_map_from_map(tiling));
1060 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1062 return sched;
1065 /* Equate the "T1P" iterators in the tiled schedule "sched"
1066 * to the block dimensions.
1068 static __isl_give isl_union_map *parametrize_tiled_schedule(
1069 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1071 isl_space *dim;
1072 isl_set *par;
1074 dim = isl_union_map_get_space(sched);
1075 par = parametrization(dim, gen->tiled_len,
1076 gen->tile_first + gen->n_grid, gen->n_grid, "b");
1077 sched = isl_union_map_intersect_range(sched,
1078 isl_union_set_from_set(par));
1080 return sched;
1083 /* Tile/wrap the P1 loops over the threads.
1085 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1086 __isl_take isl_union_map *sched)
1088 isl_space *dim;
1089 isl_map *tiling;
1090 isl_set *par;
1092 dim = isl_union_map_get_space(sched);
1094 if (gen->options->wrap)
1095 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1096 gen->shared_len, gen->n_block, gen->block_dim);
1097 else
1098 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1099 gen->shared_len, gen->n_block, gen->block_dim);
1100 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1102 sched = isl_union_map_apply_range(sched,
1103 isl_union_map_from_map(tiling));
1105 par = parametrization(dim, gen->thread_tiled_len,
1106 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1107 gen->n_block, "t");
1108 sched = isl_union_map_intersect_range(sched,
1109 isl_union_set_from_set(par));
1111 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1113 return sched;
1116 /* If the user asked for it, scale the shared memory tile loops
1117 * (T1T and T2) of "sched" by gen->tile_size[i].
1118 * If we are not performing "wrapping", then additionally scale the T1P
1119 * loops by gen->grid_dim[i].
1121 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1122 __isl_take isl_union_map *sched)
1124 int i;
1125 isl_space *dim;
1126 isl_basic_map *scale;
1127 isl_constraint *c;
1128 isl_local_space *ls;
1130 if (!gen->options->scale_tile_loops)
1131 return sched;
1133 dim = isl_union_map_get_space(sched);
1134 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1135 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1136 scale = isl_basic_map_universe(isl_space_copy(dim));
1137 ls = isl_local_space_from_space(dim);
1139 for (i = 0; i < gen->tiled_len; ++i) {
1140 int f = 1;
1142 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1143 f = gen->tile_size[i - gen->tile_first];
1144 if (!gen->options->wrap)
1145 f *= gen->grid_dim[i - gen->tile_first];
1146 } else if (i >= gen->tile_first + gen->n_grid &&
1147 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1148 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1151 c = isl_equality_alloc(isl_local_space_copy(ls));
1152 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1153 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1154 scale = isl_basic_map_add_constraint(scale, c);
1157 isl_local_space_free(ls);
1159 sched = isl_union_map_apply_range(sched,
1160 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1162 return sched;
1165 /* If we are not performing "wrapping" and if the user asked for it,
1166 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1168 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1169 __isl_take isl_union_map *sched)
1171 int i;
1172 isl_space *dim;
1173 isl_basic_map *scale;
1174 isl_constraint *c;
1175 isl_local_space *ls;
1177 if (gen->options->wrap)
1178 return sched;
1179 if (!gen->options->scale_tile_loops)
1180 return sched;
1182 dim = isl_union_map_get_space(sched);
1183 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1184 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1185 scale = isl_basic_map_universe(isl_space_copy(dim));
1186 ls = isl_local_space_from_space(dim);
1188 for (i = 0; i < gen->thread_tiled_len; ++i) {
1189 int f = 1;
1191 if (i >= gen->shared_len &&
1192 i < gen->shared_len + gen->n_block)
1193 f = gen->block_dim[i - gen->shared_len];
1195 c = isl_equality_alloc(isl_local_space_copy(ls));
1196 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1197 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1198 scale = isl_basic_map_add_constraint(scale, c);
1201 isl_local_space_free(ls);
1203 sched = isl_union_map_apply_range(sched,
1204 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1206 return sched;
1209 /* If we are not performing "wrapping" and if the user asked for it,
1210 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1212 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1213 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1215 int i;
1216 isl_space *dim;
1217 isl_basic_map *scale;
1218 isl_constraint *c;
1219 isl_local_space *ls;
1221 if (gen->options->wrap)
1222 return sched;
1223 if (!gen->options->scale_tile_loops)
1224 return sched;
1226 dim = isl_union_map_get_space(sched);
1227 dim = isl_space_add_dims(dim, isl_dim_in, len);
1228 dim = isl_space_add_dims(dim, isl_dim_out, len);
1229 scale = isl_basic_map_universe(isl_space_copy(dim));
1230 ls = isl_local_space_from_space(dim);
1232 for (i = 0; i < len; ++i) {
1233 int f = 1;
1235 if (i >= first && i < first + n_tile)
1236 f = gen->kernel->block_dim[i - first];
1238 c = isl_equality_alloc(isl_local_space_copy(ls));
1239 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1240 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1241 scale = isl_basic_map_add_constraint(scale, c);
1244 isl_local_space_free(ls);
1246 sched = isl_union_map_apply_range(sched,
1247 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1249 return sched;
1252 /* Add "len" parameters p[i] called prefix%d,
1253 * with bounds to 0 <= p[i] < size[i].
1255 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1256 int len, int *size, const char *prefix)
1258 int i;
1259 unsigned nparam;
1260 isl_space *dim;
1261 isl_basic_set *bset;
1262 isl_constraint *c;
1263 isl_local_space *ls;
1264 char name[20];
1266 nparam = isl_set_dim(set, isl_dim_param);
1267 set = isl_set_add_dims(set, isl_dim_param, len);
1269 for (i = 0; i < len; ++i) {
1270 snprintf(name, sizeof(name), "%s%d", prefix, i);
1271 set = isl_set_set_dim_name(set, isl_dim_param,
1272 nparam + i, name);
1275 dim = isl_set_get_space(set);
1276 bset = isl_basic_set_universe(isl_space_copy(dim));
1277 ls = isl_local_space_from_space(dim);
1279 for (i = 0; i < len; ++i) {
1280 c = isl_inequality_alloc(isl_local_space_copy(ls));
1281 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1282 nparam + i, 1);
1283 bset = isl_basic_set_add_constraint(bset, c);
1285 c = isl_inequality_alloc(isl_local_space_copy(ls));
1286 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1287 nparam + i, -1);
1288 c = isl_constraint_set_constant_si(c, size[i] - 1);
1289 bset = isl_basic_set_add_constraint(bset, c);
1292 isl_local_space_free(ls);
1294 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1297 /* Add "len" parameters p[i] called prefix%d,
1298 * with bounds to 0 <= p[i] < size[i].
1300 static __isl_give isl_set *add_bounded_parameters_dynamic(
1301 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1302 const char *prefix)
1304 int i, len;
1305 unsigned nparam;
1306 isl_space *space;
1307 isl_local_space *ls;
1308 char name[20];
1310 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1311 nparam = isl_set_dim(set, isl_dim_param);
1312 set = isl_set_add_dims(set, isl_dim_param, len);
1314 for (i = 0; i < len; ++i) {
1315 snprintf(name, sizeof(name), "%s%d", prefix, i);
1316 set = isl_set_set_dim_name(set, isl_dim_param,
1317 nparam + i, name);
1320 space = isl_space_params(isl_set_get_space(set));
1321 ls = isl_local_space_from_space(space);
1322 for (i = 0; i < len; ++i) {
1323 isl_pw_aff *param, *size_i, *zero;
1324 isl_set *bound;
1326 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1327 isl_dim_param, nparam + i);
1329 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1330 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1331 set = isl_set_intersect_params(set, bound);
1333 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1334 bound = isl_pw_aff_ge_set(param, zero);
1335 set = isl_set_intersect_params(set, bound);
1337 isl_local_space_free(ls);
1339 return set;
1342 /* Construct a map from an access to group->array to the corresponding
1343 * shared/private memory tile.
1344 * The map is of the form
1346 * { [D[i] -> A[a]] -> T[t] }
1348 * where D represents the initial shared_len dimensions
1349 * of the computed schedule.
1351 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1353 struct gpu_array_tile *tile;
1354 isl_multi_aff *tiling;
1356 tile = group->private_tile;
1357 if (!tile)
1358 tile = group->shared_tile;
1360 tiling = isl_multi_aff_copy(tile->tiling);
1362 return isl_map_from_multi_aff(tiling);
1365 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1367 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1368 unsigned pos)
1370 isl_val *v;
1371 int fixed;
1373 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1374 if (!v)
1375 return -1;
1376 fixed = isl_val_is_int(v);
1377 isl_val_free(v);
1379 return fixed;
1382 /* Given a schedule that iterates over all elements in a piece of an array,
1383 * perform tiling/wrapping over the threads.
1385 * In particular, we tile the final iterators so that the final thread
1386 * dimension runs over the final array dimension.
1387 * However, if those final iterators have only a single iteration,
1388 * we try to tile earlier iterators instead.
1390 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1391 __isl_take isl_map *sched)
1393 isl_space *dim;
1394 isl_union_map *usched;
1395 isl_map *tiling;
1396 isl_set *par;
1397 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1398 int n_tile;
1399 int first;
1401 n_tile = gen->kernel->n_block;
1402 if (n_tile > nvar) {
1403 int i;
1404 sched = isl_map_insert_dims(sched,
1405 isl_dim_out, 0, n_tile - nvar);
1406 for (i = 0; i < n_tile - nvar; ++i)
1407 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1408 nvar = n_tile;
1411 first = nvar - n_tile;
1413 for (; first > 0; first --)
1414 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1415 break;
1417 dim = isl_map_get_space(sched);
1418 dim = isl_space_params(dim);
1419 if (gen->options->wrap)
1420 tiling = wrap(isl_space_copy(dim), nvar, first,
1421 n_tile, gen->kernel->block_dim);
1422 else
1423 tiling = tile(isl_space_copy(dim), nvar, first,
1424 n_tile, gen->kernel->block_dim);
1425 sched = isl_map_apply_range(sched, tiling);
1427 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1428 sched = isl_map_intersect_range(sched, par);
1430 usched = isl_union_map_from_map(sched);
1431 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1432 first, n_tile);
1433 sched = isl_map_from_union_map(usched);
1435 return sched;
1438 /* Return the union of all read (read = 1) and/or write (write = 1)
1439 * access relations in the group.
1441 static __isl_give isl_union_map *group_access_relation(
1442 struct gpu_array_ref_group *group, int read, int write)
1444 int i;
1445 isl_union_map *access;
1447 access = isl_union_map_empty(isl_map_get_space(group->access));
1448 for (i = 0; i < group->n_ref; ++i) {
1449 isl_map *map_i;
1451 if (!((read && group->refs[i]->read) ||
1452 (write && group->refs[i]->write)))
1453 continue;
1454 map_i = isl_map_copy(group->refs[i]->access);
1455 access = isl_union_map_union(access,
1456 isl_union_map_from_map(map_i));
1459 return access;
1462 /* Return the union of all tagged access relations in the group.
1464 static __isl_give isl_union_map *group_tagged_access_relation(
1465 struct gpu_array_ref_group *group)
1467 int i;
1468 isl_union_map *access;
1470 access = isl_union_map_empty(isl_map_get_space(group->access));
1471 for (i = 0; i < group->n_ref; ++i) {
1472 isl_map *map_i;
1474 map_i = isl_map_copy(group->refs[i]->tagged_access);
1475 access = isl_union_map_union(access,
1476 isl_union_map_from_map(map_i));
1479 return access;
1482 /* Return the extent of "array", recomputed from the bounds.
1483 * The recomputed extent may be simpler than the original extent.
1485 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1487 int i;
1488 isl_id *id;
1489 isl_space *space;
1490 isl_local_space *ls;
1491 isl_set *extent;
1493 id = isl_set_get_tuple_id(array->extent);
1494 space = isl_set_get_space(array->extent);
1495 extent = isl_set_universe(isl_space_copy(space));
1496 ls = isl_local_space_from_space(space);
1497 for (i = 0; i < array->n_index; ++i) {
1498 isl_pw_aff *bound;
1499 isl_aff *aff;
1500 isl_pw_aff *index;
1501 isl_set *lt;
1503 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1505 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1506 isl_dim_set, i);
1507 index = isl_pw_aff_from_aff(aff);
1508 bound = isl_pw_aff_copy(array->bound[i]);
1509 bound = isl_pw_aff_from_range(bound);
1510 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1511 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1512 isl_id_copy(id));
1513 lt = isl_pw_aff_lt_set(index, bound);
1514 extent = isl_set_intersect(extent, lt);
1516 isl_local_space_free(ls);
1517 isl_id_free(id);
1519 return extent;
1522 /* Return a map from the first shared_len dimensions of the computed
1523 * schedule to the array tile in
1524 * global memory that corresponds to the shared memory copy.
1526 * In particular, return a map
1528 * { D[i] -> A[a] }
1530 * with constraints
1532 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1534 * and
1536 * 0 <= a <= array_size - 1 (2)
1538 * Note that if some stride has been detected (i.e., when
1539 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1540 * to the shifted and scaled down version.
1542 * Constraints (1) are obtained by mapping the size constraints on the
1543 * shared/private memory tile back to the access relation.
1544 * Constraints (2) are obtained from the (recomputed) extent.
1546 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1548 int i;
1549 int n_index = group->array->n_index;
1550 isl_map *tile;
1551 isl_space *space;
1552 isl_set *local;
1553 isl_set *extent;
1555 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1556 space = isl_space_range(space);
1557 local = isl_set_universe(space);
1558 for (i = 0; i < n_index; ++i) {
1559 isl_val *bound;
1561 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1562 bound = isl_val_copy(group->shared_tile->bound[i].size);
1563 bound = isl_val_sub_ui(bound, 1);
1564 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1566 local = isl_set_preimage_multi_aff(local,
1567 isl_multi_aff_copy(group->shared_tile->tiling));
1568 tile = isl_set_unwrap(local);
1569 extent = array_extent(group->array);
1570 tile = isl_map_intersect_range(tile, extent);
1572 return tile;
1575 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1576 * return the corresponding mapping from the AST schedule to
1577 * to the first shared_len dimensions of the schedule computed by PPCG.
1579 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1580 __isl_take isl_pw_multi_aff *iterator_map)
1582 isl_union_map *umap;
1583 isl_space *space;
1584 isl_map *map, *sched;;
1586 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1587 space = isl_space_from_domain(space);
1588 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1590 umap = isl_union_map_copy(gen->shared_sched);
1591 umap = isl_union_map_apply_range(umap,
1592 isl_union_map_copy(gen->shared_proj));
1593 map = isl_union_map_extract_map(umap, space);
1594 isl_union_map_free(umap);
1596 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1597 sched = isl_map_detect_equalities(sched);
1599 return isl_pw_multi_aff_from_map(sched);
1602 /* Set unroll[j] if the input dimension j is involved in
1603 * the index expression represented by ma.
1605 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1606 void *user)
1608 int i, j;
1609 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1610 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1611 int *unroll = user;
1613 for (i = 0; i < n_out; ++i) {
1614 isl_aff *aff;
1616 aff = isl_multi_aff_get_aff(ma, i);
1617 for (j = 0; j < n_in; ++j)
1618 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1619 unroll[j] = 1;
1620 isl_aff_free(aff);
1623 isl_set_free(set);
1624 isl_multi_aff_free(ma);
1625 return 0;
1628 /* Given an array pos mapping input dimensions to the corresponding
1629 * output dimension, construct the corresponding map.
1631 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1632 int *pos, int len)
1634 int i;
1635 isl_constraint *c;
1636 isl_basic_map *bmap;
1637 isl_local_space *ls;
1639 dim = isl_space_add_dims(dim, isl_dim_in, len);
1640 dim = isl_space_add_dims(dim, isl_dim_out, len);
1641 bmap = isl_basic_map_universe(isl_space_copy(dim));
1642 ls = isl_local_space_from_space(dim);
1644 for (i = 0; i < len; ++i) {
1645 c = isl_equality_alloc(isl_local_space_copy(ls));
1646 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1647 -1);
1648 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1650 bmap = isl_basic_map_add_constraint(bmap, c);
1652 isl_local_space_free(ls);
1654 return isl_map_from_basic_map(bmap);
1657 /* Remove the private tiles from all array reference groups,
1658 * except for the groups of arrays that are marked force_private.
1660 static void remove_private_tiles(struct gpu_gen *gen)
1662 int i, j;
1664 for (i = 0; i < gen->prog->n_array; ++i) {
1665 struct gpu_array_info *array = &gen->prog->array[i];
1667 if (array->force_private)
1668 continue;
1670 for (j = 0; j < array->n_group; ++j) {
1671 struct gpu_array_ref_group *group = array->groups[j];
1673 group->private_tile = free_tile(group->private_tile);
1678 /* Find all loops involved in any of the index expressions for any of
1679 * the private accesses, move them innermost and then mark them as
1680 * requiring unrolling by setting gen->first_unroll.
1681 * The loops involved should all be parallel because of the checks
1682 * we performed in check_private_group_access. Moving them innermost
1683 * is therefore a valid transformation.
1685 * If any of the arrays are marked force_private, however, then
1686 * those loops may not be parallel with respect to the marked arrays.
1687 * If any of the loops would have to be moved innermost for the
1688 * (non forced) private accesses and if there are any force_private
1689 * arrays, then we revert the decision to map the selected arrays
1690 * to private memory. An alternative solution would be to expand
1691 * the force_private arrays.
1693 * Loops up to gen->shared_len are generated before the mapping to
1694 * threads is applied. They should therefore be ignored.
1696 * We compute the hidden equalities of the schedule first
1697 * since we will need them in our calls to isl_pw_multi_aff_from_map
1698 * and because we want to make sure that the same equalities
1699 * are also available to the code generator.
1701 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1702 __isl_take isl_union_map *sched)
1704 int i, j;
1705 int unroll[gen->thread_tiled_len];
1706 int perm[gen->thread_tiled_len];
1707 isl_space *dim;
1708 isl_map *permute;
1709 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1711 gen->first_unroll = -1;
1713 sched = isl_union_map_detect_equalities(sched);
1714 for (i = 0; i < gen->thread_tiled_len; ++i)
1715 unroll[i] = 0;
1716 for (i = 0; i < gen->prog->n_array; ++i) {
1717 struct gpu_array_info *array = &gen->prog->array[i];
1719 for (j = 0; j < array->n_group; ++j) {
1720 isl_union_map *access;
1721 isl_map *acc;
1722 isl_pw_multi_aff *pma;
1724 if (!array->groups[j]->private_tile)
1725 continue;
1727 access = group_access_relation(array->groups[j], 1, 1);
1728 access = isl_union_map_apply_domain(access,
1729 isl_union_map_copy(sched));
1731 acc = isl_map_from_union_map(access);
1732 pma = isl_pw_multi_aff_from_map(acc);
1733 isl_pw_multi_aff_foreach_piece(pma,
1734 &check_unroll, unroll);
1736 isl_pw_multi_aff_free(pma);
1740 for (i = gen->shared_len; i < len; ++i)
1741 if (unroll[i])
1742 break;
1744 if (i >= len)
1745 return sched;
1747 for (i = len; i < gen->thread_tiled_len; ++i)
1748 if (unroll[i])
1749 return sched;
1751 if (gen->any_force_private) {
1752 remove_private_tiles(gen);
1753 return sched;
1756 j = 0;
1757 for (i = 0; i < gen->shared_len; ++i)
1758 perm[i] = j++;
1759 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1760 if (!unroll[i])
1761 perm[i] = j++;
1762 gen->first_unroll = j - gen->shared_len;
1763 for (i = gen->shared_len; i < len; ++i)
1764 if (unroll[i])
1765 perm[i] = j++;
1767 dim = isl_union_map_get_space(sched);
1768 permute = permutation(dim, perm, gen->thread_tiled_len);
1769 sched = isl_union_map_apply_range(sched,
1770 isl_union_map_from_map(permute));
1772 return sched;
1775 /* Given a constraint
1777 * a(p,i) + j = g f(e)
1779 * or -a(p,i) - j = g f(e) if sign < 0,
1780 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1781 * a(p,i) is assumed to be an expression in only the parameters
1782 * and the input dimensions.
1784 static void extract_stride(__isl_keep isl_constraint *c,
1785 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1787 int i;
1788 isl_val *v;
1789 isl_space *space;
1790 unsigned nparam;
1791 unsigned nvar;
1792 isl_aff *aff;
1794 isl_val_free(bound->stride);
1795 bound->stride = isl_val_copy(stride);
1797 space = isl_constraint_get_space(c);
1798 space = isl_space_domain(space);
1800 nparam = isl_space_dim(space, isl_dim_param);
1801 nvar = isl_space_dim(space, isl_dim_set);
1803 v = isl_constraint_get_constant_val(c);
1804 if (sign < 0)
1805 v = isl_val_neg(v);
1806 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1807 aff = isl_aff_set_constant_val(aff, v);
1809 for (i = 0; i < nparam; ++i) {
1810 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1811 continue;
1812 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1813 if (sign < 0)
1814 v = isl_val_neg(v);
1815 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1818 for (i = 0; i < nvar; ++i) {
1819 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1820 continue;
1821 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1822 if (sign < 0)
1823 v = isl_val_neg(v);
1824 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1827 bound->shift = aff;
1830 /* Given an equality constraint of a map with a single output dimension j,
1831 * check if the constraint is of the form
1833 * a(p,i) + j = g f(e)
1835 * with a(p,i) an expression in the parameters and input dimensions
1836 * and f(e) an expression in the existentially quantified variables.
1837 * If so, and if g is larger than any such g from a previously considered
1838 * constraint, then call extract_stride to record the stride information
1839 * in bound.
1841 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1843 int i;
1844 isl_ctx *ctx;
1845 isl_val *v;
1846 unsigned n_div;
1847 struct gpu_array_bound *bound = user;
1849 ctx = isl_constraint_get_ctx(c);
1850 n_div = isl_constraint_dim(c, isl_dim_div);
1851 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1853 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1854 int s = isl_val_sgn(v);
1855 isl_val *stride = isl_val_zero(ctx);
1857 isl_val_free(v);
1858 for (i = 0; i < n_div; ++i) {
1859 v = isl_constraint_get_coefficient_val(c,
1860 isl_dim_div, i);
1861 stride = isl_val_gcd(stride, v);
1863 if (!isl_val_is_zero(stride) &&
1864 isl_val_gt(stride, bound->stride))
1865 extract_stride(c, bound, stride, s);
1867 isl_val_free(stride);
1868 } else
1869 isl_val_free(v);
1871 isl_constraint_free(c);
1872 return 0;
1875 /* Given contraints on an array index i, check if we can find
1876 * a shift a(p) and a stride g such that
1878 * a(p) + i = 0 mod g
1880 * If so, record the information in bound and apply the mapping
1881 * i -> (i + a(p))/g to the array index in bounds and return
1882 * the new constraints.
1883 * If not, simply return the original constraints.
1885 * If bounds is a subset of the space
1887 * D -> i
1889 * then the bound recorded in bound->shift is of the form
1891 * D -> s(D)
1893 * with s(D) equal to a(p) above.
1894 * The mapping recorded in bound->shift_map is of the form
1896 * [D -> i] -> [D -> (i + S(D))/g]
1898 * This mapping is computed as follows.
1899 * We first introduce "i" in the domain through precomposition
1900 * with [D -> i] -> D obtaining
1902 * [D -> i] -> s(D)
1904 * Adding [D -> i] -> i produces
1906 * [D -> i] -> i + s(D)
1908 * and the domain product with [D -> i] -> D yields
1910 * [D -> i] -> [D -> i + s(D)]
1912 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1914 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1915 __isl_take isl_basic_map *bounds)
1917 isl_space *space;
1918 isl_basic_map *hull;
1919 isl_basic_map *shift, *id, *bmap, *scale;
1920 isl_basic_set *bset;
1921 isl_aff *aff;
1923 bound->stride = NULL;
1925 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1927 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1929 isl_basic_map_free(hull);
1931 if (!bound->stride)
1932 return bounds;
1934 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1935 space = isl_basic_map_get_space(bounds);
1936 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1937 shift = isl_basic_map_apply_range(bmap, shift);
1938 space = isl_basic_map_get_space(bounds);
1939 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1940 shift = isl_basic_map_sum(id, shift);
1941 space = isl_basic_map_get_space(bounds);
1942 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1943 shift = isl_basic_map_range_product(id, shift);
1945 space = isl_space_domain(isl_basic_map_get_space(bounds));
1946 id = isl_basic_map_identity(isl_space_map_from_set(space));
1947 space = isl_space_range(isl_basic_map_get_space(bounds));
1948 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1949 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1950 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1951 scale = isl_basic_map_from_aff(aff);
1952 scale = isl_basic_map_product(id, scale);
1954 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1955 bmap = isl_basic_map_copy(bound->shift_map);
1956 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1957 bounds = isl_basic_set_unwrap(bset);
1959 return bounds;
1962 /* Data used in compute_array_dim_size and compute_size_in_direction.
1964 * pos is the position of the variable representing the array index,
1965 * i.e., the variable for which want to compute the size. This variable
1966 * is also the last variable in the set.
1968 struct gpu_size_info {
1969 isl_basic_set *bset;
1970 struct gpu_array_bound *bound;
1971 int pos;
1974 /* Given a constraint from the basic set describing the bounds on
1975 * an array index, check if it is a lower bound, say m i >= b(x), and,
1976 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1977 * upper bound. If so, and if this bound is smaller than any bound
1978 * derived from earlier constraints, set the size to this bound on
1979 * the expression and the lower bound to ceil(b(x)/m).
1981 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1983 struct gpu_size_info *size = user;
1984 unsigned nparam;
1985 unsigned n_div;
1986 isl_val *v;
1987 isl_aff *aff;
1988 isl_aff *lb;
1990 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1991 n_div = isl_constraint_dim(c, isl_dim_div);
1993 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1994 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1995 isl_constraint_free(c);
1996 return 0;
1999 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2000 aff = isl_aff_ceil(aff);
2002 lb = isl_aff_copy(aff);
2004 aff = isl_aff_neg(aff);
2005 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2007 v = isl_basic_set_max_val(size->bset, aff);
2008 isl_aff_free(aff);
2010 if (isl_val_is_int(v)) {
2011 v = isl_val_add_ui(v, 1);
2012 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2013 isl_val_free(size->bound->size);
2014 size->bound->size = isl_val_copy(v);
2015 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2016 isl_aff_free(size->bound->lb);
2017 size->bound->lb = isl_aff_copy(lb);
2020 isl_val_free(v);
2021 isl_aff_free(lb);
2023 isl_constraint_free(c);
2025 return 0;
2028 /* Given a basic map "bounds" that maps parameters and input dimensions
2029 * to a single output dimension, look for an expression in the parameters
2030 * and input dimensions such that the range of the output dimension shifted
2031 * by this expression is a constant.
2033 * In particular, we currently only consider lower bounds on the output
2034 * dimension as candidate expressions.
2036 static int compute_array_dim_size(struct gpu_array_bound *bound,
2037 __isl_take isl_basic_map *bounds)
2039 struct gpu_size_info size;
2041 bounds = isl_basic_map_detect_equalities(bounds);
2042 bounds = check_stride(bound, bounds);
2044 bound->size = NULL;
2045 bound->lb = NULL;
2047 size.bound = bound;
2048 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2049 size.bset = isl_basic_map_wrap(bounds);
2050 size.bset = isl_basic_set_flatten(size.bset);
2051 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2052 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2053 &size);
2054 isl_basic_set_free(size.bset);
2056 return bound->size ? 0 : -1;
2059 /* Check if we can find a memory tile for the given array
2060 * based on the given accesses, and if so, put the results in "tile".
2062 * We project the accesses on each index in turn and look for a parametric
2063 * offset such that the size is constant.
2065 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2067 int i;
2069 for (i = 0; i < tile->n; ++i) {
2070 isl_map *access_i;
2071 isl_basic_map *hull;
2073 access_i = isl_map_copy(access);
2074 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2075 access_i = isl_map_project_out(access_i, isl_dim_out,
2076 1, tile->n - (i + 1));
2077 access_i = isl_map_compute_divs(access_i);
2078 hull = isl_map_simple_hull(access_i);
2079 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2080 return 0;
2083 return 1;
2086 /* Construct a map with input the shared tile loops and the loops that
2087 * will be wrapped around the threads that relates these later loops
2088 * to the thread indices and then projects them out.
2090 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2092 isl_map *priv;
2093 isl_map *tiling;
2094 isl_map *proj;
2095 isl_set *par;
2096 isl_space *dim;
2098 dim = isl_union_map_get_space(gen->shared_sched);
2100 if (gen->options->wrap)
2101 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2102 gen->shared_len, gen->n_block, gen->block_dim);
2103 else
2104 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2105 gen->shared_len, gen->n_block, gen->block_dim);
2107 priv = tiling;
2109 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2110 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2111 gen->n_block, "t");
2113 priv = isl_map_align_params(priv, isl_set_get_space(par));
2114 priv = isl_map_intersect_range(priv, par);
2116 dim = isl_map_get_space(priv);
2117 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2118 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2119 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2120 gen->shared_len);
2122 priv = isl_map_apply_range(priv, proj);
2124 return priv;
2127 /* Construct a map from domain_dim to domain_dim that increments
2128 * the dimension at position "pos" and leaves all other dimensions
2129 * constant.
2131 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2133 int i;
2134 int len = isl_space_dim(domain_dim, isl_dim_set);
2135 isl_space *dim;
2136 isl_basic_map *next;
2137 isl_local_space *ls;
2139 dim = isl_space_map_from_set(domain_dim);
2140 next = isl_basic_map_universe(isl_space_copy(dim));
2141 ls = isl_local_space_from_space(dim);
2143 for (i = 0; i < len; ++i) {
2144 isl_constraint *c;
2146 c = isl_equality_alloc(isl_local_space_copy(ls));
2147 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2148 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2149 if (i == pos)
2150 c = isl_constraint_set_constant_si(c, 1);
2151 next = isl_basic_map_add_constraint(next, c);
2154 isl_local_space_free(ls);
2156 return isl_map_from_basic_map(next);
2159 /* Check if the given access is coalesced.
2160 * That is, check whether incrementing the dimension that will get
2161 * wrapped over the last thread index results in incrementing
2162 * the last array index.
2164 * This function is only called for access relations without reuse.
2166 static int access_is_coalesced(struct gpu_gen *gen,
2167 __isl_keep isl_union_map *access)
2169 isl_space *dim;
2170 isl_map *access_map;
2171 isl_map *next_thread_x;
2172 isl_map *next_element;
2173 isl_map *map;
2174 int coalesced;
2176 access = isl_union_map_copy(access);
2177 access = isl_union_map_apply_domain(access,
2178 isl_union_map_copy(gen->tiled_sched));
2179 access_map = isl_map_from_union_map(access);
2181 dim = isl_map_get_space(access_map);
2182 dim = isl_space_domain(dim);
2183 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2185 dim = isl_map_get_space(access_map);
2186 dim = isl_space_range(dim);
2187 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2189 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2190 map = isl_map_apply_range(map, access_map);
2192 coalesced = isl_map_is_subset(map, next_element);
2194 isl_map_free(next_element);
2195 isl_map_free(map);
2197 return coalesced;
2200 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2201 * dimensions of the computed schedule, check if it is bijective for
2202 * fixed values of the first gen->shared_len dimensions.
2203 * We perform this check by equating these dimensions to parameters.
2205 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2207 int res;
2208 isl_set *par;
2209 isl_space *space;
2211 access = isl_map_copy(access);
2212 space = isl_space_params(isl_map_get_space(access));
2213 par = parametrization(space, gen->shared_len + gen->n_block,
2214 0, gen->shared_len, "s");
2215 access = isl_map_intersect_domain(access, par);
2216 res = isl_map_is_bijective(access);
2217 isl_map_free(access);
2219 return res;
2222 /* Look for the last shared tile loop that affects the offset of "tile"
2223 * and return the result.
2224 * If there is no such loop, then return the index of the loop
2225 * before the first shared tile loop, in particular gen->tile_first - 1.
2227 static int compute_tile_last_shared(struct gpu_gen *gen,
2228 struct gpu_array_tile *tile)
2230 int i, j;
2232 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2233 for (i = 0; i < tile->n; ++i) {
2234 isl_aff *lb;
2235 isl_aff *shift;
2237 lb = tile->bound[i].lb;
2238 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2239 break;
2241 shift = tile->bound[i].shift;
2242 if (!shift)
2243 continue;
2244 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2245 break;
2247 if (i < tile->n)
2248 break;
2251 return j;
2254 /* Look for the last shared tile loop that affects the offset of the
2255 * shared or private tile and store the result in group->last_shared.
2256 * If there is no such loop, then group->last_shared is set to a value
2257 * before the first shared tile loop, in particular gen->tile_first - 1.
2258 * If there is no tile defined on the array reference group,
2259 * then set group->last_shared to gen->shared_len - 1.
2261 static void set_last_shared(struct gpu_gen *gen,
2262 struct gpu_array_ref_group *group)
2264 struct gpu_array_tile *tile;
2266 group->last_shared = gen->shared_len - 1;
2268 tile = group->private_tile;
2269 if (!tile)
2270 tile = group->shared_tile;
2271 if (!tile)
2272 return;
2274 group->last_shared = compute_tile_last_shared(gen, tile);
2277 /* Compute a privatized copy of all access relations from reference groups that
2278 * are mapped to private memory and store the result in gen->privatization.
2280 * Read-only scalars and arrays containing structures are not mapped
2281 * to private memory.
2283 static void compute_private_access(struct gpu_gen *gen)
2285 int i, j;
2286 isl_union_map *private;
2288 if (!gen->options->use_private_memory)
2289 return;
2291 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2293 for (i = 0; i < gen->prog->n_array; ++i) {
2294 struct gpu_array_info *array = &gen->prog->array[i];
2296 if (gpu_array_is_read_only_scalar(array))
2297 continue;
2298 if (array->has_compound_element)
2299 continue;
2301 for (j = 0; j < array->n_group; ++j) {
2302 if (!array->groups[j]->private_tile)
2303 continue;
2305 private = isl_union_map_union(private,
2306 group_access_relation(array->groups[j], 1, 1));
2310 if (isl_union_map_is_empty(private))
2311 isl_union_map_free(private);
2312 else {
2313 isl_union_map *priv;
2315 private = isl_union_map_apply_domain(private,
2316 isl_union_map_copy(gen->shared_sched));
2317 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2318 private = isl_union_map_apply_domain(private, priv);
2319 gen->private_access = private;
2323 /* Compute the size of the tile specified by "tile"
2324 * in number of elements and return the result.
2326 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2328 int i;
2329 isl_val *size;
2331 size = isl_val_one(ctx);
2333 for (i = 0; i < tile->n; ++i)
2334 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2336 return size;
2339 /* If max_shared_memory is not set to infinity (-1), then make
2340 * sure that the total amount of shared memory required by the
2341 * array reference groups mapped to shared memory is no larger
2342 * than this maximum.
2344 * We apply a greedy approach and discard (keep in global memory)
2345 * those groups that would result in a total memory size that
2346 * is larger than the maximum.
2348 * This function should be called after any function that may
2349 * affect the decision on whether to place a reference group
2350 * in private, shared or global memory.
2352 static void check_shared_memory_bound(struct gpu_gen *gen)
2354 int i, j;
2355 isl_val *left, *size;
2357 if (gen->options->max_shared_memory < 0)
2358 return;
2360 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2362 for (i = 0; i < gen->prog->n_array; ++i) {
2363 struct gpu_array_info *array = &gen->prog->array[i];
2365 for (j = 0; j < array->n_group; ++j) {
2366 struct gpu_array_ref_group *group;
2368 group = array->groups[j];
2369 if (group->private_tile)
2370 continue;
2371 if (!group->shared_tile)
2372 continue;
2374 size = tile_size(gen->ctx, group->shared_tile);
2375 size = isl_val_mul_ui(size, array->size);
2377 if (isl_val_le(size, left)) {
2378 left = isl_val_sub(left, size);
2379 continue;
2381 isl_val_free(size);
2383 group->shared_tile = free_tile(group->shared_tile);
2387 isl_val_free(left);
2390 /* Given a description of an array tile "tile" and the "space"
2392 * { D -> A }
2394 * where D represents the first shared_len schedule dimensions
2395 * and A represents the array, construct an isl_multi_aff
2397 * { [D[i] -> A[a]] -> A'[a'] }
2399 * with A' a scaled down copy of A according to the shifts and strides
2400 * in "tile". In particular,
2402 * a' = (a + shift(i))/stride
2404 * "insert_array" represents
2406 * { [D -> A] -> D }
2408 * and is used to insert A into the domain of functions that only
2409 * reference D.
2411 static __isl_give isl_multi_aff *strided_tile(
2412 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2413 __isl_keep isl_multi_aff *insert_array)
2415 int i;
2416 isl_ctx *ctx;
2417 isl_multi_aff *shift;
2418 isl_multi_val *stride;
2419 isl_space *space2;
2420 isl_local_space *ls;
2421 isl_multi_aff *tiling;
2423 ctx = isl_space_get_ctx(space);
2424 space2 = isl_space_domain(isl_space_copy(space));
2425 ls = isl_local_space_from_space(space2);
2426 space2 = isl_space_range(isl_space_copy(space));
2427 stride = isl_multi_val_zero(space2);
2428 shift = isl_multi_aff_zero(isl_space_copy(space));
2430 for (i = 0; i < tile->n; ++i) {
2431 struct gpu_array_bound *bound = &tile->bound[i];
2432 isl_val *stride_i;
2433 isl_aff *shift_i;
2435 if (tile->bound[i].shift) {
2436 stride_i = isl_val_copy(bound->stride);
2437 shift_i = isl_aff_copy(bound->shift);
2438 } else {
2439 stride_i = isl_val_one(ctx);
2440 shift_i = isl_aff_zero_on_domain(
2441 isl_local_space_copy(ls));
2444 stride = isl_multi_val_set_val(stride, i, stride_i);
2445 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2447 isl_local_space_free(ls);
2449 shift = isl_multi_aff_pullback_multi_aff(shift,
2450 isl_multi_aff_copy(insert_array));
2452 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2453 tiling = isl_multi_aff_add(tiling, shift);
2454 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2456 return tiling;
2459 /* Compute a tiling for the array reference group "group".
2461 * The tiling is of the form
2463 * { [D[i] -> A[a]] -> T[t] }
2465 * where D represents the first shared_len schedule dimensions,
2466 * A represents the global array and T represents the shared or
2467 * private memory tile. The name of T is the name of the local
2468 * array.
2470 * If there is any stride in the accesses, then the mapping is
2472 * t = (a + shift(i))/stride - lb(i)
2474 * otherwise, it is simply
2476 * t = a - lb(i)
2478 static void compute_group_tiling(struct gpu_array_ref_group *group)
2480 int i;
2481 struct gpu_array_tile *tile;
2482 struct gpu_array_info *array = group->array;
2483 isl_space *space;
2484 isl_multi_aff *tiling, *lb, *insert_array;
2485 isl_printer *p;
2486 char *local_name;
2488 tile = group->private_tile;
2489 if (!tile)
2490 tile = group->shared_tile;
2491 if (!tile)
2492 return;
2494 space = isl_map_get_space(group->access);
2495 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2497 for (i = 0; i < tile->n; ++i)
2498 if (tile->bound[i].shift)
2499 break;
2501 if (i < tile->n)
2502 tiling = strided_tile(tile, space, insert_array);
2503 else
2504 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2506 lb = isl_multi_aff_zero(space);
2507 for (i = 0; i < tile->n; ++i) {
2508 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2509 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2511 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2513 tiling = isl_multi_aff_sub(tiling, lb);
2515 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2516 p = print_array_name(p, group);
2517 local_name = isl_printer_get_str(p);
2518 isl_printer_free(p);
2519 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2520 free(local_name);
2522 tile->tiling = tiling;
2525 /* Compute a tiling for all the array reference groups.
2527 static void compute_group_tilings(struct gpu_gen *gen)
2529 int i, j;
2531 for (i = 0; i < gen->prog->n_array; ++i) {
2532 struct gpu_array_info *array = &gen->prog->array[i];
2534 for (j = 0; j < array->n_group; ++j)
2535 compute_group_tiling(array->groups[j]);
2539 /* Fill up the groups array with singleton groups, i.e., one group
2540 * per reference, initializing the array, access, write, n_ref and refs fields.
2541 * In particular the access field is initialized to the scheduled
2542 * access relation of the array reference.
2544 * Return the number of elements initialized, i.e., the number of
2545 * active references in the current kernel.
2547 static int populate_array_references(struct gpu_array_info *array,
2548 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2550 int i;
2551 int n;
2552 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2554 n = 0;
2555 for (i = 0; i < array->n_ref; ++i) {
2556 isl_union_map *umap;
2557 isl_map *map;
2558 struct gpu_array_ref_group *group;
2559 struct gpu_stmt_access *access = array->refs[i];
2561 map = isl_map_copy(access->access);
2562 umap = isl_union_map_from_map(map);
2563 umap = isl_union_map_apply_domain(umap,
2564 isl_union_map_copy(sched));
2566 if (isl_union_map_is_empty(umap)) {
2567 isl_union_map_free(umap);
2568 continue;
2571 map = isl_map_from_union_map(umap);
2572 map = isl_map_detect_equalities(map);
2574 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2575 assert(group);
2576 group->array = array;
2577 group->access = map;
2578 group->write = access->write;
2579 group->exact_write = access->exact_write;
2580 group->refs = &array->refs[i];
2581 group->n_ref = 1;
2583 groups[n++] = group;
2586 return n;
2589 /* If group->n_ref == 1, then group->refs was set by
2590 * populate_array_references to point directly into
2591 * group->array->refs and should not be freed.
2592 * If group->n_ref > 1, then group->refs was set by join_groups
2593 * to point to a newly allocated array.
2595 static void free_array_ref_group(struct gpu_array_ref_group *group)
2597 if (!group)
2598 return;
2599 free_tile(group->shared_tile);
2600 free_tile(group->private_tile);
2601 isl_map_free(group->access);
2602 if (group->n_ref > 1)
2603 free(group->refs);
2604 free(group);
2607 /* Given a map where the input dimensions represent the tile loops,
2608 * eliminate the innermost of those that have a fixed value
2609 * until we reach one that does not (obviously) have a fixed value.
2611 static __isl_give isl_map *eliminate_fixed_inner_loops(
2612 __isl_take isl_map *access)
2614 int i, n;
2616 n = isl_map_dim(access, isl_dim_in);
2618 for (i = n - 1; i >= 0; --i) {
2619 if (!map_plain_is_fixed(access, isl_dim_in, i))
2620 break;
2621 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2623 return access;
2626 /* Check if the access relations of group1 and group2 overlap within
2627 * the innermost loop. In particular, ignore any inner dimension
2628 * with a fixed value.
2629 * The copying to and from shared memory will be performed within
2630 * the innermost actual loop so we are only allowed to consider
2631 * the dimensions up to that innermost loop while checking whether
2632 * two access relations overlap.
2634 static int accesses_overlap(struct gpu_array_ref_group *group1,
2635 struct gpu_array_ref_group *group2)
2637 int empty;
2638 isl_map *access1, *access2;
2640 access1 = isl_map_copy(group1->access);
2641 access1 = eliminate_fixed_inner_loops(access1);
2642 access2 = isl_map_copy(group2->access);
2643 access2 = eliminate_fixed_inner_loops(access2);
2644 access1 = isl_map_intersect(access1, access2);
2645 empty = isl_map_is_empty(access1);
2646 isl_map_free(access1);
2648 return !empty;
2651 /* Combine the given two groups into a single group, containing
2652 * the references of both groups.
2654 static struct gpu_array_ref_group *join_groups(
2655 struct gpu_array_ref_group *group1,
2656 struct gpu_array_ref_group *group2)
2658 int i;
2659 isl_ctx *ctx;
2660 struct gpu_array_ref_group *group;
2662 ctx = isl_map_get_ctx(group1->access);
2663 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2664 assert(group);
2665 group->array = group1->array;
2666 group->access = isl_map_union(isl_map_copy(group1->access),
2667 isl_map_copy(group2->access));
2668 group->write = group1->write || group2->write;
2669 group->exact_write = group1->exact_write && group2->exact_write;
2670 group->n_ref = group1->n_ref + group2->n_ref;
2671 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2672 group->n_ref);
2673 assert(group->refs);
2674 for (i = 0; i < group1->n_ref; ++i)
2675 group->refs[i] = group1->refs[i];
2676 for (i = 0; i < group2->n_ref; ++i)
2677 group->refs[group1->n_ref + i] = group2->refs[i];
2679 return group;
2682 /* Combine the given two groups into a single group and free
2683 * the original two groups.
2685 static struct gpu_array_ref_group *join_groups_and_free(
2686 struct gpu_array_ref_group *group1,
2687 struct gpu_array_ref_group *group2)
2689 struct gpu_array_ref_group *group;
2691 group = join_groups(group1, group2);
2692 free_array_ref_group(group1);
2693 free_array_ref_group(group2);
2694 return group;
2697 /* Compute the private and/or shared memory tiles for the array
2698 * reference group "group" of array "array".
2699 * Return 0 on success and -1 on error.
2701 * If the array is a read-only scalar or if the user requested
2702 * not to use shared or private memory, then we do not need to do anything.
2704 * If the array group involves any may writes (that are not must writes),
2705 * then we would have to make sure that we load the data into shared/private
2706 * memory first in case the data is not written by the kernel
2707 * (but still written back out to global memory).
2708 * Since we don't have any such mechanism at the moment, we don't
2709 * compute shared/private tiles for groups involving may writes.
2711 * We only try to compute a shared memory tile if there is any reuse
2712 * or if the access is not coalesced.
2714 * For computing a private memory tile, we also require that there is
2715 * some reuse. Moreover, we require that the access is private
2716 * to the thread. That is, we check that any given array element
2717 * is only accessed by a single thread.
2718 * We compute an access relation that maps the shared tile loop iterators
2719 * and the shared point loop iterators that will be wrapped over the
2720 * threads to the array elements.
2721 * We actually check that those iterators that will be wrapped
2722 * partition the array space. This check is stricter than necessary
2723 * since several iterations may be mapped onto the same thread
2724 * and then they could be allowed to access the same memory elements,
2725 * but our check does not allow this situation.
2727 * We also check that the index expression only depends on parallel
2728 * loops. That way, we can move those loops innermost and unroll them.
2729 * Again, we use a test that is stricter than necessary.
2730 * We actually check whether the index expression only depends
2731 * on the iterators that are wrapped over the threads.
2732 * These are necessarily parallel, but there may be more parallel loops.
2734 * Combining the injectivity of the first test with the single-valuedness
2735 * of the second test, we simply test for bijectivity.
2737 * If the array is marked force_private, then we bypass all checks
2738 * and assume we can (and should) use registers.
2740 * If it turns out we can (or have to) use registers, we compute
2741 * the private memory tile size using can_tile, after introducing a dependence
2742 * on the thread indices.
2744 static int compute_group_bounds_core(struct gpu_gen *gen,
2745 struct gpu_array_ref_group *group)
2747 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2748 isl_union_map *access;
2749 int n_index = group->array->n_index;
2750 int no_reuse;
2751 isl_map *acc;
2752 int force_private = group->array->force_private;
2753 int use_shared = gen->options->use_shared_memory;
2754 int use_private = force_private || gen->options->use_private_memory;
2756 if (!use_shared && !use_private)
2757 return 0;
2758 if (gpu_array_is_read_only_scalar(group->array))
2759 return 0;
2760 if (!force_private && !group->exact_write)
2761 return 0;
2763 access = group_access_relation(group, 1, 1);
2764 no_reuse = isl_union_map_is_injective(access);
2766 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2767 group->shared_tile = create_tile(ctx, group->array->n_index);
2768 if (!can_tile(group->access, group->shared_tile))
2769 group->shared_tile = free_tile(group->shared_tile);
2772 if (!force_private && (!use_private || no_reuse)) {
2773 isl_union_map_free(access);
2774 return 0;
2777 access = isl_union_map_apply_domain(access,
2778 isl_union_map_copy(gen->shared_sched));
2780 acc = isl_map_from_union_map(access);
2782 if (!force_private && !access_is_bijective(gen, acc)) {
2783 isl_map_free(acc);
2784 return 0;
2787 group->private_tile = create_tile(gen->ctx, n_index);
2788 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2789 if (!can_tile(acc, group->private_tile))
2790 group->private_tile = free_tile(group->private_tile);
2792 isl_map_free(acc);
2794 if (force_private && !group->private_tile)
2795 isl_die(ctx, isl_error_internal,
2796 "unable to map array reference group to registers",
2797 return -1);
2799 return 0;
2802 /* Compute the private and/or shared memory tiles for the array
2803 * reference group "group" of array "array" and set last_shared.
2804 * Return 0 on success and -1 on error.
2806 static int compute_group_bounds(struct gpu_gen *gen,
2807 struct gpu_array_ref_group *group)
2809 if (compute_group_bounds_core(gen, group) < 0)
2810 return -1;
2811 set_last_shared(gen, group);
2813 return 0;
2816 /* If two groups have overlapping access relations (as determined by
2817 * the "overlap" function) and if one of them involves a write,
2818 * then merge the two groups into one.
2819 * If "compute_bounds" is set, then call compute_group_bounds
2820 * on the merged groups.
2822 * Return the updated number of groups.
2823 * Return -1 on error.
2825 static int group_writes(struct gpu_gen *gen,
2826 int n, struct gpu_array_ref_group **groups,
2827 int (*overlap)(struct gpu_array_ref_group *group1,
2828 struct gpu_array_ref_group *group2), int compute_bounds)
2830 int i, j;
2832 for (i = 0; i < n; ++i) {
2833 for (j = n - 1; j > i; --j) {
2834 if (!groups[i]->write && !groups[j]->write)
2835 continue;
2837 if (!overlap(groups[i], groups[j]))
2838 continue;
2840 groups[i] = join_groups_and_free(groups[i], groups[j]);
2841 if (compute_bounds &&
2842 compute_group_bounds(gen, groups[i]) < 0)
2843 return -1;
2844 if (j != n - 1)
2845 groups[j] = groups[n - 1];
2846 groups[n - 1] = NULL;
2847 n--;
2851 return n;
2854 /* If two groups have overlapping access relations (within the innermost
2855 * loop) and if one of them involves a write, then merge the two groups
2856 * into one.
2858 * Return the updated number of groups.
2860 static int group_overlapping_writes(struct gpu_gen *gen,
2861 int n, struct gpu_array_ref_group **groups)
2863 return group_writes(gen, n, groups, &accesses_overlap, 0);
2866 /* Check if the access relations of group1 and group2 overlap within
2867 * the outermost min(group1->last_shared, group2->last_shared) loops.
2869 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2870 struct gpu_array_ref_group *group2)
2872 int last_shared;
2873 int dim;
2874 int empty;
2875 isl_map *map_i, *map_j, *map;
2877 last_shared = group1->last_shared;
2878 if (group2->last_shared < last_shared)
2879 last_shared = group2->last_shared;
2880 map_i = isl_map_copy(group1->access);
2881 dim = isl_map_dim(map_i, isl_dim_in);
2882 map_i = isl_map_eliminate(map_i, isl_dim_in,
2883 last_shared + 1, dim - (last_shared + 1));
2884 map_j = isl_map_copy(group2->access);
2885 map_j = isl_map_eliminate(map_j, isl_dim_in,
2886 last_shared + 1, dim - (last_shared + 1));
2887 map = isl_map_intersect(map_i, map_j);
2888 empty = isl_map_is_empty(map);
2889 isl_map_free(map);
2891 return !empty;
2894 /* If two groups have overlapping access relations (within the outer
2895 * last_shared loops) and if one of them involves a write,
2896 * then merge the two groups into one.
2898 * Return the updated number of groups.
2900 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2901 struct gpu_array_ref_group **groups)
2903 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2906 /* Is the size of the tile specified by "tile" smaller than the sum of
2907 * the sizes of the tiles specified by "tile1" and "tile2"?
2909 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2910 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2912 int smaller;
2913 isl_val *size, *size1, *size2;
2915 size = tile_size(ctx, tile);
2916 size1 = tile_size(ctx, tile1);
2917 size2 = tile_size(ctx, tile2);
2919 size = isl_val_sub(size, size1);
2920 size = isl_val_sub(size, size2);
2921 smaller = isl_val_is_neg(size);
2923 isl_val_free(size);
2925 return smaller;
2928 /* Given an initial grouping of array references and shared memory tiles
2929 * for each group that allows for a shared memory tile, merge two groups
2930 * if both have a shared memory tile, the merged group also has
2931 * a shared memory tile and the size of the tile for the merge group
2932 * is smaller than the sum of the tile sizes of the individual groups.
2934 * If merging two groups decreases the "last_shared" dimension of
2935 * one or both of the two groups, then we need to check for overlapping
2936 * writes again.
2938 * Return the number of groups after merging.
2939 * Return -1 on error.
2941 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2942 struct gpu_array_info *array, int n,
2943 struct gpu_array_ref_group **groups)
2945 int i, j;
2946 int recompute_overlap = 0;
2947 isl_ctx *ctx = isl_space_get_ctx(array->space);
2949 for (i = 0; i < n; ++i) {
2950 if (!groups[i]->shared_tile)
2951 continue;
2952 for (j = n - 1; j > i; --j) {
2953 isl_map *map;
2954 int empty;
2955 struct gpu_array_ref_group *group;
2957 if (!groups[j]->shared_tile)
2958 continue;
2960 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2961 isl_map_copy(groups[j]->access));
2962 empty = isl_map_is_empty(map);
2963 isl_map_free(map);
2965 if (empty)
2966 continue;
2968 group = join_groups(groups[i], groups[j]);
2969 if (compute_group_bounds(gen, group) < 0) {
2970 free_array_ref_group(group);
2971 return -1;
2973 if (!group->shared_tile ||
2974 !smaller_tile(ctx, group->shared_tile,
2975 groups[i]->shared_tile,
2976 groups[j]->shared_tile)) {
2977 free_array_ref_group(group);
2978 continue;
2981 if (group->last_shared < groups[i]->last_shared ||
2982 group->last_shared < groups[j]->last_shared)
2983 recompute_overlap = 1;
2984 free_array_ref_group(groups[i]);
2985 free_array_ref_group(groups[j]);
2986 groups[i] = group;
2987 if (j != n - 1)
2988 groups[j] = groups[n - 1];
2989 n--;
2993 if (recompute_overlap)
2994 n = group_last_shared_overlapping_writes(gen, n, groups);
2995 return n;
2998 /* Set array->n_group and array->groups to n and groups.
3000 * Additionally, set the "nr" field of each group
3001 * and the "group" field of each reference in each group.
3003 static void set_array_groups(struct gpu_array_info *array,
3004 int n, struct gpu_array_ref_group **groups)
3006 int i, j;
3008 array->n_group = n;
3009 array->groups = groups;
3011 for (i = 0; i < n; ++i) {
3012 groups[i]->nr = i;
3014 for (j = 0; j < groups[i]->n_ref; ++j)
3015 groups[i]->refs[j]->group = i;
3019 /* Group array references that should be considered together when
3020 * deciding whether to access them from private, shared or global memory.
3021 * Return -1 on error.
3023 * In particular, if two array references overlap and if one of them
3024 * is a write, then the two references are grouped together.
3025 * We first perform an initial grouping based only on the access relation.
3026 * After computing shared and private memory tiles, we check for
3027 * overlapping writes again, but this time taking into account
3028 * the "last_shared" property.
3030 * Furthermore, if two groups admit a shared memory tile and if the
3031 * combination of the two also admits a shared memory tile, we merge
3032 * the two groups.
3034 * If the array contains structures, then there is no need to compute
3035 * reference groups since we do not map such arrays to private or shared
3036 * memory.
3038 static int group_array_references(struct gpu_gen *gen,
3039 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3041 int i;
3042 int n;
3043 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3044 struct gpu_array_ref_group **groups;
3046 if (array->has_compound_element)
3047 return 0;
3049 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3050 array->n_ref);
3051 if (!groups)
3052 return -1;
3054 n = populate_array_references(array, sched, groups);
3056 n = group_overlapping_writes(gen, n, groups);
3058 for (i = 0; i < n; ++i)
3059 if (compute_group_bounds(gen, groups[i]) < 0)
3060 n = -1;
3062 n = group_last_shared_overlapping_writes(gen, n, groups);
3064 n = group_common_shared_memory_tile(gen, array, n, groups);
3066 set_array_groups(array, n, groups);
3068 if (n >= 0)
3069 return 0;
3071 for (i = 0; i < array->n_ref; ++i)
3072 free_array_ref_group(groups[i]);
3073 return -1;
3076 /* Take tiled_sched, project it onto the shared tile loops and
3077 * the loops that will be wrapped over the threads and
3078 * store the result in gen->shared_sched.
3079 * Also compute a projection that projects out the loops that will be
3080 * wrapped over the threads and store this projection in gen->shared_proj.
3082 static void compute_shared_sched(struct gpu_gen *gen)
3084 isl_space *dim;
3085 isl_map *proj;
3086 isl_set *par;
3087 isl_union_map *sched;
3089 sched = isl_union_map_copy(gen->tiled_sched);
3091 dim = isl_union_map_get_space(sched);
3092 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3093 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3095 dim = isl_union_map_get_space(sched);
3096 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3098 gen->shared_sched = sched;
3099 gen->shared_proj = isl_union_map_from_map(proj);
3102 /* For each scalar in the input program, check if there are any
3103 * order dependences active inside the current kernel, within
3104 * the same iteration of the host schedule.
3105 * If so, mark the scalar as force_private so that it will be
3106 * mapped to a register.
3108 static void check_scalar_live_ranges(struct gpu_gen *gen)
3110 int i;
3111 isl_map *proj;
3112 isl_union_map *sched;
3113 isl_union_set *domain;
3114 isl_union_map *same_host_iteration;
3116 gen->any_force_private = 0;
3118 if (!gen->options->live_range_reordering)
3119 return;
3121 sched = gen->shared_sched;
3122 sched = isl_union_map_universe(isl_union_map_copy(sched));
3123 domain = isl_union_map_domain(sched);
3125 sched = isl_union_map_copy(gen->sched);
3126 proj = projection(isl_union_map_get_space(sched),
3127 gen->untiled_len, gen->tile_first);
3128 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3129 same_host_iteration = isl_union_map_apply_range(sched,
3130 isl_union_map_reverse(isl_union_map_copy(sched)));
3132 for (i = 0; i < gen->prog->n_array; ++i) {
3133 struct gpu_array_info *array = &gen->prog->array[i];
3134 isl_union_map *order;
3136 array->force_private = 0;
3137 if (array->n_index != 0)
3138 continue;
3139 order = isl_union_map_copy(array->dep_order);
3140 order = isl_union_map_intersect_domain(order,
3141 isl_union_set_copy(domain));
3142 order = isl_union_map_intersect_range(order,
3143 isl_union_set_copy(domain));
3144 order = isl_union_map_intersect(order,
3145 isl_union_map_copy(same_host_iteration));
3146 if (!isl_union_map_is_empty(order)) {
3147 array->force_private = 1;
3148 gen->any_force_private = 1;
3150 isl_union_map_free(order);
3153 isl_union_map_free(same_host_iteration);
3154 isl_union_set_free(domain);
3157 /* Group references of all arrays in the program.
3159 static int group_references(struct gpu_gen *gen)
3161 int i;
3162 int r = 0;
3163 isl_union_map *sched;
3165 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3166 isl_union_map_copy(gen->shared_proj));
3168 for (i = 0; i < gen->prog->n_array; ++i) {
3169 r = group_array_references(gen, &gen->prog->array[i], sched);
3170 if (r < 0)
3171 break;
3174 isl_union_map_free(sched);
3176 return r;
3179 /* Free all array information that is local to the current kernel.
3181 static void free_local_array_info(struct gpu_gen *gen)
3183 int i, j;
3185 for (i = 0; i < gen->prog->n_array; ++i) {
3186 struct gpu_array_info *array = &gen->prog->array[i];
3188 for (j = 0; j < array->n_group; ++j)
3189 free_array_ref_group(array->groups[j]);
3190 free(array->groups);
3194 /* Compute the size of a bounding box around the origin and "set",
3195 * where "set" is assumed to contain only non-negative elements.
3196 * In particular, compute the maximal value of "set" in each direction
3197 * and add one.
3199 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3200 __isl_keep isl_set *context)
3202 int i, n;
3203 isl_multi_pw_aff *mpa;
3205 n = isl_set_dim(set, isl_dim_set);
3206 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3207 for (i = 0; i < n; ++i) {
3208 isl_space *space;
3209 isl_aff *one;
3210 isl_pw_aff *bound;
3212 bound = isl_set_dim_max(isl_set_copy(set), i);
3213 bound = isl_pw_aff_coalesce(bound);
3214 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3216 space = isl_pw_aff_get_domain_space(bound);
3217 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3218 one = isl_aff_add_constant_si(one, 1);
3219 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3220 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3222 isl_set_free(set);
3224 return mpa;
3227 /* Compute the effective grid size as a list of the sizes in each dimension.
3229 * The grid size specified by the user or set by default
3230 * in read_grid_sizes() and applied in tile_schedule(),
3231 * may be too large for the given code in the sense that
3232 * it may contain blocks that don't need to execute anything.
3233 * We therefore don't return this grid size, but instead the
3234 * smallest grid size that ensures that all blocks that actually
3235 * execute code are included in the grid.
3237 * We first extract a description of the grid, i.e., the possible values
3238 * of the block ids, from gen->tiled_sched.
3239 * The block ids are parameters in gen->tiled_sched.
3240 * We simply need to change them into set dimensions.
3242 * Then, for each block dimension, we compute the maximal value of the block id
3243 * and add one.
3245 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3246 struct ppcg_kernel *kernel)
3248 int i;
3249 isl_set *grid;
3251 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3252 grid = isl_set_from_params(grid);
3253 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3254 for (i = 0; i < gen->n_grid; ++i) {
3255 int pos;
3256 char name[20];
3258 snprintf(name, sizeof(name), "b%d", i);
3259 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
3260 assert(pos >= 0);
3261 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3262 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3265 return extract_size(grid, kernel->context);
3268 /* Compute the size of a fixed bounding box around the origin and "set",
3269 * where "set" is assumed to contain only non-negative elements,
3270 * and store the results in "size".
3271 * In particular, compute the maximal value of "set" in each direction
3272 * and add one.
3274 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3276 int i, n;
3277 isl_local_space *ls;
3278 isl_aff *obj;
3280 n = isl_set_dim(set, isl_dim_set);
3281 ls = isl_local_space_from_space(isl_set_get_space(set));
3282 obj = isl_aff_zero_on_domain(ls);
3283 for (i = 0; i < n; ++i) {
3284 isl_val *max;
3286 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3287 max = isl_set_max_val(set, obj);
3288 size[i] = isl_val_get_num_si(max) + 1;
3289 isl_val_free(max);
3290 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3292 isl_aff_free(obj);
3293 isl_set_free(set);
3296 /* Compute the effective block size as a list of the sizes in each dimension
3297 * and store the sizes in kernel->block_dim.
3299 * The block size specified by the user or set by default
3300 * in read_block_sizes() and applied in thread_tile_schedule(),
3301 * may be too large for the given code in the sense that
3302 * it may contain threads that don't need to execute anything.
3303 * We therefore don't store this block size in kernel->block_dim,
3304 * but instead the smallest block size that ensures that all threads
3305 * that actually execute code are included in the block.
3307 * The current implementation eliminates all parameters, ensuring
3308 * that the size is a fixed constant in each dimension.
3309 * In principle we could also compute parametric sizes.
3310 * We would have to make sure to project out all b%d and t%d parameters,
3311 * however.
3313 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3315 int i;
3316 int nparam;
3317 isl_set *block;
3318 isl_multi_pw_aff *mpa;
3320 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3321 block = isl_set_from_params(block);
3322 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3323 kernel->n_block = gen->n_block;
3324 for (i = 0; i < gen->n_block; ++i) {
3325 int pos;
3326 char name[20];
3328 snprintf(name, sizeof(name), "t%d", i);
3329 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3330 assert(pos >= 0);
3331 block = isl_set_equate(block, isl_dim_param, pos,
3332 isl_dim_set, i);
3334 nparam = isl_set_dim(block, isl_dim_param);
3335 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3337 extract_fixed_size(block, kernel->block_dim);
3340 void ppcg_kernel_free(void *user)
3342 struct ppcg_kernel *kernel = user;
3343 int i;
3345 if (!kernel)
3346 return;
3348 isl_multi_pw_aff_free(kernel->grid_size);
3349 isl_set_free(kernel->context);
3350 isl_union_set_free(kernel->arrays);
3351 isl_space_free(kernel->space);
3352 isl_ast_node_free(kernel->tree);
3354 for (i = 0; i < kernel->n_array; ++i)
3355 isl_pw_aff_list_free(kernel->array[i].bound);
3356 free(kernel->array);
3358 for (i = 0; i < kernel->n_var; ++i) {
3359 free(kernel->var[i].name);
3360 isl_vec_free(kernel->var[i].size);
3362 free(kernel->var);
3364 free(kernel);
3367 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3368 struct ppcg_kernel_var *var)
3370 int j;
3371 struct gpu_array_tile *tile;
3372 isl_printer *p;
3373 char *name;
3375 var->array = group->array;
3377 tile = group->private_tile;
3378 var->type = ppcg_access_private;
3379 if (!tile) {
3380 tile = group->shared_tile;
3381 var->type = ppcg_access_shared;
3384 p = isl_printer_to_str(ctx);
3385 p = print_array_name(p, group);
3386 var->name = isl_printer_get_str(p);
3387 isl_printer_free(p);
3389 var->size = isl_vec_alloc(ctx, group->array->n_index);
3391 for (j = 0; j < group->array->n_index; ++j)
3392 var->size = isl_vec_set_element_val(var->size, j,
3393 isl_val_copy(tile->bound[j].size));
3396 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3398 int i, j, n;
3400 n = 0;
3401 for (i = 0; i < gen->prog->n_array; ++i) {
3402 struct gpu_array_info *array = &gen->prog->array[i];
3404 for (j = 0; j < array->n_group; ++j) {
3405 struct gpu_array_ref_group *group = array->groups[j];
3406 if (group->private_tile || group->shared_tile)
3407 ++n;
3411 kernel->n_var = n;
3412 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3413 assert(kernel->var);
3415 n = 0;
3416 for (i = 0; i < gen->prog->n_array; ++i) {
3417 struct gpu_array_info *array = &gen->prog->array[i];
3419 for (j = 0; j < array->n_group; ++j) {
3420 struct gpu_array_ref_group *group = array->groups[j];
3421 if (!group->private_tile && !group->shared_tile)
3422 continue;
3423 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3424 ++n;
3429 /* The sizes of the arrays on the host that have been computed by
3430 * extract_array_info may depend on the parameters. Use the extra
3431 * constraints on the parameters that are valid at "host_domain"
3432 * to simplify these expressions and store the results in kernel->array.
3434 * We only need these localized bounds for arrays that are accessed
3435 * by the current kernel. If we have found at least one reference group
3436 * then the array is accessed by the kernel. If the array has compound
3437 * elements then we skipped the construction of array reference groups.
3439 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3440 __isl_keep isl_set *host_domain)
3442 int i, j;
3443 isl_set *context;
3445 kernel->array = isl_calloc_array(gen->ctx,
3446 struct gpu_local_array_info, gen->prog->n_array);
3447 assert(kernel->array);
3448 kernel->n_array = gen->prog->n_array;
3450 context = isl_set_copy(host_domain);
3451 context = isl_set_params(context);
3453 for (i = 0; i < gen->prog->n_array; ++i) {
3454 struct gpu_array_info *array = &gen->prog->array[i];
3455 isl_pw_aff_list *local;
3457 if (array->n_group == 0 && !array->has_compound_element)
3458 continue;
3460 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3462 for (j = 0; j < array->n_index; ++j) {
3463 isl_pw_aff *pwaff;
3465 pwaff = isl_pw_aff_copy(array->bound[j]);
3466 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3467 local = isl_pw_aff_list_add(local, pwaff);
3470 kernel->array[i].bound = local;
3472 isl_set_free(context);
3475 /* Find the element in gen->stmt that has the given "id".
3476 * Return NULL if no such gpu_stmt can be found.
3478 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3480 int i;
3482 for (i = 0; i < prog->n_stmts; ++i) {
3483 if (id == prog->stmts[i].id)
3484 break;
3487 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3490 /* Set gen->tile_len and gen->n_parallel to those of the statement
3491 * affected by the first map (part of the schedule)
3492 * on which this function is called.
3493 * Because of the way the schedule is constructed, the other statements
3494 * in the list, if any, should have the same values for these properties.
3496 static int extract_tile_len(__isl_take isl_map *map, void *user)
3498 struct gpu_gen *gen = (struct gpu_gen *) user;
3499 isl_id *id;
3500 struct gpu_stmt *stmt;
3502 id = isl_map_get_tuple_id(map, isl_dim_in);
3503 stmt = find_stmt(gen->prog, id);
3504 isl_id_free(id);
3506 isl_map_free(map);
3508 if (!stmt)
3509 isl_die(gen->ctx, isl_error_unknown,
3510 "statement not found", return -1);
3512 gen->tile_len = stmt->tile_len;
3513 gen->n_parallel = stmt->n_parallel;
3515 return -1;
3518 void ppcg_kernel_stmt_free(void *user)
3520 int i;
3521 struct ppcg_kernel_stmt *stmt = user;
3523 if (!stmt)
3524 return;
3526 switch (stmt->type) {
3527 case ppcg_kernel_copy:
3528 isl_ast_expr_free(stmt->u.c.index);
3529 isl_ast_expr_free(stmt->u.c.local_index);
3530 break;
3531 case ppcg_kernel_domain:
3532 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3533 break;
3534 case ppcg_kernel_sync:
3535 break;
3538 free(stmt);
3541 /* Set the options of "context" to
3543 * { space -> [x] : x >= first }
3545 static __isl_give isl_ast_build *set_unroll(
3546 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3547 int first)
3549 isl_ctx *ctx;
3550 isl_map *unroll;
3551 isl_union_map *opt;
3553 ctx = isl_ast_build_get_ctx(build);
3555 space = isl_space_from_domain(space);
3556 space = isl_space_add_dims(space, isl_dim_out, 1);
3557 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3558 unroll = isl_map_universe(space);
3559 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3560 opt = isl_union_map_from_map(unroll);
3562 build = isl_ast_build_set_options(build, opt);
3564 return build;
3567 /* Return a list of isl_ids of the form "prefix%d".
3569 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3570 int n, const char *prefix)
3572 int i;
3573 char name[10];
3574 isl_id_list *names;
3576 names = isl_id_list_alloc(ctx, n);
3577 for (i = 0; i < n; ++i) {
3578 isl_id *id;
3580 snprintf(name, sizeof(name), "%s%d", prefix, i);
3581 id = isl_id_alloc(ctx, name, NULL);
3582 names = isl_id_list_add(names, id);
3585 return names;
3588 /* Extend the schedule "schedule" with the part of "extension"
3589 * starting at "first" up to "len".
3591 static __isl_give isl_union_map *extend_schedule(
3592 __isl_take isl_union_map *schedule,
3593 __isl_take isl_union_map *extension, int first, int len)
3595 isl_space *space;
3596 isl_map *proj;
3597 isl_union_map *umap;
3598 isl_set *set;
3600 space = isl_union_map_get_space(schedule);
3601 space = isl_space_set_from_params(space);
3602 space = isl_space_add_dims(space, isl_dim_set, len);
3603 proj = isl_set_identity(isl_set_universe(space));
3604 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3605 extension = isl_union_map_apply_range(extension,
3606 isl_union_map_from_map(proj));
3608 schedule = isl_union_map_range_product(schedule, extension);
3610 return schedule;
3613 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3614 * to "ref_id".
3616 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3617 __isl_keep isl_id *ref_id)
3619 struct gpu_stmt_access *access;
3621 for (access = accesses; access; access = access->next)
3622 if (access->ref_id == ref_id)
3623 return access;
3625 return NULL;
3628 /* Return the index of the array called "name" in the list of arrays.
3630 static int find_array_index(struct gpu_gen *gen, const char *name)
3632 int i;
3634 for (i = 0; i < gen->prog->n_array; ++i)
3635 if (!strcmp(name, gen->prog->array[i].name))
3636 return i;
3638 return -1;
3641 /* Internal data structure for the index and AST expression transformation
3642 * callbacks for pet_stmt_build_ast_exprs.
3644 * "accesses" is the list of gpu_stmt_access in the statement.
3645 * "iterator_map" expresses the statement iterators in terms of
3646 * the AST loop iterators.
3647 * "sched2shared" expresses the first shared_len dimensions of
3648 * the computed schedule in terms of the AST loop iterators.
3650 * The following fields are set in transform_index and used in transform_expr.
3651 * "array" is the array that is being accessed.
3652 * "global" is set if the global array is accessed (rather than
3653 * shared/private memory).
3654 * "local_array" refers to information on the array specialized
3655 * to the current kernel.
3657 struct ppcg_transform_data {
3658 struct gpu_gen *gen;
3659 struct gpu_stmt_access *accesses;
3660 isl_pw_multi_aff *iterator_map;
3661 isl_pw_multi_aff *sched2shared;
3663 struct gpu_array_info *array;
3664 int global;
3665 struct gpu_local_array_info *local_array;
3668 /* Return the name of the outer array (of structs) accessed by "access".
3670 static const char *get_outer_array_name(__isl_keep isl_map *access)
3672 isl_space *space;
3673 const char *name;
3675 space = isl_space_range(isl_map_get_space(access));
3676 while (space && isl_space_is_wrapping(space))
3677 space = isl_space_domain(isl_space_unwrap(space));
3678 name = isl_space_get_tuple_name(space, isl_dim_set);
3679 isl_space_free(space);
3681 return name;
3684 /* Index transformation callback for pet_stmt_build_ast_exprs.
3686 * "index" expresses the array indices in terms of statement iterators
3688 * We first reformulate "index" in terms of the AST loop iterators.
3689 * Then we check if we are accessing the global array or
3690 * a shared/private copy. In the former case, we simply return
3691 * the updated index. If "index" is an affine expression rather
3692 * than an array access, then we also return the updated index here.
3694 * If no reference groups have been computed for the array,
3695 * then we can only be accessing the global array.
3697 * Otherwise, we apply the tiling to the index.
3698 * This tiling is of the form
3700 * [D -> A] -> T
3702 * The index is of the form
3704 * L -> A
3706 * We update the tiling to refer to the AST loop iteratos
3708 * [L -> A] -> T
3710 * and modify index to keep track of those iterators
3712 * L -> [L -> A]
3714 * Combining these two yields a tiled index expression in terms
3715 * of the AST loop iterators
3717 * L -> T
3719 static __isl_give isl_multi_pw_aff *transform_index(
3720 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3721 void *user)
3723 struct ppcg_transform_data *data = user;
3724 struct gpu_stmt_access *access;
3725 struct gpu_array_ref_group *group;
3726 struct gpu_array_tile *tile;
3727 isl_pw_multi_aff *iterator_map;
3728 int i;
3729 const char *name;
3730 isl_space *space;
3731 isl_multi_pw_aff *tiling;
3732 isl_pw_multi_aff *pma;
3733 isl_multi_pw_aff *mpa;
3735 data->array = NULL;
3737 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3738 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3740 access = find_access(data->accesses, ref_id);
3741 if (!access)
3742 return index;
3743 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3744 return index;
3746 name = get_outer_array_name(access->access);
3747 i = find_array_index(data->gen, name);
3748 if (i < 0)
3749 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3750 "cannot find array",
3751 return isl_multi_pw_aff_free(index));
3752 data->array = &data->gen->prog->array[i];
3753 data->local_array = &data->gen->kernel->array[i];
3755 if (access->group < 0) {
3756 data->global = 1;
3757 return index;
3760 group = data->array->groups[access->group];
3761 tile = group->private_tile;
3762 if (!tile)
3763 tile = group->shared_tile;
3764 data->global = !tile;
3765 if (!tile)
3766 return index;
3768 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3769 space = isl_space_map_from_set(space);
3770 pma = isl_pw_multi_aff_identity(space);
3771 pma = isl_pw_multi_aff_product(
3772 isl_pw_multi_aff_copy(data->sched2shared), pma);
3773 tiling = isl_multi_pw_aff_from_multi_aff(
3774 isl_multi_aff_copy(tile->tiling));
3775 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3777 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3778 space = isl_space_map_from_set(space);
3779 mpa = isl_multi_pw_aff_identity(space);
3780 index = isl_multi_pw_aff_range_product(mpa, index);
3781 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3783 return index;
3786 /* Dereference "expr" by adding an index [0].
3787 * The original "expr" is assumed not to have any indices.
3789 * If "expr" is a member access, then the dereferencing needs
3790 * to be applied to the structure argument of this member access.
3792 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3794 isl_ctx *ctx;
3795 isl_ast_expr *res;
3796 isl_ast_expr_list *list;
3798 if (isl_ast_expr_get_op_type(expr) == isl_ast_op_member) {
3799 isl_ast_expr *arg;
3801 arg = isl_ast_expr_get_op_arg(expr, 0);
3802 arg = dereference(arg);
3803 expr = isl_ast_expr_set_op_arg(expr, 0, arg);
3805 return expr;
3808 ctx = isl_ast_expr_get_ctx(expr);
3809 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3810 list = isl_ast_expr_list_from_ast_expr(res);
3811 res = isl_ast_expr_get_op_arg(expr, 0);
3812 res = isl_ast_expr_access(res, list);
3813 isl_ast_expr_free(expr);
3815 return res;
3818 /* Linearize the index expression "expr" based on the array bounds
3819 * of "array".
3821 * That is, transform expression
3823 * A[i_0][i_1]...[i_n]
3825 * to
3827 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3829 * where b_0, b_1, ..., b_n are the bounds on the array.
3831 * If the base of "expr" is a member access, then the linearization needs
3832 * to be applied to the structure argument of this member access.
3834 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3835 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3837 int i, n;
3838 isl_ctx *ctx;
3839 isl_set *context;
3840 isl_ast_expr *arg0;
3841 isl_ast_expr *res;
3842 isl_ast_expr_list *list;
3843 isl_ast_build *build;
3845 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3846 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3847 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3848 isl_ast_expr *arg;
3850 arg = isl_ast_expr_get_op_arg(arg0, 0);
3851 arg = gpu_local_array_info_linearize_index(array, arg);
3852 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3853 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3855 return expr;
3857 isl_ast_expr_free(arg0);
3859 ctx = isl_ast_expr_get_ctx(expr);
3860 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3861 build = isl_ast_build_from_context(context);
3863 n = isl_ast_expr_get_op_n_arg(expr);
3864 res = isl_ast_expr_get_op_arg(expr, 1);
3865 for (i = 2; i < n; ++i) {
3866 isl_pw_aff *bound_i;
3867 isl_ast_expr *expr_i;
3869 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i - 1);
3870 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3871 res = isl_ast_expr_mul(res, expr_i);
3872 expr_i = isl_ast_expr_get_op_arg(expr, i);
3873 res = isl_ast_expr_add(res, expr_i);
3876 isl_ast_build_free(build);
3878 list = isl_ast_expr_list_from_ast_expr(res);
3879 res = isl_ast_expr_get_op_arg(expr, 0);
3880 res = isl_ast_expr_access(res, list);
3882 isl_ast_expr_free(expr);
3884 return res;
3887 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3889 * If the AST expression refers to a global scalar that is not
3890 * a read-only scalar, then its address was passed to the kernel and
3891 * we need to dereference it.
3893 * If the AST expression refers to an access to a global array,
3894 * then we linearize the access exploiting the bounds in data->local_array.
3896 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3897 __isl_keep isl_id *id, void *user)
3899 struct ppcg_transform_data *data = user;
3901 if (!data->array)
3902 return expr;
3903 if (gpu_array_is_read_only_scalar(data->array))
3904 return expr;
3905 if (!data->global)
3906 return expr;
3907 if (data->array->n_index == 0)
3908 return dereference(expr);
3909 if (!data->array->linearize)
3910 return expr;
3912 return gpu_local_array_info_linearize_index(data->local_array, expr);
3915 /* This function is called for each instance of a user statement
3916 * in the kernel.
3918 * We attach a struct ppcg_kernel_stmt to the "node", containing
3919 * a computed AST expression for each access.
3920 * These AST expressions are computed from iterator_map,
3921 * which expresses the domain
3922 * elements in terms of the generated loops, and sched2shared,
3923 * which expresses the first shared_len dimensions of the schedule
3924 * computed by PPCG in terms of the generated loops.
3926 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3927 __isl_keep isl_ast_build *build, void *user)
3929 struct ppcg_transform_data data;
3930 struct gpu_gen *gen = (struct gpu_gen *) user;
3931 struct ppcg_kernel_stmt *stmt;
3932 isl_id *id;
3933 isl_pw_multi_aff *sched2shared;
3934 isl_map *map;
3935 isl_pw_multi_aff *iterator_map;
3936 isl_ast_expr *expr, *arg;
3937 isl_union_map *schedule;
3938 int i, n;
3939 struct gpu_stmt_access *access;
3941 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3942 if (!stmt)
3943 return isl_ast_node_free(node);
3945 expr = isl_ast_node_user_get_expr(node);
3946 arg = isl_ast_expr_get_op_arg(expr, 0);
3947 id = isl_ast_expr_get_id(arg);
3949 schedule = isl_ast_build_get_schedule(build);
3950 map = isl_map_reverse(isl_map_from_union_map(schedule));
3951 iterator_map = isl_pw_multi_aff_from_map(map);
3952 sched2shared = compute_sched_to_shared(gen,
3953 isl_pw_multi_aff_copy(iterator_map));
3955 stmt->type = ppcg_kernel_domain;
3956 stmt->u.d.stmt = find_stmt(gen->prog, id);
3957 if (!stmt->u.d.stmt)
3958 goto error;
3960 data.gen = gen;
3961 data.accesses = stmt->u.d.stmt->accesses;
3962 data.iterator_map = iterator_map;
3963 data.sched2shared = sched2shared;
3964 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
3965 build, &transform_index, &data,
3966 &transform_expr, &data);
3968 isl_id_free(id);
3969 isl_pw_multi_aff_free(iterator_map);
3970 isl_pw_multi_aff_free(sched2shared);
3971 isl_ast_expr_free(arg);
3972 isl_ast_expr_free(expr);
3974 id = isl_id_alloc(gen->ctx, NULL, stmt);
3975 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3976 return isl_ast_node_set_annotation(node, id);
3977 error:
3978 isl_id_free(id);
3979 isl_pw_multi_aff_free(iterator_map);
3980 ppcg_kernel_stmt_free(stmt);
3981 isl_pw_multi_aff_free(sched2shared);
3982 return isl_ast_node_free(node);
3985 /* This function is called when code has been generated for the shared
3986 * tile loops. The "schedule" refers only to the original statements.
3988 * We extend the schedule with that part of gen->local_sched that hasn't
3989 * been taken into account yet. This introduces parameters referring
3990 * to thread ids in the schedule, so we add them (with the appropriate
3991 * bounds to the context as well).
3992 * Finally, we set the appropriate unrolling options
3993 * if gen->first_unroll is set.
3995 static __isl_give isl_ast_node *create_domain_leaf(
3996 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3997 void *user)
3999 struct gpu_gen *gen = (struct gpu_gen *) user;
4000 isl_space *space;
4001 isl_union_map *sched;
4002 isl_ast_node *tree;
4003 isl_set *set;
4004 isl_id_list *iterators;
4005 int n;
4007 schedule = extend_schedule(schedule,
4008 isl_union_map_copy(gen->local_sched),
4009 gen->shared_len, gen->thread_tiled_len);
4011 space = isl_ast_build_get_schedule_space(build);
4012 set = isl_set_universe(space);
4013 set = add_bounded_parameters(set, gen->kernel->n_block,
4014 gen->kernel->block_dim, "t");
4015 build = isl_ast_build_restrict(build, set);
4017 n = gen->thread_tiled_len - gen->shared_len;
4019 if (gen->first_unroll >= 0) {
4020 space = isl_space_set_alloc(gen->ctx, 0, n);
4021 build = set_unroll(build, space, gen->first_unroll);
4023 iterators = generate_names(gen->ctx, n, "c");
4024 build = isl_ast_build_set_iterators(build, iterators);
4025 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4026 tree = isl_ast_build_ast_from_schedule(build, schedule);
4027 isl_ast_build_free(build);
4029 return tree;
4032 /* This function is called for each statement node in the AST of the code
4033 * for copying to or from shared/private memory.
4034 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4035 * statement to the node.
4036 * The statement name is "read" or "write", depending on whether we are
4037 * reading from global memory or writing to global memory.
4038 * The name of the T space is {shared,private}_<array>.
4040 * The schedule is of the form
4042 * type[A -> T] -> L
4044 * where A refers to a piece of an array and T to the corresponding
4045 * shifted tile. We split this schedule into mappings L -> A and L -> T
4046 * and store the corresponding expressions in stmt->index and stmt->local_index,
4047 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4049 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4050 __isl_keep isl_ast_build *build, void *user)
4052 struct gpu_gen *gen = (struct gpu_gen *) user;
4053 struct ppcg_kernel_stmt *stmt;
4054 isl_id *id;
4055 isl_ast_expr *expr;
4056 isl_space *space;
4057 isl_map *access, *local_access, *map;
4058 isl_pw_multi_aff *pma;
4059 const char *type;
4060 int array_index;
4062 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4063 if (!stmt)
4064 return isl_ast_node_free(node);
4066 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4067 type = isl_map_get_tuple_name(access, isl_dim_in);
4068 stmt->u.c.read = !strcmp(type, "read");
4069 access = isl_map_reverse(access);
4070 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4071 local_access = isl_map_copy(access);
4073 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4074 id = isl_map_get_tuple_id(access, isl_dim_out);
4075 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4076 access = isl_map_apply_range(access, map);
4077 pma = isl_pw_multi_aff_from_map(access);
4078 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4079 stmt->u.c.index = expr;
4081 map = isl_map_range_map(isl_map_universe(space));
4082 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4083 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4084 local_access = isl_map_apply_range(local_access, map);
4085 pma = isl_pw_multi_aff_from_map(local_access);
4086 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4087 stmt->u.c.local_index = expr;
4089 stmt->u.c.array = gen->copy_group->array;
4090 array_index = stmt->u.c.array - gen->prog->array;
4091 stmt->u.c.local_array = &gen->kernel->array[array_index];
4092 stmt->type = ppcg_kernel_copy;
4094 id = isl_id_alloc(gen->ctx, NULL, stmt);
4095 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4096 return isl_ast_node_set_annotation(node, id);
4099 /* Given a schedule of the form
4101 * [S -> A] -> L
4103 * (with S the first shared_len dimensions of the computed schedule,
4104 * A the array and L the schedule correponding to the generated loops),
4105 * indicating where to copy the array elements that need to be copied,
4106 * construct code for performing the copying.
4108 * "group" is the array reference group that is being copied
4109 * "type" is either "read" or "write"
4110 * private is set if copying needs to be performed to/from registers
4112 * We first construct a mapping to a shifted tile of the array,
4114 * [S -> A] -> T(S,A) (1)
4116 * If private is set, then we also use this mapping as a schedule
4117 * (which is already thread-specific and will be completely unrolled).
4118 * Otherwise, we wrap/tile the range over the threads.
4119 * The result is
4121 * [S -> A] -> T'(S,A)
4123 * Combined with the given schedule, we have
4125 * [S -> A] -> [L -> T'(S,A)] (2)
4127 * From the shifted tile mapping, we construct a mapping
4129 * [S -> A] -> [A -> T(S,A)]
4131 * and apply it to the schedule (2), obtaining
4133 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4135 * Note that we can project out S because it is uniquely defined by L.
4137 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4138 __isl_take isl_map *sched,
4139 const char *type, struct gpu_array_ref_group *group,
4140 __isl_take isl_ast_build *build, int private)
4142 isl_space *space;
4143 isl_ast_node *tree;
4144 isl_map *schedule, *shift, *map;
4145 isl_set *set;
4146 isl_id_list *iterators;
4147 int n;
4149 shift = shift_access(group);
4151 schedule = isl_map_copy(shift);
4152 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4153 if (!private)
4154 schedule = tile_access_schedule(gen, schedule);
4156 n = isl_map_dim(schedule, isl_dim_out);
4157 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4158 set = add_bounded_parameters(set, gen->kernel->n_block,
4159 gen->kernel->block_dim, "t");
4161 schedule = isl_map_range_product(sched, schedule);
4163 space = isl_space_domain(isl_map_get_space(shift));
4164 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4165 map = isl_map_range_product(map, shift);
4167 schedule = isl_map_apply_domain(schedule, map);
4169 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4171 build = isl_ast_build_restrict(build, set);
4173 gen->copy_group = group;
4175 if (private) {
4176 space = isl_space_range(isl_map_get_space(schedule));
4177 space = isl_space_range(isl_space_unwrap(space));
4178 build = set_unroll(build, space, 0);
4180 iterators = generate_names(gen->ctx, n, "c");
4181 build = isl_ast_build_set_iterators(build, iterators);
4182 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4183 tree = isl_ast_build_ast_from_schedule(build,
4184 isl_union_map_from_map(schedule));
4185 isl_ast_build_free(build);
4187 return tree;
4190 /* Return code for reading into or writing from shared memory
4191 * the given array reference group.
4193 * If we are performing a read from global memory to shared memory and
4194 * if the array involved is not a scalar, then we copy
4195 * the entire tile to shared memory. This may result in some extra
4196 * elements getting copied, but it should lead to simpler code
4197 * (which means that fewer registers may be needed) and less divergence.
4199 * Otherwise, we only copy the elements that will be read or have been written
4200 * in the kernel.
4203 * The input "sched" is of the form.
4205 * type[S -> A] -> L
4207 * with S the first shared_len dimensions of the computed schedule,
4208 * A the array and L the schedule correponding to the generated loops.
4210 * We first drop "type",
4212 * [S -> A] -> L
4214 * If the above conditions are satisfied, we project out A,
4215 * resulting in
4217 * S -> L
4219 * and then introduce the group tile [S -> T], resulting in
4221 * [S -> T] -> L
4223 static __isl_give isl_ast_node *copy_group_shared_accesses(
4224 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4225 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4227 const char *type;
4228 int read;
4229 isl_union_map *access;
4231 type = isl_map_get_tuple_name(sched, isl_dim_in);
4232 read = !strcmp(type, "read");
4234 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4236 if (read && !gpu_array_is_scalar(group->array)) {
4237 isl_space *space;
4238 isl_map *map;
4240 space = isl_space_domain(isl_map_get_space(sched));
4241 space = isl_space_unwrap(space);
4242 map = isl_map_domain_map(isl_map_universe(space));
4243 sched = isl_map_apply_domain(sched, map);
4245 map = group_tile(group);
4246 map = isl_map_reverse(isl_map_domain_map(map));
4247 sched = isl_map_apply_domain(sched, map);
4250 return copy_access(gen, sched, type, group, build, 0);
4253 /* Return code for reading into or writing from private memory
4254 * the given array reference group.
4256 * Let S be the first shared_len dimensions of the computed schedule,
4257 * D the iteration domains, A the array and L the schedule correponding
4258 * to the generated loops.
4259 * "sched" is of the form
4261 * type[S -> A] -> L
4263 * where type is either "read" or "write".
4264 * We apply the privatization D -> S(t), with t the thread ids,
4265 * to the access relation D -> A to obtain the privatized access relation
4267 * S(t) -> A
4269 * We drop the type from "sched" and intersect with the privatized access
4270 * relation to obtain
4272 * [S(t) -> A] -> L
4274 static __isl_give isl_ast_node *copy_group_private_accesses(
4275 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4276 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4278 const char *type;
4279 int read;
4280 isl_union_map *priv;
4281 isl_union_map *access;
4282 isl_map *access_map;
4284 type = isl_map_get_tuple_name(sched, isl_dim_in);
4285 read = !strcmp(type, "read");
4287 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4288 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4289 priv);
4291 access = group_access_relation(group, read, !read);
4292 access = isl_union_map_apply_domain(access, priv);
4293 access_map = isl_map_from_union_map(access);
4295 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4296 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4298 return copy_access(gen, sched, type, group, build, 1);
4301 /* Return code for reading into or writing from shared or private memory.
4303 * "schedule" is of the form
4305 * type[S -> A] -> L
4307 * with S be the first shared_len dimensions of the computed schedule,
4308 * A the array and L the schedule correponding to the generated loops.
4309 * The array reference group is attached to "type".
4311 static __isl_give isl_ast_node *create_access_leaf(
4312 struct gpu_gen *gen, __isl_take isl_map *schedule,
4313 __isl_take isl_ast_build *build)
4315 struct gpu_array_ref_group *group;
4316 isl_id *id;
4318 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4319 group = isl_id_get_user(id);
4320 isl_id_free(id);
4322 if (group->private_tile)
4323 return copy_group_private_accesses(gen, group, schedule,
4324 build);
4325 else
4326 return copy_group_shared_accesses(gen, group, schedule,
4327 build);
4330 /* Create a domain node representing a synchronization.
4332 static __isl_give isl_ast_node *create_sync_leaf(
4333 struct gpu_gen *gen, __isl_take isl_map *schedule,
4334 __isl_take isl_ast_build *build)
4336 struct ppcg_kernel_stmt *stmt;
4337 isl_id *id;
4338 isl_space *space;
4339 isl_ast_node *node;
4340 isl_ast_expr *expr;
4342 isl_map_free(schedule);
4344 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4345 if (!stmt)
4346 return NULL;
4348 stmt->type = ppcg_kernel_sync;
4350 space = isl_ast_build_get_schedule_space(build);
4351 space = isl_space_from_domain(space);
4352 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4353 expr = isl_ast_build_call_from_pw_multi_aff(build,
4354 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4355 node = isl_ast_node_alloc_user(expr);
4356 isl_ast_build_free(build);
4358 id = isl_id_alloc(gen->ctx, NULL, stmt);
4359 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4360 return isl_ast_node_set_annotation(node, id);
4363 /* This function is called during the code generation at the point
4364 * where the schedule domain element is completely determined by
4365 * the generated code. The input schedule contains the original
4366 * statements as well as synchronization and copy "statements".
4367 * The latter are scheduled at different points than any of the original
4368 * statements, so they will only arrive here in isolation.
4370 * If the current schedule only refers to a single statement,
4371 * we check if it is a copy or synchronization statement and
4372 * call the appropriate functions.
4373 * Otherwise, we assume we are dealing with the original statements
4374 * and we call create_domain_leaf.
4376 static __isl_give isl_ast_node *create_kernel_leaf(
4377 __isl_take isl_ast_build *build, void *user)
4379 struct gpu_gen *gen = (struct gpu_gen *) user;
4380 isl_map *map;
4381 isl_union_map *schedule;
4382 const char *name;
4384 schedule = isl_ast_build_get_schedule(build);
4386 if (isl_union_map_n_map(schedule) != 1)
4387 return create_domain_leaf(schedule, build, user);
4389 map = isl_map_from_union_map(schedule);
4390 name = isl_map_get_tuple_name(map, isl_dim_in);
4391 if (!strcmp(name, "read") || !strcmp(name, "write"))
4392 return create_access_leaf(gen, map, build);
4393 if (!strcmp(name, "sync"))
4394 return create_sync_leaf(gen, map, build);
4396 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4399 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4400 * have value 0) and all even schedule dimensions as "unroll".
4402 * That is, the options look as follows
4404 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4405 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4407 * The even positions are used to be able to schedule copying blocks
4408 * and synchronization before or after each level of the shared memory
4409 * tile loops and we want to make sure that code for these is generated
4410 * separately (within each level).
4412 static __isl_give isl_ast_build *set_atomic_and_unroll(
4413 __isl_take isl_ast_build *build,
4414 __isl_take isl_space *space, int sched_len)
4416 isl_ctx *ctx;
4417 isl_map *map;
4418 isl_constraint *c;
4419 isl_union_map *opt;
4420 isl_local_space *ls;
4421 int i, n;
4423 ctx = isl_ast_build_get_ctx(build);
4425 space = isl_space_params(space);
4426 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4427 space = isl_space_from_domain(space);
4428 space = isl_space_add_dims(space, isl_dim_out, 2);
4429 map = isl_map_universe(isl_space_copy(space));
4430 for (i = 0; i < sched_len; i += 2)
4431 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4432 ls = isl_local_space_from_space(isl_map_get_space(map));
4433 c = isl_equality_alloc(ls);
4434 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4435 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4436 c = isl_constraint_set_constant_si(c, 1);
4437 map = isl_map_add_constraint(map, c);
4438 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4439 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4440 opt = isl_union_map_from_map(map);
4442 map = isl_map_universe(space);
4443 ls = isl_local_space_from_space(isl_map_get_space(map));
4444 c = isl_equality_alloc(ls);
4445 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4446 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4447 map = isl_map_add_constraint(map, c);
4448 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4449 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4450 opt = isl_union_map_add_map(opt, map);
4452 build = isl_ast_build_set_options(build, opt);
4454 return build;
4457 /* Return a map that maps a space of dimension gen->shared_len
4458 * to its last dimensions starting at gen->tile_first.
4459 * The range is of dimension
4461 * 2 * (gen->shared_len - gen->tile_first) + 1
4463 * The input dimensions are mapped to the odd dimensions in the output,
4464 * while the even dimensions (except 2*pos) are fixed to 0.
4465 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4466 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4467 * are mapped to the output. The remaining input dimensions are projected
4468 * out and the corresponding output dimensions are fixed to 0.
4470 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4471 __isl_take isl_space *space, int pos, int val)
4473 int i, n;
4474 isl_map *proj;
4476 space = isl_space_set_from_params(space);
4477 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4478 space = isl_space_map_from_set(space);
4479 proj = isl_map_identity(space);
4480 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4481 n = gen->shared_len - gen->tile_first;
4482 for (i = 0; i <= n; ++i) {
4483 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4484 if (i == pos)
4485 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4486 else
4487 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4490 if (pos < 0)
4491 return proj;
4493 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4494 gen->shared_len - (gen->tile_first + pos));
4495 for (i = pos; i < n; ++i)
4496 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4498 return proj;
4501 /* Given the AST context schedule "schedule" and the mapping from
4502 * domains to the shared tile loops "shared_sched", add a schedule
4503 * for a synchronization operation at position "val" of loop level "pos".
4505 * schedule is of the form
4507 * D -> L
4509 * (with D the iteration domains and L the already generated loops),
4510 * while shared_sched is of the form
4512 * D -> S
4514 * We combine them into
4516 * L -> S
4518 * apply a mapping
4520 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4522 * and use the result as a schedule for "sync".
4524 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4525 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4526 __isl_keep isl_union_map *shared_sched, int pos, int val)
4528 isl_space *space;
4529 isl_map *proj, *map;
4531 shared_sched = isl_union_map_copy(shared_sched);
4532 schedule = isl_union_map_copy(schedule);
4534 space = isl_union_map_get_space(shared_sched);
4535 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4536 map = isl_map_from_union_map(schedule);
4538 proj = insert_even(gen, space, pos, val);
4539 map = isl_map_apply_range(map, proj);
4540 map = isl_map_from_range(isl_map_wrap(map));
4541 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4543 res = isl_union_map_add_map(res, map);
4545 return res;
4548 /* Given a set of wrapped references "ref", return the corresponding
4549 * access relations based on the tagged access relations "tagged".
4551 * The elements of "ref" are of the form
4553 * [D -> R]
4555 * with D an iteration domains and R a reference.
4556 * The elements of "tagged" are of the form
4558 * [D -> R] -> A
4560 * with A an array.
4562 * Extend "tagged" to include the iteration domain in the range, i.e.,
4564 * [D -> R] -> [D -> A]
4566 * apply the result to "ref" and then unwrap the resulting set
4567 * to obtain relations of the form
4569 * D -> A
4571 static __isl_give isl_union_map *wrapped_reference_to_access(
4572 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4574 isl_union_map *tag2access;
4576 tag2access = isl_union_map_copy(tagged);
4577 tag2access = isl_union_map_universe(tag2access);
4578 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4579 tag2access = isl_union_map_domain_map(tag2access);
4580 tag2access = isl_union_map_range_product(tag2access, tagged);
4582 ref = isl_union_set_coalesce(ref);
4583 ref = isl_union_set_apply(ref, tag2access);
4585 return isl_union_set_unwrap(ref);
4588 /* Given an access relation "access" from "group", remove those reads
4589 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4590 * communicate data within the same iteration of the last_shared dimension
4591 * of the group.
4593 * If the access is a read then it is necessarily an element of
4595 * live_in union (range flow)
4597 * where live_in and flow may be overapproximations.
4598 * If the access is a write then it is necessarily an element of
4600 * live_out union (domain flow)
4602 * In both cases, the access relation is also a subset of
4603 * the group access relation.
4605 * Essentially, we compute the intersection of "access" with either
4607 * live_in union (range non-local-flow)
4609 * or
4611 * live_out union (domain non-local-flow)
4613 * We first construct a relation "local"
4615 * [[D -> R] -> [D' -> R']]
4617 * of pairs of domain iterations accessing the reference group
4618 * and references in the group that are scheduled to the same iteration
4619 * of the last_shared dimension.
4621 * If this relation does not intersect the dataflow dependences,
4622 * then there is nothing we can possibly remove and we simply
4623 * return the input.
4625 * Otherwise, we remove the "local" dataflow dependences from
4626 * the set of all dataflow dependences.
4627 * Note that if the potential dataflow dependences are an overapproximation
4628 * of the actual dataflow dependences, then the result remains an
4629 * overapproximation of the non-local dataflow dependences.
4630 * Copying to/from global memory is only needed for the references
4631 * in the domain/range of the result or for accesses that are live out/in
4632 * for the entire scop.
4634 * We therefore map the domain/range of the "external" relation
4635 * to the corresponding access relation and take the union with
4636 * the live out/in relation.
4638 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4639 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4640 int read)
4642 int empty;
4643 isl_union_map *tagger;
4644 isl_union_set *domain;
4645 isl_space *space;
4646 isl_union_map *sched, *local, *tagged, *external;
4647 isl_union_set *tag_set;
4648 isl_map *proj;
4650 if (isl_union_map_is_empty(access))
4651 return access;
4653 tagged = group_tagged_access_relation(group);
4655 sched = isl_union_map_copy(gen->sched);
4657 space = isl_union_map_get_space(sched);
4658 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4659 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4661 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4662 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4663 tagger = isl_union_map_intersect_range(tagger, domain);
4664 sched = isl_union_map_apply_domain(sched, tagger);
4666 local = isl_union_map_apply_range(sched,
4667 isl_union_map_reverse(isl_union_map_copy(sched)));
4668 local = isl_union_map_intersect(local,
4669 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4671 empty = isl_union_map_is_empty(local);
4672 if (empty < 0 || empty) {
4673 isl_union_map_free(tagged);
4674 isl_union_map_free(local);
4675 if (empty < 0)
4676 return isl_union_map_free(access);
4677 return access;
4680 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4681 external = isl_union_map_intersect_params(external,
4682 isl_set_copy(gen->prog->scop->context));
4683 external = isl_union_map_subtract(external, local);
4685 if (read) {
4686 tag_set = isl_union_map_range(external);
4687 external = wrapped_reference_to_access(tag_set, tagged);
4688 external = isl_union_map_union(external,
4689 isl_union_map_copy(gen->prog->scop->live_in));
4690 } else {
4691 tag_set = isl_union_map_domain(external);
4692 external = wrapped_reference_to_access(tag_set, tagged);
4693 external = isl_union_map_union(external,
4694 isl_union_map_copy(gen->prog->scop->live_out));
4697 access = isl_union_map_intersect(access, external);
4699 return access;
4702 /* Given the AST context schedule "schedule" and the mapping from
4703 * domains to the shared tile loops "shared_sched", add a schedule
4704 * for copying an array reference group to/from shared/private memory.
4705 * "read" is set if data should be copied from global memory
4706 * to shared/private memory.
4707 * "k" represents the current group
4708 * "s" is the total number of groups
4710 * We schedule an operation before or after the innermost loop
4711 * of "shared_sched" that affects the tile of the array reference group.
4713 * schedule is of the form
4715 * D -> L
4717 * (with D the iteration domains and L the already generated loops),
4718 * while shared_sched is of the form
4720 * D -> S
4722 * We first compute the access relation for the reference group
4724 * D -> A
4726 * and remove from this access relation those reads or writes
4727 * that only needed to communicate data within the same iteration
4728 * of the last_shared dimension of the group.
4729 * We then combine what is left with shared_sched into
4731 * D -> [S -> A]
4733 * If this results in an empty relation, no copying needs to be performed
4734 * at this point.
4735 * Otherwise, we invert the relation and combine it with "schedule" into
4737 * [S -> A] -> L
4739 * The actual additional piece of the schedule is obtained from combining
4741 * [S -> A] -> S
4743 * with a mapping
4745 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4747 * The position of "val" corresponds to the innermost loop that affects
4748 * the tile and the value indicates where the copying is scheduled
4749 * with respect to the actual kernel code (at value 0).
4750 * Reads are schedule before the code, writes to global memory from
4751 * private memory are scheduled at values 1 to s, writes to global
4752 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4754 * If we are scheduling a read from global memory to shared memory,
4755 * we insert a synchronization before the kernel code (at the innermost
4756 * level).
4757 * If we are scheduling a write to global memory, then we add
4758 * a synchronization after all writes (at value 2 *s + 2).
4759 * However, there is no need for a synchronization after the outermost loop.
4760 * A write to global memory from private memory at the innermost level
4761 * does not require a synchronization, because it is covered by
4762 * the synchronization after the kernel inserted by body_schedule.
4764 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4765 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4766 __isl_keep isl_union_map *shared_sched,
4767 struct gpu_array_ref_group *group, int read, int k, int s)
4769 int n;
4770 int pos, val;
4771 isl_space *space;
4772 isl_union_map *access;
4773 isl_map *map, *proj, *access_map;
4774 isl_id *id;
4776 access = group_access_relation(group, read, !read);
4777 access = remove_local_accesses(gen, group, access, read);
4778 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4779 access);
4781 if (isl_union_map_is_empty(access)) {
4782 isl_union_map_free(access);
4783 return res;
4786 access = isl_union_map_reverse(access);
4787 access = isl_union_map_apply_range(access,
4788 isl_union_map_copy(schedule));
4789 access_map = isl_map_from_union_map(access);
4791 space = isl_space_copy(group->array->space);
4792 space = isl_space_from_range(space);
4793 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4794 map = isl_map_domain_map(isl_map_universe(space));
4796 space = isl_union_map_get_space(schedule);
4797 pos = group->last_shared + 1 - gen->tile_first;
4798 assert(pos >= 0);
4799 if (read)
4800 val = -2 - k;
4801 else if (group->private_tile)
4802 val = 1 + k;
4803 else
4804 val = 1 + s + 1 + k;
4805 proj = insert_even(gen, space, pos, val);
4806 map = isl_map_apply_range(map, proj);
4808 access_map = isl_map_range_product(access_map, map);
4810 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4811 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4813 res = isl_union_map_add_map(res, access_map);
4815 n = gen->shared_len - gen->tile_first;
4816 if (read) {
4817 if (!group->private_tile)
4818 res = add_sync_schedule(gen, res, schedule,
4819 shared_sched, n, -1);
4820 } else {
4821 if (pos == 0)
4822 return res;
4823 if (pos == n && group->private_tile)
4824 return res;
4825 res = add_sync_schedule(gen, res, schedule, shared_sched,
4826 pos, 2 * s + 2);
4829 return res;
4832 /* Return a schedule for the shared tile loops based on the current
4833 * AST context schedule.
4835 * We create a "shared_sched" that maps the domains to the first
4836 * shared_len dimensions of the computed schedule, project out the
4837 * first tile_first dimensions (as these are already covered by
4838 * the host code) and insert "statement-level" dimensions at even
4839 * positions so that we can schedule copy blocks and synchronization
4840 * before/after each level.
4842 * In particular, copy blocks are inserted inside the innermost
4843 * level that affect the tile. For the copying to global memory,
4844 * those from private memory are scheduled before those from shared
4845 * memory such that synchronization can be inserted between the two
4846 * at the innermost level.
4847 * Synchronization is inserted at the innermost level before the
4848 * actual kernel code if there is any copying from global memory
4849 * to shared memory. It is inserted unconditionally at the innermost
4850 * level after the actual kernel code and the copying to global memory
4851 * from private memory (if any). Finally, it is inserted after
4852 * any copying to global memory, except at the outermost level
4853 * and at the innermost level if there is no copying from shared
4854 * memory. The copying from private memory is covered by the unconditional
4855 * synchronization at the innermost level.
4857 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4858 __isl_take isl_union_map *schedule)
4860 isl_space *space;
4861 isl_union_map *res;
4862 isl_union_map *shared_sched;
4863 isl_union_map *sched;
4864 isl_map *proj, *map;
4865 int i, j, k, s;
4867 shared_sched = isl_union_map_copy(gen->tiled_sched);
4868 proj = projection(isl_union_map_get_space(shared_sched),
4869 gen->tiled_len, gen->shared_len);
4870 shared_sched = isl_union_map_apply_range(shared_sched,
4871 isl_union_map_from_map(proj));
4872 space = isl_union_map_get_space(shared_sched);
4873 proj = insert_even(gen, space, -1, 0);
4874 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4875 isl_union_map_from_map(proj));
4877 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4879 s = 0;
4880 for (i = 0; i < gen->prog->n_array; ++i)
4881 s += gen->prog->array[i].n_group;
4883 k = 0;
4884 for (i = 0; i < gen->prog->n_array; ++i) {
4885 struct gpu_array_info *array = &gen->prog->array[i];
4887 for (j = 0; j < array->n_group; ++j) {
4888 struct gpu_array_ref_group *group;
4890 group = array->groups[j];
4891 if (!group->private_tile && !group->shared_tile)
4892 continue;
4893 res = add_group_schedule(gen, res, schedule,
4894 shared_sched, group, 0, k, s);
4895 res = add_group_schedule(gen, res, schedule,
4896 shared_sched, group, 1, k, s);
4897 ++k;
4901 res = add_sync_schedule(gen, res, schedule, shared_sched,
4902 gen->shared_len - gen->tile_first, 1 + s);
4904 isl_union_map_free(shared_sched);
4905 isl_union_map_free(schedule);
4907 return res;
4910 /* Generate code for "kernel" in the given "context".
4912 * We first generate code for the shared tile loops (T1T, T1P and T2)
4913 * in a context that includes the block ids.
4914 * Within each iteration of these loops an additional code generation
4915 * is performed (within create_kernel_leaf) for the rest of the schedule
4916 * in a context that includes the thread ids.
4918 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4919 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4920 __isl_keep isl_multi_pw_aff *grid_size)
4922 isl_space *space;
4923 isl_set *set;
4924 isl_id_list *iterators;
4925 isl_union_map *schedule;
4926 isl_ast_node *tree;
4927 int sched_len;
4929 schedule = isl_ast_build_get_schedule(build);
4931 build = isl_ast_build_copy(build);
4932 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4933 space = isl_ast_build_get_schedule_space(build);
4934 set = isl_set_universe(isl_space_copy(space));
4935 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4936 build = isl_ast_build_restrict(build, set);
4938 schedule = body_schedule(gen, schedule);
4940 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4942 build = set_atomic_and_unroll(build, space, sched_len);
4943 iterators = generate_names(gen->ctx, sched_len, "g");
4944 build = isl_ast_build_set_iterators(build, iterators);
4945 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4946 tree = isl_ast_build_ast_from_schedule(build, schedule);
4947 isl_ast_build_free(build);
4949 return tree;
4952 /* Attach "id" to the given node.
4954 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4955 __isl_keep isl_ast_build *build, void *user)
4957 isl_id *id = user;
4959 node = isl_ast_node_set_annotation(node, id);
4961 return node;
4964 /* Construct an AST node for performing a kernel launch and attach
4965 * the information about the kernel to that node.
4967 * The kernel AST has been constructed in the context of the range
4968 * of "schedule". In particular, the grid size has been computed
4969 * in the context. We therefore still need to make sure that these
4970 * constraints are expressed in the code. We do this by creating a schedule
4972 * kernel[] -> [S -> []]
4974 * where S is the schedule domain, i.e., the range of "schedule".
4975 * The AST generation will then create a single call surrounded by
4976 * all the condition in "S" that have not been expressed yet.
4978 * The kernel information is attached to this node in attach_id.
4980 static __isl_give isl_ast_node *construct_launch(
4981 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4982 __isl_take struct ppcg_kernel *kernel)
4984 isl_id *id;
4985 isl_ctx *ctx;
4986 isl_union_set *domain;
4987 isl_set *set;
4988 isl_map *map;
4989 isl_ast_node *node;
4991 ctx = isl_ast_build_get_ctx(build);
4993 id = isl_id_alloc(ctx, NULL, kernel);
4994 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4996 domain = isl_union_map_range(schedule);
4997 set = isl_set_from_union_set(domain);
4998 map = isl_map_from_domain(set);
4999 map = isl_map_from_range(isl_map_wrap(map));
5000 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5001 schedule = isl_union_map_from_map(map);
5003 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5004 node = isl_ast_build_ast_from_schedule(build, schedule);
5005 isl_ast_build_free(build);
5007 return node;
5010 /* This function is called for each leaf in the AST of the host code.
5011 * We first specialize the schedule to the site of the leaf, compute
5012 * the size of shared memory and then construct the body of the host code
5013 * and the associated kernel.
5015 * The necessary information for printing the kernel launch is
5016 * stored in a struct ppcg_kernel and attached to the leaf node
5017 * created to represent the launch.
5019 static __isl_give isl_ast_node *create_host_leaf(
5020 __isl_take isl_ast_build *build, void *user)
5022 struct gpu_gen *gen = (struct gpu_gen *) user;
5023 isl_id *id;
5024 isl_ast_node *node;
5025 struct ppcg_kernel *kernel;
5026 isl_set *host_domain;
5027 isl_union_map *schedule;
5028 isl_union_map *local_sched;
5029 isl_union_map *access;
5030 isl_union_set *domain;
5031 int i;
5033 schedule = isl_ast_build_get_schedule(build);
5035 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5036 read_sizes(gen);
5038 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5040 local_sched = isl_union_map_copy(gen->sched);
5041 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5042 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5043 isl_union_map_copy(gen->prog->may_write));
5044 access = isl_union_map_apply_domain(access,
5045 isl_union_map_copy(local_sched));
5047 gen->tiled_sched = tile_schedule(gen, local_sched);
5048 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5049 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5051 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5052 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5053 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5055 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5056 if (!kernel)
5057 goto error;
5059 kernel->id = gen->kernel_id++;
5060 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5061 kernel->grid_size = extract_grid_size(gen, kernel);
5062 extract_block_size(gen, kernel);
5063 kernel->arrays = isl_union_map_range(access);
5064 kernel->arrays = isl_union_set_apply(kernel->arrays,
5065 isl_union_map_copy(gen->prog->to_outer));
5066 kernel->space = isl_ast_build_get_schedule_space(build);
5068 gen->private_access = NULL;
5069 compute_shared_sched(gen);
5070 gen->privatization = compute_privatization(gen);
5071 check_scalar_live_ranges(gen);
5072 if (group_references(gen) < 0)
5073 schedule = isl_union_map_free(schedule);
5074 compute_private_access(gen);
5075 host_domain = isl_set_from_union_set(isl_union_map_range(
5076 isl_union_map_copy(schedule)));
5077 localize_bounds(gen, kernel, host_domain);
5079 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5080 check_shared_memory_bound(gen);
5081 compute_group_tilings(gen);
5083 kernel->tree = generate_kernel(gen, build, host_domain,
5084 kernel->grid_size);
5085 create_kernel_vars(gen, kernel);
5087 free_local_array_info(gen);
5088 isl_map_free(gen->privatization);
5089 isl_union_map_free(gen->private_access);
5090 isl_union_map_free(gen->local_sched);
5091 isl_union_map_free(gen->tiled_sched);
5092 isl_union_map_free(gen->shared_sched);
5093 isl_union_map_free(gen->shared_proj);
5094 isl_set_free(host_domain);
5095 free(gen->tile_size);
5097 node = construct_launch(build, schedule, kernel);
5099 return node;
5100 error:
5101 isl_union_map_free(schedule);
5102 return NULL;
5105 /* Use isl to generate code for the outer gen->tile_first loops
5106 * of the global schedule in gen->sched, resulting in the host code.
5107 * Within each iteration of this partial schedule, i.e., for each kernel
5108 * launch, create_host_leaf takes care of generating the kernel code.
5110 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5112 isl_ast_build *build;
5113 isl_ast_node *tree;
5114 isl_union_map *sched;
5115 isl_map *proj;
5116 isl_id_list *iterators;
5118 sched = isl_union_map_copy(gen->sched);
5119 proj = projection(isl_union_map_get_space(sched),
5120 gen->untiled_len, gen->tile_first);
5121 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5123 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5124 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5125 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5126 build = isl_ast_build_set_iterators(build, iterators);
5127 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5128 tree = isl_ast_build_ast_from_schedule(build, sched);
5129 isl_ast_build_free(build);
5131 return tree;
5134 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5136 if (!str)
5137 return NULL;
5138 return isl_union_map_read_from_str(ctx, str);
5141 /* Information about the outermost tilable bands in the forest of bands.
5143 * tile_len and n_parallel are only sets on band_info structures
5144 * that correspond to outermost bands. For other bands (in particular,
5145 * ancestors of the outermost bands), n_parallal is set to 0.
5147 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5149 * tile_first is the number of schedule dimensions in prefix.
5151 * suffix is the schedule of the outermost tilable bands and their descendants.
5153 struct band_info {
5154 struct gpu_gen *gen;
5155 int tile_first;
5156 int tile_len;
5157 int n_parallel;
5158 isl_union_map *prefix;
5159 isl_union_map *suffix;
5162 /* Set tile_len and n_parallel of the statement to that of
5163 * their outermost band, recorded in the band_info.
5165 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5167 struct band_info *info = user;
5168 struct gpu_stmt *stmt;
5169 isl_id *id;
5171 id = isl_map_get_tuple_id(map, isl_dim_in);
5172 stmt = find_stmt(info->gen->prog, id);
5173 isl_id_free(id);
5175 stmt->tile_len = info->tile_len;
5176 stmt->n_parallel = info->n_parallel;
5178 isl_map_free(map);
5180 return 0;
5183 static void list_select_outer_band(struct gpu_gen *gen,
5184 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5186 /* Check if this band has any parallel loops. If so, take it as
5187 * the outermost tilable band. If not, continue looking for the
5188 * outermost tilable band in the children of the current band.
5190 static void band_select_outer_band(struct gpu_gen *gen,
5191 __isl_take isl_band *band, int pos, struct band_info *info)
5193 int n = isl_band_n_member(band);
5194 int n_parallel;
5196 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5197 if (!isl_band_member_is_coincident(band, n_parallel))
5198 break;
5200 info->n_parallel = n_parallel;
5201 if (n_parallel) {
5202 gen->any_parallelism = 1;
5203 info->gen = gen;
5204 info->tile_first = pos;
5205 info->tile_len = n;
5206 info->prefix = isl_band_get_prefix_schedule(band);
5207 info->suffix = isl_union_map_flat_range_product(
5208 isl_band_get_partial_schedule(band),
5209 isl_band_get_suffix_schedule(band));
5210 isl_union_map_foreach_map(info->prefix,
5211 &set_stmt_tile_len, info);
5212 } else if (isl_band_has_children(band)) {
5213 isl_band_list *children;
5214 children = isl_band_get_children(band);
5215 list_select_outer_band(gen, children, pos + n, info);
5216 } else {
5217 info->gen = gen;
5218 info->tile_first = pos + n;
5219 info->tile_len = 0;
5220 info->prefix = isl_union_map_flat_range_product(
5221 isl_band_get_prefix_schedule(band),
5222 isl_band_get_partial_schedule(band));
5223 info->suffix = isl_band_get_suffix_schedule(band);
5224 isl_union_map_foreach_map(info->prefix,
5225 &set_stmt_tile_len, info);
5228 isl_band_free(band);
5231 /* Comparison function that returns a non-zero value for band_infos
5232 * with different tile_len fields or different n_parallel fields.
5234 static int cmp_band(const void *p1, const void *p2)
5236 const struct band_info *info1 = p1;
5237 const struct band_info *info2 = p2;
5239 if (info1->tile_len != info2->tile_len)
5240 return info1->tile_len - info2->tile_len;
5242 return info1->n_parallel - info2->n_parallel;
5245 /* Extend "umap" with coordinates with fixed value "val"
5246 * to a total length of "dst_len", assuming the original dimension is "src_len".
5248 static __isl_give isl_union_map *extend_range(
5249 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5251 isl_space *dim;
5252 isl_map *map;
5253 int i;
5255 dim = isl_union_map_get_space(umap);
5256 map = isl_map_reverse(projection(dim, dst_len, src_len));
5257 for (i = src_len; i < dst_len; ++i)
5258 map = isl_map_fix_si(map, isl_dim_out, i, val);
5260 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5262 return umap;
5265 /* Group bands with the same values for tile_len and n_parallel.
5266 * The prefix schedule is then extended with a fixed coordinate that
5267 * is different for each such group.
5268 * Note that the actual values for this coordinate are not important.
5269 * The bands have already been effectively separated at a higher level
5270 * or they are independent and may be executed in parallel.
5271 * The list of band_info has been sorted before this functions is called.
5273 static void separate_bands(struct band_info *info, int n)
5275 int i;
5276 int j = 0;
5278 for (i = 0; i < n; ++i) {
5279 int l = info[i].tile_first;
5281 if (i &&
5282 (info[i].tile_len != info[i - 1].tile_len ||
5283 info[i].n_parallel != info[i - 1].n_parallel))
5284 j++;
5286 info[i].prefix = extend_range(info[i].prefix,
5287 l, l + 1, j);
5288 info[i].tile_first = l + 1;
5292 /* Select the outermost bands in the elements of the list, align
5293 * their prefix schedules, separate bands with different values
5294 * for tile_len and/or n_parallel and then combine the resulting
5295 * prefix and suffix schedules into a single pair of prefix and
5296 * suffix schedules for the entire list.
5298 static void list_select_outer_band(struct gpu_gen *gen,
5299 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5301 isl_band *band;
5302 int i;
5303 int n = isl_band_list_n_band(list);
5304 isl_ctx *ctx = isl_band_list_get_ctx(list);
5305 struct band_info *info;
5306 int max_tile_first;
5307 isl_union_map *prefix;
5308 isl_union_map *suffix;
5310 assert(n >= 1);
5311 info = isl_calloc_array(ctx, struct band_info, n);
5312 assert(info);
5314 max_tile_first = 0;
5315 for (i = 0; i < n; ++i) {
5316 band = isl_band_list_get_band(list, i);
5317 band_select_outer_band(gen, band, pos, &info[i]);
5318 if (info[i].tile_first > max_tile_first)
5319 max_tile_first = info[i].tile_first;
5322 for (i = 0; i < n; ++i) {
5323 if (info[i].tile_first == max_tile_first)
5324 continue;
5325 info[i].prefix = extend_range(info[i].prefix,
5326 info[i].tile_first, max_tile_first, 0);
5327 info[i].tile_first = max_tile_first;
5330 qsort(info, n, sizeof(struct band_info), &cmp_band);
5332 for (i = 0; i < n - 1; ++i)
5333 if (info[i].tile_len != info[i + 1].tile_len ||
5334 info[i].n_parallel != info[i + 1].n_parallel)
5335 break;
5337 if (i < n -1)
5338 separate_bands(info, n);
5340 prefix = info[0].prefix;
5341 suffix = info[0].suffix;
5343 for (i = 1; i < n; ++i) {
5344 prefix = isl_union_map_union(prefix, info[i].prefix);
5345 suffix = isl_union_map_union(suffix, info[i].suffix);
5348 list_info->tile_first = info[0].tile_first;
5349 list_info->tile_len = -1;
5350 list_info->prefix = prefix;
5351 list_info->suffix = suffix;
5353 isl_band_list_free(list);
5354 free(info);
5357 /* Select the outermost tilable band that (by construction)
5358 * has at least one parallel loop.
5359 * The starting position of the aligned band is stored in the pair
5360 * gen->tile_first.
5361 * The sizes and number of parallel loops may be different in different
5362 * parts of the band forest and are therefore stored in the gpu_stmts.
5364 * Return the complete schedule, with the tilable bands aligned
5365 * at gen->tile_first and padded with zero, if needed.
5367 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5368 __isl_keep isl_schedule *schedule)
5370 isl_band_list *list;
5371 struct band_info info;
5373 gen->n_parallel = 0;
5374 gen->tile_len = -1;
5376 list = isl_schedule_get_band_forest(schedule);
5378 if (isl_band_list_n_band(list) == 0) {
5379 isl_band_list_free(list);
5380 return isl_schedule_get_map(schedule);
5383 list_select_outer_band(gen, list, 0, &info);
5385 gen->tile_first = info.tile_first;
5386 info.suffix = align_range(info.suffix);
5388 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5391 /* Set gen->untiled_len to the number of scheduling dimensions
5392 * for the schedule of the first domain.
5393 * We assume here that this number is the same for all domains.
5395 static int set_untiled_len(__isl_take isl_map *map, void *user)
5397 unsigned *untiled_len = user;
5399 *untiled_len = isl_map_dim(map, isl_dim_out);
5401 isl_map_free(map);
5402 return -1;
5405 /* Compute an appropriate schedule based on the accesses in
5406 * gen->read and gen->write.
5408 * We use the dependences in gen->prog->scop to compute
5409 * a schedule that has a parallel loop in each tilable band.
5410 * Finally, we select the outermost tilable band.
5412 * If live range reordering is allowed, then we need to make sure
5413 * that live ranges on arrays are not run in parallel since doing
5414 * so would require array expansion. We therefore add the array
5415 * order dependences to the coincidence dependences. Non-zero array
5416 * order dependences will then prevent a schedule dimension from being
5417 * considered parallel.
5418 * Live ranges derived from scalars are allowed to be run in parallel
5419 * since we force the scalars to be mapped to private memory in
5420 * check_scalar_live_ranges.
5421 * If live range reordering is allowed, then the false dependences
5422 * are not added to the validity constraints as that would prevent
5423 * reordering. Instead, the external false dependences that enforce that reads
5424 * from potentially live-in data precede any later write and
5425 * that writes of potentially live-out data follow any other earlier write
5426 * are added to the validity constraints.
5427 * The false dependences are still added to the proximity constraints
5428 * for consistency with the case where live range reordering is not allowed.
5430 static void compute_schedule(struct gpu_gen *gen)
5432 isl_union_set *domain;
5433 isl_union_map *dep_raw, *dep;
5434 isl_union_map *validity, *proximity, *coincidence;
5435 isl_union_map *sched;
5436 isl_schedule_constraints *sc;
5437 isl_schedule *schedule;
5439 domain = isl_union_set_copy(gen->prog->scop->domain);
5440 domain = isl_union_set_intersect_params(domain,
5441 isl_set_copy(gen->prog->scop->context));
5442 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5443 if (gen->options->live_range_reordering) {
5444 sc = isl_schedule_constraints_set_conditional_validity(sc,
5445 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5446 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5447 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5448 validity = isl_union_map_copy(proximity);
5449 validity = isl_union_map_union(validity,
5450 isl_union_map_copy(gen->prog->scop->dep_external));
5451 proximity = isl_union_map_union(proximity,
5452 isl_union_map_copy(gen->prog->scop->dep_false));
5453 coincidence = isl_union_map_copy(validity);
5454 coincidence = isl_union_map_union(coincidence,
5455 isl_union_map_copy(gen->prog->array_order));
5456 } else {
5457 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5458 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5459 dep = isl_union_map_union(dep, dep_raw);
5460 dep = isl_union_map_coalesce(dep);
5461 proximity = isl_union_map_copy(dep);
5462 coincidence = isl_union_map_copy(dep);
5463 validity = dep;
5465 sc = isl_schedule_constraints_set_validity(sc, validity);
5466 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5467 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5469 if (gen->options->debug->dump_schedule_constraints)
5470 isl_schedule_constraints_dump(sc);
5471 schedule = isl_schedule_constraints_compute_schedule(sc);
5472 if (gen->options->debug->dump_schedule)
5473 isl_schedule_dump(schedule);
5475 sched = select_outer_tilable_band(gen, schedule);
5477 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5478 sched = isl_union_map_intersect_domain(sched, domain);
5479 gen->sched = sched;
5481 isl_schedule_free(schedule);
5484 /* Compute the sets of outer array elements that need to be copied in and out.
5486 * In particular, for each array that is possibly written anywhere in
5487 * gen->prog and that is visible outside the corresponding scop,
5488 * we copy out its entire extent.
5490 * Any array elements that is read without first being written needs
5491 * to be copied in. Furthermore, if there are any array elements that
5492 * are copied out, but that may not be written inside gen->prog, then
5493 * they also need to be copied in to ensure that the value after execution
5494 * is the same as the value before execution.
5495 * In case the array elements are structures, we need to take into
5496 * account that all members of the structures need to be written
5497 * by gen->prog before we can avoid copying the data structure in.
5499 * While computing the set of array elements that are copied out but
5500 * not necessarily written, we intersect both sets with the context.
5501 * This helps in those cases where the arrays are declared with a fixed size,
5502 * while the accesses are parametric and the context assigns a fixed value
5503 * to the parameters.
5505 * If an element from a local array is read without first being written,
5506 * then there is no point in copying it in since it cannot have been
5507 * written prior to the scop. Warn about the uninitialized read instead.
5509 static void compute_copy_in_and_out(struct gpu_gen *gen)
5511 int i;
5512 isl_union_set *local;
5513 isl_union_set *may_write, *must_write;
5514 isl_union_set *copy_in, *copy_out;
5515 isl_union_set *not_written;
5516 isl_union_map *uninitialized;
5517 isl_union_map *local_uninitialized;
5519 must_write = isl_union_map_range(
5520 isl_union_map_copy(gen->prog->must_write));
5521 must_write = isl_union_set_intersect_params(must_write,
5522 isl_set_copy(gen->prog->context));
5523 may_write = isl_union_map_range(
5524 isl_union_map_copy(gen->prog->may_write));
5525 may_write = isl_union_set_intersect_params(may_write,
5526 isl_set_copy(gen->prog->context));
5527 may_write = isl_union_set_universe(may_write);
5528 may_write = isl_union_set_apply(may_write,
5529 isl_union_map_copy(gen->prog->to_outer));
5530 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5531 local = isl_union_set_copy(copy_out);
5533 for (i = 0; i < gen->prog->n_array; ++i) {
5534 isl_space *space;
5535 isl_set *write_i;
5536 int empty;
5538 space = isl_space_copy(gen->prog->array[i].space);
5540 if (gen->prog->array[i].local) {
5541 isl_set *set;
5543 set = isl_set_universe(space);
5544 local = isl_union_set_add_set(local, set);
5545 continue;
5548 write_i = isl_union_set_extract_set(may_write, space);
5549 empty = isl_set_fast_is_empty(write_i);
5550 isl_set_free(write_i);
5551 if (empty)
5552 continue;
5554 write_i = isl_set_copy(gen->prog->array[i].extent);
5555 copy_out = isl_union_set_add_set(copy_out, write_i);
5557 isl_union_set_free(may_write);
5559 copy_out = isl_union_set_intersect_params(copy_out,
5560 isl_set_copy(gen->prog->context));
5562 gen->prog->copy_out = isl_union_set_copy(copy_out);
5564 copy_out = isl_union_set_apply(copy_out,
5565 isl_union_map_copy(gen->prog->to_inner));
5566 not_written = isl_union_set_subtract(copy_out, must_write);
5568 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5569 local_uninitialized = isl_union_map_copy(uninitialized);
5571 local = isl_union_set_apply(local,
5572 isl_union_map_copy(gen->prog->to_inner));
5573 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5574 local);
5575 if (!isl_union_map_is_empty(local_uninitialized)) {
5576 fprintf(stderr,
5577 "possibly uninitialized reads (not copied in):\n");
5578 isl_union_map_dump(local_uninitialized);
5580 uninitialized = isl_union_map_subtract(uninitialized,
5581 local_uninitialized);
5582 copy_in = isl_union_map_range(uninitialized);
5583 copy_in = isl_union_set_union(copy_in, not_written);
5584 copy_in = isl_union_set_apply(copy_in,
5585 isl_union_map_copy(gen->prog->to_outer));
5587 gen->prog->copy_in = copy_in;
5590 /* Extract a gpu_stmt_access from "expr", append it to the list
5591 * that ends in *next_access and return the updated end of the list.
5593 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
5594 struct gpu_stmt_access **next_access)
5596 struct gpu_stmt_access *access;
5597 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
5599 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5600 assert(access);
5601 access->next = NULL;
5602 access->read = expr->acc.read;
5603 access->write = expr->acc.write;
5604 access->access = pet_expr_access_get_may_access(expr);
5605 access->tagged_access = pet_expr_access_get_tagged_may_access(expr);
5606 access->exact_write = !expr->acc.write ||
5607 isl_map_is_equal(expr->acc.access, access->access);
5608 access->ref_id = isl_id_copy(expr->acc.ref_id);
5609 access->group = -1;
5611 *next_access = access;
5612 next_access = &(*next_access)->next;
5613 return next_access;
5616 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
5617 struct gpu_stmt_access **next_access)
5619 int i;
5621 for (i = 0; i < expr->n_arg; ++i)
5622 next_access = expr_extract_accesses(expr->args[i],
5623 next_access);
5625 if (expr->type == pet_expr_access)
5626 next_access = expr_extract_access(expr, next_access);
5628 return next_access;
5631 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
5633 struct gpu_stmt_access **next_access = &stmt->accesses;
5635 stmt->accesses = NULL;
5636 expr_extract_accesses(stmt->stmt->body, next_access);
5639 /* Return an array of gpu_stmt representing the statements in "scop".
5641 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5642 __isl_keep isl_set *context)
5644 int i;
5645 struct gpu_stmt *stmts;
5647 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
5648 if (!stmts)
5649 return NULL;
5651 for (i = 0; i < scop->n_stmt; ++i) {
5652 struct gpu_stmt *s = &stmts[i];
5654 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
5655 s->stmt = scop->stmts[i];
5656 pet_stmt_extract_accesses(s);
5659 return stmts;
5662 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5664 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5666 struct gpu_gen *gen = user;
5668 return gen->print(p, gen->prog, gen->tree, &gen->types,
5669 gen->print_user);
5672 /* Generate CUDA code for "scop" and print it to "p".
5673 * After generating an AST for the transformed scop as explained below,
5674 * we call "gen->print" to print the AST in the desired output format
5675 * to "p".
5677 * If it turns out that it does not make sense to generate GPU code,
5678 * then we generate CPU code instead.
5680 * The GPU code is generated in a context where at least one
5681 * statement instance is executed. The corresponding guard (if any) is printed
5682 * around the entire generated GPU code, except for the declaration
5683 * of the arrays that are visible outside of the scop and that therefore
5684 * cannot be declared inside the body of any possible guard.
5686 * We first compute a schedule that respects the dependences
5687 * of the original program and select the outermost band
5688 * of tilable dimensions that has at least one parallel loop.
5689 * We then have three blocks of dimensions
5691 * H B G
5693 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5694 * in
5696 * H T P G
5698 * For each iteration of the T loop and for each array, we compute
5699 * the array elements accessed by that iteration, construct a rectangular
5700 * box around it and shift it to the origin. The result is used
5701 * as shared memory for the array.
5703 * We then split off at most 2 parallel loops from the T loops and
5704 * at most 3 parallel loops from the P loops
5706 * H T1 T2 P1 P2 G
5708 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5709 * according to "grid"/"block" sizes.
5711 * H T1T T1P T2 P1T P1P P2 G
5713 * Finally, the T1P and P1P iterators are equated to the block and
5714 * thread dimensions respectively and so are effectively removed.
5715 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5716 * are run on the GPU.
5718 * Code is generated in three stages. We first generate code for the
5719 * host (the H loops), with iterators h%d. Then, for each leaf node
5720 * of the resulting AST, we generate code for the shared loops (up to
5721 * and including T2), with iterators g%d and after equating the H loops
5722 * to h%d parameters and the T1P loops to the block dimensions.
5723 * Finally, we generate code for the remaining loops in a similar fashion.
5725 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5726 struct gpu_gen *gen, struct ppcg_scop *scop,
5727 struct ppcg_options *options)
5729 struct gpu_prog *prog;
5730 isl_ctx *ctx;
5731 isl_set *context, *guard;
5733 if (!scop)
5734 return isl_printer_free(p);
5736 ctx = isl_printer_get_ctx(p);
5737 prog = gpu_prog_alloc(ctx, scop);
5738 if (!prog)
5739 return isl_printer_free(p);
5741 context = isl_set_copy(prog->context);
5742 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5743 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5745 gen->prog = prog;
5746 gen->any_parallelism = 0;
5747 compute_schedule(gen);
5749 if (!gen->any_parallelism) {
5750 isl_set_free(context);
5751 isl_set_free(guard);
5752 p = print_cpu(p, scop, options);
5753 } else {
5754 compute_copy_in_and_out(gen);
5755 gen->tree = generate_host_code(gen);
5756 p = ppcg_print_exposed_declarations(p, prog->scop);
5757 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5758 isl_ast_node_free(gen->tree);
5761 isl_union_map_free(gen->sched);
5763 gpu_prog_free(prog);
5765 return p;
5768 /* Wrapper around generate for use as a ppcg_transform callback.
5770 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5771 struct ppcg_scop *scop, void *user)
5773 struct gpu_gen *gen = user;
5775 return generate(p, gen, scop, gen->options);
5778 /* Transform the code in the file called "input" by replacing
5779 * all scops by corresponding GPU code and write the results to "out".
5781 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5782 struct ppcg_options *options,
5783 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5784 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5785 struct gpu_types *types, void *user), void *user)
5787 struct gpu_gen gen;
5788 int r;
5789 int i;
5791 gen.ctx = ctx;
5792 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5793 gen.options = options;
5794 gen.kernel_id = 0;
5795 gen.print = print;
5796 gen.print_user = user;
5797 gen.types.n = 0;
5798 gen.types.name = NULL;
5800 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5802 isl_union_map_free(gen.sizes);
5803 for (i = 0; i < gen.types.n; ++i)
5804 free(gen.types.name[i]);
5805 free(gen.types.name);
5807 return r;
5810 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5812 struct gpu_prog *prog;
5814 if (!scop)
5815 return NULL;
5817 prog = isl_calloc_type(ctx, struct gpu_prog);
5818 assert(prog);
5820 prog->ctx = ctx;
5821 prog->scop = scop;
5822 prog->context = isl_set_copy(scop->context);
5823 prog->n_stmts = scop->n_stmt;
5824 prog->stmts = extract_stmts(ctx, scop, prog->context);
5825 prog->read = isl_union_map_copy(scop->reads);
5826 prog->may_write = isl_union_map_copy(scop->may_writes);
5827 prog->must_write = isl_union_map_copy(scop->must_writes);
5828 prog->to_inner = compute_to_inner(scop);
5829 prog->to_outer = isl_union_map_copy(prog->to_inner);
5830 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5832 if (!prog->stmts)
5833 return gpu_prog_free(prog);
5835 if (collect_array_info(prog) < 0)
5836 return gpu_prog_free(prog);
5838 return prog;
5841 void *gpu_prog_free(struct gpu_prog *prog)
5843 if (!prog)
5844 return NULL;
5845 free_array_info(prog);
5846 free_stmts(prog->stmts, prog->n_stmts);
5847 isl_union_map_free(prog->to_outer);
5848 isl_union_map_free(prog->to_inner);
5849 isl_union_set_free(prog->copy_in);
5850 isl_union_set_free(prog->copy_out);
5851 isl_union_map_free(prog->read);
5852 isl_union_map_free(prog->may_write);
5853 isl_union_map_free(prog->must_write);
5854 isl_union_map_free(prog->array_order);
5855 isl_set_free(prog->context);
5856 free(prog);
5857 return NULL;