gpu.c: move map_plain_is_fixed to schedule.c
[ppcg.git] / gpu.c
blob035b2ee77a853a6ccd6e14e1c34008c9b64cf4b7
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/schedule.h>
23 #include <isl/schedule_node.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "gpu_array_tile.h"
30 #include "schedule.h"
31 #include "ppcg_options.h"
32 #include "print.h"
34 struct gpu_array_info;
36 /* A group of array references in a kernel that should be handled together.
37 * If private_tile is not NULL, then it is mapped to registers.
38 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
39 * Otherwise, it is accessed from global memory.
41 struct gpu_array_ref_group {
42 /* The references in this group access this array. */
43 struct gpu_array_info *array;
44 /* Position of this group in the list of reference groups of array. */
45 int nr;
47 /* The following fields are use during the construction of the groups.
48 * access is the combined access relation relative to the shared
49 * memory tiling. In particular, the domain of the map corresponds
50 * to the first shared_len dimensions of the computed schedule.
51 * write is set if any access in the group is a write.
52 * exact_write is set if all writes are definite writes.
53 * slice is set if there is at least one access in the group
54 * that refers to more than one element
56 isl_map *access;
57 int write;
58 int exact_write;
59 int slice;
61 /* The shared memory tile, NULL if none. */
62 struct gpu_array_tile *shared_tile;
64 /* The private memory tile, NULL if none. */
65 struct gpu_array_tile *private_tile;
67 /* References in this group; point to elements of a linked list. */
68 int n_ref;
69 struct gpu_stmt_access **refs;
71 /* Last shared memory tile dimension that affects tile of this group. */
72 int last_shared;
75 /* Print the name of the local copy of a given group of array references.
77 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
78 struct gpu_array_ref_group *group)
80 int global = 0;
82 if (group->private_tile)
83 p = isl_printer_print_str(p, "private_");
84 else if (group->shared_tile)
85 p = isl_printer_print_str(p, "shared_");
86 else
87 global = 1;
88 p = isl_printer_print_str(p, group->array->name);
89 if (!global && group->array->n_group > 1) {
90 p = isl_printer_print_str(p, "_");
91 p = isl_printer_print_int(p, group->nr);
94 return p;
97 /* Collect all references to the given array and store pointers to them
98 * in array->refs.
100 * If the array contains structures, then there is no need to collect
101 * the references since we will not be computing any reference groups.
103 static void collect_references(struct gpu_prog *prog,
104 struct gpu_array_info *array)
106 int i;
107 int n;
109 if (array->has_compound_element)
110 return;
112 n = 0;
113 for (i = 0; i < prog->n_stmts; ++i) {
114 struct gpu_stmt *stmt = &prog->stmts[i];
115 struct gpu_stmt_access *access;
117 for (access = stmt->accesses; access; access = access->next) {
118 const char *name;
119 name = isl_map_get_tuple_name(access->access,
120 isl_dim_out);
121 if (name && !strcmp(array->name, name))
122 n++;
126 array->n_ref = n;
127 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
128 assert(array->refs);
130 n = 0;
131 for (i = 0; i < prog->n_stmts; ++i) {
132 struct gpu_stmt *stmt = &prog->stmts[i];
133 struct gpu_stmt_access *access;
135 for (access = stmt->accesses; access; access = access->next) {
136 const char *name;
137 name = isl_map_get_tuple_name(access->access,
138 isl_dim_out);
139 if (!name || strcmp(array->name, name))
140 continue;
142 array->refs[n++] = access;
147 /* Compute and return the extent of "array", taking into account the set of
148 * accessed elements.
150 * In particular, the extent in the outer dimension is taken
151 * from "accessed", while the extents in the remaining dimensions
152 * are taken from array->extent.
154 * The extent in the outer dimension cannot be taken from array->extent
155 * because that may be unbounded. Furthermore, even if it is bounded,
156 * it may be larger than the piece of the array that is being accessed.
158 static __isl_give isl_set *compute_extent(struct pet_array *array,
159 __isl_keep isl_set *accessed)
161 int n_index;
162 isl_id *id;
163 isl_set *outer;
164 isl_set *extent;
166 extent = isl_set_copy(array->extent);
168 n_index = isl_set_dim(accessed, isl_dim_set);
169 if (n_index == 0)
170 return extent;
172 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
173 outer = isl_set_copy(accessed);
174 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
175 extent = isl_set_flat_product(outer, extent);
176 id = isl_set_get_tuple_id(accessed);
177 extent = isl_set_set_tuple_id(extent, id);
179 return extent;
182 /* Is the array "array" being extracted a read-only scalar?
184 * That is, is "array" a scalar that is never possibly written to.
185 * An array containing structures is never considered to be a scalar.
187 static int is_read_only_scalar(struct gpu_array_info *array,
188 struct gpu_prog *prog)
190 isl_set *space;
191 isl_union_map *write;
192 int empty;
194 if (array->has_compound_element)
195 return 0;
196 if (array->n_index != 0)
197 return 0;
199 write = isl_union_map_copy(prog->may_write);
200 space = isl_set_universe(isl_space_copy(array->space));
201 write = isl_union_map_intersect_range(write,
202 isl_union_set_from_set(space));
203 empty = isl_union_map_is_empty(write);
204 isl_union_map_free(write);
206 return empty;
209 /* Compute bounds on the host array "pa" based on the corresponding
210 * accessed elements in "arrays"
211 * and collect all references to the array.
212 * Store the results in "info".
214 * If the array is zero-dimensional and does not contain structures,
215 * i.e., if the array is a scalar, we check whether it is read-only.
216 * We also check whether the array is accessed at all.
218 static int extract_array_info(struct gpu_prog *prog,
219 struct gpu_array_info *info, struct pet_array *pa,
220 __isl_keep isl_union_set *arrays)
222 int i, empty;
223 const char *name;
224 int n_index;
225 isl_pw_aff **bounds;
226 isl_set *accessed, *extent;
228 n_index = isl_set_dim(pa->extent, isl_dim_set);
229 name = isl_set_get_tuple_name(pa->extent);
230 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index);
231 if (!bounds)
232 return -1;
234 info->space = isl_set_get_space(pa->extent);
235 info->name = strdup(name);
236 info->n_index = n_index;
237 info->bound = bounds;
238 info->linearize = prog->scop->options->linearize_device_arrays;
240 info->type = strdup(pa->element_type);
241 info->size = pa->element_size;
242 info->local = pa->declared && !pa->exposed;
243 info->has_compound_element = pa->element_is_record;
244 info->read_only_scalar = is_read_only_scalar(info, prog);
246 accessed = isl_union_set_extract_set(arrays,
247 isl_space_copy(info->space));
248 empty = isl_set_is_empty(accessed);
249 extent = compute_extent(pa, accessed);
250 isl_set_free(accessed);
251 info->extent = extent;
252 if (empty < 0)
253 return -1;
254 info->accessed = !empty;
255 for (i = 0; i < n_index; ++i) {
256 isl_set *dom;
257 isl_local_space *ls;
258 isl_aff *one;
259 isl_pw_aff *bound;
261 dom = isl_set_copy(extent);
262 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
263 n_index - (i + 1));
264 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
265 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
266 fprintf(stderr, "unable to determine extent of '%s' "
267 "in dimension %d\n", info->name, i);
268 dom = isl_set_free(dom);
270 bound = isl_set_dim_max(dom, 0);
271 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
272 ls = isl_local_space_from_space(isl_set_get_space(dom));
273 one = isl_aff_zero_on_domain(ls);
274 one = isl_aff_add_constant_si(one, 1);
275 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
276 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
278 bounds[i] = bound;
279 if (!isl_pw_aff_is_cst(bound))
280 info->linearize = 1;
283 collect_references(prog, info);
285 return 0;
288 /* Remove independence from the order constraints "order" on array "array".
289 * Since the pairs of iterations in the filter relation of an independence
290 * are guaranteed to be completely independent by the user, there is
291 * no need to ensure that live ranges are ordered along thong pairs.
292 * We make an exception for local variables, though, as the independence
293 * guarantee does not apply to those.
295 * The order constraints are used in two places.
296 * Those on scalars are used in check_scalar_live_ranges to check if
297 * we need to force the scalar to be private. Any non-local scalar
298 * should not be forced scalar if it only appears in independent loops.
299 * Those on non-scalars are added to the coincidence constraints
300 * in compute_schedule because we do not support any array expansion.
301 * Accesses to non-local arrays should not prevent a loop from being
302 * considered coincident so we should indeed remove those constraints
303 * from the order constraints.
305 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
306 struct gpu_array_info *array, __isl_take isl_union_map *order)
308 int i;
310 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
311 struct pet_independence *pi = prog->scop->pet->independences[i];
312 if (isl_union_set_contains(pi->local, array->space))
313 continue;
315 order = isl_union_map_subtract(order,
316 isl_union_map_copy(pi->filter));
319 return order;
322 /* For each array in "prog", store the (untagged) order dependences
323 * derived from the array in array->dep_order.
324 * In particular, consider all references that access the given array
325 * and take the order dependences that have one of these references
326 * as source. (Since an order dependence relates two references to
327 * the same array, the target of these order dependences will also
328 * be one of these references.)
329 * Additionally, store the union of these array->dep_order relations
330 * for all non-scalar arrays in prog->array_order.
332 void collect_order_dependences(struct gpu_prog *prog)
334 int i;
335 isl_space *space;
336 isl_union_map *accesses;
338 space = isl_union_map_get_space(prog->read);
339 prog->array_order = isl_union_map_empty(space);
341 accesses = isl_union_map_copy(prog->scop->tagged_reads);
342 accesses = isl_union_map_union(accesses,
343 isl_union_map_copy(prog->scop->tagged_may_writes));
344 accesses = isl_union_map_universe(accesses);
345 accesses = isl_union_map_apply_range(accesses,
346 isl_union_map_copy(prog->to_outer));
348 for (i = 0; i < prog->n_array; ++i) {
349 struct gpu_array_info *array = &prog->array[i];
350 isl_set *set;
351 isl_union_set *uset;
352 isl_union_map *order;
354 set = isl_set_universe(isl_space_copy(array->space));
355 uset = isl_union_set_from_set(set);
356 uset = isl_union_map_domain(
357 isl_union_map_intersect_range(isl_union_map_copy(accesses),
358 uset));
359 order = isl_union_map_copy(prog->scop->tagged_dep_order);
360 order = isl_union_map_intersect_domain(order, uset);
361 order = isl_union_map_zip(order);
362 order = isl_union_set_unwrap(isl_union_map_domain(order));
363 order = remove_independences(prog, array, order);
364 array->dep_order = order;
366 if (gpu_array_is_scalar(array) && !array->has_compound_element)
367 continue;
369 prog->array_order = isl_union_map_union(prog->array_order,
370 isl_union_map_copy(array->dep_order));
373 isl_union_map_free(accesses);
376 /* Construct a gpu_array_info for each array referenced by prog->scop and
377 * collect them in prog->array.
379 * The sizes are based on the extents and the set of possibly accessed
380 * elements by "prog".
381 * If there are any member accesses involved, then they are first mapped
382 * to the outer arrays of structs.
384 * If we are allowing live range reordering, then also set
385 * the dep_order field. Otherwise leave it NULL.
387 static int collect_array_info(struct gpu_prog *prog)
389 int i;
390 int r = 0;
391 isl_union_set *arrays;
393 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
394 arrays = isl_union_set_union(arrays,
395 isl_union_map_range(isl_union_map_copy(prog->may_write)));
397 arrays = isl_union_set_apply(arrays,
398 isl_union_map_copy(prog->to_outer));
400 arrays = isl_union_set_coalesce(arrays);
402 prog->n_array = prog->scop->pet->n_array;
403 prog->array = isl_calloc_array(prog->ctx,
404 struct gpu_array_info, prog->n_array);
405 assert(prog->array);
406 for (i = 0; i < prog->scop->pet->n_array; ++i)
407 if (extract_array_info(prog, &prog->array[i],
408 prog->scop->pet->arrays[i], arrays) < 0)
409 r = -1;
411 isl_union_set_free(arrays);
413 if (prog->scop->options->live_range_reordering)
414 collect_order_dependences(prog);
416 return r;
419 static void free_array_info(struct gpu_prog *prog)
421 int i, j;
423 for (i = 0; i < prog->n_array; ++i) {
424 int n_index = prog->array[i].n_index;
425 free(prog->array[i].type);
426 free(prog->array[i].name);
427 for (j = 0; j < n_index; ++j)
428 isl_pw_aff_free(prog->array[i].bound[j]);
429 isl_space_free(prog->array[i].space);
430 isl_set_free(prog->array[i].extent);
431 free(prog->array[i].bound);
432 free(prog->array[i].refs);
433 isl_union_map_free(prog->array[i].dep_order);
435 free(prog->array);
438 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
439 * as an array or through a pointer reference, but as a single data element.
440 * At the moment, scalars are represented as zero-dimensional arrays.
441 * Note that the single data element may be an entire structure.
443 int gpu_array_is_scalar(struct gpu_array_info *array)
445 return array->n_index == 0;
448 /* Is "array" a read-only scalar?
450 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
452 return array->read_only_scalar;
455 /* Return the set of parameter values for which the array has a positive
456 * size in all dimensions.
457 * If the sizes are only valid for some parameter values, then those
458 * constraints are also taken into account.
460 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
462 int i;
463 isl_space *space;
464 isl_set *guard;
466 space = isl_space_params(isl_space_copy(array->space));
467 guard = isl_set_universe(space);
469 for (i = 0; i < array->n_index; ++i) {
470 isl_pw_aff *bound;
471 isl_set *guard_i, *zero;
473 bound = isl_pw_aff_copy(array->bound[i]);
474 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
475 zero = isl_pw_aff_zero_set(bound);
476 guard_i = isl_set_subtract(guard_i, zero);
477 guard = isl_set_intersect(guard, guard_i);
480 return guard;
483 /* Internal data structure for extract_size_of_type.
484 * "type" specifies the name of the space that we want to extract.
485 * "res" is used to store the subset of that space.
487 struct ppcg_extract_size_data {
488 const char *type;
489 isl_set *res;
492 /* This function is called for each set in a union_set.
493 * If the name of the set matches data->type, we store the
494 * set in data->res.
496 static int extract_size_of_type(__isl_take isl_set *size, void *user)
498 struct ppcg_extract_size_data *data = user;
499 const char *name;
501 name = isl_set_get_tuple_name(size);
502 if (name && !strcmp(name, data->type)) {
503 data->res = size;
504 return -1;
507 isl_set_free(size);
508 return 0;
511 /* Given a union map { kernel[i] -> *[...] },
512 * return the range in the space called "type" for the kernel with
513 * sequence number "id".
515 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
516 const char *type, int id)
518 isl_space *space;
519 isl_set *dom;
520 isl_union_set *local_sizes;
521 struct ppcg_extract_size_data data = { type, NULL };
523 if (!sizes)
524 return NULL;
526 space = isl_union_map_get_space(sizes);
527 space = isl_space_set_from_params(space);
528 space = isl_space_add_dims(space, isl_dim_set, 1);
529 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
530 dom = isl_set_universe(space);
531 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
533 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
534 isl_union_map_copy(sizes));
535 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
536 isl_union_set_free(local_sizes);
537 return data.res;
540 /* Given a singleton set, extract the first (at most *len) elements
541 * of the single integer tuple into *sizes and update *len if needed.
543 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
545 int i;
546 int dim;
548 if (!set)
549 return;
551 dim = isl_set_dim(set, isl_dim_set);
552 if (dim < *len)
553 *len = dim;
555 for (i = 0; i < *len; ++i) {
556 isl_val *v;
558 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
559 assert(v);
561 sizes[i] = isl_val_get_num_si(v);
562 isl_val_free(v);
565 isl_set_free(set);
568 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
569 * if the option debug->dump_sizes is set.
571 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
572 int *sizes, int len)
574 int i;
575 isl_space *space;
576 isl_map *map;
578 if (!gen->options->debug->dump_sizes)
579 return;
581 space = isl_union_map_get_space(gen->used_sizes);
582 space = isl_space_set_from_params(space);
583 space = isl_space_add_dims(space, isl_dim_set, 1);
584 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
585 space = isl_space_from_domain(space);
586 space = isl_space_add_dims(space, isl_dim_out, len);
587 space = isl_space_set_tuple_name(space, isl_dim_out, type);
589 map = isl_map_universe(space);
590 map = isl_map_fix_si(map, isl_dim_in, 0, id);
591 for (i = 0; i < len; ++i)
592 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
594 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
597 /* Extract user specified "tile" sizes from the "sizes" command line option,
598 * defaulting to option->tile_size in each dimension.
599 * Add the effectively used sizes to gen->used_sizes.
601 static void read_tile_sizes(struct gpu_gen *gen)
603 int n;
604 isl_set *size;
606 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
607 assert(gen->tile_size);
608 for (n = 0; n < gen->tile_len; ++n)
609 gen->tile_size[n] = gen->options->tile_size;
611 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
612 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
613 set_used_sizes(gen, "tile", gen->kernel_id,
614 gen->tile_size, gen->tile_len);
616 if (gen->n_parallel > gen->tile_len)
617 gen->n_parallel = gen->tile_len;
620 /* Extract user specified "block" sizes from the "sizes" command line option,
621 * after filling in some potentially useful defaults.
622 * Add the effectively used sizes to gen->used_sizes.
624 static void read_block_sizes(struct gpu_gen *gen)
626 int n;
627 isl_set *size;
629 n = gen->n_parallel;
630 gen->n_block = (n <= 3) ? n : 3;
631 switch (gen->n_block) {
632 case 1:
633 gen->block_dim[0] = 512;
634 break;
635 case 2:
636 gen->block_dim[0] = 32;
637 gen->block_dim[1] = 16;
638 break;
639 default:
640 gen->block_dim[0] = 32;
641 gen->block_dim[1] = 4;
642 gen->block_dim[2] = 4;
643 break;
646 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
647 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
648 set_used_sizes(gen, "block", gen->kernel_id,
649 gen->block_dim, gen->n_block);
652 /* Extract user specified "grid" sizes from the "sizes" command line option,
653 * after filling in some potentially useful defaults.
654 * Add the effectively used sizes to gen->used_sizes.
656 static void read_grid_sizes(struct gpu_gen *gen)
658 int n = gen->n_parallel;
659 isl_set *size;
661 gen->n_grid = (n <= 2) ? n : 2;
662 switch (gen->n_grid) {
663 case 1:
664 gen->grid_dim[0] = 32768;
665 break;
666 default:
667 gen->grid_dim[0] = 256;
668 gen->grid_dim[1] = 256;
669 break;
672 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
673 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
674 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
677 /* Extract user specified sizes from the "sizes" command line option
678 * after filling in some potentially useful defaults.
680 static void read_sizes(struct gpu_gen *gen)
682 read_tile_sizes(gen);
683 read_block_sizes(gen);
684 read_grid_sizes(gen);
687 static void *free_stmts(struct gpu_stmt *stmts, int n)
689 int i;
691 if (!stmts)
692 return NULL;
694 for (i = 0; i < n; ++i) {
695 struct gpu_stmt_access *access, *next;
697 for (access = stmts[i].accesses; access; access = next) {
698 next = access->next;
699 isl_id_free(access->ref_id);
700 isl_map_free(access->access);
701 isl_map_free(access->tagged_access);
702 free(access);
705 isl_id_free(stmts[i].id);
707 free(stmts);
709 return NULL;
712 /* Construct a map from a domain of dimensionality "len"
713 * to a domain of dimensionality "len" + "tile_len" that tiles
714 * the "tile_len" coordinates starting at "first".
715 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
716 * "dim" prescribes the parameters.
718 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
719 int first, int tile_len, int *tile_size)
721 int i;
722 isl_basic_map *bmap;
723 isl_constraint *c;
724 isl_local_space *ls;
726 dim = isl_space_add_dims(dim, isl_dim_in, len);
727 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
728 bmap = isl_basic_map_universe(isl_space_copy(dim));
729 ls = isl_local_space_from_space(dim);
731 for (i = 0; i < len - tile_len; ++i) {
732 int j = i < first ? i : i + tile_len;
733 int k = i < first ? i : i + 2 * tile_len;
735 c = isl_equality_alloc(isl_local_space_copy(ls));
736 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
737 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
738 bmap = isl_basic_map_add_constraint(bmap, c);
741 for (i = 0; i < tile_len; ++i) {
742 c = isl_equality_alloc(isl_local_space_copy(ls));
743 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
744 first + i, -1);
745 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
746 first + i, tile_size[i]);
747 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
748 first + i + tile_len, 1);
749 bmap = isl_basic_map_add_constraint(bmap, c);
751 c = isl_inequality_alloc(isl_local_space_copy(ls));
752 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
753 first + i + tile_len, 1);
754 bmap = isl_basic_map_add_constraint(bmap, c);
756 c = isl_inequality_alloc(isl_local_space_copy(ls));
757 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
758 first + i + tile_len, -1);
759 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
760 bmap = isl_basic_map_add_constraint(bmap, c);
763 isl_local_space_free(ls);
765 return isl_map_from_basic_map(bmap);
768 /* Construct a map from a domain of dimensionality "len"
769 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
770 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
771 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
772 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
773 * that are projected out at the end.
774 * "dim" prescribes the parameters.
776 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
777 int first, int wrap_len, int *wrap_size)
779 int i;
780 isl_basic_map *bmap;
781 isl_constraint *c;
782 isl_local_space *ls;
784 dim = isl_space_add_dims(dim, isl_dim_in, len);
785 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
786 bmap = isl_basic_map_universe(isl_space_copy(dim));
787 ls = isl_local_space_from_space(dim);
789 for (i = 0; i < len; ++i) {
790 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
792 c = isl_equality_alloc(isl_local_space_copy(ls));
793 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
794 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
795 bmap = isl_basic_map_add_constraint(bmap, c);
798 for (i = 0; i < wrap_len; ++i) {
799 c = isl_equality_alloc(isl_local_space_copy(ls));
800 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
801 first + i, -1);
802 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
803 first + wrap_len + i, 1);
804 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
805 first + 2 * wrap_len + i, wrap_size[i]);
806 bmap = isl_basic_map_add_constraint(bmap, c);
808 c = isl_inequality_alloc(isl_local_space_copy(ls));
809 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
810 first + wrap_len + i, 1);
811 bmap = isl_basic_map_add_constraint(bmap, c);
813 c = isl_inequality_alloc(isl_local_space_copy(ls));
814 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
815 first + wrap_len + i, -1);
816 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
817 bmap = isl_basic_map_add_constraint(bmap, c);
820 isl_local_space_free(ls);
822 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
823 first + 2 * wrap_len, wrap_len);
825 return isl_map_from_basic_map(bmap);
828 /* Tile the B loops over the tile sizes and then tile/wrap
829 * the T1 loops over the blocks.
831 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
832 __isl_take isl_union_map *sched)
834 isl_space *dim;
835 isl_map *tiling, *block_tiling;
837 dim = isl_union_map_get_space(sched);
838 tiling = tile(isl_space_copy(dim), gen->untiled_len,
839 gen->tile_first, gen->tile_len, gen->tile_size);
841 if (gen->options->wrap)
842 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
843 gen->tile_first, gen->n_grid, gen->grid_dim);
844 else
845 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
846 gen->tile_first, gen->n_grid, gen->grid_dim);
848 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
850 tiling = isl_map_apply_range(tiling, block_tiling);
852 sched = isl_union_map_apply_range(sched,
853 isl_union_map_from_map(tiling));
855 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
857 return sched;
860 /* Equate the "T1P" iterators in the tiled schedule "sched"
861 * to the block dimensions.
863 static __isl_give isl_union_map *parametrize_tiled_schedule(
864 struct gpu_gen *gen, __isl_take isl_union_map *sched)
866 isl_space *dim;
867 isl_set *par;
869 dim = isl_union_map_get_space(sched);
870 par = parametrization(dim, gen->tiled_len,
871 gen->tile_first + gen->n_grid, gen->kernel->block_ids);
872 sched = isl_union_map_intersect_range(sched,
873 isl_union_set_from_set(par));
875 return sched;
878 /* Tile/wrap the P1 loops over the threads.
880 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
881 __isl_take isl_union_map *sched)
883 isl_space *dim;
884 isl_map *tiling;
885 isl_set *par;
887 dim = isl_union_map_get_space(sched);
889 if (gen->options->wrap)
890 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
891 gen->shared_len, gen->n_block, gen->block_dim);
892 else
893 tiling = tile(isl_space_copy(dim), gen->tiled_len,
894 gen->shared_len, gen->n_block, gen->block_dim);
895 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
897 sched = isl_union_map_apply_range(sched,
898 isl_union_map_from_map(tiling));
900 par = parametrization(dim, gen->thread_tiled_len,
901 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
902 gen->kernel->thread_ids);
903 sched = isl_union_map_intersect_range(sched,
904 isl_union_set_from_set(par));
906 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
908 return sched;
911 /* If the user asked for it, scale the shared memory tile loops
912 * (T1T and T2) of "sched" by gen->tile_size[i].
913 * If we are not performing "wrapping", then additionally scale the T1P
914 * loops by gen->grid_dim[i].
916 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
917 __isl_take isl_union_map *sched)
919 int i;
920 isl_space *dim;
921 isl_basic_map *scale;
922 isl_constraint *c;
923 isl_local_space *ls;
925 if (!gen->options->scale_tile_loops)
926 return sched;
928 dim = isl_union_map_get_space(sched);
929 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
930 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
931 scale = isl_basic_map_universe(isl_space_copy(dim));
932 ls = isl_local_space_from_space(dim);
934 for (i = 0; i < gen->tiled_len; ++i) {
935 int f = 1;
937 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
938 f = gen->tile_size[i - gen->tile_first];
939 if (!gen->options->wrap)
940 f *= gen->grid_dim[i - gen->tile_first];
941 } else if (i >= gen->tile_first + gen->n_grid &&
942 i < gen->tile_first + gen->n_grid + gen->tile_len) {
943 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
946 c = isl_equality_alloc(isl_local_space_copy(ls));
947 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
948 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
949 scale = isl_basic_map_add_constraint(scale, c);
952 isl_local_space_free(ls);
954 sched = isl_union_map_apply_range(sched,
955 isl_union_map_from_map(isl_map_from_basic_map(scale)));
957 return sched;
960 /* If we are not performing "wrapping" and if the user asked for it,
961 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
963 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
964 __isl_take isl_union_map *sched)
966 int i;
967 isl_space *dim;
968 isl_basic_map *scale;
969 isl_constraint *c;
970 isl_local_space *ls;
972 if (gen->options->wrap)
973 return sched;
974 if (!gen->options->scale_tile_loops)
975 return sched;
977 dim = isl_union_map_get_space(sched);
978 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
979 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
980 scale = isl_basic_map_universe(isl_space_copy(dim));
981 ls = isl_local_space_from_space(dim);
983 for (i = 0; i < gen->thread_tiled_len; ++i) {
984 int f = 1;
986 if (i >= gen->shared_len &&
987 i < gen->shared_len + gen->n_block)
988 f = gen->block_dim[i - gen->shared_len];
990 c = isl_equality_alloc(isl_local_space_copy(ls));
991 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
992 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
993 scale = isl_basic_map_add_constraint(scale, c);
996 isl_local_space_free(ls);
998 sched = isl_union_map_apply_range(sched,
999 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1001 return sched;
1004 /* If we are not performing "wrapping" and if the user asked for it,
1005 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1007 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1008 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1010 int i;
1011 isl_space *dim;
1012 isl_basic_map *scale;
1013 isl_constraint *c;
1014 isl_local_space *ls;
1016 if (gen->options->wrap)
1017 return sched;
1018 if (!gen->options->scale_tile_loops)
1019 return sched;
1021 dim = isl_union_map_get_space(sched);
1022 dim = isl_space_add_dims(dim, isl_dim_in, len);
1023 dim = isl_space_add_dims(dim, isl_dim_out, len);
1024 scale = isl_basic_map_universe(isl_space_copy(dim));
1025 ls = isl_local_space_from_space(dim);
1027 for (i = 0; i < len; ++i) {
1028 int f = 1;
1030 if (i >= first && i < first + n_tile)
1031 f = gen->kernel->block_dim[i - first];
1033 c = isl_equality_alloc(isl_local_space_copy(ls));
1034 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1035 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1036 scale = isl_basic_map_add_constraint(scale, c);
1039 isl_local_space_free(ls);
1041 sched = isl_union_map_apply_range(sched,
1042 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1044 return sched;
1047 /* Add parameters p[i] with identifiers "ids" to "set",
1048 * with bounds to 0 <= p[i] < size[i].
1050 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1051 int *size, __isl_keep isl_id_list *ids)
1053 int i, len;
1054 unsigned nparam;
1056 len = isl_id_list_n_id(ids);
1057 nparam = isl_set_dim(set, isl_dim_param);
1058 set = isl_set_add_dims(set, isl_dim_param, len);
1060 for (i = 0; i < len; ++i) {
1061 isl_id *id;
1063 id = isl_id_list_get_id(ids, i);
1064 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1065 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
1066 set = isl_set_upper_bound_si(set, isl_dim_param,
1067 nparam + i, size[i] - 1);
1070 return set;
1073 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
1074 * with
1076 * { : 0 <= p[i] < size[i] }
1078 * or an overapproximation.
1080 static __isl_give isl_set *add_bounded_parameters_dynamic(
1081 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1082 __isl_keep isl_id_list *ids)
1084 int i, len;
1085 unsigned nparam;
1086 isl_space *space;
1087 isl_local_space *ls;
1089 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1090 nparam = isl_set_dim(set, isl_dim_param);
1091 set = isl_set_add_dims(set, isl_dim_param, len);
1093 for (i = 0; i < len; ++i) {
1094 isl_id *id;
1096 id = isl_id_list_get_id(ids, i);
1097 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1100 space = isl_space_params(isl_set_get_space(set));
1101 ls = isl_local_space_from_space(space);
1102 for (i = 0; i < len; ++i) {
1103 isl_pw_aff *param, *size_i, *zero;
1104 isl_set *bound;
1106 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1107 isl_dim_param, nparam + i);
1109 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1110 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1111 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1112 set = isl_set_intersect_params(set, bound);
1114 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1115 bound = isl_pw_aff_ge_set(param, zero);
1116 set = isl_set_intersect_params(set, bound);
1118 isl_local_space_free(ls);
1120 return set;
1123 /* Construct a map from an access to group->array to the corresponding
1124 * shared/private memory tile.
1125 * The map is of the form
1127 * { [D[i] -> A[a]] -> T[t] }
1129 * where D represents the initial shared_len dimensions
1130 * of the computed schedule.
1132 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1134 struct gpu_array_tile *tile;
1135 isl_multi_aff *tiling;
1137 tile = group->private_tile;
1138 if (!tile)
1139 tile = group->shared_tile;
1141 tiling = isl_multi_aff_copy(tile->tiling);
1143 return isl_map_from_multi_aff(tiling);
1146 /* Given a schedule that iterates over all elements in a piece of an array,
1147 * perform tiling/wrapping over the threads.
1149 * In particular, we tile the final iterators so that the final thread
1150 * dimension runs over the final array dimension.
1151 * However, if those final iterators have only a single iteration,
1152 * we try to tile earlier iterators instead.
1154 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1155 __isl_take isl_map *sched)
1157 isl_space *dim;
1158 isl_union_map *usched;
1159 isl_map *tiling;
1160 isl_set *par;
1161 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1162 int n_tile;
1163 int first;
1165 n_tile = gen->kernel->n_block;
1166 if (n_tile > nvar) {
1167 int i;
1168 sched = isl_map_insert_dims(sched,
1169 isl_dim_out, 0, n_tile - nvar);
1170 for (i = 0; i < n_tile - nvar; ++i)
1171 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1172 nvar = n_tile;
1175 first = nvar - n_tile;
1177 for (; first > 0; first --)
1178 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1179 break;
1181 dim = isl_map_get_space(sched);
1182 dim = isl_space_params(dim);
1183 if (gen->options->wrap)
1184 tiling = wrap(isl_space_copy(dim), nvar, first,
1185 n_tile, gen->kernel->block_dim);
1186 else
1187 tiling = tile(isl_space_copy(dim), nvar, first,
1188 n_tile, gen->kernel->block_dim);
1189 sched = isl_map_apply_range(sched, tiling);
1191 par = parametrization(dim, nvar + n_tile, first + n_tile,
1192 gen->kernel->thread_ids);
1193 sched = isl_map_intersect_range(sched, par);
1195 usched = isl_union_map_from_map(sched);
1196 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1197 first, n_tile);
1198 sched = isl_map_from_union_map(usched);
1200 return sched;
1203 /* Return the union of all read (read = 1) and/or write (write = 1)
1204 * access relations in the group.
1206 static __isl_give isl_union_map *group_access_relation(
1207 struct gpu_array_ref_group *group, int read, int write)
1209 int i;
1210 isl_union_map *access;
1212 access = isl_union_map_empty(isl_map_get_space(group->access));
1213 for (i = 0; i < group->n_ref; ++i) {
1214 isl_map *map_i;
1216 if (!((read && group->refs[i]->read) ||
1217 (write && group->refs[i]->write)))
1218 continue;
1219 map_i = isl_map_copy(group->refs[i]->access);
1220 access = isl_union_map_union(access,
1221 isl_union_map_from_map(map_i));
1224 return access;
1227 /* Return the union of all tagged access relations in the group.
1229 static __isl_give isl_union_map *group_tagged_access_relation(
1230 struct gpu_array_ref_group *group)
1232 int i;
1233 isl_union_map *access;
1235 access = isl_union_map_empty(isl_map_get_space(group->access));
1236 for (i = 0; i < group->n_ref; ++i) {
1237 isl_map *map_i;
1239 map_i = isl_map_copy(group->refs[i]->tagged_access);
1240 access = isl_union_map_union(access,
1241 isl_union_map_from_map(map_i));
1244 return access;
1247 /* Return the extent of "array", recomputed from the bounds.
1248 * The recomputed extent may be simpler than the original extent.
1250 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1252 int i;
1253 isl_id *id;
1254 isl_space *space;
1255 isl_local_space *ls;
1256 isl_set *extent;
1258 id = isl_set_get_tuple_id(array->extent);
1259 space = isl_set_get_space(array->extent);
1260 extent = isl_set_universe(isl_space_copy(space));
1261 ls = isl_local_space_from_space(space);
1262 for (i = 0; i < array->n_index; ++i) {
1263 isl_pw_aff *bound;
1264 isl_aff *aff;
1265 isl_pw_aff *index;
1266 isl_set *lt;
1268 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1270 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1271 isl_dim_set, i);
1272 index = isl_pw_aff_from_aff(aff);
1273 bound = isl_pw_aff_copy(array->bound[i]);
1274 bound = isl_pw_aff_from_range(bound);
1275 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1276 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1277 isl_id_copy(id));
1278 lt = isl_pw_aff_lt_set(index, bound);
1279 extent = isl_set_intersect(extent, lt);
1281 isl_local_space_free(ls);
1282 isl_id_free(id);
1284 return extent;
1287 /* Return a map from the first shared_len dimensions of the computed
1288 * schedule to the array tile in
1289 * global memory that corresponds to the shared memory copy.
1291 * In particular, return a map
1293 * { D[i] -> A[a] }
1295 * with constraints
1297 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1299 * and
1301 * 0 <= a <= array_size - 1 (2)
1303 * Note that if some stride has been detected (i.e., when
1304 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1305 * to the shifted and scaled down version.
1307 * Constraints (1) are obtained by mapping the size constraints on the
1308 * shared/private memory tile back to the access relation.
1309 * Constraints (2) are obtained from the (recomputed) extent.
1311 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1313 int i;
1314 int n_index = group->array->n_index;
1315 isl_map *tile;
1316 isl_space *space;
1317 isl_set *local;
1318 isl_set *extent;
1320 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1321 space = isl_space_range(space);
1322 local = isl_set_universe(space);
1323 for (i = 0; i < n_index; ++i) {
1324 isl_val *bound;
1326 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1327 bound = isl_val_copy(group->shared_tile->bound[i].size);
1328 bound = isl_val_sub_ui(bound, 1);
1329 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1331 local = isl_set_preimage_multi_aff(local,
1332 isl_multi_aff_copy(group->shared_tile->tiling));
1333 tile = isl_set_unwrap(local);
1334 extent = array_extent(group->array);
1335 tile = isl_map_intersect_range(tile, extent);
1337 return tile;
1340 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1341 * return the corresponding mapping from the AST schedule to
1342 * to the first shared_len dimensions of the schedule computed by PPCG.
1344 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1345 __isl_take isl_pw_multi_aff *iterator_map)
1347 isl_union_map *umap;
1348 isl_space *space;
1349 isl_map *map, *sched;;
1351 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1352 space = isl_space_from_domain(space);
1353 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1355 umap = isl_union_map_copy(gen->shared_sched);
1356 umap = isl_union_map_apply_range(umap,
1357 isl_union_map_copy(gen->shared_proj));
1358 map = isl_union_map_extract_map(umap, space);
1359 isl_union_map_free(umap);
1361 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1362 sched = isl_map_detect_equalities(sched);
1364 return isl_pw_multi_aff_from_map(sched);
1367 /* Set unroll[j] if the input dimension j is involved in
1368 * the index expression represented by ma.
1370 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1371 void *user)
1373 int i, j;
1374 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1375 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1376 int *unroll = user;
1378 for (i = 0; i < n_out; ++i) {
1379 isl_aff *aff;
1381 aff = isl_multi_aff_get_aff(ma, i);
1382 for (j = 0; j < n_in; ++j)
1383 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1384 unroll[j] = 1;
1385 isl_aff_free(aff);
1388 isl_set_free(set);
1389 isl_multi_aff_free(ma);
1390 return 0;
1393 /* Given an array pos mapping input dimensions to the corresponding
1394 * output dimension, construct the corresponding map.
1396 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1397 int *pos, int len)
1399 int i;
1400 isl_constraint *c;
1401 isl_basic_map *bmap;
1402 isl_local_space *ls;
1404 dim = isl_space_add_dims(dim, isl_dim_in, len);
1405 dim = isl_space_add_dims(dim, isl_dim_out, len);
1406 bmap = isl_basic_map_universe(isl_space_copy(dim));
1407 ls = isl_local_space_from_space(dim);
1409 for (i = 0; i < len; ++i) {
1410 c = isl_equality_alloc(isl_local_space_copy(ls));
1411 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1412 -1);
1413 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1415 bmap = isl_basic_map_add_constraint(bmap, c);
1417 isl_local_space_free(ls);
1419 return isl_map_from_basic_map(bmap);
1422 /* Remove the private tiles from all array reference groups,
1423 * except for the groups of arrays that are marked force_private.
1425 static void remove_private_tiles(struct gpu_gen *gen)
1427 int i, j;
1429 for (i = 0; i < gen->prog->n_array; ++i) {
1430 struct gpu_array_info *array = &gen->prog->array[i];
1432 if (array->force_private)
1433 continue;
1435 for (j = 0; j < array->n_group; ++j) {
1436 struct gpu_array_ref_group *group = array->groups[j];
1438 group->private_tile =
1439 gpu_array_tile_free(group->private_tile);
1444 /* Find all loops involved in any of the index expressions for any of
1445 * the private accesses, move them innermost and then mark them as
1446 * requiring unrolling by setting gen->first_unroll.
1447 * The loops involved should all be parallel because of the checks
1448 * we performed in check_private_group_access. Moving them innermost
1449 * is therefore a valid transformation.
1451 * If any of the arrays are marked force_private, however, then
1452 * those loops may not be parallel with respect to the marked arrays.
1453 * If any of the loops would have to be moved innermost for the
1454 * (non forced) private accesses and if there are any force_private
1455 * arrays, then we revert the decision to map the selected arrays
1456 * to private memory. An alternative solution would be to expand
1457 * the force_private arrays.
1459 * Loops up to gen->shared_len are generated before the mapping to
1460 * threads is applied. They should therefore be ignored.
1462 * We compute the hidden equalities of the schedule first
1463 * since we will need them in our calls to isl_pw_multi_aff_from_map
1464 * and because we want to make sure that the same equalities
1465 * are also available to the code generator.
1467 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1468 __isl_take isl_union_map *sched)
1470 int i, j;
1471 int unroll[gen->thread_tiled_len];
1472 int perm[gen->thread_tiled_len];
1473 isl_space *dim;
1474 isl_map *permute;
1475 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1477 gen->first_unroll = -1;
1479 sched = isl_union_map_detect_equalities(sched);
1480 for (i = 0; i < gen->thread_tiled_len; ++i)
1481 unroll[i] = 0;
1482 for (i = 0; i < gen->prog->n_array; ++i) {
1483 struct gpu_array_info *array = &gen->prog->array[i];
1485 for (j = 0; j < array->n_group; ++j) {
1486 isl_union_map *access;
1487 isl_map *acc;
1488 isl_pw_multi_aff *pma;
1490 if (!array->groups[j]->private_tile)
1491 continue;
1493 access = group_access_relation(array->groups[j], 1, 1);
1494 access = isl_union_map_apply_domain(access,
1495 isl_union_map_copy(sched));
1497 acc = isl_map_from_union_map(access);
1498 pma = isl_pw_multi_aff_from_map(acc);
1499 isl_pw_multi_aff_foreach_piece(pma,
1500 &check_unroll, unroll);
1502 isl_pw_multi_aff_free(pma);
1506 for (i = gen->shared_len; i < len; ++i)
1507 if (unroll[i])
1508 break;
1510 if (i >= len)
1511 return sched;
1513 for (i = len; i < gen->thread_tiled_len; ++i)
1514 if (unroll[i])
1515 return sched;
1517 if (gen->any_force_private) {
1518 remove_private_tiles(gen);
1519 return sched;
1522 j = 0;
1523 for (i = 0; i < gen->shared_len; ++i)
1524 perm[i] = j++;
1525 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1526 if (!unroll[i])
1527 perm[i] = j++;
1528 gen->first_unroll = j - gen->shared_len;
1529 for (i = gen->shared_len; i < len; ++i)
1530 if (unroll[i])
1531 perm[i] = j++;
1533 dim = isl_union_map_get_space(sched);
1534 permute = permutation(dim, perm, gen->thread_tiled_len);
1535 sched = isl_union_map_apply_range(sched,
1536 isl_union_map_from_map(permute));
1538 return sched;
1541 /* Given a constraint
1543 * a(p,i) + j = g f(e)
1545 * or -a(p,i) - j = g f(e) if sign < 0,
1546 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1547 * a(p,i) is assumed to be an expression in only the parameters
1548 * and the input dimensions.
1550 static void extract_stride(__isl_keep isl_constraint *c,
1551 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1553 int i;
1554 isl_val *v;
1555 isl_space *space;
1556 unsigned nparam;
1557 unsigned nvar;
1558 isl_aff *aff;
1560 isl_val_free(bound->stride);
1561 bound->stride = isl_val_copy(stride);
1563 space = isl_constraint_get_space(c);
1564 space = isl_space_domain(space);
1566 nparam = isl_space_dim(space, isl_dim_param);
1567 nvar = isl_space_dim(space, isl_dim_set);
1569 v = isl_constraint_get_constant_val(c);
1570 if (sign < 0)
1571 v = isl_val_neg(v);
1572 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1573 aff = isl_aff_set_constant_val(aff, v);
1575 for (i = 0; i < nparam; ++i) {
1576 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1577 continue;
1578 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1579 if (sign < 0)
1580 v = isl_val_neg(v);
1581 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1584 for (i = 0; i < nvar; ++i) {
1585 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1586 continue;
1587 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1588 if (sign < 0)
1589 v = isl_val_neg(v);
1590 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1593 bound->shift = aff;
1596 /* Given an equality constraint of a map with a single output dimension j,
1597 * check if the constraint is of the form
1599 * a(p,i) + j = g f(e)
1601 * with a(p,i) an expression in the parameters and input dimensions
1602 * and f(e) an expression in the existentially quantified variables.
1603 * If so, and if g is larger than any such g from a previously considered
1604 * constraint, then call extract_stride to record the stride information
1605 * in bound.
1607 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1609 int i;
1610 isl_ctx *ctx;
1611 isl_val *v;
1612 unsigned n_div;
1613 struct gpu_array_bound *bound = user;
1615 ctx = isl_constraint_get_ctx(c);
1616 n_div = isl_constraint_dim(c, isl_dim_div);
1617 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1619 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1620 int s = isl_val_sgn(v);
1621 isl_val *stride = isl_val_zero(ctx);
1623 isl_val_free(v);
1624 for (i = 0; i < n_div; ++i) {
1625 v = isl_constraint_get_coefficient_val(c,
1626 isl_dim_div, i);
1627 stride = isl_val_gcd(stride, v);
1629 if (!isl_val_is_zero(stride) &&
1630 isl_val_gt(stride, bound->stride))
1631 extract_stride(c, bound, stride, s);
1633 isl_val_free(stride);
1634 } else
1635 isl_val_free(v);
1637 isl_constraint_free(c);
1638 return 0;
1641 /* Given contraints on an array index i, check if we can find
1642 * a shift a(p) and a stride g such that
1644 * a(p) + i = 0 mod g
1646 * If so, record the information in bound and apply the mapping
1647 * i -> (i + a(p))/g to the array index in bounds and return
1648 * the new constraints.
1649 * If not, simply return the original constraints.
1651 * If bounds is a subset of the space
1653 * D -> i
1655 * then the bound recorded in bound->shift is of the form
1657 * D -> s(D)
1659 * with s(D) equal to a(p) above.
1660 * Next, we construct a mapping of the form
1662 * [D -> i] -> [D -> (i + S(D))/g]
1664 * This mapping is computed as follows.
1665 * We first introduce "i" in the domain through precomposition
1666 * with [D -> i] -> D obtaining
1668 * [D -> i] -> s(D)
1670 * Adding [D -> i] -> i produces
1672 * [D -> i] -> i + s(D)
1674 * and the domain product with [D -> i] -> D yields
1676 * [D -> i] -> [D -> i + s(D)]
1678 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1680 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1681 __isl_take isl_basic_map *bounds)
1683 isl_space *space;
1684 isl_basic_map *hull;
1685 isl_basic_map *shift, *id, *bmap, *scale;
1686 isl_basic_set *bset;
1687 isl_aff *aff;
1689 bound->stride = NULL;
1691 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1693 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1695 isl_basic_map_free(hull);
1697 if (!bound->stride)
1698 return bounds;
1700 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1701 space = isl_basic_map_get_space(bounds);
1702 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1703 shift = isl_basic_map_apply_range(bmap, shift);
1704 space = isl_basic_map_get_space(bounds);
1705 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1706 shift = isl_basic_map_sum(id, shift);
1707 space = isl_basic_map_get_space(bounds);
1708 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1709 shift = isl_basic_map_range_product(id, shift);
1711 space = isl_space_domain(isl_basic_map_get_space(bounds));
1712 id = isl_basic_map_identity(isl_space_map_from_set(space));
1713 space = isl_space_range(isl_basic_map_get_space(bounds));
1714 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1715 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1716 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1717 scale = isl_basic_map_from_aff(aff);
1718 scale = isl_basic_map_product(id, scale);
1720 bmap = isl_basic_map_apply_range(shift, scale);
1721 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1722 bounds = isl_basic_set_unwrap(bset);
1724 return bounds;
1727 /* Data used in compute_array_dim_size and compute_size_in_direction.
1729 * pos is the position of the variable representing the array index,
1730 * i.e., the variable for which want to compute the size. This variable
1731 * is also the last variable in the set.
1733 struct gpu_size_info {
1734 isl_basic_set *bset;
1735 struct gpu_array_bound *bound;
1736 int pos;
1739 /* Given a constraint from the basic set describing the bounds on
1740 * an array index, check if it is a lower bound, say m i >= b(x), and,
1741 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1742 * upper bound. If so, and if this bound is smaller than any bound
1743 * derived from earlier constraints, set the size to this bound on
1744 * the expression and the lower bound to ceil(b(x)/m).
1746 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1748 struct gpu_size_info *size = user;
1749 unsigned nparam;
1750 unsigned n_div;
1751 isl_val *v;
1752 isl_aff *aff;
1753 isl_aff *lb;
1755 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1756 n_div = isl_constraint_dim(c, isl_dim_div);
1758 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1759 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1760 isl_constraint_free(c);
1761 return 0;
1764 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1765 aff = isl_aff_ceil(aff);
1767 lb = isl_aff_copy(aff);
1769 aff = isl_aff_neg(aff);
1770 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1772 v = isl_basic_set_max_val(size->bset, aff);
1773 isl_aff_free(aff);
1775 if (isl_val_is_int(v)) {
1776 v = isl_val_add_ui(v, 1);
1777 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
1778 isl_val_free(size->bound->size);
1779 size->bound->size = isl_val_copy(v);
1780 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1781 isl_aff_free(size->bound->lb);
1782 size->bound->lb = isl_aff_copy(lb);
1785 isl_val_free(v);
1786 isl_aff_free(lb);
1788 isl_constraint_free(c);
1790 return 0;
1793 /* Given a basic map "bounds" that maps parameters and input dimensions
1794 * to a single output dimension, look for an expression in the parameters
1795 * and input dimensions such that the range of the output dimension shifted
1796 * by this expression is a constant.
1798 * In particular, we currently only consider lower bounds on the output
1799 * dimension as candidate expressions.
1801 static int compute_array_dim_size(struct gpu_array_bound *bound,
1802 __isl_take isl_basic_map *bounds)
1804 struct gpu_size_info size;
1806 bounds = isl_basic_map_detect_equalities(bounds);
1807 bounds = check_stride(bound, bounds);
1809 bound->size = NULL;
1810 bound->lb = NULL;
1812 size.bound = bound;
1813 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
1814 size.bset = isl_basic_map_wrap(bounds);
1815 size.bset = isl_basic_set_flatten(size.bset);
1816 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
1817 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
1818 &size);
1819 isl_basic_set_free(size.bset);
1821 return bound->size ? 0 : -1;
1824 /* Check if we can find a memory tile for the given array
1825 * based on the given accesses, and if so, put the results in "tile".
1827 * We project the accesses on each index in turn and look for a parametric
1828 * offset such that the size is constant.
1830 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
1832 int i;
1834 for (i = 0; i < tile->n; ++i) {
1835 isl_map *access_i;
1836 isl_basic_map *hull;
1838 access_i = isl_map_copy(access);
1839 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
1840 access_i = isl_map_project_out(access_i, isl_dim_out,
1841 1, tile->n - (i + 1));
1842 access_i = isl_map_compute_divs(access_i);
1843 hull = isl_map_simple_hull(access_i);
1844 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
1845 return 0;
1848 return 1;
1851 /* Construct a map with input the shared tile loops and the loops that
1852 * will be wrapped around the threads that relates these later loops
1853 * to the thread indices and then projects them out.
1855 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1857 isl_map *priv;
1858 isl_map *tiling;
1859 isl_map *proj;
1860 isl_set *par;
1861 isl_space *dim;
1863 dim = isl_union_map_get_space(gen->shared_sched);
1865 if (gen->options->wrap)
1866 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
1867 gen->shared_len, gen->n_block, gen->block_dim);
1868 else
1869 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
1870 gen->shared_len, gen->n_block, gen->block_dim);
1872 priv = tiling;
1874 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
1875 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1876 gen->kernel->thread_ids);
1878 priv = isl_map_align_params(priv, isl_set_get_space(par));
1879 priv = isl_map_intersect_range(priv, par);
1881 dim = isl_map_get_space(priv);
1882 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1883 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1884 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
1885 gen->shared_len);
1887 priv = isl_map_apply_range(priv, proj);
1889 return priv;
1892 /* Construct a map from domain_dim to domain_dim that increments
1893 * the dimension at position "pos" and leaves all other dimensions
1894 * constant.
1896 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
1898 int i;
1899 int len = isl_space_dim(domain_dim, isl_dim_set);
1900 isl_space *dim;
1901 isl_basic_map *next;
1902 isl_local_space *ls;
1904 dim = isl_space_map_from_set(domain_dim);
1905 next = isl_basic_map_universe(isl_space_copy(dim));
1906 ls = isl_local_space_from_space(dim);
1908 for (i = 0; i < len; ++i) {
1909 isl_constraint *c;
1911 c = isl_equality_alloc(isl_local_space_copy(ls));
1912 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
1913 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1914 if (i == pos)
1915 c = isl_constraint_set_constant_si(c, 1);
1916 next = isl_basic_map_add_constraint(next, c);
1919 isl_local_space_free(ls);
1921 return isl_map_from_basic_map(next);
1924 /* Check if the given access is coalesced.
1925 * That is, check whether incrementing the dimension that will get
1926 * wrapped over the last thread index results in incrementing
1927 * the last array index.
1929 * This function is only called for access relations without reuse and
1930 * kernels with at least one block dimension.
1932 static int access_is_coalesced(struct gpu_gen *gen,
1933 __isl_keep isl_union_map *access)
1935 isl_space *dim;
1936 isl_map *access_map;
1937 isl_map *next_thread_x;
1938 isl_map *next_element;
1939 isl_map *map;
1940 int coalesced;
1942 access = isl_union_map_copy(access);
1943 access = isl_union_map_apply_domain(access,
1944 isl_union_map_copy(gen->tiled_sched));
1945 access_map = isl_map_from_union_map(access);
1947 dim = isl_map_get_space(access_map);
1948 dim = isl_space_domain(dim);
1949 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
1951 dim = isl_map_get_space(access_map);
1952 dim = isl_space_range(dim);
1953 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
1955 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
1956 map = isl_map_apply_range(map, access_map);
1958 coalesced = isl_map_is_subset(map, next_element);
1960 isl_map_free(next_element);
1961 isl_map_free(map);
1963 return coalesced;
1966 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
1967 * dimensions of the computed schedule, check if it is bijective for
1968 * fixed values of the first gen->shared_len dimensions.
1969 * We perform this check by equating these dimensions to parameters.
1971 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
1973 int res;
1974 isl_set *par;
1975 isl_space *space;
1976 isl_id_list *ids;
1978 access = isl_map_copy(access);
1979 space = isl_space_params(isl_map_get_space(access));
1980 ids = ppcg_scop_generate_names(gen->prog->scop, gen->shared_len, "s");
1981 par = parametrization(space, gen->shared_len + gen->n_block, 0, ids);
1982 isl_id_list_free(ids);
1983 access = isl_map_intersect_domain(access, par);
1984 res = isl_map_is_bijective(access);
1985 isl_map_free(access);
1987 return res;
1990 /* Look for the last shared tile loop that affects the offset of "tile"
1991 * and return the result.
1992 * If there is no such loop, then return the index of the loop
1993 * before the first shared tile loop, in particular gen->tile_first - 1.
1995 static int compute_tile_last_shared(struct gpu_gen *gen,
1996 struct gpu_array_tile *tile)
1998 int i, j;
2000 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2001 for (i = 0; i < tile->n; ++i) {
2002 isl_aff *lb;
2003 isl_aff *shift;
2005 lb = tile->bound[i].lb;
2006 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2007 break;
2009 shift = tile->bound[i].shift;
2010 if (!shift)
2011 continue;
2012 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2013 break;
2015 if (i < tile->n)
2016 break;
2019 return j;
2022 /* Look for the last shared tile loop that affects the offset of the
2023 * shared or private tile and store the result in group->last_shared.
2024 * If there is no such loop, then group->last_shared is set to a value
2025 * before the first shared tile loop, in particular gen->tile_first - 1.
2026 * If there is no tile defined on the array reference group,
2027 * then set group->last_shared to gen->shared_len - 1.
2029 static void set_last_shared(struct gpu_gen *gen,
2030 struct gpu_array_ref_group *group)
2032 struct gpu_array_tile *tile;
2034 group->last_shared = gen->shared_len - 1;
2036 tile = group->private_tile;
2037 if (!tile)
2038 tile = group->shared_tile;
2039 if (!tile)
2040 return;
2042 group->last_shared = compute_tile_last_shared(gen, tile);
2045 /* If max_shared_memory is not set to infinity (-1), then make
2046 * sure that the total amount of shared memory required by the
2047 * array reference groups mapped to shared memory is no larger
2048 * than this maximum.
2050 * We apply a greedy approach and discard (keep in global memory)
2051 * those groups that would result in a total memory size that
2052 * is larger than the maximum.
2054 * This function should be called after any function that may
2055 * affect the decision on whether to place a reference group
2056 * in private, shared or global memory.
2058 static void check_shared_memory_bound(struct gpu_gen *gen)
2060 int i, j;
2061 isl_val *left, *size;
2063 if (gen->options->max_shared_memory < 0)
2064 return;
2066 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2068 for (i = 0; i < gen->prog->n_array; ++i) {
2069 struct gpu_array_info *array = &gen->prog->array[i];
2071 for (j = 0; j < array->n_group; ++j) {
2072 struct gpu_array_ref_group *group;
2074 group = array->groups[j];
2075 if (group->private_tile)
2076 continue;
2077 if (!group->shared_tile)
2078 continue;
2080 size = gpu_array_tile_size(group->shared_tile);
2081 size = isl_val_mul_ui(size, array->size);
2083 if (isl_val_le(size, left)) {
2084 left = isl_val_sub(left, size);
2085 continue;
2087 isl_val_free(size);
2089 group->shared_tile =
2090 gpu_array_tile_free(group->shared_tile);
2094 isl_val_free(left);
2097 /* Given a description of an array tile "tile" and the "space"
2099 * { D -> A }
2101 * where D represents the first shared_len schedule dimensions
2102 * and A represents the array, construct an isl_multi_aff
2104 * { [D[i] -> A[a]] -> A'[a'] }
2106 * with A' a scaled down copy of A according to the shifts and strides
2107 * in "tile". In particular,
2109 * a' = (a + shift(i))/stride
2111 * "insert_array" represents
2113 * { [D -> A] -> D }
2115 * and is used to insert A into the domain of functions that only
2116 * reference D.
2118 static __isl_give isl_multi_aff *strided_tile(
2119 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2120 __isl_keep isl_multi_aff *insert_array)
2122 int i;
2123 isl_ctx *ctx;
2124 isl_multi_aff *shift;
2125 isl_multi_val *stride;
2126 isl_space *space2;
2127 isl_local_space *ls;
2128 isl_multi_aff *tiling;
2130 ctx = isl_space_get_ctx(space);
2131 space2 = isl_space_domain(isl_space_copy(space));
2132 ls = isl_local_space_from_space(space2);
2133 space2 = isl_space_range(isl_space_copy(space));
2134 stride = isl_multi_val_zero(space2);
2135 shift = isl_multi_aff_zero(isl_space_copy(space));
2137 for (i = 0; i < tile->n; ++i) {
2138 struct gpu_array_bound *bound = &tile->bound[i];
2139 isl_val *stride_i;
2140 isl_aff *shift_i;
2142 if (tile->bound[i].shift) {
2143 stride_i = isl_val_copy(bound->stride);
2144 shift_i = isl_aff_copy(bound->shift);
2145 } else {
2146 stride_i = isl_val_one(ctx);
2147 shift_i = isl_aff_zero_on_domain(
2148 isl_local_space_copy(ls));
2151 stride = isl_multi_val_set_val(stride, i, stride_i);
2152 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2154 isl_local_space_free(ls);
2156 shift = isl_multi_aff_pullback_multi_aff(shift,
2157 isl_multi_aff_copy(insert_array));
2159 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2160 tiling = isl_multi_aff_add(tiling, shift);
2161 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2163 return tiling;
2166 /* Compute a tiling for the array reference group "group".
2168 * The tiling is of the form
2170 * { [D[i] -> A[a]] -> T[t] }
2172 * where D represents the first shared_len schedule dimensions,
2173 * A represents the global array and T represents the shared or
2174 * private memory tile. The name of T is the name of the local
2175 * array.
2177 * If there is any stride in the accesses, then the mapping is
2179 * t = (a + shift(i))/stride - lb(i)
2181 * otherwise, it is simply
2183 * t = a - lb(i)
2185 static void compute_group_tiling(struct gpu_array_ref_group *group)
2187 int i;
2188 struct gpu_array_tile *tile;
2189 struct gpu_array_info *array = group->array;
2190 isl_space *space;
2191 isl_multi_aff *tiling, *lb, *insert_array;
2192 isl_printer *p;
2193 char *local_name;
2195 tile = group->private_tile;
2196 if (!tile)
2197 tile = group->shared_tile;
2198 if (!tile)
2199 return;
2201 space = isl_map_get_space(group->access);
2202 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2204 for (i = 0; i < tile->n; ++i)
2205 if (tile->bound[i].shift)
2206 break;
2208 if (i < tile->n)
2209 tiling = strided_tile(tile, space, insert_array);
2210 else
2211 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2213 lb = isl_multi_aff_zero(space);
2214 for (i = 0; i < tile->n; ++i) {
2215 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2216 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2218 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2220 tiling = isl_multi_aff_sub(tiling, lb);
2222 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2223 p = print_array_name(p, group);
2224 local_name = isl_printer_get_str(p);
2225 isl_printer_free(p);
2226 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2227 free(local_name);
2229 tile->tiling = tiling;
2232 /* Compute a tiling for all the array reference groups.
2234 static void compute_group_tilings(struct gpu_gen *gen)
2236 int i, j;
2238 for (i = 0; i < gen->prog->n_array; ++i) {
2239 struct gpu_array_info *array = &gen->prog->array[i];
2241 for (j = 0; j < array->n_group; ++j)
2242 compute_group_tiling(array->groups[j]);
2246 /* Fill up the groups array with singleton groups, i.e., one group
2247 * per reference, initializing the array, access, write, n_ref and refs fields.
2248 * In particular the access field is initialized to the scheduled
2249 * access relation of the array reference.
2251 * Return the number of elements initialized, i.e., the number of
2252 * active references in the current kernel.
2254 static int populate_array_references(struct gpu_array_info *array,
2255 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2257 int i;
2258 int n;
2259 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2261 n = 0;
2262 for (i = 0; i < array->n_ref; ++i) {
2263 isl_union_map *umap;
2264 isl_map *map;
2265 struct gpu_array_ref_group *group;
2266 struct gpu_stmt_access *access = array->refs[i];
2268 map = isl_map_copy(access->access);
2269 umap = isl_union_map_from_map(map);
2270 umap = isl_union_map_apply_domain(umap,
2271 isl_union_map_copy(sched));
2273 if (isl_union_map_is_empty(umap)) {
2274 isl_union_map_free(umap);
2275 continue;
2278 map = isl_map_from_union_map(umap);
2279 map = isl_map_detect_equalities(map);
2281 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2282 assert(group);
2283 group->array = array;
2284 group->access = map;
2285 group->write = access->write;
2286 group->exact_write = access->exact_write;
2287 group->slice = access->n_index < array->n_index;
2288 group->refs = &array->refs[i];
2289 group->n_ref = 1;
2291 groups[n++] = group;
2294 return n;
2297 /* If group->n_ref == 1, then group->refs was set by
2298 * populate_array_references to point directly into
2299 * group->array->refs and should not be freed.
2300 * If group->n_ref > 1, then group->refs was set by join_groups
2301 * to point to a newly allocated array.
2303 static void free_array_ref_group(struct gpu_array_ref_group *group)
2305 if (!group)
2306 return;
2307 gpu_array_tile_free(group->shared_tile);
2308 gpu_array_tile_free(group->private_tile);
2309 isl_map_free(group->access);
2310 if (group->n_ref > 1)
2311 free(group->refs);
2312 free(group);
2315 /* Given a map where the input dimensions represent the tile loops,
2316 * eliminate the innermost of those that have a fixed value
2317 * until we reach one that does not (obviously) have a fixed value.
2319 static __isl_give isl_map *eliminate_fixed_inner_loops(
2320 __isl_take isl_map *access)
2322 int i, n;
2324 n = isl_map_dim(access, isl_dim_in);
2326 for (i = n - 1; i >= 0; --i) {
2327 if (!map_plain_is_fixed(access, isl_dim_in, i))
2328 break;
2329 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2331 return access;
2334 /* Check if the access relations of group1 and group2 overlap within
2335 * the innermost loop. In particular, ignore any inner dimension
2336 * with a fixed value.
2337 * The copying to and from shared memory will be performed within
2338 * the innermost actual loop so we are only allowed to consider
2339 * the dimensions up to that innermost loop while checking whether
2340 * two access relations overlap.
2342 static int accesses_overlap(struct gpu_array_ref_group *group1,
2343 struct gpu_array_ref_group *group2)
2345 int empty;
2346 isl_map *access1, *access2;
2348 access1 = isl_map_copy(group1->access);
2349 access1 = eliminate_fixed_inner_loops(access1);
2350 access2 = isl_map_copy(group2->access);
2351 access2 = eliminate_fixed_inner_loops(access2);
2352 access1 = isl_map_intersect(access1, access2);
2353 empty = isl_map_is_empty(access1);
2354 isl_map_free(access1);
2356 return !empty;
2359 /* Combine the given two groups into a single group, containing
2360 * the references of both groups.
2362 static struct gpu_array_ref_group *join_groups(
2363 struct gpu_array_ref_group *group1,
2364 struct gpu_array_ref_group *group2)
2366 int i;
2367 isl_ctx *ctx;
2368 struct gpu_array_ref_group *group;
2370 ctx = isl_map_get_ctx(group1->access);
2371 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2372 assert(group);
2373 group->array = group1->array;
2374 group->access = isl_map_union(isl_map_copy(group1->access),
2375 isl_map_copy(group2->access));
2376 group->write = group1->write || group2->write;
2377 group->exact_write = group1->exact_write && group2->exact_write;
2378 group->slice = group1->slice || group2->slice;
2379 group->n_ref = group1->n_ref + group2->n_ref;
2380 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2381 group->n_ref);
2382 assert(group->refs);
2383 for (i = 0; i < group1->n_ref; ++i)
2384 group->refs[i] = group1->refs[i];
2385 for (i = 0; i < group2->n_ref; ++i)
2386 group->refs[group1->n_ref + i] = group2->refs[i];
2388 return group;
2391 /* Combine the given two groups into a single group and free
2392 * the original two groups.
2394 static struct gpu_array_ref_group *join_groups_and_free(
2395 struct gpu_array_ref_group *group1,
2396 struct gpu_array_ref_group *group2)
2398 struct gpu_array_ref_group *group;
2400 group = join_groups(group1, group2);
2401 free_array_ref_group(group1);
2402 free_array_ref_group(group2);
2403 return group;
2406 /* Report that the array reference group with the given access relation
2407 * is not mapped to shared memory in the given kernel because
2408 * it does not exhibit any reuse and is considered to be coalesced.
2410 static void report_no_reuse_and_coalesced(struct ppcg_kernel *kernel,
2411 __isl_keep isl_union_map *access)
2413 isl_ctx *ctx;
2414 isl_printer *p;
2416 ctx = isl_union_map_get_ctx(access);
2417 p = isl_printer_to_file(ctx, stdout);
2418 p = isl_printer_print_str(p, "Array reference group ");
2419 p = isl_printer_print_union_map(p, access);
2420 p = isl_printer_print_str(p,
2421 " not considered for mapping to shared memory in kernel");
2422 p = isl_printer_print_int(p, kernel->id);
2423 p = isl_printer_print_str(p,
2424 " because it exhibits no reuse and is considered to be coalesced");
2425 p = isl_printer_end_line(p);
2426 isl_printer_free(p);
2429 /* Compute the private and/or shared memory tiles for the array
2430 * reference group "group" of array "array".
2431 * Return 0 on success and -1 on error.
2433 * If the array is a read-only scalar or if the user requested
2434 * not to use shared or private memory, then we do not need to do anything.
2436 * If any reference in the reference group accesses more than one element,
2437 * then we would have to make sure that the layout in shared memory
2438 * is the same as that in global memory. Since we do not handle this yet
2439 * (and it may not even be possible), we refuse to map to private or
2440 * shared memory in such cases.
2442 * If the array group involves any may writes (that are not must writes),
2443 * then we would have to make sure that we load the data into shared/private
2444 * memory first in case the data is not written by the kernel
2445 * (but still written back out to global memory).
2446 * Since we don't have any such mechanism at the moment, we don't
2447 * compute shared/private tiles for groups involving may writes.
2449 * We only try to compute a shared memory tile if there is any reuse
2450 * or if the access is not coalesced.
2452 * For computing a private memory tile, we also require that there is
2453 * some reuse. Moreover, we require that the access is private
2454 * to the thread. That is, we check that any given array element
2455 * is only accessed by a single thread.
2456 * We compute an access relation that maps the shared tile loop iterators
2457 * and the shared point loop iterators that will be wrapped over the
2458 * threads to the array elements.
2459 * We actually check that those iterators that will be wrapped
2460 * partition the array space. This check is stricter than necessary
2461 * since several iterations may be mapped onto the same thread
2462 * and then they could be allowed to access the same memory elements,
2463 * but our check does not allow this situation.
2465 * We also check that the index expression only depends on parallel
2466 * loops. That way, we can move those loops innermost and unroll them.
2467 * Again, we use a test that is stricter than necessary.
2468 * We actually check whether the index expression only depends
2469 * on the iterators that are wrapped over the threads.
2470 * These are necessarily parallel, but there may be more parallel loops.
2472 * Combining the injectivity of the first test with the single-valuedness
2473 * of the second test, we simply test for bijectivity.
2475 * If the array is marked force_private, then we bypass all checks
2476 * and assume we can (and should) use registers.
2478 * If it turns out we can (or have to) use registers, we compute
2479 * the private memory tile size using can_tile, after introducing a dependence
2480 * on the thread indices.
2482 static int compute_group_bounds_core(struct gpu_gen *gen,
2483 struct gpu_array_ref_group *group)
2485 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2486 isl_union_map *access;
2487 int n_index = group->array->n_index;
2488 int no_reuse, coalesced;
2489 isl_map *acc;
2490 int force_private = group->array->force_private;
2491 int use_shared = gen->options->use_shared_memory && gen->n_block > 0;
2492 int use_private = force_private || gen->options->use_private_memory;
2494 if (!use_shared && !use_private)
2495 return 0;
2496 if (gpu_array_is_read_only_scalar(group->array))
2497 return 0;
2498 if (!force_private && !group->exact_write)
2499 return 0;
2500 if (group->slice)
2501 return 0;
2503 access = group_access_relation(group, 1, 1);
2504 no_reuse = isl_union_map_is_injective(access);
2505 if (use_shared && no_reuse)
2506 coalesced = access_is_coalesced(gen, access);
2508 if (gen->options->debug->verbose && use_shared && no_reuse && coalesced)
2509 report_no_reuse_and_coalesced(gen->kernel, access);
2511 if (use_shared && (!no_reuse || !coalesced)) {
2512 group->shared_tile = gpu_array_tile_create(ctx,
2513 group->array->n_index);
2514 assert(group->shared_tile);
2515 if (!can_tile(group->access, group->shared_tile))
2516 group->shared_tile =
2517 gpu_array_tile_free(group->shared_tile);
2520 if (!force_private && (!use_private || no_reuse)) {
2521 isl_union_map_free(access);
2522 return 0;
2525 access = isl_union_map_apply_domain(access,
2526 isl_union_map_copy(gen->shared_sched));
2528 acc = isl_map_from_union_map(access);
2530 if (!force_private && !access_is_bijective(gen, acc)) {
2531 isl_map_free(acc);
2532 return 0;
2535 group->private_tile = gpu_array_tile_create(gen->ctx, n_index);
2536 assert(group->private_tile);
2537 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2538 if (!can_tile(acc, group->private_tile))
2539 group->private_tile = gpu_array_tile_free(group->private_tile);
2541 isl_map_free(acc);
2543 if (force_private && !group->private_tile)
2544 isl_die(ctx, isl_error_internal,
2545 "unable to map array reference group to registers",
2546 return -1);
2548 return 0;
2551 /* Compute the private and/or shared memory tiles for the array
2552 * reference group "group" of array "array" and set last_shared.
2553 * Return 0 on success and -1 on error.
2555 static int compute_group_bounds(struct gpu_gen *gen,
2556 struct gpu_array_ref_group *group)
2558 if (compute_group_bounds_core(gen, group) < 0)
2559 return -1;
2560 set_last_shared(gen, group);
2562 return 0;
2565 /* If two groups have overlapping access relations (as determined by
2566 * the "overlap" function) and if one of them involves a write,
2567 * then merge the two groups into one.
2568 * If "compute_bounds" is set, then call compute_group_bounds
2569 * on the merged groups.
2571 * Return the updated number of groups.
2572 * Return -1 on error.
2574 static int group_writes(struct gpu_gen *gen,
2575 int n, struct gpu_array_ref_group **groups,
2576 int (*overlap)(struct gpu_array_ref_group *group1,
2577 struct gpu_array_ref_group *group2), int compute_bounds)
2579 int i, j;
2581 for (i = 0; i < n; ++i) {
2582 for (j = n - 1; j > i; --j) {
2583 if (!groups[i]->write && !groups[j]->write)
2584 continue;
2586 if (!overlap(groups[i], groups[j]))
2587 continue;
2589 groups[i] = join_groups_and_free(groups[i], groups[j]);
2590 if (j != n - 1)
2591 groups[j] = groups[n - 1];
2592 groups[n - 1] = NULL;
2593 n--;
2595 if (compute_bounds &&
2596 compute_group_bounds(gen, groups[i]) < 0)
2597 return -1;
2601 return n;
2604 /* If two groups have overlapping access relations (within the innermost
2605 * loop) and if one of them involves a write, then merge the two groups
2606 * into one.
2608 * Return the updated number of groups.
2610 static int group_overlapping_writes(struct gpu_gen *gen,
2611 int n, struct gpu_array_ref_group **groups)
2613 return group_writes(gen, n, groups, &accesses_overlap, 0);
2616 /* Check if the access relations of group1 and group2 overlap within
2617 * the outermost min(group1->last_shared, group2->last_shared) loops.
2619 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2620 struct gpu_array_ref_group *group2)
2622 int last_shared;
2623 int dim;
2624 int empty;
2625 isl_map *map_i, *map_j, *map;
2627 last_shared = group1->last_shared;
2628 if (group2->last_shared < last_shared)
2629 last_shared = group2->last_shared;
2630 map_i = isl_map_copy(group1->access);
2631 dim = isl_map_dim(map_i, isl_dim_in);
2632 map_i = isl_map_eliminate(map_i, isl_dim_in,
2633 last_shared + 1, dim - (last_shared + 1));
2634 map_j = isl_map_copy(group2->access);
2635 map_j = isl_map_eliminate(map_j, isl_dim_in,
2636 last_shared + 1, dim - (last_shared + 1));
2637 map = isl_map_intersect(map_i, map_j);
2638 empty = isl_map_is_empty(map);
2639 isl_map_free(map);
2641 return !empty;
2644 /* If two groups have overlapping access relations (within the outer
2645 * last_shared loops) and if one of them involves a write,
2646 * then merge the two groups into one.
2648 * Return the updated number of groups.
2650 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2651 struct gpu_array_ref_group **groups)
2653 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2656 /* Is the size of the tile specified by "tile" smaller than the sum of
2657 * the sizes of the tiles specified by "tile1" and "tile2"?
2659 static int smaller_tile(struct gpu_array_tile *tile,
2660 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2662 int smaller;
2663 isl_val *size, *size1, *size2;
2665 size = gpu_array_tile_size(tile);
2666 size1 = gpu_array_tile_size(tile1);
2667 size2 = gpu_array_tile_size(tile2);
2669 size = isl_val_sub(size, size1);
2670 size = isl_val_sub(size, size2);
2671 smaller = isl_val_is_neg(size);
2673 isl_val_free(size);
2675 return smaller;
2678 /* Given an initial grouping of array references and shared memory tiles
2679 * for each group that allows for a shared memory tile, merge two groups
2680 * if both have a shared memory tile, the merged group also has
2681 * a shared memory tile and the size of the tile for the merge group
2682 * is smaller than the sum of the tile sizes of the individual groups.
2684 * If merging two groups decreases the "last_shared" dimension of
2685 * one or both of the two groups, then we need to check for overlapping
2686 * writes again.
2688 * Return the number of groups after merging.
2689 * Return -1 on error.
2691 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2692 struct gpu_array_info *array, int n,
2693 struct gpu_array_ref_group **groups)
2695 int i, j;
2696 int recompute_overlap = 0;
2697 isl_ctx *ctx = isl_space_get_ctx(array->space);
2699 for (i = 0; i < n; ++i) {
2700 if (!groups[i]->shared_tile)
2701 continue;
2702 for (j = n - 1; j > i; --j) {
2703 isl_map *map;
2704 int empty;
2705 struct gpu_array_ref_group *group;
2707 if (!groups[j]->shared_tile)
2708 continue;
2710 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2711 isl_map_copy(groups[j]->access));
2712 empty = isl_map_is_empty(map);
2713 isl_map_free(map);
2715 if (empty)
2716 continue;
2718 group = join_groups(groups[i], groups[j]);
2719 if (compute_group_bounds(gen, group) < 0) {
2720 free_array_ref_group(group);
2721 return -1;
2723 if (!group->shared_tile ||
2724 !smaller_tile(group->shared_tile,
2725 groups[i]->shared_tile,
2726 groups[j]->shared_tile)) {
2727 free_array_ref_group(group);
2728 continue;
2731 if (group->last_shared < groups[i]->last_shared ||
2732 group->last_shared < groups[j]->last_shared)
2733 recompute_overlap = 1;
2734 free_array_ref_group(groups[i]);
2735 free_array_ref_group(groups[j]);
2736 groups[i] = group;
2737 if (j != n - 1)
2738 groups[j] = groups[n - 1];
2739 n--;
2743 if (recompute_overlap)
2744 n = group_last_shared_overlapping_writes(gen, n, groups);
2745 return n;
2748 /* Set array->n_group and array->groups to n and groups.
2750 * Additionally, set the "nr" field of each group
2751 * and the "group" field of each reference in each group.
2753 static void set_array_groups(struct gpu_array_info *array,
2754 int n, struct gpu_array_ref_group **groups)
2756 int i, j;
2758 array->n_group = n;
2759 array->groups = groups;
2761 for (i = 0; i < n; ++i) {
2762 groups[i]->nr = i;
2764 for (j = 0; j < groups[i]->n_ref; ++j)
2765 groups[i]->refs[j]->group = i;
2769 /* Group array references that should be considered together when
2770 * deciding whether to access them from private, shared or global memory.
2771 * Return -1 on error.
2773 * In particular, if two array references overlap and if one of them
2774 * is a write, then the two references are grouped together.
2775 * We first perform an initial grouping based only on the access relation.
2776 * After computing shared and private memory tiles, we check for
2777 * overlapping writes again, but this time taking into account
2778 * the "last_shared" property.
2780 * Furthermore, if two groups admit a shared memory tile and if the
2781 * combination of the two also admits a shared memory tile, we merge
2782 * the two groups.
2784 * If the array contains structures, then there is no need to compute
2785 * reference groups since we do not map such arrays to private or shared
2786 * memory.
2788 static int group_array_references(struct gpu_gen *gen,
2789 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2791 int i;
2792 int n;
2793 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2794 struct gpu_array_ref_group **groups;
2796 if (array->has_compound_element)
2797 return 0;
2799 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2800 array->n_ref);
2801 if (!groups)
2802 return -1;
2804 n = populate_array_references(array, sched, groups);
2806 n = group_overlapping_writes(gen, n, groups);
2808 for (i = 0; i < n; ++i)
2809 if (compute_group_bounds(gen, groups[i]) < 0)
2810 n = -1;
2812 n = group_last_shared_overlapping_writes(gen, n, groups);
2814 n = group_common_shared_memory_tile(gen, array, n, groups);
2816 set_array_groups(array, n, groups);
2818 if (n >= 0)
2819 return 0;
2821 for (i = 0; i < array->n_ref; ++i)
2822 free_array_ref_group(groups[i]);
2823 return -1;
2826 /* Take tiled_sched, project it onto the shared tile loops and
2827 * the loops that will be wrapped over the threads and
2828 * store the result in gen->shared_sched.
2829 * Also compute a projection that projects out the loops that will be
2830 * wrapped over the threads and store this projection in gen->shared_proj.
2832 static void compute_shared_sched(struct gpu_gen *gen)
2834 isl_space *dim;
2835 isl_map *proj;
2836 isl_set *par;
2837 isl_union_map *sched;
2839 sched = isl_union_map_copy(gen->tiled_sched);
2841 dim = isl_union_map_get_space(sched);
2842 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2843 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2845 dim = isl_union_map_get_space(sched);
2846 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2848 gen->shared_sched = sched;
2849 gen->shared_proj = isl_union_map_from_map(proj);
2852 /* For each scalar in the input program, check if there are any
2853 * order dependences active inside the current kernel, within
2854 * the same iteration of the host schedule.
2855 * If so, mark the scalar as force_private so that it will be
2856 * mapped to a register.
2858 static void check_scalar_live_ranges(struct gpu_gen *gen)
2860 int i;
2861 isl_map *proj;
2862 isl_union_map *sched;
2863 isl_union_set *domain;
2864 isl_union_map *same_host_iteration;
2866 gen->any_force_private = 0;
2868 if (!gen->options->live_range_reordering)
2869 return;
2871 sched = gen->shared_sched;
2872 sched = isl_union_map_universe(isl_union_map_copy(sched));
2873 domain = isl_union_map_domain(sched);
2875 sched = isl_union_map_copy(gen->sched);
2876 proj = projection(isl_union_map_get_space(sched),
2877 gen->untiled_len, gen->tile_first);
2878 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2879 same_host_iteration = isl_union_map_apply_range(sched,
2880 isl_union_map_reverse(isl_union_map_copy(sched)));
2882 for (i = 0; i < gen->prog->n_array; ++i) {
2883 struct gpu_array_info *array = &gen->prog->array[i];
2884 isl_union_map *order;
2886 array->force_private = 0;
2887 if (array->n_index != 0)
2888 continue;
2889 order = isl_union_map_copy(array->dep_order);
2890 order = isl_union_map_intersect_domain(order,
2891 isl_union_set_copy(domain));
2892 order = isl_union_map_intersect_range(order,
2893 isl_union_set_copy(domain));
2894 order = isl_union_map_intersect(order,
2895 isl_union_map_copy(same_host_iteration));
2896 if (!isl_union_map_is_empty(order)) {
2897 array->force_private = 1;
2898 gen->any_force_private = 1;
2900 isl_union_map_free(order);
2903 isl_union_map_free(same_host_iteration);
2904 isl_union_set_free(domain);
2907 /* Group references of all arrays in the program.
2909 static int group_references(struct gpu_gen *gen)
2911 int i;
2912 int r = 0;
2913 isl_union_map *sched;
2915 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2916 isl_union_map_copy(gen->shared_proj));
2918 for (i = 0; i < gen->prog->n_array; ++i) {
2919 r = group_array_references(gen, &gen->prog->array[i], sched);
2920 if (r < 0)
2921 break;
2924 isl_union_map_free(sched);
2926 return r;
2929 /* Free all array information that is local to the current kernel.
2931 static void free_local_array_info(struct gpu_gen *gen)
2933 int i, j;
2935 for (i = 0; i < gen->prog->n_array; ++i) {
2936 struct gpu_array_info *array = &gen->prog->array[i];
2938 for (j = 0; j < array->n_group; ++j)
2939 free_array_ref_group(array->groups[j]);
2940 free(array->groups);
2944 /* Compute the size of a bounding box around the origin and "set",
2945 * where "set" is assumed to contain only non-negative elements.
2946 * In particular, compute the maximal value of "set" in each direction
2947 * and add one.
2949 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
2950 __isl_keep isl_set *context)
2952 int i, n;
2953 isl_multi_pw_aff *mpa;
2955 n = isl_set_dim(set, isl_dim_set);
2956 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
2957 for (i = 0; i < n; ++i) {
2958 isl_space *space;
2959 isl_aff *one;
2960 isl_pw_aff *bound;
2962 bound = isl_set_dim_max(isl_set_copy(set), i);
2963 bound = isl_pw_aff_coalesce(bound);
2964 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
2966 space = isl_pw_aff_get_domain_space(bound);
2967 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2968 one = isl_aff_add_constant_si(one, 1);
2969 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2970 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2972 isl_set_free(set);
2974 return mpa;
2977 /* Compute the effective grid size as a list of the sizes in each dimension.
2979 * The grid size specified by the user or set by default
2980 * in read_grid_sizes() and applied in tile_schedule(),
2981 * may be too large for the given code in the sense that
2982 * it may contain blocks that don't need to execute anything.
2983 * We therefore don't return this grid size, but instead the
2984 * smallest grid size that ensures that all blocks that actually
2985 * execute code are included in the grid.
2987 * We first extract a description of the grid, i.e., the possible values
2988 * of the block ids, from gen->tiled_sched.
2989 * The block ids are parameters in gen->tiled_sched.
2990 * We simply need to change them into set dimensions.
2992 * Then, for each block dimension, we compute the maximal value of the block id
2993 * and add one.
2995 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2996 struct ppcg_kernel *kernel)
2998 int i;
2999 isl_set *grid;
3001 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3002 grid = isl_set_from_params(grid);
3003 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3004 for (i = 0; i < gen->n_grid; ++i) {
3005 int pos;
3006 isl_id *id;
3008 id = isl_id_list_get_id(kernel->block_ids, i);
3009 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
3010 isl_id_free(id);
3011 assert(pos >= 0);
3012 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3013 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3016 return extract_size(grid, kernel->context);
3019 /* Compute the size of a fixed bounding box around the origin and "set",
3020 * where "set" is assumed to contain only non-negative elements,
3021 * and store the results in "size".
3022 * In particular, compute the maximal value of "set" in each direction
3023 * and add one.
3025 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3027 int i, n;
3028 isl_local_space *ls;
3029 isl_aff *obj;
3031 n = isl_set_dim(set, isl_dim_set);
3032 ls = isl_local_space_from_space(isl_set_get_space(set));
3033 obj = isl_aff_zero_on_domain(ls);
3034 for (i = 0; i < n; ++i) {
3035 isl_val *max;
3037 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3038 max = isl_set_max_val(set, obj);
3039 size[i] = isl_val_get_num_si(max) + 1;
3040 isl_val_free(max);
3041 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3043 isl_aff_free(obj);
3044 isl_set_free(set);
3047 /* Compute the effective block size as a list of the sizes in each dimension
3048 * and store the sizes in kernel->block_dim.
3050 * The block size specified by the user or set by default
3051 * in read_block_sizes() and applied in thread_tile_schedule(),
3052 * may be too large for the given code in the sense that
3053 * it may contain threads that don't need to execute anything.
3054 * We therefore don't store this block size in kernel->block_dim,
3055 * but instead the smallest block size that ensures that all threads
3056 * that actually execute code are included in the block.
3058 * The current implementation eliminates all parameters, ensuring
3059 * that the size is a fixed constant in each dimension.
3060 * In principle we could also compute parametric sizes.
3061 * We would have to make sure to project out all b%d and t%d parameters,
3062 * however.
3064 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3066 int i;
3067 int nparam;
3068 isl_set *block;
3069 isl_multi_pw_aff *mpa;
3071 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3072 block = isl_set_from_params(block);
3073 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3074 kernel->n_block = gen->n_block;
3075 for (i = 0; i < gen->n_block; ++i) {
3076 int pos;
3077 isl_id *id;
3079 id = isl_id_list_get_id(kernel->thread_ids, i);
3080 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
3081 isl_id_free(id);
3082 assert(pos >= 0);
3083 block = isl_set_equate(block, isl_dim_param, pos,
3084 isl_dim_set, i);
3086 nparam = isl_set_dim(block, isl_dim_param);
3087 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3089 extract_fixed_size(block, kernel->block_dim);
3092 void ppcg_kernel_free(void *user)
3094 struct ppcg_kernel *kernel = user;
3095 int i;
3097 if (!kernel)
3098 return;
3100 isl_id_list_free(kernel->block_ids);
3101 isl_id_list_free(kernel->thread_ids);
3102 isl_multi_pw_aff_free(kernel->grid_size);
3103 isl_set_free(kernel->context);
3104 isl_union_set_free(kernel->arrays);
3105 isl_space_free(kernel->space);
3106 isl_ast_node_free(kernel->tree);
3108 for (i = 0; i < kernel->n_array; ++i)
3109 isl_pw_aff_list_free(kernel->array[i].bound);
3110 free(kernel->array);
3112 for (i = 0; i < kernel->n_var; ++i) {
3113 free(kernel->var[i].name);
3114 isl_vec_free(kernel->var[i].size);
3116 free(kernel->var);
3118 free(kernel);
3121 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3122 struct ppcg_kernel_var *var)
3124 int j;
3125 struct gpu_array_tile *tile;
3126 isl_printer *p;
3127 char *name;
3129 var->array = group->array;
3131 tile = group->private_tile;
3132 var->type = ppcg_access_private;
3133 if (!tile) {
3134 tile = group->shared_tile;
3135 var->type = ppcg_access_shared;
3138 p = isl_printer_to_str(ctx);
3139 p = print_array_name(p, group);
3140 var->name = isl_printer_get_str(p);
3141 isl_printer_free(p);
3143 var->size = isl_vec_alloc(ctx, group->array->n_index);
3145 for (j = 0; j < group->array->n_index; ++j)
3146 var->size = isl_vec_set_element_val(var->size, j,
3147 isl_val_copy(tile->bound[j].size));
3150 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3152 int i, j, n;
3154 n = 0;
3155 for (i = 0; i < gen->prog->n_array; ++i) {
3156 struct gpu_array_info *array = &gen->prog->array[i];
3158 for (j = 0; j < array->n_group; ++j) {
3159 struct gpu_array_ref_group *group = array->groups[j];
3160 if (group->private_tile || group->shared_tile)
3161 ++n;
3165 kernel->n_var = n;
3166 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3167 assert(kernel->var);
3169 n = 0;
3170 for (i = 0; i < gen->prog->n_array; ++i) {
3171 struct gpu_array_info *array = &gen->prog->array[i];
3173 for (j = 0; j < array->n_group; ++j) {
3174 struct gpu_array_ref_group *group = array->groups[j];
3175 if (!group->private_tile && !group->shared_tile)
3176 continue;
3177 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3178 ++n;
3183 /* Replace "pa" by the zero function defined over the universe domain
3184 * in the space of "pa".
3186 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
3188 isl_space *space;
3189 isl_aff *zero;
3191 space = isl_space_domain(isl_pw_aff_get_space(pa));
3192 isl_pw_aff_free(pa);
3193 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3195 return isl_pw_aff_from_aff(zero);
3198 /* The sizes of the arrays on the host that have been computed by
3199 * extract_array_info may depend on the parameters. Use the extra
3200 * constraints on the parameters that are valid at "host_domain"
3201 * to simplify these expressions and store the results in kernel->array.
3203 * We only need these localized bounds for arrays that are accessed
3204 * by the current kernel. If we have found at least one reference group
3205 * then the array is accessed by the kernel. If the array has compound
3206 * elements then we skipped the construction of array reference groups.
3208 * The resulting sizes may be functions that are nowhere defined
3209 * in case the access function cannot possibly access anything inside
3210 * the kernel for some reason. If so, they are replaced by the zero
3211 * function. Since the access function cannot actually access anything,
3212 * there is no harm in printing the array sizes as zero.
3214 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3215 __isl_keep isl_set *host_domain)
3217 int i, j;
3218 isl_set *context;
3220 kernel->array = isl_calloc_array(gen->ctx,
3221 struct gpu_local_array_info, gen->prog->n_array);
3222 assert(kernel->array);
3223 kernel->n_array = gen->prog->n_array;
3225 context = isl_set_copy(host_domain);
3226 context = isl_set_params(context);
3228 for (i = 0; i < gen->prog->n_array; ++i) {
3229 struct gpu_array_info *array = &gen->prog->array[i];
3230 isl_pw_aff_list *local;
3232 if (array->n_group == 0 && !array->has_compound_element)
3233 continue;
3235 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3237 for (j = 0; j < array->n_index; ++j) {
3238 isl_pw_aff *pwaff;
3239 int empty;
3241 pwaff = isl_pw_aff_copy(array->bound[j]);
3242 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3243 empty = isl_pw_aff_is_empty(pwaff);
3244 if (empty < 0)
3245 pwaff = isl_pw_aff_free(pwaff);
3246 else if (empty)
3247 pwaff = set_universally_zero(pwaff);
3248 local = isl_pw_aff_list_add(local, pwaff);
3251 kernel->array[i].n_index = array->n_index;
3252 kernel->array[i].bound = local;
3254 isl_set_free(context);
3257 /* Find the element in gen->stmt that has the given "id".
3258 * Return NULL if no such gpu_stmt can be found.
3260 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3262 int i;
3264 for (i = 0; i < prog->n_stmts; ++i) {
3265 if (id == prog->stmts[i].id)
3266 break;
3269 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3272 /* Set gen->tile_len and gen->n_parallel to those of the statement
3273 * affected by the first map (part of the schedule)
3274 * on which this function is called.
3275 * Because of the way the schedule is constructed, the other statements
3276 * in the list, if any, should have the same values for these properties.
3278 static int extract_tile_len(__isl_take isl_map *map, void *user)
3280 struct gpu_gen *gen = (struct gpu_gen *) user;
3281 isl_id *id;
3282 struct gpu_stmt *stmt;
3284 id = isl_map_get_tuple_id(map, isl_dim_in);
3285 stmt = find_stmt(gen->prog, id);
3286 isl_id_free(id);
3288 isl_map_free(map);
3290 if (!stmt)
3291 isl_die(gen->ctx, isl_error_unknown,
3292 "statement not found", return -1);
3294 gen->tile_len = stmt->tile_len;
3295 gen->n_parallel = stmt->n_parallel;
3297 return -1;
3300 void ppcg_kernel_stmt_free(void *user)
3302 int i;
3303 struct ppcg_kernel_stmt *stmt = user;
3305 if (!stmt)
3306 return;
3308 switch (stmt->type) {
3309 case ppcg_kernel_copy:
3310 isl_ast_expr_free(stmt->u.c.index);
3311 isl_ast_expr_free(stmt->u.c.local_index);
3312 break;
3313 case ppcg_kernel_domain:
3314 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3315 break;
3316 case ppcg_kernel_sync:
3317 break;
3320 free(stmt);
3323 /* Set the options of "context" to
3325 * { space -> [x] : x >= first }
3327 static __isl_give isl_ast_build *set_unroll(
3328 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3329 int first)
3331 isl_ctx *ctx;
3332 isl_map *unroll;
3333 isl_union_map *opt;
3335 ctx = isl_ast_build_get_ctx(build);
3337 space = isl_space_from_domain(space);
3338 space = isl_space_add_dims(space, isl_dim_out, 1);
3339 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3340 unroll = isl_map_universe(space);
3341 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3342 opt = isl_union_map_from_map(unroll);
3344 build = isl_ast_build_set_options(build, opt);
3346 return build;
3349 /* Extend the schedule "schedule" with the part of "extension"
3350 * starting at "first" up to "len".
3352 static __isl_give isl_union_map *extend_schedule(
3353 __isl_take isl_union_map *schedule,
3354 __isl_take isl_union_map *extension, int first, int len)
3356 isl_space *space;
3357 isl_map *proj;
3358 isl_union_map *umap;
3359 isl_set *set;
3361 space = isl_union_map_get_space(schedule);
3362 space = isl_space_set_from_params(space);
3363 space = isl_space_add_dims(space, isl_dim_set, len);
3364 proj = isl_set_identity(isl_set_universe(space));
3365 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3366 extension = isl_union_map_apply_range(extension,
3367 isl_union_map_from_map(proj));
3369 schedule = isl_union_map_range_product(schedule, extension);
3371 return schedule;
3374 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3375 * to "ref_id".
3377 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3378 __isl_keep isl_id *ref_id)
3380 struct gpu_stmt_access *access;
3382 for (access = accesses; access; access = access->next)
3383 if (access->ref_id == ref_id)
3384 return access;
3386 return NULL;
3389 /* Return the index of the array called "name" in the list of arrays.
3391 static int find_array_index(struct gpu_gen *gen, const char *name)
3393 int i;
3395 for (i = 0; i < gen->prog->n_array; ++i)
3396 if (!strcmp(name, gen->prog->array[i].name))
3397 return i;
3399 return -1;
3402 /* Internal data structure for the index and AST expression transformation
3403 * callbacks for pet_stmt_build_ast_exprs.
3405 * "accesses" is the list of gpu_stmt_access in the statement.
3406 * "iterator_map" expresses the statement iterators in terms of
3407 * the AST loop iterators.
3408 * "sched2shared" expresses the first shared_len dimensions of
3409 * the computed schedule in terms of the AST loop iterators.
3411 * The following fields are set in transform_index and used in transform_expr.
3412 * "array" is the array that is being accessed.
3413 * "global" is set if the global array is accessed (rather than
3414 * shared/private memory).
3415 * "local_array" refers to information on the array specialized
3416 * to the current kernel.
3418 struct ppcg_transform_data {
3419 struct gpu_gen *gen;
3420 struct gpu_stmt_access *accesses;
3421 isl_pw_multi_aff *iterator_map;
3422 isl_pw_multi_aff *sched2shared;
3424 struct gpu_array_info *array;
3425 int global;
3426 struct gpu_local_array_info *local_array;
3429 /* Return the name of the outer array (of structs) accessed by "access".
3431 static const char *get_outer_array_name(__isl_keep isl_map *access)
3433 isl_space *space;
3434 const char *name;
3436 space = isl_space_range(isl_map_get_space(access));
3437 while (space && isl_space_is_wrapping(space))
3438 space = isl_space_domain(isl_space_unwrap(space));
3439 name = isl_space_get_tuple_name(space, isl_dim_set);
3440 isl_space_free(space);
3442 return name;
3445 /* Index transformation callback for pet_stmt_build_ast_exprs.
3447 * "index" expresses the array indices in terms of statement iterators
3449 * We first reformulate "index" in terms of the AST loop iterators.
3450 * Then we check if we are accessing the global array or
3451 * a shared/private copy. In the former case, we simply return
3452 * the updated index. If "index" is an affine expression rather
3453 * than an array access, then we also return the updated index here.
3455 * If no reference groups have been computed for the array,
3456 * then we can only be accessing the global array.
3458 * Otherwise, we apply the tiling to the index.
3459 * This tiling is of the form
3461 * [D -> A] -> T
3463 * The index is of the form
3465 * L -> A
3467 * We update the tiling to refer to the AST loop iterators
3469 * [L -> A] -> T
3471 * and modify index to keep track of those iterators
3473 * L -> [L -> A]
3475 * Combining these two yields a tiled index expression in terms
3476 * of the AST loop iterators
3478 * L -> T
3480 static __isl_give isl_multi_pw_aff *transform_index(
3481 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3482 void *user)
3484 struct ppcg_transform_data *data = user;
3485 struct gpu_stmt_access *access;
3486 struct gpu_array_ref_group *group;
3487 struct gpu_array_tile *tile;
3488 isl_pw_multi_aff *iterator_map;
3489 int i;
3490 const char *name;
3491 isl_space *space;
3492 isl_multi_pw_aff *tiling;
3493 isl_pw_multi_aff *pma;
3494 isl_multi_pw_aff *mpa;
3496 data->array = NULL;
3498 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3499 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3501 access = find_access(data->accesses, ref_id);
3502 if (!access)
3503 return index;
3504 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3505 return index;
3507 name = get_outer_array_name(access->access);
3508 i = find_array_index(data->gen, name);
3509 if (i < 0)
3510 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3511 "cannot find array",
3512 return isl_multi_pw_aff_free(index));
3513 data->array = &data->gen->prog->array[i];
3514 data->local_array = &data->gen->kernel->array[i];
3516 if (access->group < 0) {
3517 data->global = 1;
3518 return index;
3521 group = data->array->groups[access->group];
3522 tile = group->private_tile;
3523 if (!tile)
3524 tile = group->shared_tile;
3525 data->global = !tile;
3526 if (!tile)
3527 return index;
3529 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3530 space = isl_space_map_from_set(space);
3531 pma = isl_pw_multi_aff_identity(space);
3532 pma = isl_pw_multi_aff_product(
3533 isl_pw_multi_aff_copy(data->sched2shared), pma);
3534 tiling = isl_multi_pw_aff_from_multi_aff(
3535 isl_multi_aff_copy(tile->tiling));
3536 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3538 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3539 space = isl_space_map_from_set(space);
3540 mpa = isl_multi_pw_aff_identity(space);
3541 index = isl_multi_pw_aff_range_product(mpa, index);
3542 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3544 return index;
3547 /* Dereference "expr" by adding an index [0].
3548 * The original "expr" is assumed not to have any indices.
3550 * If "expr" is a member access, then the dereferencing needs
3551 * to be applied to the structure argument of this member access.
3553 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3555 isl_ctx *ctx;
3556 isl_ast_expr *arg0, *res;
3557 isl_ast_expr_list *list;
3559 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3560 if (!arg0)
3561 return isl_ast_expr_free(expr);
3562 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3563 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3564 isl_ast_expr *arg;
3566 arg = isl_ast_expr_get_op_arg(arg0, 0);
3567 arg = dereference(arg);
3568 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3569 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3571 return expr;
3573 isl_ast_expr_free(arg0);
3575 ctx = isl_ast_expr_get_ctx(expr);
3576 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3577 list = isl_ast_expr_list_from_ast_expr(res);
3578 res = isl_ast_expr_get_op_arg(expr, 0);
3579 res = isl_ast_expr_access(res, list);
3580 isl_ast_expr_free(expr);
3582 return res;
3585 /* Linearize the index expression "expr" based on the array bounds
3586 * of "array".
3588 * That is, transform expression
3590 * A[i_0][i_1]...[i_n]
3592 * to
3594 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3596 * where b_0, b_1, ..., b_n are the bounds on the array.
3598 * If the base of "expr" is a member access, then the linearization needs
3599 * to be applied to the structure argument of this member access.
3601 * In the base case, if "expr" has no arguments (other than the name of
3602 * the array), then we are passing an entire array to a function.
3603 * In this case, there is nothing to linearize.
3604 * Note that at this point an expression with no arguments can
3605 * only be an entire array because the scalar case and
3606 * the case of single struct are handled by the caller.
3608 * If the number of specified index expressions in "expr"
3609 * is smaller than the dimension of the accessed array,
3610 * then the missing i_j also do not appear in the linearized expression.
3611 * Furthermore, since such an expression does not refer to a single
3612 * element while the default linearized expression would refer to
3613 * a single element, we return the expression
3615 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
3617 * instead. Note that because of the special case handling above,
3618 * we can assume here that here that there is at least one index expression.
3620 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3621 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3623 int i, n;
3624 isl_ctx *ctx;
3625 isl_set *context;
3626 isl_ast_expr *arg0;
3627 isl_ast_expr *res;
3628 isl_ast_expr_list *list;
3629 isl_ast_build *build;
3631 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3632 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3633 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3634 isl_ast_expr *arg;
3636 arg = isl_ast_expr_get_op_arg(arg0, 0);
3637 arg = gpu_local_array_info_linearize_index(array, arg);
3638 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3639 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3641 return expr;
3643 isl_ast_expr_free(arg0);
3645 if (isl_ast_expr_get_op_n_arg(expr) == 1)
3646 return expr;
3648 ctx = isl_ast_expr_get_ctx(expr);
3649 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3650 build = isl_ast_build_from_context(context);
3652 n = isl_ast_expr_get_op_n_arg(expr);
3653 res = isl_ast_expr_get_op_arg(expr, 1);
3654 for (i = 1; i < array->n_index; ++i) {
3655 isl_pw_aff *bound_i;
3656 isl_ast_expr *expr_i;
3658 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
3659 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3660 res = isl_ast_expr_mul(res, expr_i);
3662 if (i + 1 >= n)
3663 continue;
3664 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
3665 res = isl_ast_expr_add(res, expr_i);
3668 isl_ast_build_free(build);
3670 if (1 + array->n_index > n) {
3671 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
3672 } else {
3673 list = isl_ast_expr_list_from_ast_expr(res);
3674 res = isl_ast_expr_get_op_arg(expr, 0);
3675 res = isl_ast_expr_access(res, list);
3678 isl_ast_expr_free(expr);
3680 return res;
3683 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3685 * If the AST expression refers to an array that is not accessed
3686 * at all, then this means the value of the expression is not used,
3687 * so we might as well print zero (NULL pointer) instead.
3689 * If the AST expression refers to a global scalar that is not
3690 * a read-only scalar, then its address was passed to the kernel and
3691 * we need to dereference it.
3693 * If the AST expression refers to an access to a global array,
3694 * then we linearize the access exploiting the bounds in data->local_array.
3696 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3697 __isl_keep isl_id *id, void *user)
3699 struct ppcg_transform_data *data = user;
3701 if (!data->array)
3702 return expr;
3703 if (!data->array->accessed) {
3704 isl_ctx *ctx;
3706 ctx = isl_ast_expr_get_ctx(expr);
3707 isl_ast_expr_free(expr);
3708 return isl_ast_expr_from_val(isl_val_zero(ctx));
3710 if (gpu_array_is_read_only_scalar(data->array))
3711 return expr;
3712 if (!data->global)
3713 return expr;
3714 if (data->array->n_index == 0)
3715 return dereference(expr);
3716 if (!data->array->linearize)
3717 return expr;
3719 return gpu_local_array_info_linearize_index(data->local_array, expr);
3722 /* This function is called for each instance of a user statement
3723 * in the kernel.
3725 * We attach a struct ppcg_kernel_stmt to the "node", containing
3726 * a computed AST expression for each access.
3727 * These AST expressions are computed from iterator_map,
3728 * which expresses the domain
3729 * elements in terms of the generated loops, and sched2shared,
3730 * which expresses the first shared_len dimensions of the schedule
3731 * computed by PPCG in terms of the generated loops.
3733 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3734 __isl_keep isl_ast_build *build, void *user)
3736 struct ppcg_transform_data data;
3737 struct gpu_gen *gen = (struct gpu_gen *) user;
3738 struct ppcg_kernel_stmt *stmt;
3739 isl_id *id;
3740 isl_pw_multi_aff *sched2shared;
3741 isl_map *map;
3742 isl_pw_multi_aff *iterator_map;
3743 isl_ast_expr *expr, *arg;
3744 isl_union_map *schedule;
3746 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3747 if (!stmt)
3748 return isl_ast_node_free(node);
3750 expr = isl_ast_node_user_get_expr(node);
3751 arg = isl_ast_expr_get_op_arg(expr, 0);
3752 id = isl_ast_expr_get_id(arg);
3754 schedule = isl_ast_build_get_schedule(build);
3755 map = isl_map_reverse(isl_map_from_union_map(schedule));
3756 iterator_map = isl_pw_multi_aff_from_map(map);
3757 sched2shared = compute_sched_to_shared(gen,
3758 isl_pw_multi_aff_copy(iterator_map));
3760 stmt->type = ppcg_kernel_domain;
3761 stmt->u.d.stmt = find_stmt(gen->prog, id);
3762 if (!stmt->u.d.stmt)
3763 isl_die(gen->ctx, isl_error_internal,
3764 "statement not found", goto error);
3766 data.gen = gen;
3767 data.accesses = stmt->u.d.stmt->accesses;
3768 data.iterator_map = iterator_map;
3769 data.sched2shared = sched2shared;
3770 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
3771 build, &transform_index, &data,
3772 &transform_expr, &data);
3774 isl_id_free(id);
3775 isl_pw_multi_aff_free(iterator_map);
3776 isl_pw_multi_aff_free(sched2shared);
3777 isl_ast_expr_free(arg);
3778 isl_ast_expr_free(expr);
3780 id = isl_id_alloc(gen->ctx, NULL, stmt);
3781 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3782 return isl_ast_node_set_annotation(node, id);
3783 error:
3784 isl_id_free(id);
3785 isl_pw_multi_aff_free(iterator_map);
3786 ppcg_kernel_stmt_free(stmt);
3787 isl_pw_multi_aff_free(sched2shared);
3788 return isl_ast_node_free(node);
3791 /* This function is called when code has been generated for the shared
3792 * tile loops. The "schedule" refers only to the original statements.
3794 * We extend the schedule with that part of gen->local_sched that hasn't
3795 * been taken into account yet. This introduces parameters referring
3796 * to thread ids in the schedule, so we add them (with the appropriate
3797 * bounds to the context as well).
3798 * Finally, we set the appropriate unrolling options
3799 * if gen->first_unroll is set.
3801 static __isl_give isl_ast_node *create_domain_leaf(
3802 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3803 void *user)
3805 struct gpu_gen *gen = (struct gpu_gen *) user;
3806 isl_space *space;
3807 isl_union_map *sched;
3808 isl_ast_node *tree;
3809 isl_set *set;
3810 isl_id_list *iterators;
3811 int n;
3813 schedule = extend_schedule(schedule,
3814 isl_union_map_copy(gen->local_sched),
3815 gen->shared_len, gen->thread_tiled_len);
3817 space = isl_ast_build_get_schedule_space(build);
3818 set = isl_set_universe(space);
3819 set = add_bounded_parameters(set, gen->kernel->block_dim,
3820 gen->kernel->thread_ids);
3821 build = isl_ast_build_restrict(build, set);
3823 n = gen->thread_tiled_len - gen->shared_len;
3825 if (gen->first_unroll >= 0) {
3826 space = isl_space_set_alloc(gen->ctx, 0, n);
3827 build = set_unroll(build, space, gen->first_unroll);
3829 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
3830 build = isl_ast_build_set_iterators(build, iterators);
3831 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3832 tree = isl_ast_build_node_from_schedule_map(build, schedule);
3833 isl_ast_build_free(build);
3835 return tree;
3838 /* This function is called for each statement node in the AST of the code
3839 * for copying to or from shared/private memory.
3840 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3841 * statement to the node.
3842 * The statement name is "read" or "write", depending on whether we are
3843 * reading from global memory or writing to global memory.
3844 * The name of the T space is {shared,private}_<array>.
3846 * The schedule is of the form
3848 * type[A -> T] -> L
3850 * where A refers to a piece of an array and T to the corresponding
3851 * shifted tile. We split this schedule into mappings L -> A and L -> T
3852 * and store the corresponding expressions in stmt->index and stmt->local_index,
3853 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3855 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3856 __isl_keep isl_ast_build *build, void *user)
3858 struct gpu_gen *gen = (struct gpu_gen *) user;
3859 struct ppcg_kernel_stmt *stmt;
3860 isl_id *id;
3861 isl_ast_expr *expr;
3862 isl_space *space;
3863 isl_map *access, *local_access, *map;
3864 isl_pw_multi_aff *pma;
3865 const char *type;
3866 int array_index;
3868 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3869 if (!stmt)
3870 return isl_ast_node_free(node);
3872 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3873 type = isl_map_get_tuple_name(access, isl_dim_in);
3874 stmt->u.c.read = !strcmp(type, "read");
3875 access = isl_map_reverse(access);
3876 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3877 local_access = isl_map_copy(access);
3879 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3880 id = isl_map_get_tuple_id(access, isl_dim_out);
3881 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3882 access = isl_map_apply_range(access, map);
3883 pma = isl_pw_multi_aff_from_map(access);
3884 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3885 stmt->u.c.index = expr;
3887 map = isl_map_range_map(isl_map_universe(space));
3888 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3889 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3890 local_access = isl_map_apply_range(local_access, map);
3891 pma = isl_pw_multi_aff_from_map(local_access);
3892 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
3893 stmt->u.c.local_index = expr;
3895 stmt->u.c.array = gen->copy_group->array;
3896 array_index = stmt->u.c.array - gen->prog->array;
3897 stmt->u.c.local_array = &gen->kernel->array[array_index];
3898 stmt->type = ppcg_kernel_copy;
3900 id = isl_id_alloc(gen->ctx, NULL, stmt);
3901 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3902 return isl_ast_node_set_annotation(node, id);
3905 /* Given a schedule of the form
3907 * [S -> A] -> L
3909 * (with S the first shared_len dimensions of the computed schedule,
3910 * A the array and L the schedule correponding to the generated loops),
3911 * indicating where to copy the array elements that need to be copied,
3912 * construct code for performing the copying.
3914 * "group" is the array reference group that is being copied
3915 * "type" is either "read" or "write"
3916 * private is set if copying needs to be performed to/from registers
3918 * We first construct a mapping to a shifted tile of the array,
3920 * [S -> A] -> T(S,A) (1)
3922 * If private is set, then we also use this mapping as a schedule
3923 * (which is already thread-specific and will be completely unrolled).
3924 * Otherwise, we wrap/tile the range over the threads.
3925 * The result is
3927 * [S -> A] -> T'(S,A)
3929 * Combined with the given schedule, we have
3931 * [S -> A] -> [L -> T'(S,A)] (2)
3933 * From the shifted tile mapping, we construct a mapping
3935 * [S -> A] -> [A -> T(S,A)]
3937 * and apply it to the schedule (2), obtaining
3939 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3941 * Note that we can project out S because it is uniquely defined by L.
3943 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3944 __isl_take isl_map *sched,
3945 const char *type, struct gpu_array_ref_group *group,
3946 __isl_take isl_ast_build *build, int private)
3948 isl_space *space;
3949 isl_ast_node *tree;
3950 isl_map *schedule, *shift, *map;
3951 isl_set *set;
3952 isl_id_list *iterators;
3953 int n;
3955 shift = shift_access(group);
3957 schedule = isl_map_copy(shift);
3958 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
3959 if (!private)
3960 schedule = tile_access_schedule(gen, schedule);
3962 n = isl_map_dim(schedule, isl_dim_out);
3963 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3964 set = add_bounded_parameters(set, gen->kernel->block_dim,
3965 gen->kernel->thread_ids);
3967 schedule = isl_map_range_product(sched, schedule);
3969 space = isl_space_domain(isl_map_get_space(shift));
3970 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3971 map = isl_map_range_product(map, shift);
3973 schedule = isl_map_apply_domain(schedule, map);
3975 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
3977 build = isl_ast_build_restrict(build, set);
3979 gen->copy_group = group;
3981 if (private) {
3982 space = isl_space_range(isl_map_get_space(schedule));
3983 space = isl_space_range(isl_space_unwrap(space));
3984 build = set_unroll(build, space, 0);
3986 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
3987 build = isl_ast_build_set_iterators(build, iterators);
3988 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3989 tree = isl_ast_build_node_from_schedule_map(build,
3990 isl_union_map_from_map(schedule));
3991 isl_ast_build_free(build);
3993 return tree;
3996 /* Return code for reading into or writing from shared memory
3997 * the given array reference group.
3999 * If we are performing a read from global memory to shared memory and
4000 * if the array involved is not a scalar, then we copy
4001 * the entire tile to shared memory. This may result in some extra
4002 * elements getting copied, but it should lead to simpler code
4003 * (which means that fewer registers may be needed) and less divergence.
4005 * Otherwise, we only copy the elements that will be read or have been written
4006 * in the kernel.
4009 * The input "sched" is of the form.
4011 * type[S -> A] -> L
4013 * with S the first shared_len dimensions of the computed schedule,
4014 * A the array and L the schedule correponding to the generated loops.
4016 * We first drop "type",
4018 * [S -> A] -> L
4020 * If the above conditions are satisfied, we project out A,
4021 * resulting in
4023 * S -> L
4025 * and then introduce the group tile [S -> T], resulting in
4027 * [S -> T] -> L
4029 static __isl_give isl_ast_node *copy_group_shared_accesses(
4030 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4031 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4033 const char *type;
4034 int read;
4035 isl_union_map *access;
4037 type = isl_map_get_tuple_name(sched, isl_dim_in);
4038 read = !strcmp(type, "read");
4040 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4042 if (read && !gpu_array_is_scalar(group->array)) {
4043 isl_space *space;
4044 isl_map *map;
4046 space = isl_space_domain(isl_map_get_space(sched));
4047 space = isl_space_unwrap(space);
4048 map = isl_map_domain_map(isl_map_universe(space));
4049 sched = isl_map_apply_domain(sched, map);
4051 map = group_tile(group);
4052 map = isl_map_reverse(isl_map_domain_map(map));
4053 sched = isl_map_apply_domain(sched, map);
4056 return copy_access(gen, sched, type, group, build, 0);
4059 /* Return code for reading into or writing from private memory
4060 * the given array reference group.
4062 * Let S be the first shared_len dimensions of the computed schedule,
4063 * D the iteration domains, A the array and L the schedule correponding
4064 * to the generated loops.
4065 * "sched" is of the form
4067 * type[S -> A] -> L
4069 * where type is either "read" or "write".
4070 * We apply the privatization D -> S(t), with t the thread ids,
4071 * to the access relation D -> A to obtain the privatized access relation
4073 * S(t) -> A
4075 * We drop the type from "sched" and intersect with the privatized access
4076 * relation to obtain
4078 * [S(t) -> A] -> L
4080 static __isl_give isl_ast_node *copy_group_private_accesses(
4081 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4082 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4084 const char *type;
4085 int read;
4086 isl_union_map *priv;
4087 isl_union_map *access;
4088 isl_map *access_map;
4090 type = isl_map_get_tuple_name(sched, isl_dim_in);
4091 read = !strcmp(type, "read");
4093 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4094 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4095 priv);
4097 access = group_access_relation(group, read, !read);
4098 access = isl_union_map_apply_domain(access, priv);
4099 access_map = isl_map_from_union_map(access);
4101 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4102 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4104 return copy_access(gen, sched, type, group, build, 1);
4107 /* Return code for reading into or writing from shared or private memory.
4109 * "schedule" is of the form
4111 * type[S -> A] -> L
4113 * with S be the first shared_len dimensions of the computed schedule,
4114 * A the array and L the schedule correponding to the generated loops.
4115 * The array reference group is attached to "type".
4117 static __isl_give isl_ast_node *create_access_leaf(
4118 struct gpu_gen *gen, __isl_take isl_map *schedule,
4119 __isl_take isl_ast_build *build)
4121 struct gpu_array_ref_group *group;
4122 isl_id *id;
4124 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4125 group = isl_id_get_user(id);
4126 isl_id_free(id);
4128 if (group->private_tile)
4129 return copy_group_private_accesses(gen, group, schedule,
4130 build);
4131 else
4132 return copy_group_shared_accesses(gen, group, schedule,
4133 build);
4136 /* Create a domain node representing a synchronization.
4138 static __isl_give isl_ast_node *create_sync_leaf(
4139 struct gpu_gen *gen, __isl_take isl_map *schedule,
4140 __isl_take isl_ast_build *build)
4142 struct ppcg_kernel_stmt *stmt;
4143 isl_id *id;
4144 isl_space *space;
4145 isl_ast_node *node;
4146 isl_ast_expr *expr;
4148 isl_map_free(schedule);
4150 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4151 if (!stmt)
4152 return NULL;
4154 stmt->type = ppcg_kernel_sync;
4156 space = isl_ast_build_get_schedule_space(build);
4157 space = isl_space_from_domain(space);
4158 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4159 expr = isl_ast_build_call_from_pw_multi_aff(build,
4160 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4161 node = isl_ast_node_alloc_user(expr);
4162 isl_ast_build_free(build);
4164 id = isl_id_alloc(gen->ctx, NULL, stmt);
4165 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4166 return isl_ast_node_set_annotation(node, id);
4169 /* This function is called during the code generation at the point
4170 * where the schedule domain element is completely determined by
4171 * the generated code. The input schedule contains the original
4172 * statements as well as synchronization and copy "statements".
4173 * The latter are scheduled at different points than any of the original
4174 * statements, so they will only arrive here in isolation.
4176 * If the current schedule only refers to a single statement,
4177 * we check if it is a copy or synchronization statement and
4178 * call the appropriate functions.
4179 * Otherwise, we assume we are dealing with the original statements
4180 * and we call create_domain_leaf.
4182 static __isl_give isl_ast_node *create_kernel_leaf(
4183 __isl_take isl_ast_build *build, void *user)
4185 struct gpu_gen *gen = (struct gpu_gen *) user;
4186 isl_map *map;
4187 isl_union_map *schedule;
4188 const char *name;
4190 schedule = isl_ast_build_get_schedule(build);
4192 if (isl_union_map_n_map(schedule) != 1)
4193 return create_domain_leaf(schedule, build, user);
4195 map = isl_map_from_union_map(schedule);
4196 name = isl_map_get_tuple_name(map, isl_dim_in);
4197 if (!strcmp(name, "read") || !strcmp(name, "write"))
4198 return create_access_leaf(gen, map, build);
4199 if (!strcmp(name, "sync"))
4200 return create_sync_leaf(gen, map, build);
4202 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4205 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4206 * have value 0) and all even schedule dimensions as "unroll".
4208 * That is, the options look as follows
4210 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4211 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4213 * The even positions are used to be able to schedule copying blocks
4214 * and synchronization before or after each level of the shared memory
4215 * tile loops and we want to make sure that code for these is generated
4216 * separately (within each level).
4218 static __isl_give isl_ast_build *set_atomic_and_unroll(
4219 __isl_take isl_ast_build *build,
4220 __isl_take isl_space *space, int sched_len)
4222 isl_ctx *ctx;
4223 isl_map *map;
4224 isl_constraint *c;
4225 isl_union_map *opt;
4226 isl_local_space *ls;
4227 int i, n;
4229 ctx = isl_ast_build_get_ctx(build);
4231 space = isl_space_params(space);
4232 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4233 space = isl_space_from_domain(space);
4234 space = isl_space_add_dims(space, isl_dim_out, 2);
4235 map = isl_map_universe(isl_space_copy(space));
4236 for (i = 0; i < sched_len; i += 2)
4237 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4238 ls = isl_local_space_from_space(isl_map_get_space(map));
4239 c = isl_equality_alloc(ls);
4240 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4241 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4242 c = isl_constraint_set_constant_si(c, 1);
4243 map = isl_map_add_constraint(map, c);
4244 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4245 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4246 opt = isl_union_map_from_map(map);
4248 map = isl_map_universe(space);
4249 ls = isl_local_space_from_space(isl_map_get_space(map));
4250 c = isl_equality_alloc(ls);
4251 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4252 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4253 map = isl_map_add_constraint(map, c);
4254 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4255 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4256 opt = isl_union_map_add_map(opt, map);
4258 build = isl_ast_build_set_options(build, opt);
4260 return build;
4263 /* Return a map that maps a space of dimension gen->shared_len
4264 * to its last dimensions starting at gen->tile_first.
4265 * The range is of dimension
4267 * 2 * (gen->shared_len - gen->tile_first) + 1
4269 * The input dimensions are mapped to the odd dimensions in the output,
4270 * while the even dimensions (except 2*pos) are fixed to 0.
4271 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4272 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4273 * are mapped to the output. The remaining input dimensions are projected
4274 * out and the corresponding output dimensions are fixed to 0.
4276 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4277 __isl_take isl_space *space, int pos, int val)
4279 int i, n;
4280 isl_map *proj;
4282 space = isl_space_set_from_params(space);
4283 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4284 space = isl_space_map_from_set(space);
4285 proj = isl_map_identity(space);
4286 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4287 n = gen->shared_len - gen->tile_first;
4288 for (i = 0; i <= n; ++i) {
4289 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4290 if (i == pos)
4291 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4292 else
4293 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4296 if (pos < 0)
4297 return proj;
4299 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4300 gen->shared_len - (gen->tile_first + pos));
4301 for (i = pos; i < n; ++i)
4302 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4304 return proj;
4307 /* Given the AST context schedule "schedule" and the mapping from
4308 * domains to the shared tile loops "shared_sched", add a schedule
4309 * for a synchronization operation at position "val" of loop level "pos".
4311 * schedule is of the form
4313 * D -> L
4315 * (with D the iteration domains and L the already generated loops),
4316 * while shared_sched is of the form
4318 * D -> S
4320 * We combine them into
4322 * L -> S
4324 * apply a mapping
4326 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4328 * and use the result as a schedule for "sync".
4330 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4331 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4332 __isl_keep isl_union_map *shared_sched, int pos, int val)
4334 isl_space *space;
4335 isl_map *proj, *map;
4337 shared_sched = isl_union_map_copy(shared_sched);
4338 schedule = isl_union_map_copy(schedule);
4340 space = isl_union_map_get_space(shared_sched);
4341 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4342 map = isl_map_from_union_map(schedule);
4344 proj = insert_even(gen, space, pos, val);
4345 map = isl_map_apply_range(map, proj);
4346 map = isl_map_from_range(isl_map_wrap(map));
4347 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4349 res = isl_union_map_add_map(res, map);
4351 return res;
4354 /* Given a set of wrapped references "ref", return the corresponding
4355 * access relations based on the tagged access relations "tagged".
4357 * The elements of "ref" are of the form
4359 * [D -> R]
4361 * with D an iteration domains and R a reference.
4362 * The elements of "tagged" are of the form
4364 * [D -> R] -> A
4366 * with A an array.
4368 * Extend "tagged" to include the iteration domain in the range, i.e.,
4370 * [D -> R] -> [D -> A]
4372 * apply the result to "ref" and then unwrap the resulting set
4373 * to obtain relations of the form
4375 * D -> A
4377 static __isl_give isl_union_map *wrapped_reference_to_access(
4378 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4380 isl_union_map *tag2access;
4382 tag2access = isl_union_map_copy(tagged);
4383 tag2access = isl_union_map_universe(tag2access);
4384 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4385 tag2access = isl_union_map_domain_map(tag2access);
4386 tag2access = isl_union_map_range_product(tag2access, tagged);
4388 ref = isl_union_set_coalesce(ref);
4389 ref = isl_union_set_apply(ref, tag2access);
4391 return isl_union_set_unwrap(ref);
4394 /* Given an access relation "access" from "group", remove those reads
4395 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4396 * communicate data within the same iteration of the last_shared dimension
4397 * of the group.
4399 * If the access is a read then it is either an element of
4401 * live_in union (range flow)
4403 * where live_in and flow may be overapproximations, or
4404 * it reads an uninitialized value (that is not live-in because
4405 * there is an intermediate kill) or it reads a value that was
4406 * written within the same (compound) statement instance.
4407 * If the access is a write then it is either an element of
4409 * live_out union (domain flow)
4411 * or it writes a value that is never read (and is not live-out
4412 * because of an intermediate kill) or only
4413 * within the same (compound) statement instance.
4414 * In both cases, the access relation is also a subset of
4415 * the group access relation.
4417 * The cases where an uninitialized value is read or a value is written
4418 * that is never read or where the dataflow occurs within a statement
4419 * instance are also considered local and may also be removed.
4421 * Essentially, we compute the intersection of "access" with either
4423 * live_in union (range non-local-flow)
4425 * or
4427 * live_out union (domain non-local-flow)
4429 * We first construct a relation "local"
4431 * [[D -> R] -> [D' -> R']]
4433 * of pairs of domain iterations accessing the reference group
4434 * and references in the group that are scheduled to the same iteration
4435 * of the last_shared dimension.
4437 * If this relation does not intersect the dataflow dependences,
4438 * then there is nothing we can possibly remove, unless the dataflow
4439 * dependences themselves only relate a subset of the accesses.
4440 * In particular, the accesses may not be involved in any dataflow
4441 * dependences, either because they are uninitialized reads/dead writes
4442 * or because the dataflow occurs inside a statement instance.
4444 * Since the computation below may break up the access relation
4445 * into smaller pieces, we only perform the intersection with
4446 * the non-local dependent accesses if the local pairs
4447 * intersect the dataflow dependences. Otherwise, we intersect
4448 * with the universe of the non-local dependent accesses.
4449 * This should at least remove accesses from statements that
4450 * do not participate in any dependences.
4452 * In particular, we remove the "local" dataflow dependences from
4453 * the set of all dataflow dependences.
4454 * Note that if the potential dataflow dependences are an overapproximation
4455 * of the actual dataflow dependences, then the result remains an
4456 * overapproximation of the non-local dataflow dependences.
4457 * Copying to/from global memory is only needed for the references
4458 * in the domain/range of the result or for accesses that are live out/in
4459 * for the entire scop.
4461 * We therefore map the domain/range of the "external" relation
4462 * to the corresponding access relation and take the union with
4463 * the live out/in relation.
4465 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4466 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4467 int read)
4469 int empty;
4470 isl_union_pw_multi_aff *tagger;
4471 isl_union_set *domain;
4472 isl_space *space;
4473 isl_union_map *sched, *local, *tagged, *external;
4474 isl_union_set *tag_set;
4475 isl_map *proj;
4477 if (isl_union_map_is_empty(access))
4478 return access;
4480 tagged = group_tagged_access_relation(group);
4482 sched = isl_union_map_copy(gen->sched);
4484 space = isl_union_map_get_space(sched);
4485 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4486 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4488 tagger = isl_union_pw_multi_aff_copy(gen->prog->scop->tagger);
4489 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4490 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
4491 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
4493 local = isl_union_map_apply_range(sched,
4494 isl_union_map_reverse(isl_union_map_copy(sched)));
4495 local = isl_union_map_intersect(local,
4496 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4498 empty = isl_union_map_is_empty(local);
4500 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4501 external = isl_union_map_intersect_params(external,
4502 isl_set_copy(gen->prog->scop->context));
4503 external = isl_union_map_subtract(external, local);
4505 if (read) {
4506 tag_set = isl_union_map_range(external);
4507 external = wrapped_reference_to_access(tag_set, tagged);
4508 external = isl_union_map_union(external,
4509 isl_union_map_copy(gen->prog->scop->live_in));
4510 } else {
4511 tag_set = isl_union_map_domain(external);
4512 external = wrapped_reference_to_access(tag_set, tagged);
4513 external = isl_union_map_union(external,
4514 isl_union_map_copy(gen->prog->scop->live_out));
4517 if (empty < 0)
4518 external = isl_union_map_free(external);
4519 else if (empty)
4520 external = isl_union_map_universe(external);
4522 access = isl_union_map_intersect(access, external);
4524 return access;
4527 /* Given the AST context schedule "schedule" and the mapping from
4528 * domains to the shared tile loops "shared_sched", add a schedule
4529 * for copying an array reference group to/from shared/private memory.
4530 * "read" is set if data should be copied from global memory
4531 * to shared/private memory.
4532 * "k" represents the current group
4533 * "s" is the total number of groups
4535 * We schedule an operation before or after the innermost loop
4536 * of "shared_sched" that affects the tile of the array reference group.
4538 * schedule is of the form
4540 * D -> L
4542 * (with D the iteration domains and L the already generated loops),
4543 * while shared_sched is of the form
4545 * D -> S
4547 * We first compute the access relation for the reference group
4549 * D -> A
4551 * and remove from this access relation those reads or writes
4552 * that only needed to communicate data within the same iteration
4553 * of the last_shared dimension of the group.
4554 * We then combine what is left with shared_sched into
4556 * D -> [S -> A]
4558 * If this results in an empty relation, no copying needs to be performed
4559 * at this point.
4560 * Otherwise, we invert the relation and combine it with "schedule" into
4562 * [S -> A] -> L
4564 * The actual additional piece of the schedule is obtained from combining
4566 * [S -> A] -> S
4568 * with a mapping
4570 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4572 * The position of "val" corresponds to the innermost loop that affects
4573 * the tile and the value indicates where the copying is scheduled
4574 * with respect to the actual kernel code (at value 0).
4575 * Reads are schedule before the code, writes to global memory from
4576 * private memory are scheduled at values 1 to s, writes to global
4577 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4579 * If we are scheduling a read from global memory to shared memory,
4580 * we insert a synchronization before the kernel code (at the innermost
4581 * level).
4582 * If we are scheduling a write to global memory, then we add
4583 * a synchronization after all writes (at value 2 *s + 2).
4584 * However, there is no need for a synchronization after the outermost loop.
4585 * A write to global memory from private memory at the innermost level
4586 * does not require a synchronization, because it is covered by
4587 * the synchronization after the kernel inserted by body_schedule.
4589 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4590 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4591 __isl_keep isl_union_map *shared_sched,
4592 struct gpu_array_ref_group *group, int read, int k, int s)
4594 int n;
4595 int pos, val;
4596 isl_space *space;
4597 isl_union_map *access;
4598 isl_map *map, *proj, *access_map;
4599 isl_id *id;
4601 access = group_access_relation(group, read, !read);
4602 access = remove_local_accesses(gen, group, access, read);
4603 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4604 access);
4606 if (isl_union_map_is_empty(access)) {
4607 isl_union_map_free(access);
4608 return res;
4611 access = isl_union_map_reverse(access);
4612 access = isl_union_map_apply_range(access,
4613 isl_union_map_copy(schedule));
4614 access_map = isl_map_from_union_map(access);
4616 space = isl_space_copy(group->array->space);
4617 space = isl_space_from_range(space);
4618 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4619 map = isl_map_domain_map(isl_map_universe(space));
4621 space = isl_union_map_get_space(schedule);
4622 pos = group->last_shared + 1 - gen->tile_first;
4623 assert(pos >= 0);
4624 if (read)
4625 val = -2 - k;
4626 else if (group->private_tile)
4627 val = 1 + k;
4628 else
4629 val = 1 + s + 1 + k;
4630 proj = insert_even(gen, space, pos, val);
4631 map = isl_map_apply_range(map, proj);
4633 access_map = isl_map_range_product(access_map, map);
4635 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4636 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4638 res = isl_union_map_add_map(res, access_map);
4640 n = gen->shared_len - gen->tile_first;
4641 if (read) {
4642 if (!group->private_tile)
4643 res = add_sync_schedule(gen, res, schedule,
4644 shared_sched, n, -1);
4645 } else {
4646 if (pos == 0)
4647 return res;
4648 if (pos == n && group->private_tile)
4649 return res;
4650 res = add_sync_schedule(gen, res, schedule, shared_sched,
4651 pos, 2 * s + 2);
4654 return res;
4657 /* Return a schedule for the shared tile loops based on the current
4658 * AST context schedule.
4660 * We create a "shared_sched" that maps the domains to the first
4661 * shared_len dimensions of the computed schedule, project out the
4662 * first tile_first dimensions (as these are already covered by
4663 * the host code) and insert "statement-level" dimensions at even
4664 * positions so that we can schedule copy blocks and synchronization
4665 * before/after each level.
4667 * In particular, copy blocks are inserted inside the innermost
4668 * level that affect the tile. For the copying to global memory,
4669 * those from private memory are scheduled before those from shared
4670 * memory such that synchronization can be inserted between the two
4671 * at the innermost level.
4672 * Synchronization is inserted at the innermost level before the
4673 * actual kernel code if there is any copying from global memory
4674 * to shared memory. It is inserted unconditionally at the innermost
4675 * level after the actual kernel code and the copying to global memory
4676 * from private memory (if any). Finally, it is inserted after
4677 * any copying to global memory, except at the outermost level
4678 * and at the innermost level if there is no copying from shared
4679 * memory. The copying from private memory is covered by the unconditional
4680 * synchronization at the innermost level.
4682 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4683 __isl_take isl_union_map *schedule)
4685 isl_space *space;
4686 isl_union_map *res;
4687 isl_union_map *shared_sched;
4688 isl_union_map *sched;
4689 isl_map *proj, *map;
4690 int i, j, k, s;
4692 shared_sched = isl_union_map_copy(gen->tiled_sched);
4693 proj = projection(isl_union_map_get_space(shared_sched),
4694 gen->tiled_len, gen->shared_len);
4695 shared_sched = isl_union_map_apply_range(shared_sched,
4696 isl_union_map_from_map(proj));
4697 space = isl_union_map_get_space(shared_sched);
4698 proj = insert_even(gen, space, -1, 0);
4699 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4700 isl_union_map_from_map(proj));
4702 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4704 s = 0;
4705 for (i = 0; i < gen->prog->n_array; ++i)
4706 s += gen->prog->array[i].n_group;
4708 k = 0;
4709 for (i = 0; i < gen->prog->n_array; ++i) {
4710 struct gpu_array_info *array = &gen->prog->array[i];
4712 for (j = 0; j < array->n_group; ++j) {
4713 struct gpu_array_ref_group *group;
4715 group = array->groups[j];
4716 if (!group->private_tile && !group->shared_tile)
4717 continue;
4718 res = add_group_schedule(gen, res, schedule,
4719 shared_sched, group, 0, k, s);
4720 res = add_group_schedule(gen, res, schedule,
4721 shared_sched, group, 1, k, s);
4722 ++k;
4726 res = add_sync_schedule(gen, res, schedule, shared_sched,
4727 gen->shared_len - gen->tile_first, 1 + s);
4729 isl_union_map_free(shared_sched);
4730 isl_union_map_free(schedule);
4732 return res;
4735 /* Generate code for "kernel" in the given "context".
4737 * We first generate code for the shared tile loops (T1T, T1P and T2)
4738 * in a context that includes the block ids.
4739 * Within each iteration of these loops an additional code generation
4740 * is performed (within create_kernel_leaf) for the rest of the schedule
4741 * in a context that includes the thread ids.
4743 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4744 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4745 __isl_keep isl_multi_pw_aff *grid_size)
4747 isl_space *space;
4748 isl_set *set;
4749 isl_id_list *iterators;
4750 isl_union_map *schedule;
4751 isl_ast_node *tree;
4752 int sched_len;
4754 schedule = isl_ast_build_get_schedule(build);
4756 build = isl_ast_build_copy(build);
4757 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4758 space = isl_ast_build_get_schedule_space(build);
4759 set = isl_set_universe(isl_space_copy(space));
4760 set = add_bounded_parameters_dynamic(set, grid_size,
4761 gen->kernel->block_ids);
4762 build = isl_ast_build_restrict(build, set);
4764 schedule = body_schedule(gen, schedule);
4766 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4768 build = set_atomic_and_unroll(build, space, sched_len);
4769 iterators = ppcg_scop_generate_names(gen->prog->scop, sched_len, "g");
4770 build = isl_ast_build_set_iterators(build, iterators);
4771 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4772 tree = isl_ast_build_node_from_schedule_map(build, schedule);
4773 isl_ast_build_free(build);
4775 return tree;
4778 /* Attach "id" to the given node.
4780 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4781 __isl_keep isl_ast_build *build, void *user)
4783 isl_id *id = user;
4785 node = isl_ast_node_set_annotation(node, id);
4787 return node;
4790 /* Construct an AST node for performing a kernel launch and attach
4791 * the information about the kernel to that node.
4793 * The kernel AST has been constructed in the context of the range
4794 * of "schedule". In particular, the grid size has been computed
4795 * in the context. We therefore still need to make sure that these
4796 * constraints are expressed in the code. We do this by creating a schedule
4798 * kernel[] -> [S -> []]
4800 * where S is the schedule domain, i.e., the range of "schedule".
4801 * The AST generation will then create a single call surrounded by
4802 * all the condition in "S" that have not been expressed yet.
4804 * The kernel information is attached to this node in attach_id.
4806 static __isl_give isl_ast_node *construct_launch(
4807 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4808 __isl_take struct ppcg_kernel *kernel)
4810 isl_id *id;
4811 isl_ctx *ctx;
4812 isl_union_set *domain;
4813 isl_set *set;
4814 isl_map *map;
4815 isl_ast_node *node;
4817 ctx = isl_ast_build_get_ctx(build);
4819 id = isl_id_alloc(ctx, NULL, kernel);
4820 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4822 domain = isl_union_map_range(schedule);
4823 set = isl_set_from_union_set(domain);
4824 map = isl_map_from_domain(set);
4825 map = isl_map_from_range(isl_map_wrap(map));
4826 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4827 schedule = isl_union_map_from_map(map);
4829 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4830 node = isl_ast_build_node_from_schedule_map(build, schedule);
4831 isl_ast_build_free(build);
4833 return node;
4836 /* This function is called for each leaf in the AST of the host code.
4837 * We first specialize the schedule to the site of the leaf, compute
4838 * the size of shared memory and then construct the body of the host code
4839 * and the associated kernel.
4841 * The necessary information for printing the kernel launch is
4842 * stored in a struct ppcg_kernel and attached to the leaf node
4843 * created to represent the launch.
4845 static __isl_give isl_ast_node *create_host_leaf(
4846 __isl_take isl_ast_build *build, void *user)
4848 struct gpu_gen *gen = (struct gpu_gen *) user;
4849 isl_id *id;
4850 isl_ast_node *node;
4851 struct ppcg_kernel *kernel;
4852 isl_set *host_domain;
4853 isl_union_map *schedule;
4854 isl_union_map *local_sched;
4855 isl_union_map *access;
4856 isl_union_set *domain;
4857 int i;
4859 schedule = isl_ast_build_get_schedule(build);
4861 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4862 read_sizes(gen);
4864 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4866 local_sched = isl_union_map_copy(gen->sched);
4867 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4868 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4869 isl_union_map_copy(gen->prog->may_write));
4870 access = isl_union_map_apply_domain(access,
4871 isl_union_map_copy(local_sched));
4873 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4874 if (!kernel)
4875 goto error;
4876 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
4877 gen->n_grid, "b");
4878 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
4879 gen->n_block, "t");
4881 gen->tiled_sched = tile_schedule(gen, local_sched);
4882 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4883 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4885 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4886 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4887 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4889 kernel->id = gen->kernel_id++;
4890 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4891 kernel->grid_size = extract_grid_size(gen, kernel);
4892 extract_block_size(gen, kernel);
4893 kernel->arrays = isl_union_map_range(access);
4894 kernel->arrays = isl_union_set_apply(kernel->arrays,
4895 isl_union_map_copy(gen->prog->to_outer));
4896 kernel->space = isl_ast_build_get_schedule_space(build);
4898 compute_shared_sched(gen);
4899 gen->privatization = compute_privatization(gen);
4900 check_scalar_live_ranges(gen);
4901 if (group_references(gen) < 0)
4902 schedule = isl_union_map_free(schedule);
4903 host_domain = isl_set_from_union_set(isl_union_map_range(
4904 isl_union_map_copy(schedule)));
4905 localize_bounds(gen, kernel, host_domain);
4907 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4908 check_shared_memory_bound(gen);
4909 compute_group_tilings(gen);
4911 kernel->tree = generate_kernel(gen, build, host_domain,
4912 kernel->grid_size);
4913 create_kernel_vars(gen, kernel);
4915 free_local_array_info(gen);
4916 isl_map_free(gen->privatization);
4917 isl_union_map_free(gen->local_sched);
4918 isl_union_map_free(gen->tiled_sched);
4919 isl_union_map_free(gen->shared_sched);
4920 isl_union_map_free(gen->shared_proj);
4921 isl_set_free(host_domain);
4922 free(gen->tile_size);
4924 node = construct_launch(build, schedule, kernel);
4926 return node;
4927 error:
4928 isl_union_map_free(schedule);
4929 return NULL;
4932 /* Use isl to generate code for the outer gen->tile_first loops
4933 * of the global schedule in gen->sched, resulting in the host code.
4934 * Within each iteration of this partial schedule, i.e., for each kernel
4935 * launch, create_host_leaf takes care of generating the kernel code.
4937 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4939 isl_ast_build *build;
4940 isl_ast_node *tree;
4941 isl_union_map *sched;
4942 isl_map *proj;
4943 isl_id_list *iterators;
4945 sched = isl_union_map_copy(gen->sched);
4946 proj = projection(isl_union_map_get_space(sched),
4947 gen->untiled_len, gen->tile_first);
4948 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4950 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4951 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4952 iterators = ppcg_scop_generate_names(gen->prog->scop,
4953 gen->tile_first, "h");
4954 build = isl_ast_build_set_iterators(build, iterators);
4955 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4956 tree = isl_ast_build_node_from_schedule_map(build, sched);
4957 isl_ast_build_free(build);
4959 return tree;
4962 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4964 if (!str)
4965 return NULL;
4966 return isl_union_map_read_from_str(ctx, str);
4969 /* Information about the outermost tilable bands in the forest of bands.
4971 * tile_len and n_parallel are only sets on band_info structures
4972 * that correspond to outermost bands. For other bands (in particular,
4973 * ancestors of the outermost bands), n_parallal is set to 0.
4975 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4977 * tile_first is the number of schedule dimensions in prefix.
4979 * suffix is the schedule of the outermost tilable bands and their descendants.
4981 struct band_info {
4982 struct gpu_gen *gen;
4983 int tile_first;
4984 int tile_len;
4985 int n_parallel;
4986 isl_union_map *prefix;
4987 isl_union_map *suffix;
4990 /* Set tile_len and n_parallel of the statement to that of
4991 * their outermost band, recorded in the band_info.
4993 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4995 struct band_info *info = user;
4996 struct gpu_stmt *stmt;
4997 isl_id *id;
4999 id = isl_map_get_tuple_id(map, isl_dim_in);
5000 stmt = find_stmt(info->gen->prog, id);
5001 isl_id_free(id);
5003 stmt->tile_len = info->tile_len;
5004 stmt->n_parallel = info->n_parallel;
5006 isl_map_free(map);
5008 return 0;
5011 static void select_outer_band(struct gpu_gen *gen,
5012 __isl_take isl_schedule_node *node, int pos, struct band_info *info);
5014 /* Check if this band node is tilable and has any parallel loops. If so,
5015 * take it as the outermost tilable band. If not, continue looking for the
5016 * outermost tilable band in the children of the current band.
5018 static void band_select_outer_band(struct gpu_gen *gen,
5019 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
5021 int n = isl_schedule_node_band_n_member(node);
5022 int n_parallel;
5024 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5025 if (!isl_schedule_node_band_member_get_coincident(node,
5026 n_parallel))
5027 break;
5029 if (!isl_schedule_node_band_get_permutable(node) || n_parallel == 0) {
5030 node = isl_schedule_node_child(node, 0);
5031 select_outer_band(gen, node, pos + n, info);
5032 return;
5035 info->n_parallel = n_parallel;
5036 gen->any_parallelism = 1;
5037 info->gen = gen;
5038 info->tile_first = pos;
5039 info->tile_len = n;
5040 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
5041 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
5042 isl_union_map_foreach_map(info->prefix, &set_stmt_tile_len, info);
5044 isl_schedule_node_free(node);
5047 /* Comparison function that returns a non-zero value for band_infos
5048 * with different tile_len fields or different n_parallel fields.
5050 static int cmp_band(const void *p1, const void *p2)
5052 const struct band_info *info1 = p1;
5053 const struct band_info *info2 = p2;
5055 if (info1->tile_len != info2->tile_len)
5056 return info1->tile_len - info2->tile_len;
5058 return info1->n_parallel - info2->n_parallel;
5061 /* Extend "umap" with coordinates with fixed value "val"
5062 * to a total length of "dst_len", assuming the original dimension is "src_len".
5064 static __isl_give isl_union_map *extend_range(
5065 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5067 isl_space *dim;
5068 isl_map *map;
5069 int i;
5071 dim = isl_union_map_get_space(umap);
5072 map = isl_map_reverse(projection(dim, dst_len, src_len));
5073 for (i = src_len; i < dst_len; ++i)
5074 map = isl_map_fix_si(map, isl_dim_out, i, val);
5076 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5078 return umap;
5081 /* Insert a new dimension at position "pos" in the range of "umap"
5082 * with fixed value "val", assuming the original dimension of the range
5083 * of "umap" is "src_len".
5085 static __isl_give isl_union_map *insert_range(__isl_take isl_union_map *umap,
5086 int src_len, int pos, int val)
5088 isl_space *space;
5089 isl_map *map;
5091 space = isl_union_map_get_space(umap);
5092 map = project_out(space, src_len + 1, pos, 1);
5093 map = isl_map_reverse(map);
5094 map = isl_map_fix_si(map, isl_dim_out, pos, val);
5096 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5098 return umap;
5101 /* Group bands with the same values for tile_len and n_parallel.
5102 * The prefix schedule is then extended with a fixed coordinate that
5103 * is different for each such group.
5104 * Note that the actual values for this coordinate are not important.
5105 * The bands have already been effectively separated at a higher level
5106 * or they are independent and may be executed in parallel.
5107 * The list of band_info has been sorted before this functions is called.
5109 static void separate_bands(struct band_info *info, int n)
5111 int i;
5112 int j = 0;
5114 for (i = 0; i < n; ++i) {
5115 int l = info[i].tile_first;
5117 if (i &&
5118 (info[i].tile_len != info[i - 1].tile_len ||
5119 info[i].n_parallel != info[i - 1].n_parallel))
5120 j++;
5122 info[i].prefix = extend_range(info[i].prefix,
5123 l, l + 1, j);
5124 info[i].tile_first = l + 1;
5128 /* Select the outermost bands in the elements of the sequence or set
5129 * node "node", align their prefix schedules. Separate all bands
5130 * if "serialize" is set and otherwise separate bands with different values
5131 * for tile_len and/or n_parallel. Finally, combine the resulting
5132 * prefix and suffix schedules into a single pair of prefix and
5133 * suffix schedules for the entire list.
5135 static void list_select_outer_band(struct gpu_gen *gen,
5136 __isl_take isl_schedule_node *node, int pos,
5137 struct band_info *list_info, int serialize)
5139 int i;
5140 int n = isl_schedule_node_n_children(node);
5141 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
5142 struct band_info *info;
5143 int max_tile_first;
5144 isl_union_map *prefix;
5145 isl_union_map *suffix;
5147 assert(n >= 1);
5148 info = isl_calloc_array(ctx, struct band_info, n);
5149 assert(info);
5151 max_tile_first = 0;
5152 for (i = 0; i < n; ++i) {
5153 isl_schedule_node *child;
5154 child = isl_schedule_node_get_child(node, i);
5155 select_outer_band(gen, child, pos, &info[i]);
5156 if (info[i].tile_first > max_tile_first)
5157 max_tile_first = info[i].tile_first;
5160 for (i = 0; i < n; ++i) {
5161 if (info[i].tile_first == max_tile_first)
5162 continue;
5163 info[i].prefix = extend_range(info[i].prefix,
5164 info[i].tile_first, max_tile_first, 0);
5165 info[i].tile_first = max_tile_first;
5168 if (serialize) {
5169 for (i = 0; i < n; ++i) {
5170 int l = info[i].tile_first;
5171 info[i].prefix = insert_range(info[i].prefix, l,
5172 pos, i);
5173 info[i].tile_first = l + 1;
5175 } else {
5176 qsort(info, n, sizeof(struct band_info), &cmp_band);
5178 for (i = 0; i < n - 1; ++i)
5179 if (info[i].tile_len != info[i + 1].tile_len ||
5180 info[i].n_parallel != info[i + 1].n_parallel)
5181 break;
5183 if (i < n - 1)
5184 separate_bands(info, n);
5187 prefix = info[0].prefix;
5188 suffix = info[0].suffix;
5190 for (i = 1; i < n; ++i) {
5191 prefix = isl_union_map_union(prefix, info[i].prefix);
5192 suffix = isl_union_map_union(suffix, info[i].suffix);
5195 list_info->tile_first = info[0].tile_first;
5196 list_info->tile_len = -1;
5197 list_info->prefix = prefix;
5198 list_info->suffix = suffix;
5200 isl_schedule_node_free(node);
5201 free(info);
5204 /* Select the outermost bands in the elements of the set node "node".
5205 * If the schedule_separate_components is set, then separate all bands.
5207 static void set_select_outer_band(struct gpu_gen *gen,
5208 __isl_take isl_schedule_node *node, int pos,
5209 struct band_info *list_info)
5211 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
5212 int serialize;
5214 serialize = isl_options_get_schedule_separate_components(ctx);
5215 list_select_outer_band(gen, node, pos, list_info, serialize);
5218 /* Select the outermost bands in the elements of the sequence node "node",
5219 * separating all bands.
5221 static void sequence_select_outer_band(struct gpu_gen *gen,
5222 __isl_take isl_schedule_node *node, int pos,
5223 struct band_info *list_info)
5225 list_select_outer_band(gen, node, pos, list_info, 1);
5228 /* If we reach a leaf node, then we have not found any outer tilable
5229 * band with parallel loops, so consider the leaf node as the outermost
5230 * tilable band.
5232 static void leaf_select_outer_band(struct gpu_gen *gen,
5233 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
5235 info->gen = gen;
5236 info->tile_first = pos;
5237 info->tile_len = 0;
5238 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
5239 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
5240 isl_union_map_foreach_map(info->prefix, &set_stmt_tile_len, info);
5242 isl_schedule_node_free(node);
5245 /* Select the outermost tilable band in the subtree that "node" points to.
5247 static void select_outer_band(struct gpu_gen *gen,
5248 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
5250 enum isl_schedule_node_type type;
5252 type = isl_schedule_node_get_type(node);
5253 switch (type) {
5254 case isl_schedule_node_domain:
5255 case isl_schedule_node_filter:
5256 node = isl_schedule_node_child(node, 0);
5257 select_outer_band(gen, node, pos, info);
5258 return;
5259 case isl_schedule_node_leaf:
5260 leaf_select_outer_band(gen, node, pos, info);
5261 return;
5262 case isl_schedule_node_band:
5263 band_select_outer_band(gen, node, pos, info);
5264 return;
5265 case isl_schedule_node_set:
5266 set_select_outer_band(gen, node, pos, info);
5267 return;
5268 case isl_schedule_node_sequence:
5269 sequence_select_outer_band(gen, node, pos, info);
5270 return;
5271 default:
5272 isl_die(isl_schedule_node_get_ctx(node),
5273 isl_error_unsupported, "unhandled schedule node type",
5274 node = node);
5275 case isl_schedule_node_error:
5276 info->prefix = NULL;
5277 info->suffix = NULL;
5278 break;
5281 isl_schedule_node_free(node);
5284 /* Select the outermost tilable band that (by construction)
5285 * has at least one parallel loop.
5286 * The starting position of the aligned band is stored in the pair
5287 * gen->tile_first.
5288 * The sizes and number of parallel loops may be different in different
5289 * parts of the band forest and are therefore stored in the gpu_stmts.
5291 * Return the complete schedule, with the tilable bands aligned
5292 * at gen->tile_first and padded with zero, if needed.
5294 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5295 __isl_keep isl_schedule *schedule)
5297 isl_schedule_node *node;
5298 struct band_info info;
5300 gen->n_parallel = 0;
5301 gen->tile_len = -1;
5303 node = isl_schedule_get_root(schedule);
5304 select_outer_band(gen, node, 0, &info);
5306 gen->tile_first = info.tile_first;
5307 info.suffix = align_range(info.suffix);
5309 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5312 /* Set gen->untiled_len to the number of scheduling dimensions
5313 * for the schedule of the first domain.
5314 * We assume here that this number is the same for all domains.
5316 static int set_untiled_len(__isl_take isl_map *map, void *user)
5318 unsigned *untiled_len = user;
5320 *untiled_len = isl_map_dim(map, isl_dim_out);
5322 isl_map_free(map);
5323 return -1;
5326 /* Compute an appropriate schedule based on the accesses in
5327 * gen->read and gen->write.
5329 * We use the dependences in gen->prog->scop to compute
5330 * a schedule that has a parallel loop in each tilable band.
5331 * Finally, we select the outermost tilable band.
5333 * If live range reordering is allowed, then we need to make sure
5334 * that live ranges on arrays are not run in parallel since doing
5335 * so would require array expansion. We therefore add the array
5336 * order dependences to the coincidence dependences. Non-zero array
5337 * order dependences will then prevent a schedule dimension from being
5338 * considered parallel.
5339 * Live ranges derived from scalars are allowed to be run in parallel
5340 * since we force the scalars to be mapped to private memory in
5341 * check_scalar_live_ranges.
5342 * If live range reordering is allowed, then the false dependences
5343 * are not added to the validity constraints as that would prevent
5344 * reordering. Instead, the external false dependences that enforce that reads
5345 * from potentially live-in data precede any later write and
5346 * that writes of potentially live-out data follow any other earlier write
5347 * are added to the validity and the coincidence constraints.
5348 * The false dependences are still added to the proximity constraints
5349 * for consistency with the case where live range reordering is not allowed.
5350 * The coincidence constraints then consist of flow dependences,
5351 * external false dependences and array order dependences.
5352 * The independences can be filtered out from the first two sets.
5353 * They have already been filtered out from the array order dependences
5354 * on a per array basis in collect_order_dependences.
5355 * There is no need for a per array handling of the other two sets
5356 * as there should be no flow or external false dependence on local
5357 * variables that can be filtered out.
5359 static void compute_schedule(struct gpu_gen *gen)
5361 isl_union_set *domain;
5362 isl_union_map *dep_raw, *dep;
5363 isl_union_map *validity, *proximity, *coincidence;
5364 isl_union_map *sched;
5365 isl_schedule_constraints *sc;
5366 isl_schedule *schedule;
5368 domain = isl_union_set_copy(gen->prog->scop->domain);
5369 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5370 sc = isl_schedule_constraints_set_context(sc,
5371 isl_set_copy(gen->prog->scop->context));
5372 if (gen->options->live_range_reordering) {
5373 sc = isl_schedule_constraints_set_conditional_validity(sc,
5374 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5375 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5376 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5377 validity = isl_union_map_copy(proximity);
5378 validity = isl_union_map_union(validity,
5379 isl_union_map_copy(gen->prog->scop->dep_external));
5380 proximity = isl_union_map_union(proximity,
5381 isl_union_map_copy(gen->prog->scop->dep_false));
5382 coincidence = isl_union_map_copy(validity);
5383 coincidence = isl_union_map_subtract(coincidence,
5384 isl_union_map_copy(gen->prog->scop->independence));
5385 coincidence = isl_union_map_union(coincidence,
5386 isl_union_map_copy(gen->prog->array_order));
5387 } else {
5388 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5389 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5390 dep = isl_union_map_union(dep, dep_raw);
5391 dep = isl_union_map_coalesce(dep);
5392 proximity = isl_union_map_copy(dep);
5393 coincidence = isl_union_map_copy(dep);
5394 validity = dep;
5396 sc = isl_schedule_constraints_set_validity(sc, validity);
5397 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5398 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5400 if (gen->options->debug->dump_schedule_constraints)
5401 isl_schedule_constraints_dump(sc);
5402 schedule = isl_schedule_constraints_compute_schedule(sc);
5403 if (gen->options->debug->dump_schedule)
5404 isl_schedule_dump(schedule);
5406 sched = select_outer_tilable_band(gen, schedule);
5408 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5409 sched = isl_union_map_intersect_domain(sched, domain);
5410 gen->sched = sched;
5412 isl_schedule_free(schedule);
5415 /* Compute the sets of outer array elements that need to be copied in and out.
5417 * In particular, for each array that is possibly written anywhere in
5418 * gen->prog and that is visible outside the corresponding scop,
5419 * we copy out its entire extent.
5421 * Any array elements that is read without first being written needs
5422 * to be copied in. Furthermore, if there are any array elements that
5423 * are copied out, but that may not be written inside gen->prog, then
5424 * they also need to be copied in to ensure that the value after execution
5425 * is the same as the value before execution, at least for those array
5426 * elements that may have their values preserved by the scop.
5427 * In case the array elements are structures, we need to take into
5428 * account that all members of the structures need to be written
5429 * by gen->prog before we can avoid copying the data structure in.
5431 * While computing the set of array elements that are copied out but
5432 * not necessarily written, we intersect both sets with the context.
5433 * This helps in those cases where the arrays are declared with a fixed size,
5434 * while the accesses are parametric and the context assigns a fixed value
5435 * to the parameters.
5437 * If an element from a local array is read without first being written,
5438 * then there is no point in copying it in since it cannot have been
5439 * written prior to the scop. Warn about the uninitialized read instead.
5441 static void compute_copy_in_and_out(struct gpu_gen *gen)
5443 int i;
5444 isl_union_set *local;
5445 isl_union_set *may_write, *must_write;
5446 isl_union_set *copy_in, *copy_out;
5447 isl_union_set *not_written;
5448 isl_union_map *uninitialized;
5449 isl_union_map *local_uninitialized;
5451 must_write = isl_union_map_range(
5452 isl_union_map_copy(gen->prog->must_write));
5453 must_write = isl_union_set_intersect_params(must_write,
5454 isl_set_copy(gen->prog->context));
5455 may_write = isl_union_map_range(
5456 isl_union_map_copy(gen->prog->may_write));
5457 may_write = isl_union_set_intersect_params(may_write,
5458 isl_set_copy(gen->prog->context));
5459 may_write = isl_union_set_universe(may_write);
5460 may_write = isl_union_set_apply(may_write,
5461 isl_union_map_copy(gen->prog->to_outer));
5462 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5463 local = isl_union_set_copy(copy_out);
5465 for (i = 0; i < gen->prog->n_array; ++i) {
5466 isl_space *space;
5467 isl_set *write_i;
5468 int empty;
5470 space = isl_space_copy(gen->prog->array[i].space);
5472 if (gen->prog->array[i].local) {
5473 isl_set *set;
5475 set = isl_set_universe(space);
5476 local = isl_union_set_add_set(local, set);
5477 continue;
5480 write_i = isl_union_set_extract_set(may_write, space);
5481 empty = isl_set_plain_is_empty(write_i);
5482 isl_set_free(write_i);
5483 if (empty)
5484 continue;
5486 write_i = isl_set_copy(gen->prog->array[i].extent);
5487 copy_out = isl_union_set_add_set(copy_out, write_i);
5489 isl_union_set_free(may_write);
5491 copy_out = isl_union_set_intersect_params(copy_out,
5492 isl_set_copy(gen->prog->context));
5494 gen->prog->copy_out = isl_union_set_copy(copy_out);
5496 copy_out = isl_union_set_apply(copy_out,
5497 isl_union_map_copy(gen->prog->to_inner));
5498 copy_out = isl_union_set_intersect(copy_out,
5499 isl_union_set_copy(gen->prog->may_persist));
5500 not_written = isl_union_set_subtract(copy_out, must_write);
5502 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5503 local_uninitialized = isl_union_map_copy(uninitialized);
5505 local = isl_union_set_apply(local,
5506 isl_union_map_copy(gen->prog->to_inner));
5507 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5508 local);
5509 if (!isl_union_map_is_empty(local_uninitialized)) {
5510 fprintf(stderr,
5511 "possibly uninitialized reads (not copied in):\n");
5512 isl_union_map_dump(local_uninitialized);
5514 uninitialized = isl_union_map_subtract(uninitialized,
5515 local_uninitialized);
5516 copy_in = isl_union_map_range(uninitialized);
5517 copy_in = isl_union_set_union(copy_in, not_written);
5518 copy_in = isl_union_set_apply(copy_in,
5519 isl_union_map_copy(gen->prog->to_outer));
5521 gen->prog->copy_in = copy_in;
5524 /* Internal data structure for extract_access.
5525 * "next_access" points to the end of a linked list that is extended
5526 * by extract_access.
5527 * "single_expression" is set if the access expressions belong to
5528 * an expression statement (i.e., a statement without internal control).
5529 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5531 struct ppcg_extract_access_data {
5532 struct gpu_stmt_access **next_access;
5533 int single_expression;
5534 isl_union_map *any_to_outer;
5537 /* Given a tagged access relation to a single array "tagged", extract it
5538 * as a map, taking into account that the input may be empty.
5539 * If the access relation is empty, then it does not contain
5540 * any space information, so we try to recover it from the index
5541 * expression.
5542 * The space of the index expression is of the form I -> A,
5543 * with I the statement instances and A the array, or [I -> F] -> A,
5544 * with F the filters corresponding to arguments.
5545 * We first drop F, if present, obtaining I -> A.
5546 * Then we construct I -> R, with R the reference tag,
5547 * combine the two into I -> [R -> A] and uncurry to obtain
5548 * the final result [I -> R] -> A.
5549 * Note that the index expression may have a lower dimension
5550 * than that of the array, but this dimension is not used
5551 * if the access relation is empty.
5553 static __isl_give isl_map *extract_single_tagged_access(
5554 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5556 int empty;
5557 isl_id *id;
5558 isl_space *space, *space2;
5559 isl_multi_pw_aff *index;
5561 empty = isl_union_map_is_empty(tagged);
5562 if (empty < 0)
5563 goto error;
5564 if (!empty)
5565 return isl_map_from_union_map(tagged);
5566 isl_union_map_free(tagged);
5568 index = pet_expr_access_get_index(expr);
5569 space = isl_multi_pw_aff_get_space(index);
5570 isl_multi_pw_aff_free(index);
5571 if (isl_space_domain_is_wrapping(space))
5572 space = isl_space_domain_factor_domain(space);
5573 space2 = isl_space_copy(space);
5574 space2 = isl_space_from_domain(isl_space_domain(space));
5575 id = pet_expr_access_get_ref_id(expr);
5576 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5577 space = isl_space_range_product(space2, space);
5578 space = isl_space_uncurry(space);
5580 return isl_map_empty(space);
5581 error:
5582 isl_union_map_free(tagged);
5583 return NULL;
5586 /* Extract a gpu_stmt_access from "expr", append it to the list
5587 * that ends in *data->next_access and update the end of the list.
5588 * If the access expression performs a write, then it is considered
5589 * exact only if it appears in a single expression statement and
5590 * if its may access relation is equal to its must access relation.
5592 * The combined set of may accesses may be union if member accesses
5593 * are involved, but the entire set is derived from a single reference and
5594 * therefore from a single index expression. These accesses therefore
5595 * all map to the same outer array.
5597 static int extract_access(__isl_keep pet_expr *expr, void *user)
5599 struct ppcg_extract_access_data *data = user;
5600 isl_union_map *tagged;
5601 struct gpu_stmt_access *access;
5602 isl_ctx *ctx = pet_expr_get_ctx(expr);
5603 isl_multi_pw_aff *index;
5605 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5606 assert(access);
5607 access->next = NULL;
5608 access->read = pet_expr_access_is_read(expr);
5609 access->write = pet_expr_access_is_write(expr);
5610 tagged = pet_expr_access_get_tagged_may_read(expr);
5611 tagged = isl_union_map_union(tagged,
5612 pet_expr_access_get_tagged_may_write(expr));
5613 tagged = isl_union_map_apply_range(tagged,
5614 isl_union_map_copy(data->any_to_outer));
5615 if (!access->write) {
5616 access->exact_write = 1;
5617 } else if (!data->single_expression) {
5618 access->exact_write = 0;
5619 } else {
5620 isl_union_map *must, *may;
5621 may = isl_union_map_copy(tagged);
5622 may = isl_union_map_domain_factor_domain(may);
5623 must = pet_expr_access_get_must_write(expr);
5624 access->exact_write = isl_union_map_is_equal(must, may);
5625 isl_union_map_free(must);
5626 isl_union_map_free(may);
5628 index = pet_expr_access_get_index(expr);
5629 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5630 isl_multi_pw_aff_free(index);
5631 access->ref_id = pet_expr_access_get_ref_id(expr);
5632 access->group = -1;
5633 access->tagged_access = extract_single_tagged_access(tagged, expr);
5634 access->access = isl_map_copy(access->tagged_access);
5635 access->access = isl_map_domain_factor_domain(access->access);
5637 *data->next_access = access;
5638 data->next_access = &(*data->next_access)->next;
5640 if (!access->access)
5641 return -1;
5643 return 0;
5646 /* Construct a linked list of gpu_stmt_access objects,
5647 * one for each access expression in the statement body.
5648 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5650 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5651 __isl_keep isl_union_map *any_to_outer)
5653 struct ppcg_extract_access_data data;
5655 stmt->accesses = NULL;
5656 data.next_access = &stmt->accesses;
5657 data.single_expression =
5658 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5659 data.any_to_outer = any_to_outer;
5660 return pet_tree_foreach_access_expr(stmt->stmt->body,
5661 &extract_access, &data);
5664 /* Return an array of gpu_stmt representing the statements in "scop".
5666 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5667 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5669 int i;
5670 struct gpu_stmt *stmts;
5672 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5673 if (!stmts)
5674 return NULL;
5676 for (i = 0; i < scop->pet->n_stmt; ++i) {
5677 struct gpu_stmt *s = &stmts[i];
5679 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5680 s->stmt = scop->pet->stmts[i];
5681 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5682 return free_stmts(stmts, i + 1);
5685 return stmts;
5688 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5690 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5692 struct gpu_gen *gen = user;
5694 return gen->print(p, gen->prog, gen->tree, &gen->types,
5695 gen->print_user);
5698 /* Generate CUDA code for "scop" and print it to "p".
5699 * After generating an AST for the transformed scop as explained below,
5700 * we call "gen->print" to print the AST in the desired output format
5701 * to "p".
5703 * If it turns out that it does not make sense to generate GPU code,
5704 * then we generate CPU code instead.
5706 * The GPU code is generated in a context where at least one
5707 * statement instance is executed. The corresponding guard (if any) is printed
5708 * around the entire generated GPU code, except for the declaration
5709 * of the arrays that are visible outside of the scop and that therefore
5710 * cannot be declared inside the body of any possible guard.
5712 * We first compute a schedule that respects the dependences
5713 * of the original program and select the outermost band
5714 * of tilable dimensions that has at least one parallel loop.
5715 * We then have three blocks of dimensions
5717 * H B G
5719 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5720 * in
5722 * H T P G
5724 * For each iteration of the T loop and for each array, we compute
5725 * the array elements accessed by that iteration, construct a rectangular
5726 * box around it and shift it to the origin. The result is used
5727 * as shared memory for the array.
5729 * We then split off at most 2 parallel loops from the T loops and
5730 * at most 3 parallel loops from the P loops
5732 * H T1 T2 P1 P2 G
5734 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5735 * according to "grid"/"block" sizes.
5737 * H T1T T1P T2 P1T P1P P2 G
5739 * Finally, the T1P and P1P iterators are equated to the block and
5740 * thread dimensions respectively and so are effectively removed.
5741 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5742 * are run on the GPU.
5744 * Code is generated in three stages. We first generate code for the
5745 * host (the H loops), with iterators h%d. Then, for each leaf node
5746 * of the resulting AST, we generate code for the shared loops (up to
5747 * and including T2), with iterators g%d and after equating the H loops
5748 * to h%d parameters and the T1P loops to the block dimensions.
5749 * Finally, we generate code for the remaining loops in a similar fashion.
5751 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5752 struct gpu_gen *gen, struct ppcg_scop *scop,
5753 struct ppcg_options *options)
5755 struct gpu_prog *prog;
5756 isl_ctx *ctx;
5757 isl_set *context, *guard;
5759 if (!scop)
5760 return isl_printer_free(p);
5762 ctx = isl_printer_get_ctx(p);
5763 prog = gpu_prog_alloc(ctx, scop);
5764 if (!prog)
5765 return isl_printer_free(p);
5767 context = isl_set_copy(prog->context);
5768 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5769 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5771 gen->prog = prog;
5772 gen->any_parallelism = 0;
5773 compute_schedule(gen);
5775 if (!gen->any_parallelism) {
5776 isl_set_free(context);
5777 isl_set_free(guard);
5778 p = print_cpu(p, scop, options);
5779 } else {
5780 compute_copy_in_and_out(gen);
5781 gen->tree = generate_host_code(gen);
5782 p = ppcg_print_exposed_declarations(p, prog->scop);
5783 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5784 isl_ast_node_free(gen->tree);
5787 isl_union_map_free(gen->sched);
5789 gpu_prog_free(prog);
5791 return p;
5794 /* Wrapper around generate for use as a ppcg_transform callback.
5796 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5797 struct ppcg_scop *scop, void *user)
5799 struct gpu_gen *gen = user;
5801 return generate(p, gen, scop, gen->options);
5804 /* Transform the code in the file called "input" by replacing
5805 * all scops by corresponding GPU code and write the results to "out".
5807 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5808 struct ppcg_options *options,
5809 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5810 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5811 struct gpu_types *types, void *user), void *user)
5813 struct gpu_gen gen;
5814 int r;
5815 int i;
5817 gen.ctx = ctx;
5818 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5819 gen.options = options;
5820 gen.kernel_id = 0;
5821 gen.print = print;
5822 gen.print_user = user;
5823 gen.types.n = 0;
5824 gen.types.name = NULL;
5826 if (options->debug->dump_sizes) {
5827 isl_space *space = isl_space_params_alloc(ctx, 0);
5828 gen.used_sizes = isl_union_map_empty(space);
5831 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5833 if (options->debug->dump_sizes) {
5834 isl_union_map_dump(gen.used_sizes);
5835 isl_union_map_free(gen.used_sizes);
5838 isl_union_map_free(gen.sizes);
5839 for (i = 0; i < gen.types.n; ++i)
5840 free(gen.types.name[i]);
5841 free(gen.types.name);
5843 return r;
5846 /* Compute the set of inner array elements that may have their values
5847 * preserved by "prog". In particular, collect the array elements of
5848 * arrays that are not local to "prog" and remove those elements that
5849 * are definitely killed or definitely written by "prog".
5851 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5853 int i;
5854 isl_union_set *may_persist, *killed;
5855 isl_union_map *must_kill;
5857 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5858 for (i = 0; i < prog->n_array; ++i) {
5859 isl_set *extent;
5861 if (prog->array[i].local)
5862 continue;
5864 extent = isl_set_copy(prog->array[i].extent);
5865 may_persist = isl_union_set_add_set(may_persist, extent);
5868 may_persist = isl_union_set_intersect_params(may_persist,
5869 isl_set_copy(prog->context));
5870 may_persist = isl_union_set_apply(may_persist,
5871 isl_union_map_copy(prog->to_inner));
5872 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5873 killed = isl_union_map_range(must_kill);
5874 must_kill = isl_union_map_copy(prog->must_write);
5875 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5877 may_persist = isl_union_set_subtract(may_persist, killed);
5878 return may_persist;
5881 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5883 struct gpu_prog *prog;
5884 isl_space *space;
5885 isl_map *id;
5887 if (!scop)
5888 return NULL;
5890 prog = isl_calloc_type(ctx, struct gpu_prog);
5891 assert(prog);
5893 prog->ctx = ctx;
5894 prog->scop = scop;
5895 prog->context = isl_set_copy(scop->context);
5896 prog->n_stmts = scop->pet->n_stmt;
5897 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5898 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5899 space = isl_union_map_get_space(prog->any_to_outer);
5900 space = isl_space_set_from_params(space);
5901 space = isl_space_add_dims(space, isl_dim_set, 1);
5902 space = isl_space_map_from_set(space);
5903 id = isl_map_identity(space);
5904 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5905 prog->stmts = extract_stmts(ctx, scop,
5906 prog->context, prog->any_to_outer);
5907 prog->read = isl_union_map_copy(scop->reads);
5908 prog->may_write = isl_union_map_copy(scop->may_writes);
5909 prog->must_write = isl_union_map_copy(scop->must_writes);
5910 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5911 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5912 prog->to_outer = isl_union_map_copy(prog->to_inner);
5913 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5915 if (!prog->stmts)
5916 return gpu_prog_free(prog);
5918 if (collect_array_info(prog) < 0)
5919 return gpu_prog_free(prog);
5920 prog->may_persist = compute_may_persist(prog);
5922 return prog;
5925 void *gpu_prog_free(struct gpu_prog *prog)
5927 if (!prog)
5928 return NULL;
5929 free_array_info(prog);
5930 free_stmts(prog->stmts, prog->n_stmts);
5931 isl_union_map_free(prog->any_to_outer);
5932 isl_union_map_free(prog->to_outer);
5933 isl_union_map_free(prog->to_inner);
5934 isl_union_set_free(prog->copy_in);
5935 isl_union_set_free(prog->copy_out);
5936 isl_union_map_free(prog->read);
5937 isl_union_map_free(prog->may_write);
5938 isl_union_map_free(prog->must_write);
5939 isl_union_map_free(prog->tagged_must_kill);
5940 isl_union_map_free(prog->array_order);
5941 isl_union_set_free(prog->may_persist);
5942 isl_set_free(prog->context);
5943 free(prog);
5944 return NULL;