gpu: mark all ancestor nodes of kernels as atomic
[ppcg.git] / gpu.c
blob2f0f3c7f6cbf51799fabee6b81279f7e0235f650
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 "gpu_group.h"
31 #include "schedule.h"
32 #include "ppcg_options.h"
33 #include "print.h"
35 struct gpu_array_info;
37 /* Collect all references to the given array and store pointers to them
38 * in array->refs.
40 * If the array contains structures, then there is no need to collect
41 * the references since we will not be computing any reference groups.
43 static void collect_references(struct gpu_prog *prog,
44 struct gpu_array_info *array)
46 int i;
47 int n;
49 if (array->has_compound_element)
50 return;
52 n = 0;
53 for (i = 0; i < prog->n_stmts; ++i) {
54 struct gpu_stmt *stmt = &prog->stmts[i];
55 struct gpu_stmt_access *access;
57 for (access = stmt->accesses; access; access = access->next) {
58 const char *name;
59 name = isl_map_get_tuple_name(access->access,
60 isl_dim_out);
61 if (name && !strcmp(array->name, name))
62 n++;
66 array->n_ref = n;
67 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
68 assert(array->refs);
70 n = 0;
71 for (i = 0; i < prog->n_stmts; ++i) {
72 struct gpu_stmt *stmt = &prog->stmts[i];
73 struct gpu_stmt_access *access;
75 for (access = stmt->accesses; access; access = access->next) {
76 const char *name;
77 name = isl_map_get_tuple_name(access->access,
78 isl_dim_out);
79 if (!name || strcmp(array->name, name))
80 continue;
82 array->refs[n++] = access;
87 /* Compute and return the extent of "array", taking into account the set of
88 * accessed elements.
90 * In particular, the extent in the outer dimension is taken
91 * from "accessed", while the extents in the remaining dimensions
92 * are taken from array->extent.
94 * The extent in the outer dimension cannot be taken from array->extent
95 * because that may be unbounded. Furthermore, even if it is bounded,
96 * it may be larger than the piece of the array that is being accessed.
98 static __isl_give isl_set *compute_extent(struct pet_array *array,
99 __isl_keep isl_set *accessed)
101 int n_index;
102 isl_id *id;
103 isl_set *outer;
104 isl_set *extent;
106 extent = isl_set_copy(array->extent);
108 n_index = isl_set_dim(accessed, isl_dim_set);
109 if (n_index == 0)
110 return extent;
112 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
113 outer = isl_set_copy(accessed);
114 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
115 extent = isl_set_flat_product(outer, extent);
116 id = isl_set_get_tuple_id(accessed);
117 extent = isl_set_set_tuple_id(extent, id);
119 return extent;
122 /* Is the array "array" being extracted a read-only scalar?
124 * That is, is "array" a scalar that is never possibly written to.
125 * An array containing structures is never considered to be a scalar.
127 static int is_read_only_scalar(struct gpu_array_info *array,
128 struct gpu_prog *prog)
130 isl_set *space;
131 isl_union_map *write;
132 int empty;
134 if (array->has_compound_element)
135 return 0;
136 if (array->n_index != 0)
137 return 0;
139 write = isl_union_map_copy(prog->may_write);
140 space = isl_set_universe(isl_space_copy(array->space));
141 write = isl_union_map_intersect_range(write,
142 isl_union_set_from_set(space));
143 empty = isl_union_map_is_empty(write);
144 isl_union_map_free(write);
146 return empty;
149 /* Compute bounds on the host array "pa" based on the corresponding
150 * accessed elements in "arrays"
151 * and collect all references to the array.
152 * Store the results in "info".
154 * If the array is zero-dimensional and does not contain structures,
155 * i.e., if the array is a scalar, we check whether it is read-only.
156 * We also check whether the array is accessed at all.
158 static int extract_array_info(struct gpu_prog *prog,
159 struct gpu_array_info *info, struct pet_array *pa,
160 __isl_keep isl_union_set *arrays)
162 int i, empty;
163 const char *name;
164 int n_index;
165 isl_pw_aff **bounds;
166 isl_set *accessed, *extent;
168 n_index = isl_set_dim(pa->extent, isl_dim_set);
169 name = isl_set_get_tuple_name(pa->extent);
170 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index);
171 if (!bounds)
172 return -1;
174 info->space = isl_set_get_space(pa->extent);
175 info->name = strdup(name);
176 info->n_index = n_index;
177 info->bound = bounds;
178 info->linearize = prog->scop->options->linearize_device_arrays;
180 info->type = strdup(pa->element_type);
181 info->size = pa->element_size;
182 info->local = pa->declared && !pa->exposed;
183 info->has_compound_element = pa->element_is_record;
184 info->read_only_scalar = is_read_only_scalar(info, prog);
186 accessed = isl_union_set_extract_set(arrays,
187 isl_space_copy(info->space));
188 empty = isl_set_is_empty(accessed);
189 extent = compute_extent(pa, accessed);
190 isl_set_free(accessed);
191 info->extent = extent;
192 if (empty < 0)
193 return -1;
194 info->accessed = !empty;
195 for (i = 0; i < n_index; ++i) {
196 isl_set *dom;
197 isl_local_space *ls;
198 isl_aff *one;
199 isl_pw_aff *bound;
201 dom = isl_set_copy(extent);
202 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
203 n_index - (i + 1));
204 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
205 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
206 fprintf(stderr, "unable to determine extent of '%s' "
207 "in dimension %d\n", info->name, i);
208 dom = isl_set_free(dom);
210 bound = isl_set_dim_max(dom, 0);
211 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
212 ls = isl_local_space_from_space(isl_set_get_space(dom));
213 one = isl_aff_zero_on_domain(ls);
214 one = isl_aff_add_constant_si(one, 1);
215 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
216 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
218 bounds[i] = bound;
219 if (!isl_pw_aff_is_cst(bound))
220 info->linearize = 1;
223 collect_references(prog, info);
225 return 0;
228 /* Remove independence from the order constraints "order" on array "array".
229 * Since the pairs of iterations in the filter relation of an independence
230 * are guaranteed to be completely independent by the user, there is
231 * no need to ensure that live ranges are ordered along thong pairs.
232 * We make an exception for local variables, though, as the independence
233 * guarantee does not apply to those.
235 * The order constraints are used in two places.
236 * Those on scalars are used in check_scalar_live_ranges to check if
237 * we need to force the scalar to be private. Any non-local scalar
238 * should not be forced scalar if it only appears in independent loops.
239 * Those on non-scalars are added to the coincidence constraints
240 * in compute_schedule because we do not support any array expansion.
241 * Accesses to non-local arrays should not prevent a loop from being
242 * considered coincident so we should indeed remove those constraints
243 * from the order constraints.
245 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
246 struct gpu_array_info *array, __isl_take isl_union_map *order)
248 int i;
250 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
251 struct pet_independence *pi = prog->scop->pet->independences[i];
252 if (isl_union_set_contains(pi->local, array->space))
253 continue;
255 order = isl_union_map_subtract(order,
256 isl_union_map_copy(pi->filter));
259 return order;
262 /* For each array in "prog", store the (untagged) order dependences
263 * derived from the array in array->dep_order.
264 * In particular, consider all references that access the given array
265 * and take the order dependences that have one of these references
266 * as source. (Since an order dependence relates two references to
267 * the same array, the target of these order dependences will also
268 * be one of these references.)
269 * Additionally, store the union of these array->dep_order relations
270 * for all non-scalar arrays in prog->array_order.
272 void collect_order_dependences(struct gpu_prog *prog)
274 int i;
275 isl_space *space;
276 isl_union_map *accesses;
278 space = isl_union_map_get_space(prog->read);
279 prog->array_order = isl_union_map_empty(space);
281 accesses = isl_union_map_copy(prog->scop->tagged_reads);
282 accesses = isl_union_map_union(accesses,
283 isl_union_map_copy(prog->scop->tagged_may_writes));
284 accesses = isl_union_map_universe(accesses);
285 accesses = isl_union_map_apply_range(accesses,
286 isl_union_map_copy(prog->to_outer));
288 for (i = 0; i < prog->n_array; ++i) {
289 struct gpu_array_info *array = &prog->array[i];
290 isl_set *set;
291 isl_union_set *uset;
292 isl_union_map *order;
294 set = isl_set_universe(isl_space_copy(array->space));
295 uset = isl_union_set_from_set(set);
296 uset = isl_union_map_domain(
297 isl_union_map_intersect_range(isl_union_map_copy(accesses),
298 uset));
299 order = isl_union_map_copy(prog->scop->tagged_dep_order);
300 order = isl_union_map_intersect_domain(order, uset);
301 order = isl_union_map_zip(order);
302 order = isl_union_set_unwrap(isl_union_map_domain(order));
303 order = remove_independences(prog, array, order);
304 array->dep_order = order;
306 if (gpu_array_is_scalar(array) && !array->has_compound_element)
307 continue;
309 prog->array_order = isl_union_map_union(prog->array_order,
310 isl_union_map_copy(array->dep_order));
313 isl_union_map_free(accesses);
316 /* Construct a gpu_array_info for each array referenced by prog->scop and
317 * collect them in prog->array.
319 * The sizes are based on the extents and the set of possibly accessed
320 * elements by "prog".
321 * If there are any member accesses involved, then they are first mapped
322 * to the outer arrays of structs.
324 * If we are allowing live range reordering, then also set
325 * the dep_order field. Otherwise leave it NULL.
327 static int collect_array_info(struct gpu_prog *prog)
329 int i;
330 int r = 0;
331 isl_union_set *arrays;
333 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
334 arrays = isl_union_set_union(arrays,
335 isl_union_map_range(isl_union_map_copy(prog->may_write)));
337 arrays = isl_union_set_apply(arrays,
338 isl_union_map_copy(prog->to_outer));
340 arrays = isl_union_set_coalesce(arrays);
342 prog->n_array = prog->scop->pet->n_array;
343 prog->array = isl_calloc_array(prog->ctx,
344 struct gpu_array_info, prog->n_array);
345 assert(prog->array);
346 for (i = 0; i < prog->scop->pet->n_array; ++i)
347 if (extract_array_info(prog, &prog->array[i],
348 prog->scop->pet->arrays[i], arrays) < 0)
349 r = -1;
351 isl_union_set_free(arrays);
353 if (prog->scop->options->live_range_reordering)
354 collect_order_dependences(prog);
356 return r;
359 static void free_array_info(struct gpu_prog *prog)
361 int i, j;
363 for (i = 0; i < prog->n_array; ++i) {
364 int n_index = prog->array[i].n_index;
365 free(prog->array[i].type);
366 free(prog->array[i].name);
367 for (j = 0; j < n_index; ++j)
368 isl_pw_aff_free(prog->array[i].bound[j]);
369 isl_space_free(prog->array[i].space);
370 isl_set_free(prog->array[i].extent);
371 free(prog->array[i].bound);
372 free(prog->array[i].refs);
373 isl_union_map_free(prog->array[i].dep_order);
375 free(prog->array);
378 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
379 * as an array or through a pointer reference, but as a single data element.
380 * At the moment, scalars are represented as zero-dimensional arrays.
381 * Note that the single data element may be an entire structure.
383 int gpu_array_is_scalar(struct gpu_array_info *array)
385 return array->n_index == 0;
388 /* Is "array" a read-only scalar?
390 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
392 return array->read_only_scalar;
395 /* Return the set of parameter values for which the array has a positive
396 * size in all dimensions.
397 * If the sizes are only valid for some parameter values, then those
398 * constraints are also taken into account.
400 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
402 int i;
403 isl_space *space;
404 isl_set *guard;
406 space = isl_space_params(isl_space_copy(array->space));
407 guard = isl_set_universe(space);
409 for (i = 0; i < array->n_index; ++i) {
410 isl_pw_aff *bound;
411 isl_set *guard_i, *zero;
413 bound = isl_pw_aff_copy(array->bound[i]);
414 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
415 zero = isl_pw_aff_zero_set(bound);
416 guard_i = isl_set_subtract(guard_i, zero);
417 guard = isl_set_intersect(guard, guard_i);
420 return guard;
423 /* Internal data structure for extract_size_of_type.
424 * "type" specifies the name of the space that we want to extract.
425 * "res" is used to store the subset of that space.
427 struct ppcg_extract_size_data {
428 const char *type;
429 isl_set *res;
432 /* This function is called for each set in a union_set.
433 * If the name of the set matches data->type, we store the
434 * set in data->res.
436 static int extract_size_of_type(__isl_take isl_set *size, void *user)
438 struct ppcg_extract_size_data *data = user;
439 const char *name;
441 name = isl_set_get_tuple_name(size);
442 if (name && !strcmp(name, data->type)) {
443 data->res = size;
444 return -1;
447 isl_set_free(size);
448 return 0;
451 /* Given a union map { kernel[i] -> *[...] },
452 * return the range in the space called "type" for the kernel with
453 * sequence number "id".
455 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
456 const char *type, int id)
458 isl_space *space;
459 isl_set *dom;
460 isl_union_set *local_sizes;
461 struct ppcg_extract_size_data data = { type, NULL };
463 if (!sizes)
464 return NULL;
466 space = isl_union_map_get_space(sizes);
467 space = isl_space_set_from_params(space);
468 space = isl_space_add_dims(space, isl_dim_set, 1);
469 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
470 dom = isl_set_universe(space);
471 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
473 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
474 isl_union_map_copy(sizes));
475 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
476 isl_union_set_free(local_sizes);
477 return data.res;
480 /* Given a singleton set, extract the first (at most *len) elements
481 * of the single integer tuple into *sizes and update *len if needed.
483 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
485 int i;
486 int dim;
488 if (!set)
489 return;
491 dim = isl_set_dim(set, isl_dim_set);
492 if (dim < *len)
493 *len = dim;
495 for (i = 0; i < *len; ++i) {
496 isl_val *v;
498 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
499 assert(v);
501 sizes[i] = isl_val_get_num_si(v);
502 isl_val_free(v);
505 isl_set_free(set);
508 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
509 * if the option debug->dump_sizes is set.
511 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
512 int *sizes, int len)
514 int i;
515 isl_space *space;
516 isl_map *map;
518 if (!gen->options->debug->dump_sizes)
519 return;
521 space = isl_union_map_get_space(gen->used_sizes);
522 space = isl_space_set_from_params(space);
523 space = isl_space_add_dims(space, isl_dim_set, 1);
524 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
525 space = isl_space_from_domain(space);
526 space = isl_space_add_dims(space, isl_dim_out, len);
527 space = isl_space_set_tuple_name(space, isl_dim_out, type);
529 map = isl_map_universe(space);
530 map = isl_map_fix_si(map, isl_dim_in, 0, id);
531 for (i = 0; i < len; ++i)
532 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
534 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
537 /* Extract user specified "tile" sizes from the "sizes" command line option,
538 * defaulting to option->tile_size in each dimension.
539 * Add the effectively used sizes to gen->used_sizes.
541 static void read_tile_sizes(struct gpu_gen *gen)
543 int n;
544 isl_set *size;
546 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
547 assert(gen->tile_size);
548 for (n = 0; n < gen->tile_len; ++n)
549 gen->tile_size[n] = gen->options->tile_size;
551 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
552 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
553 set_used_sizes(gen, "tile", gen->kernel_id,
554 gen->tile_size, gen->tile_len);
556 if (gen->n_parallel > gen->tile_len)
557 gen->n_parallel = gen->tile_len;
560 /* Extract user specified "block" sizes from the "sizes" command line option,
561 * after filling in some potentially useful defaults.
562 * Add the effectively used sizes to gen->used_sizes.
564 static void read_block_sizes(struct gpu_gen *gen)
566 int n;
567 isl_set *size;
569 n = gen->n_parallel;
570 gen->n_block = (n <= 3) ? n : 3;
571 switch (gen->n_block) {
572 case 1:
573 gen->block_dim[0] = 512;
574 break;
575 case 2:
576 gen->block_dim[0] = 32;
577 gen->block_dim[1] = 16;
578 break;
579 default:
580 gen->block_dim[0] = 32;
581 gen->block_dim[1] = 4;
582 gen->block_dim[2] = 4;
583 break;
586 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
587 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
588 set_used_sizes(gen, "block", gen->kernel_id,
589 gen->block_dim, gen->n_block);
592 /* Extract user specified "grid" sizes from the "sizes" command line option,
593 * after filling in some potentially useful defaults.
594 * Add the effectively used sizes to gen->used_sizes.
596 static void read_grid_sizes(struct gpu_gen *gen)
598 int n = gen->n_parallel;
599 isl_set *size;
601 gen->n_grid = (n <= 2) ? n : 2;
602 switch (gen->n_grid) {
603 case 1:
604 gen->grid_dim[0] = 32768;
605 break;
606 default:
607 gen->grid_dim[0] = 256;
608 gen->grid_dim[1] = 256;
609 break;
612 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
613 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
614 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
617 /* Extract user specified sizes from the "sizes" command line option
618 * after filling in some potentially useful defaults.
620 static void read_sizes(struct gpu_gen *gen)
622 read_tile_sizes(gen);
623 read_block_sizes(gen);
624 read_grid_sizes(gen);
627 static void *free_stmts(struct gpu_stmt *stmts, int n)
629 int i;
631 if (!stmts)
632 return NULL;
634 for (i = 0; i < n; ++i) {
635 struct gpu_stmt_access *access, *next;
637 for (access = stmts[i].accesses; access; access = next) {
638 next = access->next;
639 isl_id_free(access->ref_id);
640 isl_map_free(access->access);
641 isl_map_free(access->tagged_access);
642 free(access);
645 isl_id_free(stmts[i].id);
647 free(stmts);
649 return NULL;
652 /* Construct a map from a domain of dimensionality "len"
653 * to a domain of dimensionality "len" + "tile_len" that tiles
654 * the "tile_len" coordinates starting at "first".
655 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
656 * "dim" prescribes the parameters.
658 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
659 int first, int tile_len, int *tile_size)
661 int i;
662 isl_basic_map *bmap;
663 isl_constraint *c;
664 isl_local_space *ls;
666 dim = isl_space_add_dims(dim, isl_dim_in, len);
667 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
668 bmap = isl_basic_map_universe(isl_space_copy(dim));
669 ls = isl_local_space_from_space(dim);
671 for (i = 0; i < len - tile_len; ++i) {
672 int j = i < first ? i : i + tile_len;
673 int k = i < first ? i : i + 2 * tile_len;
675 c = isl_equality_alloc(isl_local_space_copy(ls));
676 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
677 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
678 bmap = isl_basic_map_add_constraint(bmap, c);
681 for (i = 0; i < tile_len; ++i) {
682 c = isl_equality_alloc(isl_local_space_copy(ls));
683 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
684 first + i, -1);
685 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
686 first + i, tile_size[i]);
687 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
688 first + i + tile_len, 1);
689 bmap = isl_basic_map_add_constraint(bmap, c);
691 c = isl_inequality_alloc(isl_local_space_copy(ls));
692 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
693 first + i + tile_len, 1);
694 bmap = isl_basic_map_add_constraint(bmap, c);
696 c = isl_inequality_alloc(isl_local_space_copy(ls));
697 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
698 first + i + tile_len, -1);
699 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
700 bmap = isl_basic_map_add_constraint(bmap, c);
703 isl_local_space_free(ls);
705 return isl_map_from_basic_map(bmap);
708 /* Construct a map from a domain of dimensionality "len"
709 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
710 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
711 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
712 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
713 * that are projected out at the end.
714 * "dim" prescribes the parameters.
716 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
717 int first, int wrap_len, int *wrap_size)
719 int i;
720 isl_basic_map *bmap;
721 isl_constraint *c;
722 isl_local_space *ls;
724 dim = isl_space_add_dims(dim, isl_dim_in, len);
725 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
726 bmap = isl_basic_map_universe(isl_space_copy(dim));
727 ls = isl_local_space_from_space(dim);
729 for (i = 0; i < len; ++i) {
730 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
732 c = isl_equality_alloc(isl_local_space_copy(ls));
733 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
734 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
735 bmap = isl_basic_map_add_constraint(bmap, c);
738 for (i = 0; i < wrap_len; ++i) {
739 c = isl_equality_alloc(isl_local_space_copy(ls));
740 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
741 first + i, -1);
742 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
743 first + wrap_len + i, 1);
744 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
745 first + 2 * wrap_len + i, wrap_size[i]);
746 bmap = isl_basic_map_add_constraint(bmap, c);
748 c = isl_inequality_alloc(isl_local_space_copy(ls));
749 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
750 first + wrap_len + i, 1);
751 bmap = isl_basic_map_add_constraint(bmap, c);
753 c = isl_inequality_alloc(isl_local_space_copy(ls));
754 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
755 first + wrap_len + i, -1);
756 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
757 bmap = isl_basic_map_add_constraint(bmap, c);
760 isl_local_space_free(ls);
762 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
763 first + 2 * wrap_len, wrap_len);
765 return isl_map_from_basic_map(bmap);
768 /* Tile the B loops over the tile sizes and then tile/wrap
769 * the T1 loops over the blocks.
771 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
772 __isl_take isl_union_map *sched)
774 isl_space *dim;
775 isl_map *tiling, *block_tiling;
777 dim = isl_union_map_get_space(sched);
778 tiling = tile(isl_space_copy(dim), gen->untiled_len,
779 gen->tile_first, gen->tile_len, gen->tile_size);
781 if (gen->options->wrap)
782 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
783 gen->tile_first, gen->n_grid, gen->grid_dim);
784 else
785 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
786 gen->tile_first, gen->n_grid, gen->grid_dim);
788 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
790 tiling = isl_map_apply_range(tiling, block_tiling);
792 sched = isl_union_map_apply_range(sched,
793 isl_union_map_from_map(tiling));
795 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
797 return sched;
800 /* Equate the "T1P" iterators in the tiled schedule "sched"
801 * to the block dimensions.
803 static __isl_give isl_union_map *parametrize_tiled_schedule(
804 struct gpu_gen *gen, __isl_take isl_union_map *sched)
806 isl_space *dim;
807 isl_set *par;
809 dim = isl_union_map_get_space(sched);
810 par = parametrization(dim, gen->tiled_len,
811 gen->tile_first + gen->n_grid, gen->kernel->block_ids);
812 sched = isl_union_map_intersect_range(sched,
813 isl_union_set_from_set(par));
815 return sched;
818 /* Tile/wrap the P1 loops over the threads.
820 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
821 __isl_take isl_union_map *sched)
823 isl_space *dim;
824 isl_map *tiling;
825 isl_set *par;
827 dim = isl_union_map_get_space(sched);
829 if (gen->options->wrap)
830 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
831 gen->shared_len, gen->n_block, gen->block_dim);
832 else
833 tiling = tile(isl_space_copy(dim), gen->tiled_len,
834 gen->shared_len, gen->n_block, gen->block_dim);
835 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
837 sched = isl_union_map_apply_range(sched,
838 isl_union_map_from_map(tiling));
840 par = parametrization(dim, gen->thread_tiled_len,
841 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
842 gen->kernel->thread_ids);
843 sched = isl_union_map_intersect_range(sched,
844 isl_union_set_from_set(par));
846 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
848 return sched;
851 /* If the user asked for it, scale the shared memory tile loops
852 * (T1T and T2) of "sched" by gen->tile_size[i].
853 * If we are not performing "wrapping", then additionally scale the T1P
854 * loops by gen->grid_dim[i].
856 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
857 __isl_take isl_union_map *sched)
859 int i;
860 isl_space *dim;
861 isl_basic_map *scale;
862 isl_constraint *c;
863 isl_local_space *ls;
865 if (!gen->options->scale_tile_loops)
866 return sched;
868 dim = isl_union_map_get_space(sched);
869 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
870 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
871 scale = isl_basic_map_universe(isl_space_copy(dim));
872 ls = isl_local_space_from_space(dim);
874 for (i = 0; i < gen->tiled_len; ++i) {
875 int f = 1;
877 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
878 f = gen->tile_size[i - gen->tile_first];
879 if (!gen->options->wrap)
880 f *= gen->grid_dim[i - gen->tile_first];
881 } else if (i >= gen->tile_first + gen->n_grid &&
882 i < gen->tile_first + gen->n_grid + gen->tile_len) {
883 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
886 c = isl_equality_alloc(isl_local_space_copy(ls));
887 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
888 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
889 scale = isl_basic_map_add_constraint(scale, c);
892 isl_local_space_free(ls);
894 sched = isl_union_map_apply_range(sched,
895 isl_union_map_from_map(isl_map_from_basic_map(scale)));
897 return sched;
900 /* If we are not performing "wrapping" and if the user asked for it,
901 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
903 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
904 __isl_take isl_union_map *sched)
906 int i;
907 isl_space *dim;
908 isl_basic_map *scale;
909 isl_constraint *c;
910 isl_local_space *ls;
912 if (gen->options->wrap)
913 return sched;
914 if (!gen->options->scale_tile_loops)
915 return sched;
917 dim = isl_union_map_get_space(sched);
918 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
919 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
920 scale = isl_basic_map_universe(isl_space_copy(dim));
921 ls = isl_local_space_from_space(dim);
923 for (i = 0; i < gen->thread_tiled_len; ++i) {
924 int f = 1;
926 if (i >= gen->shared_len &&
927 i < gen->shared_len + gen->n_block)
928 f = gen->block_dim[i - gen->shared_len];
930 c = isl_equality_alloc(isl_local_space_copy(ls));
931 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
932 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
933 scale = isl_basic_map_add_constraint(scale, c);
936 isl_local_space_free(ls);
938 sched = isl_union_map_apply_range(sched,
939 isl_union_map_from_map(isl_map_from_basic_map(scale)));
941 return sched;
944 /* If we are not performing "wrapping" and if the user asked for it,
945 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
947 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
948 __isl_take isl_union_map *sched, int len, int first, int n_tile)
950 int i;
951 isl_space *dim;
952 isl_basic_map *scale;
953 isl_constraint *c;
954 isl_local_space *ls;
956 if (gen->options->wrap)
957 return sched;
958 if (!gen->options->scale_tile_loops)
959 return sched;
961 dim = isl_union_map_get_space(sched);
962 dim = isl_space_add_dims(dim, isl_dim_in, len);
963 dim = isl_space_add_dims(dim, isl_dim_out, len);
964 scale = isl_basic_map_universe(isl_space_copy(dim));
965 ls = isl_local_space_from_space(dim);
967 for (i = 0; i < len; ++i) {
968 int f = 1;
970 if (i >= first && i < first + n_tile)
971 f = gen->kernel->block_dim[i - first];
973 c = isl_equality_alloc(isl_local_space_copy(ls));
974 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
975 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
976 scale = isl_basic_map_add_constraint(scale, c);
979 isl_local_space_free(ls);
981 sched = isl_union_map_apply_range(sched,
982 isl_union_map_from_map(isl_map_from_basic_map(scale)));
984 return sched;
987 /* Add parameters p[i] with identifiers "ids" to "set",
988 * with bounds to 0 <= p[i] < size[i].
990 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
991 int *size, __isl_keep isl_id_list *ids)
993 int i, len;
994 unsigned nparam;
996 len = isl_id_list_n_id(ids);
997 nparam = isl_set_dim(set, isl_dim_param);
998 set = isl_set_add_dims(set, isl_dim_param, len);
1000 for (i = 0; i < len; ++i) {
1001 isl_id *id;
1003 id = isl_id_list_get_id(ids, i);
1004 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1005 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
1006 set = isl_set_upper_bound_si(set, isl_dim_param,
1007 nparam + i, size[i] - 1);
1010 return set;
1013 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
1014 * with
1016 * { : 0 <= p[i] < size[i] }
1018 * or an overapproximation.
1020 static __isl_give isl_set *add_bounded_parameters_dynamic(
1021 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1022 __isl_keep isl_id_list *ids)
1024 int i, len;
1025 unsigned nparam;
1026 isl_space *space;
1027 isl_local_space *ls;
1029 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1030 nparam = isl_set_dim(set, isl_dim_param);
1031 set = isl_set_add_dims(set, isl_dim_param, len);
1033 for (i = 0; i < len; ++i) {
1034 isl_id *id;
1036 id = isl_id_list_get_id(ids, i);
1037 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1040 space = isl_space_params(isl_set_get_space(set));
1041 ls = isl_local_space_from_space(space);
1042 for (i = 0; i < len; ++i) {
1043 isl_pw_aff *param, *size_i, *zero;
1044 isl_set *bound;
1046 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1047 isl_dim_param, nparam + i);
1049 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1050 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1051 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1052 set = isl_set_intersect_params(set, bound);
1054 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1055 bound = isl_pw_aff_ge_set(param, zero);
1056 set = isl_set_intersect_params(set, bound);
1058 isl_local_space_free(ls);
1060 return set;
1063 /* Construct a map from an access to group->array to the corresponding
1064 * shared/private memory tile.
1065 * The map is of the form
1067 * { [D[i] -> A[a]] -> T[t] }
1069 * where D represents the initial shared_len dimensions
1070 * of the computed schedule.
1072 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1074 struct gpu_array_tile *tile;
1075 isl_multi_aff *tiling;
1077 tile = group->private_tile;
1078 if (!tile)
1079 tile = group->shared_tile;
1081 tiling = isl_multi_aff_copy(tile->tiling);
1083 return isl_map_from_multi_aff(tiling);
1086 /* Given a schedule that iterates over all elements in a piece of an array,
1087 * perform tiling/wrapping over the threads.
1089 * In particular, we tile the final iterators so that the final thread
1090 * dimension runs over the final array dimension.
1091 * However, if those final iterators have only a single iteration,
1092 * we try to tile earlier iterators instead.
1094 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1095 __isl_take isl_map *sched)
1097 isl_space *dim;
1098 isl_union_map *usched;
1099 isl_map *tiling;
1100 isl_set *par;
1101 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1102 int n_tile;
1103 int first;
1105 n_tile = gen->kernel->n_block;
1106 if (n_tile > nvar) {
1107 int i;
1108 sched = isl_map_insert_dims(sched,
1109 isl_dim_out, 0, n_tile - nvar);
1110 for (i = 0; i < n_tile - nvar; ++i)
1111 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1112 nvar = n_tile;
1115 first = nvar - n_tile;
1117 for (; first > 0; first --)
1118 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1119 break;
1121 dim = isl_map_get_space(sched);
1122 dim = isl_space_params(dim);
1123 if (gen->options->wrap)
1124 tiling = wrap(isl_space_copy(dim), nvar, first,
1125 n_tile, gen->kernel->block_dim);
1126 else
1127 tiling = tile(isl_space_copy(dim), nvar, first,
1128 n_tile, gen->kernel->block_dim);
1129 sched = isl_map_apply_range(sched, tiling);
1131 par = parametrization(dim, nvar + n_tile, first + n_tile,
1132 gen->kernel->thread_ids);
1133 sched = isl_map_intersect_range(sched, par);
1135 usched = isl_union_map_from_map(sched);
1136 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1137 first, n_tile);
1138 sched = isl_map_from_union_map(usched);
1140 return sched;
1143 /* Return the union of all tagged access relations in the group.
1145 static __isl_give isl_union_map *group_tagged_access_relation(
1146 struct gpu_array_ref_group *group)
1148 int i;
1149 isl_union_map *access;
1151 access = isl_union_map_empty(isl_map_get_space(group->access));
1152 for (i = 0; i < group->n_ref; ++i) {
1153 isl_map *map_i;
1155 map_i = isl_map_copy(group->refs[i]->tagged_access);
1156 access = isl_union_map_union(access,
1157 isl_union_map_from_map(map_i));
1160 return access;
1163 /* Return the extent of "array", recomputed from the bounds.
1164 * The recomputed extent may be simpler than the original extent.
1166 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1168 int i;
1169 isl_id *id;
1170 isl_space *space;
1171 isl_local_space *ls;
1172 isl_set *extent;
1174 id = isl_set_get_tuple_id(array->extent);
1175 space = isl_set_get_space(array->extent);
1176 extent = isl_set_universe(isl_space_copy(space));
1177 ls = isl_local_space_from_space(space);
1178 for (i = 0; i < array->n_index; ++i) {
1179 isl_pw_aff *bound;
1180 isl_aff *aff;
1181 isl_pw_aff *index;
1182 isl_set *lt;
1184 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1186 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1187 isl_dim_set, i);
1188 index = isl_pw_aff_from_aff(aff);
1189 bound = isl_pw_aff_copy(array->bound[i]);
1190 bound = isl_pw_aff_from_range(bound);
1191 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1192 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1193 isl_id_copy(id));
1194 lt = isl_pw_aff_lt_set(index, bound);
1195 extent = isl_set_intersect(extent, lt);
1197 isl_local_space_free(ls);
1198 isl_id_free(id);
1200 return extent;
1203 /* Return a map from the first shared_len dimensions of the computed
1204 * schedule to the array tile in
1205 * global memory that corresponds to the shared memory copy.
1207 * In particular, return a map
1209 * { D[i] -> A[a] }
1211 * with constraints
1213 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1215 * and
1217 * 0 <= a <= array_size - 1 (2)
1219 * Note that if some stride has been detected (i.e., when
1220 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1221 * to the shifted and scaled down version.
1223 * Constraints (1) are obtained by mapping the size constraints on the
1224 * shared/private memory tile back to the access relation.
1225 * Constraints (2) are obtained from the (recomputed) extent.
1227 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1229 int i;
1230 int n_index = group->array->n_index;
1231 isl_map *tile;
1232 isl_space *space;
1233 isl_set *local;
1234 isl_set *extent;
1236 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1237 space = isl_space_range(space);
1238 local = isl_set_universe(space);
1239 for (i = 0; i < n_index; ++i) {
1240 isl_val *bound;
1242 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1243 bound = isl_val_copy(group->shared_tile->bound[i].size);
1244 bound = isl_val_sub_ui(bound, 1);
1245 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1247 local = isl_set_preimage_multi_aff(local,
1248 isl_multi_aff_copy(group->shared_tile->tiling));
1249 tile = isl_set_unwrap(local);
1250 extent = array_extent(group->array);
1251 tile = isl_map_intersect_range(tile, extent);
1253 return tile;
1256 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1257 * return the corresponding mapping from the AST schedule to
1258 * to the first shared_len dimensions of the schedule computed by PPCG.
1260 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1261 __isl_take isl_pw_multi_aff *iterator_map)
1263 isl_union_map *umap;
1264 isl_space *space;
1265 isl_map *map, *sched;;
1267 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1268 space = isl_space_from_domain(space);
1269 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1271 umap = isl_union_map_copy(gen->shared_sched);
1272 umap = isl_union_map_apply_range(umap,
1273 isl_union_map_copy(gen->shared_proj));
1274 map = isl_union_map_extract_map(umap, space);
1275 isl_union_map_free(umap);
1277 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1278 sched = isl_map_detect_equalities(sched);
1280 return isl_pw_multi_aff_from_map(sched);
1283 /* Set unroll[j] if the input dimension j is involved in
1284 * the index expression represented by ma.
1286 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1287 void *user)
1289 int i, j;
1290 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1291 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1292 int *unroll = user;
1294 for (i = 0; i < n_out; ++i) {
1295 isl_aff *aff;
1297 aff = isl_multi_aff_get_aff(ma, i);
1298 for (j = 0; j < n_in; ++j)
1299 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1300 unroll[j] = 1;
1301 isl_aff_free(aff);
1304 isl_set_free(set);
1305 isl_multi_aff_free(ma);
1306 return 0;
1309 /* Given an array pos mapping input dimensions to the corresponding
1310 * output dimension, construct the corresponding map.
1312 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1313 int *pos, int len)
1315 int i;
1316 isl_constraint *c;
1317 isl_basic_map *bmap;
1318 isl_local_space *ls;
1320 dim = isl_space_add_dims(dim, isl_dim_in, len);
1321 dim = isl_space_add_dims(dim, isl_dim_out, len);
1322 bmap = isl_basic_map_universe(isl_space_copy(dim));
1323 ls = isl_local_space_from_space(dim);
1325 for (i = 0; i < len; ++i) {
1326 c = isl_equality_alloc(isl_local_space_copy(ls));
1327 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1328 -1);
1329 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1331 bmap = isl_basic_map_add_constraint(bmap, c);
1333 isl_local_space_free(ls);
1335 return isl_map_from_basic_map(bmap);
1338 /* Remove the private tiles from all array reference groups,
1339 * except for the groups of arrays that are marked force_private.
1341 static void remove_private_tiles(struct gpu_gen *gen)
1343 int i, j;
1345 for (i = 0; i < gen->kernel->n_array; ++i) {
1346 struct gpu_local_array_info *local = &gen->kernel->array[i];
1348 if (local->force_private)
1349 continue;
1351 for (j = 0; j < local->n_group; ++j) {
1352 struct gpu_array_ref_group *group = local->groups[j];
1354 group->private_tile =
1355 gpu_array_tile_free(group->private_tile);
1360 /* Find all loops involved in any of the index expressions for any of
1361 * the private accesses, move them innermost and then mark them as
1362 * requiring unrolling by setting gen->first_unroll.
1363 * The loops involved should all be parallel because of the checks
1364 * we performed in check_private_group_access. Moving them innermost
1365 * is therefore a valid transformation.
1367 * If any of the arrays are marked force_private, however, then
1368 * those loops may not be parallel with respect to the marked arrays.
1369 * If any of the loops would have to be moved innermost for the
1370 * (non forced) private accesses and if there are any force_private
1371 * arrays, then we revert the decision to map the selected arrays
1372 * to private memory. An alternative solution would be to expand
1373 * the force_private arrays.
1375 * Loops up to gen->shared_len are generated before the mapping to
1376 * threads is applied. They should therefore be ignored.
1378 * We compute the hidden equalities of the schedule first
1379 * since we will need them in our calls to isl_pw_multi_aff_from_map
1380 * and because we want to make sure that the same equalities
1381 * are also available to the code generator.
1383 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1384 __isl_take isl_union_map *sched)
1386 struct ppcg_kernel *kernel = gen->kernel;
1387 int i, j;
1388 int unroll[gen->thread_tiled_len];
1389 int perm[gen->thread_tiled_len];
1390 isl_space *dim;
1391 isl_map *permute;
1392 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1394 gen->first_unroll = -1;
1396 sched = isl_union_map_detect_equalities(sched);
1397 for (i = 0; i < gen->thread_tiled_len; ++i)
1398 unroll[i] = 0;
1399 for (i = 0; i < kernel->n_array; ++i) {
1400 struct gpu_local_array_info *array = &kernel->array[i];
1402 for (j = 0; j < array->n_group; ++j) {
1403 isl_union_map *access;
1404 isl_map *acc;
1405 isl_pw_multi_aff *pma;
1407 if (!array->groups[j]->private_tile)
1408 continue;
1410 access = gpu_array_ref_group_access_relation(
1411 array->groups[j], 1, 1);
1412 access = isl_union_map_apply_domain(access,
1413 isl_union_map_copy(sched));
1415 acc = isl_map_from_union_map(access);
1416 pma = isl_pw_multi_aff_from_map(acc);
1417 isl_pw_multi_aff_foreach_piece(pma,
1418 &check_unroll, unroll);
1420 isl_pw_multi_aff_free(pma);
1424 for (i = gen->shared_len; i < len; ++i)
1425 if (unroll[i])
1426 break;
1428 if (i >= len)
1429 return sched;
1431 for (i = len; i < gen->thread_tiled_len; ++i)
1432 if (unroll[i])
1433 return sched;
1435 if (kernel->any_force_private) {
1436 remove_private_tiles(gen);
1437 return sched;
1440 j = 0;
1441 for (i = 0; i < gen->shared_len; ++i)
1442 perm[i] = j++;
1443 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1444 if (!unroll[i])
1445 perm[i] = j++;
1446 gen->first_unroll = j - gen->shared_len;
1447 for (i = gen->shared_len; i < len; ++i)
1448 if (unroll[i])
1449 perm[i] = j++;
1451 dim = isl_union_map_get_space(sched);
1452 permute = permutation(dim, perm, gen->thread_tiled_len);
1453 sched = isl_union_map_apply_range(sched,
1454 isl_union_map_from_map(permute));
1456 return sched;
1459 /* Construct a map with input the shared tile loops and the loops that
1460 * will be wrapped around the threads that relates these later loops
1461 * to the thread indices and then projects them out.
1463 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1465 isl_map *priv;
1466 isl_map *tiling;
1467 isl_map *proj;
1468 isl_set *par;
1469 isl_space *dim;
1471 dim = isl_union_map_get_space(gen->shared_sched);
1473 if (gen->options->wrap)
1474 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
1475 gen->shared_len, gen->n_block, gen->block_dim);
1476 else
1477 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
1478 gen->shared_len, gen->n_block, gen->block_dim);
1480 priv = tiling;
1482 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
1483 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1484 gen->kernel->thread_ids);
1486 priv = isl_map_align_params(priv, isl_set_get_space(par));
1487 priv = isl_map_intersect_range(priv, par);
1489 dim = isl_map_get_space(priv);
1490 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1491 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1492 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
1493 gen->shared_len);
1495 priv = isl_map_apply_range(priv, proj);
1497 return priv;
1500 /* If max_shared_memory is not set to infinity (-1), then make
1501 * sure that the total amount of shared memory required by the
1502 * array reference groups mapped to shared memory is no larger
1503 * than this maximum.
1505 * We apply a greedy approach and discard (keep in global memory)
1506 * those groups that would result in a total memory size that
1507 * is larger than the maximum.
1509 * This function should be called after any function that may
1510 * affect the decision on whether to place a reference group
1511 * in private, shared or global memory.
1513 static void check_shared_memory_bound(struct gpu_gen *gen)
1515 int i, j;
1516 isl_val *left, *size;
1518 if (gen->options->max_shared_memory < 0)
1519 return;
1521 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
1523 for (i = 0; i < gen->kernel->n_array; ++i) {
1524 struct gpu_local_array_info *local = &gen->kernel->array[i];
1526 for (j = 0; j < local->n_group; ++j) {
1527 struct gpu_array_ref_group *group;
1529 group = local->groups[j];
1530 if (group->private_tile)
1531 continue;
1532 if (!group->shared_tile)
1533 continue;
1535 size = gpu_array_tile_size(group->shared_tile);
1536 size = isl_val_mul_ui(size, local->array->size);
1538 if (isl_val_le(size, left)) {
1539 left = isl_val_sub(left, size);
1540 continue;
1542 isl_val_free(size);
1544 group->shared_tile =
1545 gpu_array_tile_free(group->shared_tile);
1549 isl_val_free(left);
1552 /* Compute a tiling for all the array reference groups.
1554 static void compute_group_tilings(struct gpu_gen *gen)
1556 int i, j;
1558 for (i = 0; i < gen->kernel->n_array; ++i) {
1559 struct gpu_local_array_info *array = &gen->kernel->array[i];
1561 for (j = 0; j < array->n_group; ++j)
1562 gpu_array_ref_group_compute_tiling(array->groups[j]);
1566 /* Take tiled_sched, project it onto the shared tile loops and
1567 * the loops that will be wrapped over the threads and
1568 * store the result in gen->shared_sched.
1569 * Also compute a projection that projects out the loops that will be
1570 * wrapped over the threads and store this projection in gen->shared_proj.
1572 static void compute_shared_sched(struct gpu_gen *gen)
1574 isl_space *dim;
1575 isl_map *proj;
1576 isl_set *par;
1577 isl_union_map *sched;
1579 sched = isl_union_map_copy(gen->tiled_sched);
1581 dim = isl_union_map_get_space(sched);
1582 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
1583 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
1585 dim = isl_union_map_get_space(sched);
1586 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
1588 gen->shared_sched = sched;
1589 gen->shared_proj = isl_union_map_from_map(proj);
1592 /* Compute the size of a bounding box around the origin and "set",
1593 * where "set" is assumed to contain only non-negative elements.
1594 * In particular, compute the maximal value of "set" in each direction
1595 * and add one.
1597 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
1598 __isl_keep isl_set *context)
1600 int i, n;
1601 isl_multi_pw_aff *mpa;
1603 n = isl_set_dim(set, isl_dim_set);
1604 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
1605 for (i = 0; i < n; ++i) {
1606 isl_space *space;
1607 isl_aff *one;
1608 isl_pw_aff *bound;
1610 bound = isl_set_dim_max(isl_set_copy(set), i);
1611 bound = isl_pw_aff_coalesce(bound);
1612 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
1614 space = isl_pw_aff_get_domain_space(bound);
1615 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1616 one = isl_aff_add_constant_si(one, 1);
1617 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
1618 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
1620 isl_set_free(set);
1622 return mpa;
1625 /* Compute the effective grid size as a list of the sizes in each dimension.
1627 * The grid size specified by the user or set by default
1628 * in read_grid_sizes() and applied in tile_schedule(),
1629 * may be too large for the given code in the sense that
1630 * it may contain blocks that don't need to execute anything.
1631 * We therefore don't return this grid size, but instead the
1632 * smallest grid size that ensures that all blocks that actually
1633 * execute code are included in the grid.
1635 * We first extract a description of the grid, i.e., the possible values
1636 * of the block ids, from gen->tiled_sched.
1637 * The block ids are parameters in gen->tiled_sched.
1638 * We simply need to change them into set dimensions.
1640 * Then, for each block dimension, we compute the maximal value of the block id
1641 * and add one.
1643 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
1644 struct ppcg_kernel *kernel)
1646 int i;
1647 isl_set *grid;
1649 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
1650 grid = isl_set_from_params(grid);
1651 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
1652 for (i = 0; i < gen->n_grid; ++i) {
1653 int pos;
1654 isl_id *id;
1656 id = isl_id_list_get_id(kernel->block_ids, i);
1657 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1658 isl_id_free(id);
1659 assert(pos >= 0);
1660 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1661 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1664 return extract_size(grid, kernel->context);
1667 /* Compute the size of a fixed bounding box around the origin and "set",
1668 * where "set" is assumed to contain only non-negative elements,
1669 * and store the results in "size".
1670 * In particular, compute the maximal value of "set" in each direction
1671 * and add one.
1673 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1675 int i, n;
1676 isl_local_space *ls;
1677 isl_aff *obj;
1679 n = isl_set_dim(set, isl_dim_set);
1680 ls = isl_local_space_from_space(isl_set_get_space(set));
1681 obj = isl_aff_zero_on_domain(ls);
1682 for (i = 0; i < n; ++i) {
1683 isl_val *max;
1685 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1686 max = isl_set_max_val(set, obj);
1687 size[i] = isl_val_get_num_si(max) + 1;
1688 isl_val_free(max);
1689 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1691 isl_aff_free(obj);
1692 isl_set_free(set);
1695 /* Compute the effective block size as a list of the sizes in each dimension
1696 * and store the sizes in kernel->block_dim.
1698 * The block size specified by the user or set by default
1699 * in read_block_sizes() and applied in thread_tile_schedule(),
1700 * may be too large for the given code in the sense that
1701 * it may contain threads that don't need to execute anything.
1702 * We therefore don't store this block size in kernel->block_dim,
1703 * but instead the smallest block size that ensures that all threads
1704 * that actually execute code are included in the block.
1706 * The current implementation eliminates all parameters, ensuring
1707 * that the size is a fixed constant in each dimension.
1708 * In principle we could also compute parametric sizes.
1709 * We would have to make sure to project out all b%d and t%d parameters,
1710 * however.
1712 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
1714 int i;
1715 int nparam;
1716 isl_set *block;
1717 isl_multi_pw_aff *mpa;
1719 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
1720 block = isl_set_from_params(block);
1721 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
1722 kernel->n_block = gen->n_block;
1723 for (i = 0; i < gen->n_block; ++i) {
1724 int pos;
1725 isl_id *id;
1727 id = isl_id_list_get_id(kernel->thread_ids, i);
1728 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1729 isl_id_free(id);
1730 assert(pos >= 0);
1731 block = isl_set_equate(block, isl_dim_param, pos,
1732 isl_dim_set, i);
1734 nparam = isl_set_dim(block, isl_dim_param);
1735 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1737 extract_fixed_size(block, kernel->block_dim);
1740 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1742 int i, j;
1744 if (!kernel)
1745 return NULL;
1747 isl_id_list_free(kernel->block_ids);
1748 isl_id_list_free(kernel->thread_ids);
1749 isl_multi_pw_aff_free(kernel->grid_size);
1750 isl_set_free(kernel->context);
1751 isl_union_set_free(kernel->arrays);
1752 isl_space_free(kernel->space);
1753 isl_ast_node_free(kernel->tree);
1755 for (i = 0; i < kernel->n_array; ++i) {
1756 struct gpu_local_array_info *array = &kernel->array[i];
1758 for (j = 0; j < array->n_group; ++j)
1759 gpu_array_ref_group_free(array->groups[j]);
1760 free(array->groups);
1762 isl_pw_aff_list_free(array->bound);
1764 free(kernel->array);
1766 for (i = 0; i < kernel->n_var; ++i) {
1767 free(kernel->var[i].name);
1768 isl_vec_free(kernel->var[i].size);
1770 free(kernel->var);
1772 free(kernel);
1774 return NULL;
1777 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1779 static void ppcg_kernel_free_wrap(void *user)
1781 struct ppcg_kernel *kernel = user;
1783 ppcg_kernel_free(kernel);
1786 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1787 struct ppcg_kernel_var *var)
1789 int j;
1790 struct gpu_array_tile *tile;
1791 isl_printer *p;
1792 char *name;
1794 var->array = group->array;
1796 tile = group->private_tile;
1797 var->type = ppcg_access_private;
1798 if (!tile) {
1799 tile = group->shared_tile;
1800 var->type = ppcg_access_shared;
1803 p = isl_printer_to_str(ctx);
1804 p = gpu_array_ref_group_print_name(group, p);
1805 var->name = isl_printer_get_str(p);
1806 isl_printer_free(p);
1808 var->size = isl_vec_alloc(ctx, group->array->n_index);
1810 for (j = 0; j < group->array->n_index; ++j)
1811 var->size = isl_vec_set_element_val(var->size, j,
1812 isl_val_copy(tile->bound[j].size));
1815 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
1817 int i, j, n;
1819 n = 0;
1820 for (i = 0; i < kernel->n_array; ++i) {
1821 struct gpu_local_array_info *array = &kernel->array[i];
1823 for (j = 0; j < array->n_group; ++j) {
1824 struct gpu_array_ref_group *group = array->groups[j];
1825 if (group->private_tile || group->shared_tile)
1826 ++n;
1830 kernel->n_var = n;
1831 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
1832 assert(kernel->var);
1834 n = 0;
1835 for (i = 0; i < kernel->n_array; ++i) {
1836 struct gpu_local_array_info *array = &kernel->array[i];
1838 for (j = 0; j < array->n_group; ++j) {
1839 struct gpu_array_ref_group *group = array->groups[j];
1840 if (!group->private_tile && !group->shared_tile)
1841 continue;
1842 create_kernel_var(gen->ctx, group, &kernel->var[n]);
1843 ++n;
1848 /* Replace "pa" by the zero function defined over the universe domain
1849 * in the space of "pa".
1851 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1853 isl_space *space;
1854 isl_aff *zero;
1856 space = isl_space_domain(isl_pw_aff_get_space(pa));
1857 isl_pw_aff_free(pa);
1858 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1860 return isl_pw_aff_from_aff(zero);
1863 /* The sizes of the arrays on the host that have been computed by
1864 * extract_array_info may depend on the parameters. Use the extra
1865 * constraints on the parameters that are valid at "host_domain"
1866 * to simplify these expressions and store the results in kernel->array.
1868 * We only need these localized bounds for arrays that are accessed
1869 * by the current kernel. If we have found at least one reference group
1870 * then the array is accessed by the kernel. If the array has compound
1871 * elements then we skipped the construction of array reference groups.
1873 * The resulting sizes may be functions that are nowhere defined
1874 * in case the access function cannot possibly access anything inside
1875 * the kernel for some reason. If so, they are replaced by the zero
1876 * function. Since the access function cannot actually access anything,
1877 * there is no harm in printing the array sizes as zero.
1879 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
1880 __isl_keep isl_set *host_domain)
1882 int i, j;
1883 isl_set *context;
1885 context = isl_set_copy(host_domain);
1886 context = isl_set_params(context);
1888 for (i = 0; i < kernel->n_array; ++i) {
1889 struct gpu_local_array_info *local = &kernel->array[i];
1890 isl_pw_aff_list *bound;
1891 int n_index;
1893 if (local->n_group == 0 && !local->array->has_compound_element)
1894 continue;
1896 n_index = local->array->n_index;
1897 bound = isl_pw_aff_list_alloc(gen->ctx, n_index);
1899 for (j = 0; j < n_index; ++j) {
1900 isl_pw_aff *pwaff;
1901 int empty;
1903 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1904 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1905 empty = isl_pw_aff_is_empty(pwaff);
1906 if (empty < 0)
1907 pwaff = isl_pw_aff_free(pwaff);
1908 else if (empty)
1909 pwaff = set_universally_zero(pwaff);
1910 bound = isl_pw_aff_list_add(bound, pwaff);
1913 local->n_index = n_index;
1914 local->bound = bound;
1916 isl_set_free(context);
1919 /* Create the array of gpu_local_array_info structures "array"
1920 * inside "kernel". The number of elements in this array is
1921 * the same as the number of arrays in "prog".
1922 * Initialize the "array" field of each local array to point
1923 * to the corresponding array in "prog".
1925 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1926 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1928 int i;
1929 isl_ctx *ctx;
1931 ctx = isl_set_get_ctx(prog->context);
1932 kernel->array = isl_calloc_array(ctx,
1933 struct gpu_local_array_info, prog->n_array);
1934 if (!kernel->array)
1935 return ppcg_kernel_free(kernel);
1936 kernel->n_array = prog->n_array;
1938 for (i = 0; i < prog->n_array; ++i)
1939 kernel->array[i].array = &prog->array[i];
1941 return kernel;
1944 /* Find the element in gen->stmt that has the given "id".
1945 * Return NULL if no such gpu_stmt can be found.
1947 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1949 int i;
1951 for (i = 0; i < prog->n_stmts; ++i) {
1952 if (id == prog->stmts[i].id)
1953 break;
1956 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1959 /* Set gen->tile_len and gen->n_parallel to those of the statement
1960 * affected by the first map (part of the schedule)
1961 * on which this function is called.
1962 * Because of the way the schedule is constructed, the other statements
1963 * in the list, if any, should have the same values for these properties.
1965 static int extract_tile_len(__isl_take isl_map *map, void *user)
1967 struct gpu_gen *gen = (struct gpu_gen *) user;
1968 isl_id *id;
1969 struct gpu_stmt *stmt;
1971 id = isl_map_get_tuple_id(map, isl_dim_in);
1972 stmt = find_stmt(gen->prog, id);
1973 isl_id_free(id);
1975 isl_map_free(map);
1977 if (!stmt)
1978 isl_die(gen->ctx, isl_error_unknown,
1979 "statement not found", return -1);
1981 gen->tile_len = stmt->tile_len;
1982 gen->n_parallel = stmt->n_parallel;
1984 return -1;
1987 void ppcg_kernel_stmt_free(void *user)
1989 int i;
1990 struct ppcg_kernel_stmt *stmt = user;
1992 if (!stmt)
1993 return;
1995 switch (stmt->type) {
1996 case ppcg_kernel_copy:
1997 isl_ast_expr_free(stmt->u.c.index);
1998 isl_ast_expr_free(stmt->u.c.local_index);
1999 break;
2000 case ppcg_kernel_domain:
2001 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
2002 break;
2003 case ppcg_kernel_sync:
2004 break;
2007 free(stmt);
2010 /* Set the options of "context" to
2012 * { space -> [x] : x >= first }
2014 static __isl_give isl_ast_build *set_unroll(
2015 __isl_take isl_ast_build *build, __isl_take isl_space *space,
2016 int first)
2018 isl_ctx *ctx;
2019 isl_map *unroll;
2020 isl_union_map *opt;
2022 ctx = isl_ast_build_get_ctx(build);
2024 space = isl_space_from_domain(space);
2025 space = isl_space_add_dims(space, isl_dim_out, 1);
2026 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
2027 unroll = isl_map_universe(space);
2028 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
2029 opt = isl_union_map_from_map(unroll);
2031 build = isl_ast_build_set_options(build, opt);
2033 return build;
2036 /* Extend the schedule "schedule" with the part of "extension"
2037 * starting at "first" up to "len".
2039 static __isl_give isl_union_map *extend_schedule(
2040 __isl_take isl_union_map *schedule,
2041 __isl_take isl_union_map *extension, int first, int len)
2043 isl_space *space;
2044 isl_map *proj;
2045 isl_union_map *umap;
2046 isl_set *set;
2048 space = isl_union_map_get_space(schedule);
2049 space = isl_space_set_from_params(space);
2050 space = isl_space_add_dims(space, isl_dim_set, len);
2051 proj = isl_set_identity(isl_set_universe(space));
2052 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
2053 extension = isl_union_map_apply_range(extension,
2054 isl_union_map_from_map(proj));
2056 schedule = isl_union_map_range_product(schedule, extension);
2058 return schedule;
2061 /* Return the gpu_stmt_access in the list "accesses" that corresponds
2062 * to "ref_id".
2064 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
2065 __isl_keep isl_id *ref_id)
2067 struct gpu_stmt_access *access;
2069 for (access = accesses; access; access = access->next)
2070 if (access->ref_id == ref_id)
2071 return access;
2073 return NULL;
2076 /* Return the index of the array called "name" in the list of arrays.
2078 static int find_array_index(struct gpu_gen *gen, const char *name)
2080 int i;
2082 for (i = 0; i < gen->prog->n_array; ++i)
2083 if (!strcmp(name, gen->prog->array[i].name))
2084 return i;
2086 return -1;
2089 /* Internal data structure for the index and AST expression transformation
2090 * callbacks for pet_stmt_build_ast_exprs.
2092 * "accesses" is the list of gpu_stmt_access in the statement.
2093 * "iterator_map" expresses the statement iterators in terms of
2094 * the AST loop iterators.
2095 * "sched2shared" expresses the first shared_len dimensions of
2096 * the computed schedule in terms of the AST loop iterators.
2098 * The following fields are set in transform_index and used in transform_expr.
2099 * "array" is the array that is being accessed.
2100 * "global" is set if the global array is accessed (rather than
2101 * shared/private memory).
2102 * "local_array" refers to information on the array specialized
2103 * to the current kernel.
2105 struct ppcg_transform_data {
2106 struct gpu_gen *gen;
2107 struct gpu_stmt_access *accesses;
2108 isl_pw_multi_aff *iterator_map;
2109 isl_pw_multi_aff *sched2shared;
2111 struct gpu_array_info *array;
2112 int global;
2113 struct gpu_local_array_info *local_array;
2116 /* Return the name of the outer array (of structs) accessed by "access".
2118 static const char *get_outer_array_name(__isl_keep isl_map *access)
2120 isl_space *space;
2121 const char *name;
2123 space = isl_space_range(isl_map_get_space(access));
2124 while (space && isl_space_is_wrapping(space))
2125 space = isl_space_domain(isl_space_unwrap(space));
2126 name = isl_space_get_tuple_name(space, isl_dim_set);
2127 isl_space_free(space);
2129 return name;
2132 /* Return a pointer to the gpu_array_ref_group in "local"
2133 * that contains the reference "access".
2134 * Return NULL if no such group can be found.
2136 static struct gpu_array_ref_group *find_ref_group(
2137 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
2139 int i, j;
2141 for (i = 0; i < local->n_group; ++i) {
2142 struct gpu_array_ref_group *group = local->groups[i];
2144 for (j = 0; j < group->n_ref; ++j)
2145 if (group->refs[j] == access)
2146 return group;
2149 return NULL;
2152 /* Index transformation callback for pet_stmt_build_ast_exprs.
2154 * "index" expresses the array indices in terms of statement iterators
2156 * We first reformulate "index" in terms of the AST loop iterators.
2157 * Then we check if we are accessing the global array or
2158 * a shared/private copy. In the former case, we simply return
2159 * the updated index. If "index" is an affine expression rather
2160 * than an array access, then we also return the updated index here.
2162 * If no reference groups have been computed for the array,
2163 * then we can only be accessing the global array.
2165 * Otherwise, we apply the tiling to the index.
2166 * This tiling is of the form
2168 * [D -> A] -> T
2170 * The index is of the form
2172 * L -> A
2174 * We update the tiling to refer to the AST loop iterators
2176 * [L -> A] -> T
2178 * and modify index to keep track of those iterators
2180 * L -> [L -> A]
2182 * Combining these two yields a tiled index expression in terms
2183 * of the AST loop iterators
2185 * L -> T
2187 static __isl_give isl_multi_pw_aff *transform_index(
2188 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
2189 void *user)
2191 struct ppcg_transform_data *data = user;
2192 struct gpu_stmt_access *access;
2193 struct gpu_array_ref_group *group;
2194 struct gpu_array_tile *tile;
2195 isl_pw_multi_aff *iterator_map;
2196 int i;
2197 const char *name;
2198 isl_space *space;
2199 isl_multi_pw_aff *tiling;
2200 isl_pw_multi_aff *pma;
2201 isl_multi_pw_aff *mpa;
2203 data->array = NULL;
2205 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
2206 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
2208 access = find_access(data->accesses, ref_id);
2209 if (!access)
2210 return index;
2211 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
2212 return index;
2214 name = get_outer_array_name(access->access);
2215 i = find_array_index(data->gen, name);
2216 if (i < 0)
2217 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
2218 "cannot find array",
2219 return isl_multi_pw_aff_free(index));
2220 data->array = &data->gen->prog->array[i];
2221 data->local_array = &data->gen->kernel->array[i];
2223 group = find_ref_group(data->local_array, access);
2224 if (!group) {
2225 data->global = 1;
2226 return index;
2229 tile = group->private_tile;
2230 if (!tile)
2231 tile = group->shared_tile;
2232 data->global = !tile;
2233 if (!tile)
2234 return index;
2236 space = isl_space_range(isl_multi_pw_aff_get_space(index));
2237 space = isl_space_map_from_set(space);
2238 pma = isl_pw_multi_aff_identity(space);
2239 pma = isl_pw_multi_aff_product(
2240 isl_pw_multi_aff_copy(data->sched2shared), pma);
2241 tiling = isl_multi_pw_aff_from_multi_aff(
2242 isl_multi_aff_copy(tile->tiling));
2243 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
2245 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
2246 space = isl_space_map_from_set(space);
2247 mpa = isl_multi_pw_aff_identity(space);
2248 index = isl_multi_pw_aff_range_product(mpa, index);
2249 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
2251 return index;
2254 /* Dereference "expr" by adding an index [0].
2255 * The original "expr" is assumed not to have any indices.
2257 * If "expr" is a member access, then the dereferencing needs
2258 * to be applied to the structure argument of this member access.
2260 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
2262 isl_ctx *ctx;
2263 isl_ast_expr *arg0, *res;
2264 isl_ast_expr_list *list;
2266 arg0 = isl_ast_expr_get_op_arg(expr, 0);
2267 if (!arg0)
2268 return isl_ast_expr_free(expr);
2269 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
2270 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
2271 isl_ast_expr *arg;
2273 arg = isl_ast_expr_get_op_arg(arg0, 0);
2274 arg = dereference(arg);
2275 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
2276 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
2278 return expr;
2280 isl_ast_expr_free(arg0);
2282 ctx = isl_ast_expr_get_ctx(expr);
2283 res = isl_ast_expr_from_val(isl_val_zero(ctx));
2284 list = isl_ast_expr_list_from_ast_expr(res);
2285 res = isl_ast_expr_get_op_arg(expr, 0);
2286 res = isl_ast_expr_access(res, list);
2287 isl_ast_expr_free(expr);
2289 return res;
2292 /* Linearize the index expression "expr" based on the array bounds
2293 * of "array".
2295 * That is, transform expression
2297 * A[i_0][i_1]...[i_n]
2299 * to
2301 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
2303 * where b_0, b_1, ..., b_n are the bounds on the array.
2305 * If the base of "expr" is a member access, then the linearization needs
2306 * to be applied to the structure argument of this member access.
2308 * In the base case, if "expr" has no arguments (other than the name of
2309 * the array), then we are passing an entire array to a function.
2310 * In this case, there is nothing to linearize.
2311 * Note that at this point an expression with no arguments can
2312 * only be an entire array because the scalar case and
2313 * the case of single struct are handled by the caller.
2315 * If the number of specified index expressions in "expr"
2316 * is smaller than the dimension of the accessed array,
2317 * then the missing i_j also do not appear in the linearized expression.
2318 * Furthermore, since such an expression does not refer to a single
2319 * element while the default linearized expression would refer to
2320 * a single element, we return the expression
2322 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
2324 * instead. Note that because of the special case handling above,
2325 * we can assume here that here that there is at least one index expression.
2327 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
2328 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
2330 int i, n;
2331 isl_ctx *ctx;
2332 isl_set *context;
2333 isl_ast_expr *arg0;
2334 isl_ast_expr *res;
2335 isl_ast_expr_list *list;
2336 isl_ast_build *build;
2338 arg0 = isl_ast_expr_get_op_arg(expr, 0);
2339 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
2340 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
2341 isl_ast_expr *arg;
2343 arg = isl_ast_expr_get_op_arg(arg0, 0);
2344 arg = gpu_local_array_info_linearize_index(array, arg);
2345 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
2346 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
2348 return expr;
2350 isl_ast_expr_free(arg0);
2352 if (isl_ast_expr_get_op_n_arg(expr) == 1)
2353 return expr;
2355 ctx = isl_ast_expr_get_ctx(expr);
2356 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
2357 build = isl_ast_build_from_context(context);
2359 n = isl_ast_expr_get_op_n_arg(expr);
2360 res = isl_ast_expr_get_op_arg(expr, 1);
2361 for (i = 1; i < array->n_index; ++i) {
2362 isl_pw_aff *bound_i;
2363 isl_ast_expr *expr_i;
2365 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
2366 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
2367 res = isl_ast_expr_mul(res, expr_i);
2369 if (i + 1 >= n)
2370 continue;
2371 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
2372 res = isl_ast_expr_add(res, expr_i);
2375 isl_ast_build_free(build);
2377 if (1 + array->n_index > n) {
2378 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
2379 } else {
2380 list = isl_ast_expr_list_from_ast_expr(res);
2381 res = isl_ast_expr_get_op_arg(expr, 0);
2382 res = isl_ast_expr_access(res, list);
2385 isl_ast_expr_free(expr);
2387 return res;
2390 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
2392 * If the AST expression refers to an array that is not accessed
2393 * at all, then this means the value of the expression is not used,
2394 * so we might as well print zero (NULL pointer) instead.
2396 * If the AST expression refers to a global scalar that is not
2397 * a read-only scalar, then its address was passed to the kernel and
2398 * we need to dereference it.
2400 * If the AST expression refers to an access to a global array,
2401 * then we linearize the access exploiting the bounds in data->local_array.
2403 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
2404 __isl_keep isl_id *id, void *user)
2406 struct ppcg_transform_data *data = user;
2408 if (!data->array)
2409 return expr;
2410 if (!data->array->accessed) {
2411 isl_ctx *ctx;
2413 ctx = isl_ast_expr_get_ctx(expr);
2414 isl_ast_expr_free(expr);
2415 return isl_ast_expr_from_val(isl_val_zero(ctx));
2417 if (gpu_array_is_read_only_scalar(data->array))
2418 return expr;
2419 if (!data->global)
2420 return expr;
2421 if (data->array->n_index == 0)
2422 return dereference(expr);
2423 if (!data->array->linearize)
2424 return expr;
2426 return gpu_local_array_info_linearize_index(data->local_array, expr);
2429 /* This function is called for each instance of a user statement
2430 * in the kernel.
2432 * We attach a struct ppcg_kernel_stmt to the "node", containing
2433 * a computed AST expression for each access.
2434 * These AST expressions are computed from iterator_map,
2435 * which expresses the domain
2436 * elements in terms of the generated loops, and sched2shared,
2437 * which expresses the first shared_len dimensions of the schedule
2438 * computed by PPCG in terms of the generated loops.
2440 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
2441 __isl_keep isl_ast_build *build, void *user)
2443 struct ppcg_transform_data data;
2444 struct gpu_gen *gen = (struct gpu_gen *) user;
2445 struct ppcg_kernel_stmt *stmt;
2446 isl_id *id;
2447 isl_pw_multi_aff *sched2shared;
2448 isl_map *map;
2449 isl_pw_multi_aff *iterator_map;
2450 isl_ast_expr *expr, *arg;
2451 isl_union_map *schedule;
2453 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2454 if (!stmt)
2455 return isl_ast_node_free(node);
2457 expr = isl_ast_node_user_get_expr(node);
2458 arg = isl_ast_expr_get_op_arg(expr, 0);
2459 id = isl_ast_expr_get_id(arg);
2461 schedule = isl_ast_build_get_schedule(build);
2462 map = isl_map_reverse(isl_map_from_union_map(schedule));
2463 iterator_map = isl_pw_multi_aff_from_map(map);
2464 sched2shared = compute_sched_to_shared(gen,
2465 isl_pw_multi_aff_copy(iterator_map));
2467 stmt->type = ppcg_kernel_domain;
2468 stmt->u.d.stmt = find_stmt(gen->prog, id);
2469 if (!stmt->u.d.stmt)
2470 isl_die(gen->ctx, isl_error_internal,
2471 "statement not found", goto error);
2473 data.gen = gen;
2474 data.accesses = stmt->u.d.stmt->accesses;
2475 data.iterator_map = iterator_map;
2476 data.sched2shared = sched2shared;
2477 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
2478 build, &transform_index, &data,
2479 &transform_expr, &data);
2481 isl_id_free(id);
2482 isl_pw_multi_aff_free(iterator_map);
2483 isl_pw_multi_aff_free(sched2shared);
2484 isl_ast_expr_free(arg);
2485 isl_ast_expr_free(expr);
2487 id = isl_id_alloc(gen->ctx, NULL, stmt);
2488 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2489 return isl_ast_node_set_annotation(node, id);
2490 error:
2491 isl_id_free(id);
2492 isl_pw_multi_aff_free(iterator_map);
2493 ppcg_kernel_stmt_free(stmt);
2494 isl_pw_multi_aff_free(sched2shared);
2495 return isl_ast_node_free(node);
2498 /* This function is called when code has been generated for the shared
2499 * tile loops. The "schedule" refers only to the original statements.
2501 * We extend the schedule with that part of gen->local_sched that hasn't
2502 * been taken into account yet. This introduces parameters referring
2503 * to thread ids in the schedule, so we add them (with the appropriate
2504 * bounds to the context as well).
2505 * Finally, we set the appropriate unrolling options
2506 * if gen->first_unroll is set.
2508 static __isl_give isl_ast_node *create_domain_leaf(
2509 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
2510 void *user)
2512 struct gpu_gen *gen = (struct gpu_gen *) user;
2513 isl_space *space;
2514 isl_union_map *sched;
2515 isl_ast_node *tree;
2516 isl_set *set;
2517 isl_id_list *iterators;
2518 int n;
2520 schedule = extend_schedule(schedule,
2521 isl_union_map_copy(gen->local_sched),
2522 gen->shared_len, gen->thread_tiled_len);
2524 space = isl_ast_build_get_schedule_space(build);
2525 set = isl_set_universe(space);
2526 set = add_bounded_parameters(set, gen->kernel->block_dim,
2527 gen->kernel->thread_ids);
2528 build = isl_ast_build_restrict(build, set);
2530 n = gen->thread_tiled_len - gen->shared_len;
2532 if (gen->first_unroll >= 0) {
2533 space = isl_space_set_alloc(gen->ctx, 0, n);
2534 build = set_unroll(build, space, gen->first_unroll);
2536 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
2537 build = isl_ast_build_set_iterators(build, iterators);
2538 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
2539 tree = isl_ast_build_node_from_schedule_map(build, schedule);
2540 isl_ast_build_free(build);
2542 return tree;
2545 /* This function is called for each statement node in the AST of the code
2546 * for copying to or from shared/private memory.
2547 * Attach a pointer to a ppcg_kernel_stmt representing the copy
2548 * statement to the node.
2549 * The statement name is "read" or "write", depending on whether we are
2550 * reading from global memory or writing to global memory.
2551 * The name of the T space is {shared,private}_<array>.
2553 * The schedule is of the form
2555 * type[A -> T] -> L
2557 * where A refers to a piece of an array and T to the corresponding
2558 * shifted tile. We split this schedule into mappings L -> A and L -> T
2559 * and store the corresponding expressions in stmt->index and stmt->local_index,
2560 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
2562 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
2563 __isl_keep isl_ast_build *build, void *user)
2565 struct gpu_gen *gen = (struct gpu_gen *) user;
2566 struct ppcg_kernel_stmt *stmt;
2567 isl_id *id;
2568 isl_ast_expr *expr;
2569 isl_space *space;
2570 isl_map *access, *local_access, *map;
2571 isl_pw_multi_aff *pma;
2572 const char *type;
2573 int array_index;
2575 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2576 if (!stmt)
2577 return isl_ast_node_free(node);
2579 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
2580 type = isl_map_get_tuple_name(access, isl_dim_in);
2581 stmt->u.c.read = !strcmp(type, "read");
2582 access = isl_map_reverse(access);
2583 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
2584 local_access = isl_map_copy(access);
2586 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
2587 id = isl_map_get_tuple_id(access, isl_dim_out);
2588 map = isl_map_set_tuple_id(map, isl_dim_in, id);
2589 access = isl_map_apply_range(access, map);
2590 pma = isl_pw_multi_aff_from_map(access);
2591 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
2592 stmt->u.c.index = expr;
2594 map = isl_map_range_map(isl_map_universe(space));
2595 id = isl_map_get_tuple_id(local_access, isl_dim_out);
2596 map = isl_map_set_tuple_id(map, isl_dim_in, id);
2597 local_access = isl_map_apply_range(local_access, map);
2598 pma = isl_pw_multi_aff_from_map(local_access);
2599 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
2600 stmt->u.c.local_index = expr;
2602 stmt->u.c.array = gen->copy_group->array;
2603 array_index = stmt->u.c.array - gen->prog->array;
2604 stmt->u.c.local_array = &gen->kernel->array[array_index];
2605 stmt->type = ppcg_kernel_copy;
2607 id = isl_id_alloc(gen->ctx, NULL, stmt);
2608 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2609 return isl_ast_node_set_annotation(node, id);
2612 /* Given a schedule of the form
2614 * [S -> A] -> L
2616 * (with S the first shared_len dimensions of the computed schedule,
2617 * A the array and L the schedule correponding to the generated loops),
2618 * indicating where to copy the array elements that need to be copied,
2619 * construct code for performing the copying.
2621 * "group" is the array reference group that is being copied
2622 * "type" is either "read" or "write"
2623 * private is set if copying needs to be performed to/from registers
2625 * We first construct a mapping to a shifted tile of the array,
2627 * [S -> A] -> T(S,A) (1)
2629 * If private is set, then we also use this mapping as a schedule
2630 * (which is already thread-specific and will be completely unrolled).
2631 * Otherwise, we wrap/tile the range over the threads.
2632 * The result is
2634 * [S -> A] -> T'(S,A)
2636 * Combined with the given schedule, we have
2638 * [S -> A] -> [L -> T'(S,A)] (2)
2640 * From the shifted tile mapping, we construct a mapping
2642 * [S -> A] -> [A -> T(S,A)]
2644 * and apply it to the schedule (2), obtaining
2646 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
2648 * Note that we can project out S because it is uniquely defined by L.
2650 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
2651 __isl_take isl_map *sched,
2652 const char *type, struct gpu_array_ref_group *group,
2653 __isl_take isl_ast_build *build, int private)
2655 isl_space *space;
2656 isl_ast_node *tree;
2657 isl_map *schedule, *shift, *map;
2658 isl_set *set;
2659 isl_id_list *iterators;
2660 int n;
2662 shift = shift_access(group);
2664 schedule = isl_map_copy(shift);
2665 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
2666 if (!private)
2667 schedule = tile_access_schedule(gen, schedule);
2669 n = isl_map_dim(schedule, isl_dim_out);
2670 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
2671 set = add_bounded_parameters(set, gen->kernel->block_dim,
2672 gen->kernel->thread_ids);
2674 schedule = isl_map_range_product(sched, schedule);
2676 space = isl_space_domain(isl_map_get_space(shift));
2677 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
2678 map = isl_map_range_product(map, shift);
2680 schedule = isl_map_apply_domain(schedule, map);
2682 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
2684 build = isl_ast_build_restrict(build, set);
2686 gen->copy_group = group;
2688 if (private) {
2689 space = isl_space_range(isl_map_get_space(schedule));
2690 space = isl_space_range(isl_space_unwrap(space));
2691 build = set_unroll(build, space, 0);
2693 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
2694 build = isl_ast_build_set_iterators(build, iterators);
2695 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
2696 tree = isl_ast_build_node_from_schedule_map(build,
2697 isl_union_map_from_map(schedule));
2698 isl_ast_build_free(build);
2700 return tree;
2703 /* Return code for reading into or writing from shared memory
2704 * the given array reference group.
2706 * If we are performing a read from global memory to shared memory and
2707 * if the array involved is not a scalar, then we copy
2708 * the entire tile to shared memory. This may result in some extra
2709 * elements getting copied, but it should lead to simpler code
2710 * (which means that fewer registers may be needed) and less divergence.
2712 * Otherwise, we only copy the elements that will be read or have been written
2713 * in the kernel.
2716 * The input "sched" is of the form.
2718 * type[S -> A] -> L
2720 * with S the first shared_len dimensions of the computed schedule,
2721 * A the array and L the schedule correponding to the generated loops.
2723 * We first drop "type",
2725 * [S -> A] -> L
2727 * If the above conditions are satisfied, we project out A,
2728 * resulting in
2730 * S -> L
2732 * and then introduce the group tile [S -> T], resulting in
2734 * [S -> T] -> L
2736 static __isl_give isl_ast_node *copy_group_shared_accesses(
2737 struct gpu_gen *gen, struct gpu_array_ref_group *group,
2738 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
2740 const char *type;
2741 int read;
2742 isl_union_map *access;
2744 type = isl_map_get_tuple_name(sched, isl_dim_in);
2745 read = !strcmp(type, "read");
2747 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
2749 if (read && !gpu_array_is_scalar(group->array)) {
2750 isl_space *space;
2751 isl_map *map;
2753 space = isl_space_domain(isl_map_get_space(sched));
2754 space = isl_space_unwrap(space);
2755 map = isl_map_domain_map(isl_map_universe(space));
2756 sched = isl_map_apply_domain(sched, map);
2758 map = group_tile(group);
2759 map = isl_map_reverse(isl_map_domain_map(map));
2760 sched = isl_map_apply_domain(sched, map);
2763 return copy_access(gen, sched, type, group, build, 0);
2766 /* Return code for reading into or writing from private memory
2767 * the given array reference group.
2769 * Let S be the first shared_len dimensions of the computed schedule,
2770 * D the iteration domains, A the array and L the schedule correponding
2771 * to the generated loops.
2772 * "sched" is of the form
2774 * type[S -> A] -> L
2776 * where type is either "read" or "write".
2777 * We apply the privatization D -> S(t), with t the thread ids,
2778 * to the access relation D -> A to obtain the privatized access relation
2780 * S(t) -> A
2782 * We drop the type from "sched" and intersect with the privatized access
2783 * relation to obtain
2785 * [S(t) -> A] -> L
2787 static __isl_give isl_ast_node *copy_group_private_accesses(
2788 struct gpu_gen *gen, struct gpu_array_ref_group *group,
2789 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
2791 const char *type;
2792 int read;
2793 isl_union_map *priv;
2794 isl_union_map *access;
2795 isl_map *access_map;
2797 type = isl_map_get_tuple_name(sched, isl_dim_in);
2798 read = !strcmp(type, "read");
2800 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2801 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2802 priv);
2804 access = gpu_array_ref_group_access_relation(group, read, !read);
2805 access = isl_union_map_apply_domain(access, priv);
2806 access_map = isl_map_from_union_map(access);
2808 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
2809 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
2811 return copy_access(gen, sched, type, group, build, 1);
2814 /* Return code for reading into or writing from shared or private memory.
2816 * "schedule" is of the form
2818 * type[S -> A] -> L
2820 * with S be the first shared_len dimensions of the computed schedule,
2821 * A the array and L the schedule correponding to the generated loops.
2822 * The array reference group is attached to "type".
2824 static __isl_give isl_ast_node *create_access_leaf(
2825 struct gpu_gen *gen, __isl_take isl_map *schedule,
2826 __isl_take isl_ast_build *build)
2828 struct gpu_array_ref_group *group;
2829 isl_id *id;
2831 id = isl_map_get_tuple_id(schedule, isl_dim_in);
2832 group = isl_id_get_user(id);
2833 isl_id_free(id);
2835 if (group->private_tile)
2836 return copy_group_private_accesses(gen, group, schedule,
2837 build);
2838 else
2839 return copy_group_shared_accesses(gen, group, schedule,
2840 build);
2843 /* Create a domain node representing a synchronization.
2845 static __isl_give isl_ast_node *create_sync_leaf(
2846 struct gpu_gen *gen, __isl_take isl_map *schedule,
2847 __isl_take isl_ast_build *build)
2849 struct ppcg_kernel_stmt *stmt;
2850 isl_id *id;
2851 isl_space *space;
2852 isl_ast_node *node;
2853 isl_ast_expr *expr;
2855 isl_map_free(schedule);
2857 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2858 if (!stmt)
2859 return NULL;
2861 stmt->type = ppcg_kernel_sync;
2863 space = isl_ast_build_get_schedule_space(build);
2864 space = isl_space_from_domain(space);
2865 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
2866 expr = isl_ast_build_call_from_pw_multi_aff(build,
2867 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
2868 node = isl_ast_node_alloc_user(expr);
2869 isl_ast_build_free(build);
2871 id = isl_id_alloc(gen->ctx, NULL, stmt);
2872 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2873 return isl_ast_node_set_annotation(node, id);
2876 /* This function is called during the code generation at the point
2877 * where the schedule domain element is completely determined by
2878 * the generated code. The input schedule contains the original
2879 * statements as well as synchronization and copy "statements".
2880 * The latter are scheduled at different points than any of the original
2881 * statements, so they will only arrive here in isolation.
2883 * If the current schedule only refers to a single statement,
2884 * we check if it is a copy or synchronization statement and
2885 * call the appropriate functions.
2886 * Otherwise, we assume we are dealing with the original statements
2887 * and we call create_domain_leaf.
2889 static __isl_give isl_ast_node *create_kernel_leaf(
2890 __isl_take isl_ast_build *build, void *user)
2892 struct gpu_gen *gen = (struct gpu_gen *) user;
2893 isl_map *map;
2894 isl_union_map *schedule;
2895 const char *name;
2897 schedule = isl_ast_build_get_schedule(build);
2899 if (isl_union_map_n_map(schedule) != 1)
2900 return create_domain_leaf(schedule, build, user);
2902 map = isl_map_from_union_map(schedule);
2903 name = isl_map_get_tuple_name(map, isl_dim_in);
2904 if (!strcmp(name, "read") || !strcmp(name, "write"))
2905 return create_access_leaf(gen, map, build);
2906 if (!strcmp(name, "sync"))
2907 return create_sync_leaf(gen, map, build);
2909 return create_domain_leaf(isl_union_map_from_map(map), build, user);
2912 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
2913 * have value 0) and all even schedule dimensions as "unroll".
2915 * That is, the options look as follows
2917 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
2918 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
2920 * The even positions are used to be able to schedule copying blocks
2921 * and synchronization before or after each level of the shared memory
2922 * tile loops and we want to make sure that code for these is generated
2923 * separately (within each level).
2925 static __isl_give isl_ast_build *set_atomic_and_unroll(
2926 __isl_take isl_ast_build *build,
2927 __isl_take isl_space *space, int sched_len)
2929 isl_ctx *ctx;
2930 isl_map *map;
2931 isl_constraint *c;
2932 isl_union_map *opt;
2933 isl_local_space *ls;
2934 int i, n;
2936 ctx = isl_ast_build_get_ctx(build);
2938 space = isl_space_params(space);
2939 space = isl_space_add_dims(space, isl_dim_set, sched_len);
2940 space = isl_space_from_domain(space);
2941 space = isl_space_add_dims(space, isl_dim_out, 2);
2942 map = isl_map_universe(isl_space_copy(space));
2943 for (i = 0; i < sched_len; i += 2)
2944 map = isl_map_fix_si(map, isl_dim_in, i, 0);
2945 ls = isl_local_space_from_space(isl_map_get_space(map));
2946 c = isl_equality_alloc(ls);
2947 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
2948 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
2949 c = isl_constraint_set_constant_si(c, 1);
2950 map = isl_map_add_constraint(map, c);
2951 map = isl_map_project_out(map, isl_dim_out, 1, 1);
2952 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
2953 opt = isl_union_map_from_map(map);
2955 map = isl_map_universe(space);
2956 ls = isl_local_space_from_space(isl_map_get_space(map));
2957 c = isl_equality_alloc(ls);
2958 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
2959 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
2960 map = isl_map_add_constraint(map, c);
2961 map = isl_map_project_out(map, isl_dim_out, 1, 1);
2962 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
2963 opt = isl_union_map_add_map(opt, map);
2965 build = isl_ast_build_set_options(build, opt);
2967 return build;
2970 /* Return a map that maps a space of dimension gen->shared_len
2971 * to its last dimensions starting at gen->tile_first.
2972 * The range is of dimension
2974 * 2 * (gen->shared_len - gen->tile_first) + 1
2976 * The input dimensions are mapped to the odd dimensions in the output,
2977 * while the even dimensions (except 2*pos) are fixed to 0.
2978 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
2979 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
2980 * are mapped to the output. The remaining input dimensions are projected
2981 * out and the corresponding output dimensions are fixed to 0.
2983 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
2984 __isl_take isl_space *space, int pos, int val)
2986 int i, n;
2987 isl_map *proj;
2989 space = isl_space_set_from_params(space);
2990 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
2991 space = isl_space_map_from_set(space);
2992 proj = isl_map_identity(space);
2993 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
2994 n = gen->shared_len - gen->tile_first;
2995 for (i = 0; i <= n; ++i) {
2996 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
2997 if (i == pos)
2998 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
2999 else
3000 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
3003 if (pos < 0)
3004 return proj;
3006 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
3007 gen->shared_len - (gen->tile_first + pos));
3008 for (i = pos; i < n; ++i)
3009 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
3011 return proj;
3014 /* Given the AST context schedule "schedule" and the mapping from
3015 * domains to the shared tile loops "shared_sched", add a schedule
3016 * for a synchronization operation at position "val" of loop level "pos".
3018 * schedule is of the form
3020 * D -> L
3022 * (with D the iteration domains and L the already generated loops),
3023 * while shared_sched is of the form
3025 * D -> S
3027 * We combine them into
3029 * L -> S
3031 * apply a mapping
3033 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3035 * and use the result as a schedule for "sync".
3037 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
3038 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3039 __isl_keep isl_union_map *shared_sched, int pos, int val)
3041 isl_space *space;
3042 isl_map *proj, *map;
3044 shared_sched = isl_union_map_copy(shared_sched);
3045 schedule = isl_union_map_copy(schedule);
3047 space = isl_union_map_get_space(shared_sched);
3048 schedule = isl_union_map_apply_domain(shared_sched, schedule);
3049 map = isl_map_from_union_map(schedule);
3051 proj = insert_even(gen, space, pos, val);
3052 map = isl_map_apply_range(map, proj);
3053 map = isl_map_from_range(isl_map_wrap(map));
3054 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
3056 res = isl_union_map_add_map(res, map);
3058 return res;
3061 /* Given a set of wrapped references "ref", return the corresponding
3062 * access relations based on the tagged access relations "tagged".
3064 * The elements of "ref" are of the form
3066 * [D -> R]
3068 * with D an iteration domains and R a reference.
3069 * The elements of "tagged" are of the form
3071 * [D -> R] -> A
3073 * with A an array.
3075 * Extend "tagged" to include the iteration domain in the range, i.e.,
3077 * [D -> R] -> [D -> A]
3079 * apply the result to "ref" and then unwrap the resulting set
3080 * to obtain relations of the form
3082 * D -> A
3084 static __isl_give isl_union_map *wrapped_reference_to_access(
3085 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
3087 isl_union_map *tag2access;
3089 tag2access = isl_union_map_copy(tagged);
3090 tag2access = isl_union_map_universe(tag2access);
3091 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
3092 tag2access = isl_union_map_domain_map(tag2access);
3093 tag2access = isl_union_map_range_product(tag2access, tagged);
3095 ref = isl_union_set_coalesce(ref);
3096 ref = isl_union_set_apply(ref, tag2access);
3098 return isl_union_set_unwrap(ref);
3101 /* Given an access relation "access" from "group", remove those reads
3102 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
3103 * communicate data within the same iteration of the last_shared dimension
3104 * of the group.
3106 * If the access is a read then it is either an element of
3108 * live_in union (range flow)
3110 * where live_in and flow may be overapproximations, or
3111 * it reads an uninitialized value (that is not live-in because
3112 * there is an intermediate kill) or it reads a value that was
3113 * written within the same (compound) statement instance.
3114 * If the access is a write then it is either an element of
3116 * live_out union (domain flow)
3118 * or it writes a value that is never read (and is not live-out
3119 * because of an intermediate kill) or only
3120 * within the same (compound) statement instance.
3121 * In both cases, the access relation is also a subset of
3122 * the group access relation.
3124 * The cases where an uninitialized value is read or a value is written
3125 * that is never read or where the dataflow occurs within a statement
3126 * instance are also considered local and may also be removed.
3128 * Essentially, we compute the intersection of "access" with either
3130 * live_in union (range non-local-flow)
3132 * or
3134 * live_out union (domain non-local-flow)
3136 * We first construct a relation "local"
3138 * [[D -> R] -> [D' -> R']]
3140 * of pairs of domain iterations accessing the reference group
3141 * and references in the group that are scheduled to the same iteration
3142 * of the last_shared dimension.
3144 * If this relation does not intersect the dataflow dependences,
3145 * then there is nothing we can possibly remove, unless the dataflow
3146 * dependences themselves only relate a subset of the accesses.
3147 * In particular, the accesses may not be involved in any dataflow
3148 * dependences, either because they are uninitialized reads/dead writes
3149 * or because the dataflow occurs inside a statement instance.
3151 * Since the computation below may break up the access relation
3152 * into smaller pieces, we only perform the intersection with
3153 * the non-local dependent accesses if the local pairs
3154 * intersect the dataflow dependences. Otherwise, we intersect
3155 * with the universe of the non-local dependent accesses.
3156 * This should at least remove accesses from statements that
3157 * do not participate in any dependences.
3159 * In particular, we remove the "local" dataflow dependences from
3160 * the set of all dataflow dependences.
3161 * Note that if the potential dataflow dependences are an overapproximation
3162 * of the actual dataflow dependences, then the result remains an
3163 * overapproximation of the non-local dataflow dependences.
3164 * Copying to/from global memory is only needed for the references
3165 * in the domain/range of the result or for accesses that are live out/in
3166 * for the entire scop.
3168 * We therefore map the domain/range of the "external" relation
3169 * to the corresponding access relation and take the union with
3170 * the live out/in relation.
3172 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
3173 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
3174 int read)
3176 int empty;
3177 isl_union_pw_multi_aff *tagger;
3178 isl_union_set *domain;
3179 isl_space *space;
3180 isl_union_map *sched, *local, *tagged, *external;
3181 isl_union_set *tag_set;
3182 isl_map *proj;
3184 if (isl_union_map_is_empty(access))
3185 return access;
3187 tagged = group_tagged_access_relation(group);
3189 sched = isl_union_map_copy(gen->sched);
3191 space = isl_union_map_get_space(sched);
3192 proj = projection(space, gen->untiled_len, group->last_shared + 1);
3193 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3195 tagger = isl_union_pw_multi_aff_copy(gen->prog->scop->tagger);
3196 domain = isl_union_map_domain(isl_union_map_copy(tagged));
3197 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
3198 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
3200 local = isl_union_map_apply_range(sched,
3201 isl_union_map_reverse(isl_union_map_copy(sched)));
3202 local = isl_union_map_intersect(local,
3203 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
3205 empty = isl_union_map_is_empty(local);
3207 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
3208 external = isl_union_map_intersect_params(external,
3209 isl_set_copy(gen->prog->scop->context));
3210 external = isl_union_map_subtract(external, local);
3212 if (read) {
3213 tag_set = isl_union_map_range(external);
3214 external = wrapped_reference_to_access(tag_set, tagged);
3215 external = isl_union_map_union(external,
3216 isl_union_map_copy(gen->prog->scop->live_in));
3217 } else {
3218 tag_set = isl_union_map_domain(external);
3219 external = wrapped_reference_to_access(tag_set, tagged);
3220 external = isl_union_map_union(external,
3221 isl_union_map_copy(gen->prog->scop->live_out));
3224 if (empty < 0)
3225 external = isl_union_map_free(external);
3226 else if (empty)
3227 external = isl_union_map_universe(external);
3229 access = isl_union_map_intersect(access, external);
3231 return access;
3234 /* Given the AST context schedule "schedule" and the mapping from
3235 * domains to the shared tile loops "shared_sched", add a schedule
3236 * for copying an array reference group to/from shared/private memory.
3237 * "read" is set if data should be copied from global memory
3238 * to shared/private memory.
3239 * "k" represents the current group
3240 * "s" is the total number of groups
3242 * We schedule an operation before or after the innermost loop
3243 * of "shared_sched" that affects the tile of the array reference group.
3245 * schedule is of the form
3247 * D -> L
3249 * (with D the iteration domains and L the already generated loops),
3250 * while shared_sched is of the form
3252 * D -> S
3254 * We first compute the access relation for the reference group
3256 * D -> A
3258 * and remove from this access relation those reads or writes
3259 * that only needed to communicate data within the same iteration
3260 * of the last_shared dimension of the group.
3261 * We then combine what is left with shared_sched into
3263 * D -> [S -> A]
3265 * If this results in an empty relation, no copying needs to be performed
3266 * at this point.
3267 * Otherwise, we invert the relation and combine it with "schedule" into
3269 * [S -> A] -> L
3271 * The actual additional piece of the schedule is obtained from combining
3273 * [S -> A] -> S
3275 * with a mapping
3277 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3279 * The position of "val" corresponds to the innermost loop that affects
3280 * the tile and the value indicates where the copying is scheduled
3281 * with respect to the actual kernel code (at value 0).
3282 * Reads are schedule before the code, writes to global memory from
3283 * private memory are scheduled at values 1 to s, writes to global
3284 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
3286 * If we are scheduling a read from global memory to shared memory,
3287 * we insert a synchronization before the kernel code (at the innermost
3288 * level).
3289 * If we are scheduling a write to global memory, then we add
3290 * a synchronization after all writes (at value 2 *s + 2).
3291 * However, there is no need for a synchronization after the outermost loop.
3292 * A write to global memory from private memory at the innermost level
3293 * does not require a synchronization, because it is covered by
3294 * the synchronization after the kernel inserted by body_schedule.
3296 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
3297 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3298 __isl_keep isl_union_map *shared_sched,
3299 struct gpu_array_ref_group *group, int read, int k, int s)
3301 int n;
3302 int pos, val;
3303 isl_space *space;
3304 isl_union_map *access;
3305 isl_map *map, *proj, *access_map;
3306 isl_id *id;
3308 access = gpu_array_ref_group_access_relation(group, read, !read);
3309 access = remove_local_accesses(gen, group, access, read);
3310 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
3311 access);
3313 if (isl_union_map_is_empty(access)) {
3314 isl_union_map_free(access);
3315 return res;
3318 access = isl_union_map_reverse(access);
3319 access = isl_union_map_apply_range(access,
3320 isl_union_map_copy(schedule));
3321 access_map = isl_map_from_union_map(access);
3323 space = isl_space_copy(group->array->space);
3324 space = isl_space_from_range(space);
3325 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
3326 map = isl_map_domain_map(isl_map_universe(space));
3328 space = isl_union_map_get_space(schedule);
3329 pos = group->last_shared + 1 - gen->tile_first;
3330 assert(pos >= 0);
3331 if (read)
3332 val = -2 - k;
3333 else if (group->private_tile)
3334 val = 1 + k;
3335 else
3336 val = 1 + s + 1 + k;
3337 proj = insert_even(gen, space, pos, val);
3338 map = isl_map_apply_range(map, proj);
3340 access_map = isl_map_range_product(access_map, map);
3342 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
3343 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
3345 res = isl_union_map_add_map(res, access_map);
3347 n = gen->shared_len - gen->tile_first;
3348 if (read) {
3349 if (!group->private_tile)
3350 res = add_sync_schedule(gen, res, schedule,
3351 shared_sched, n, -1);
3352 } else {
3353 if (pos == 0)
3354 return res;
3355 if (pos == n && group->private_tile)
3356 return res;
3357 res = add_sync_schedule(gen, res, schedule, shared_sched,
3358 pos, 2 * s + 2);
3361 return res;
3364 /* Return a schedule for the shared tile loops based on the current
3365 * AST context schedule.
3367 * We create a "shared_sched" that maps the domains to the first
3368 * shared_len dimensions of the computed schedule, project out the
3369 * first tile_first dimensions (as these are already covered by
3370 * the host code) and insert "statement-level" dimensions at even
3371 * positions so that we can schedule copy blocks and synchronization
3372 * before/after each level.
3374 * In particular, copy blocks are inserted inside the innermost
3375 * level that affect the tile. For the copying to global memory,
3376 * those from private memory are scheduled before those from shared
3377 * memory such that synchronization can be inserted between the two
3378 * at the innermost level.
3379 * Synchronization is inserted at the innermost level before the
3380 * actual kernel code if there is any copying from global memory
3381 * to shared memory. It is inserted unconditionally at the innermost
3382 * level after the actual kernel code and the copying to global memory
3383 * from private memory (if any). Finally, it is inserted after
3384 * any copying to global memory, except at the outermost level
3385 * and at the innermost level if there is no copying from shared
3386 * memory. The copying from private memory is covered by the unconditional
3387 * synchronization at the innermost level.
3389 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
3390 __isl_take isl_union_map *schedule)
3392 isl_space *space;
3393 isl_union_map *res;
3394 isl_union_map *shared_sched;
3395 isl_union_map *sched;
3396 isl_map *proj, *map;
3397 int i, j, k, s;
3399 shared_sched = isl_union_map_copy(gen->tiled_sched);
3400 proj = projection(isl_union_map_get_space(shared_sched),
3401 gen->tiled_len, gen->shared_len);
3402 shared_sched = isl_union_map_apply_range(shared_sched,
3403 isl_union_map_from_map(proj));
3404 space = isl_union_map_get_space(shared_sched);
3405 proj = insert_even(gen, space, -1, 0);
3406 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
3407 isl_union_map_from_map(proj));
3409 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
3411 s = 0;
3412 for (i = 0; i < gen->kernel->n_array; ++i)
3413 s += gen->kernel->array[i].n_group;
3415 k = 0;
3416 for (i = 0; i < gen->kernel->n_array; ++i) {
3417 struct gpu_local_array_info *array = &gen->kernel->array[i];
3419 for (j = 0; j < array->n_group; ++j) {
3420 struct gpu_array_ref_group *group;
3422 group = array->groups[j];
3423 if (!group->private_tile && !group->shared_tile)
3424 continue;
3425 res = add_group_schedule(gen, res, schedule,
3426 shared_sched, group, 0, k, s);
3427 res = add_group_schedule(gen, res, schedule,
3428 shared_sched, group, 1, k, s);
3429 ++k;
3433 res = add_sync_schedule(gen, res, schedule, shared_sched,
3434 gen->shared_len - gen->tile_first, 1 + s);
3436 isl_union_map_free(shared_sched);
3437 isl_union_map_free(schedule);
3439 return res;
3442 /* Generate code for "kernel" in the given "context".
3444 * We first generate code for the shared tile loops (T1T, T1P and T2)
3445 * in a context that includes the block ids.
3446 * Within each iteration of these loops an additional code generation
3447 * is performed (within create_kernel_leaf) for the rest of the schedule
3448 * in a context that includes the thread ids.
3450 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
3451 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
3452 __isl_keep isl_multi_pw_aff *grid_size)
3454 isl_space *space;
3455 isl_set *set;
3456 isl_id_list *iterators;
3457 isl_union_map *schedule;
3458 isl_ast_node *tree;
3459 int sched_len;
3461 schedule = isl_ast_build_get_schedule(build);
3463 build = isl_ast_build_copy(build);
3464 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
3465 space = isl_ast_build_get_schedule_space(build);
3466 set = isl_set_universe(isl_space_copy(space));
3467 set = add_bounded_parameters_dynamic(set, grid_size,
3468 gen->kernel->block_ids);
3469 build = isl_ast_build_restrict(build, set);
3471 schedule = body_schedule(gen, schedule);
3473 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
3475 build = set_atomic_and_unroll(build, space, sched_len);
3476 iterators = ppcg_scop_generate_names(gen->prog->scop, sched_len, "g");
3477 build = isl_ast_build_set_iterators(build, iterators);
3478 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
3479 tree = isl_ast_build_node_from_schedule_map(build, schedule);
3480 isl_ast_build_free(build);
3482 return tree;
3485 /* Attach "id" to the given node.
3487 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
3488 __isl_keep isl_ast_build *build, void *user)
3490 isl_id *id = user;
3492 node = isl_ast_node_set_annotation(node, id);
3494 return node;
3497 /* Construct an AST node for performing a kernel launch and attach
3498 * the information about the kernel to that node.
3500 * The kernel AST has been constructed in the context of the range
3501 * of "schedule". In particular, the grid size has been computed
3502 * in the context. We therefore still need to make sure that these
3503 * constraints are expressed in the code. We do this by creating a schedule
3505 * kernel[] -> [S -> []]
3507 * where S is the schedule domain, i.e., the range of "schedule".
3508 * The AST generation will then create a single call surrounded by
3509 * all the condition in "S" that have not been expressed yet.
3511 * The kernel information is attached to this node in attach_id.
3513 static __isl_give isl_ast_node *construct_launch(
3514 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
3515 __isl_take struct ppcg_kernel *kernel)
3517 isl_id *id;
3518 isl_ctx *ctx;
3519 isl_union_set *domain;
3520 isl_set *set;
3521 isl_map *map;
3522 isl_ast_node *node;
3524 ctx = isl_ast_build_get_ctx(build);
3526 id = isl_id_alloc(ctx, NULL, kernel);
3527 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3529 domain = isl_union_map_range(schedule);
3530 set = isl_set_from_union_set(domain);
3531 map = isl_map_from_domain(set);
3532 map = isl_map_from_range(isl_map_wrap(map));
3533 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
3534 schedule = isl_union_map_from_map(map);
3536 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
3537 node = isl_ast_build_node_from_schedule_map(build, schedule);
3538 isl_ast_build_free(build);
3540 return node;
3543 /* This function is called for each leaf in the AST of the host code.
3544 * We first specialize the schedule to the site of the leaf, compute
3545 * the size of shared memory and then construct the body of the host code
3546 * and the associated kernel.
3548 * The necessary information for printing the kernel launch is
3549 * stored in a struct ppcg_kernel and attached to the leaf node
3550 * created to represent the launch.
3552 static __isl_give isl_ast_node *create_host_leaf(
3553 __isl_take isl_ast_build *build, void *user)
3555 struct gpu_gen *gen = (struct gpu_gen *) user;
3556 isl_id *id;
3557 isl_ast_node *node;
3558 struct ppcg_kernel *kernel;
3559 isl_set *host_domain;
3560 isl_union_map *schedule;
3561 isl_union_map *local_sched;
3562 isl_union_map *access;
3563 isl_union_set *domain;
3564 int i;
3566 schedule = isl_ast_build_get_schedule(build);
3568 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
3569 read_sizes(gen);
3571 domain = isl_union_map_domain(isl_union_map_copy(schedule));
3573 local_sched = isl_union_map_copy(gen->sched);
3574 local_sched = isl_union_map_intersect_domain(local_sched, domain);
3575 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
3576 isl_union_map_copy(gen->prog->may_write));
3577 access = isl_union_map_apply_domain(access,
3578 isl_union_map_copy(local_sched));
3580 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3581 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3582 if (!kernel)
3583 goto error;
3584 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3585 gen->n_grid, "b");
3586 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3587 gen->n_block, "t");
3589 gen->tiled_sched = tile_schedule(gen, local_sched);
3590 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
3591 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
3593 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
3594 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
3595 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
3597 kernel->ctx = gen->ctx;
3598 kernel->options = gen->options;
3599 kernel->id = gen->kernel_id++;
3600 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
3601 kernel->grid_size = extract_grid_size(gen, kernel);
3602 extract_block_size(gen, kernel);
3603 kernel->arrays = isl_union_map_range(access);
3604 kernel->arrays = isl_union_set_apply(kernel->arrays,
3605 isl_union_map_copy(gen->prog->to_outer));
3606 kernel->space = isl_ast_build_get_schedule_space(build);
3608 compute_shared_sched(gen);
3609 gen->privatization = compute_privatization(gen);
3610 if (gpu_group_references(gen) < 0)
3611 schedule = isl_union_map_free(schedule);
3612 host_domain = isl_set_from_union_set(isl_union_map_range(
3613 isl_union_map_copy(schedule)));
3614 localize_bounds(gen, kernel, host_domain);
3616 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
3617 check_shared_memory_bound(gen);
3618 compute_group_tilings(gen);
3620 kernel->tree = generate_kernel(gen, build, host_domain,
3621 kernel->grid_size);
3622 create_kernel_vars(gen, kernel);
3624 isl_map_free(gen->privatization);
3625 isl_union_map_free(gen->local_sched);
3626 isl_union_map_free(gen->tiled_sched);
3627 isl_union_map_free(gen->shared_sched);
3628 isl_union_map_free(gen->shared_proj);
3629 isl_set_free(host_domain);
3630 free(gen->tile_size);
3632 node = construct_launch(build, schedule, kernel);
3634 return node;
3635 error:
3636 isl_union_map_free(schedule);
3637 return NULL;
3640 /* Use isl to generate host code from gen->host_schedule, which corresponds to
3641 * the outer gen->tile_first loops of the global schedule in gen->sched.
3642 * Within each iteration of this partial schedule, i.e., for each kernel
3643 * launch, create_host_leaf takes care of generating the kernel code.
3645 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
3647 isl_ast_build *build;
3648 isl_ast_node *tree;
3649 isl_schedule *schedule;
3650 isl_id_list *iterators;
3652 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
3653 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
3654 iterators = ppcg_scop_generate_names(gen->prog->scop,
3655 gen->tile_first, "h");
3656 build = isl_ast_build_set_iterators(build, iterators);
3657 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
3658 schedule = isl_schedule_copy(gen->host_schedule);
3659 tree = isl_ast_build_node_from_schedule(build, schedule);
3660 isl_ast_build_free(build);
3662 return tree;
3665 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
3667 if (!str)
3668 return NULL;
3669 return isl_union_map_read_from_str(ctx, str);
3672 /* Information about the outermost tilable bands in the forest of bands.
3674 * tile_len and n_parallel are only sets on band_info structures
3675 * that correspond to outermost bands. For other bands (in particular,
3676 * ancestors of the outermost bands), n_parallal is set to 0.
3678 * prefix is the (padded) schedule leading up to the outermost tilable bands.
3680 * tile_first is the number of schedule dimensions in prefix.
3682 * suffix is the schedule of the outermost tilable bands and their descendants.
3684 struct band_info {
3685 struct gpu_gen *gen;
3686 int tile_first;
3687 int tile_len;
3688 int n_parallel;
3689 isl_union_map *prefix;
3690 isl_union_map *suffix;
3693 /* Set tile_len and n_parallel of the statement to that of
3694 * their outermost band, recorded in the band_info.
3696 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
3698 struct band_info *info = user;
3699 struct gpu_stmt *stmt;
3700 isl_id *id;
3702 id = isl_map_get_tuple_id(map, isl_dim_in);
3703 stmt = find_stmt(info->gen->prog, id);
3704 isl_id_free(id);
3706 stmt->tile_len = info->tile_len;
3707 stmt->n_parallel = info->n_parallel;
3709 isl_map_free(map);
3711 return 0;
3714 /* Mark all dimensions in the current band node atomic.
3716 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3718 int i, n;
3720 n = isl_schedule_node_band_n_member(node);
3721 for (i = 0; i < n; ++i)
3722 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3723 isl_ast_loop_atomic);
3725 return node;
3728 /* Mark "node" atomic, if it is a band node.
3729 * Do the same for all ancestors.
3730 * Return a pointer to "node" (in the updated schedule tree).
3732 static __isl_give isl_schedule_node *atomic_ancestors(
3733 __isl_take isl_schedule_node *node)
3735 int pos;
3737 if (!node)
3738 return NULL;
3739 if (!isl_schedule_node_has_parent(node))
3740 return node;
3742 pos = isl_schedule_node_get_child_position(node);
3743 node = isl_schedule_node_parent(node);
3744 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3745 node = atomic(node);
3746 node = atomic_ancestors(node);
3747 node = isl_schedule_node_child(node, pos);
3749 return node;
3752 /* If the domain elements that reach "node" live in more than one space,
3753 * then group the domain elements into a single space, named kernelX,
3754 * with X the kernel sequence number.
3755 * Note that these groups may be scheduled in a different
3756 * order so that the name of the group may not match the name of
3757 * the corresponding kernel.
3758 * Also, mark all outer band nodes as atomic to ensure each kernel is only
3759 * scheduled once.
3761 static __isl_give isl_schedule_node *group_statements(struct gpu_gen *gen,
3762 __isl_take isl_schedule_node *node)
3764 char buffer[20];
3765 isl_id *id;
3766 isl_union_set *domain;
3767 int single_statement;
3769 domain = isl_schedule_node_get_universe_domain(node);
3770 single_statement = isl_union_set_n_set(domain) == 1;
3771 isl_union_set_free(domain);
3773 node = atomic_ancestors(node);
3775 if (single_statement)
3776 return node;
3778 snprintf(buffer, sizeof(buffer), "kernel%d", gen->kernel_id++);
3779 id = isl_id_alloc(gen->ctx, buffer, NULL);
3780 node = isl_schedule_node_group(node, id);
3781 node = isl_schedule_node_parent(node);
3783 return node;
3786 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
3787 __isl_take isl_schedule_node *node, int pos, struct band_info *info);
3789 /* Check if this band node is tilable and has any parallel loops. If so,
3790 * take it as the outermost tilable band. If not, continue looking for the
3791 * outermost tilable band in the children of the current band.
3792 * Return a pointer to the same node in a tree where all outermost tilable
3793 * bands in the current subtree have been removed.
3795 static __isl_give isl_schedule_node *band_select_outer_band(struct gpu_gen *gen,
3796 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
3798 int n = isl_schedule_node_band_n_member(node);
3799 int n_parallel;
3801 for (n_parallel = 0; n_parallel < n; ++n_parallel)
3802 if (!isl_schedule_node_band_member_get_coincident(node,
3803 n_parallel))
3804 break;
3806 if (!isl_schedule_node_band_get_permutable(node) || n_parallel == 0) {
3807 node = isl_schedule_node_child(node, 0);
3808 node = select_outer_band(gen, node, pos + n, info);
3809 return isl_schedule_node_parent(node);
3812 info->n_parallel = n_parallel;
3813 gen->any_parallelism = 1;
3814 info->gen = gen;
3815 info->tile_first = pos;
3816 info->tile_len = n;
3817 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3818 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
3819 isl_union_map_foreach_map(info->prefix, &set_stmt_tile_len, info);
3821 node = isl_schedule_node_cut(node);
3822 node = group_statements(gen, node);
3824 return node;
3827 /* Extend "umap" with coordinates with fixed value "val"
3828 * to a total length of "dst_len", assuming the original dimension is "src_len".
3830 static __isl_give isl_union_map *extend_range(
3831 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
3833 isl_space *dim;
3834 isl_map *map;
3835 int i;
3837 dim = isl_union_map_get_space(umap);
3838 map = isl_map_reverse(projection(dim, dst_len, src_len));
3839 for (i = src_len; i < dst_len; ++i)
3840 map = isl_map_fix_si(map, isl_dim_out, i, val);
3842 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
3844 return umap;
3847 /* Select the outermost bands in the elements of the sequence or set
3848 * node "node", align their prefix schedules and combine the resulting
3849 * prefix and suffix schedules into a single pair of prefix and
3850 * suffix schedules for the entire list.
3851 * Return a pointer to the same node in a tree where all outermost tilable
3852 * bands in the current subtree have been removed.
3854 static __isl_give isl_schedule_node *list_select_outer_band(
3855 struct gpu_gen *gen, __isl_take isl_schedule_node *node, int pos,
3856 struct band_info *list_info)
3858 int i;
3859 int n = isl_schedule_node_n_children(node);
3860 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
3861 struct band_info *info;
3862 int max_tile_first;
3863 isl_union_map *prefix;
3864 isl_union_map *suffix;
3866 assert(n >= 1);
3867 info = isl_calloc_array(ctx, struct band_info, n);
3868 assert(info);
3870 max_tile_first = 0;
3871 for (i = 0; i < n; ++i) {
3872 node = isl_schedule_node_child(node, i);
3873 node = select_outer_band(gen, node, pos, &info[i]);
3874 if (info[i].tile_first > max_tile_first)
3875 max_tile_first = info[i].tile_first;
3876 node = isl_schedule_node_parent(node);
3879 for (i = 0; i < n; ++i) {
3880 if (info[i].tile_first == max_tile_first)
3881 continue;
3882 info[i].prefix = extend_range(info[i].prefix,
3883 info[i].tile_first, max_tile_first, 0);
3884 info[i].tile_first = max_tile_first;
3887 prefix = info[0].prefix;
3888 suffix = info[0].suffix;
3890 for (i = 1; i < n; ++i) {
3891 prefix = isl_union_map_union(prefix, info[i].prefix);
3892 suffix = isl_union_map_union(suffix, info[i].suffix);
3895 list_info->tile_first = info[0].tile_first;
3896 list_info->tile_len = -1;
3897 list_info->prefix = prefix;
3898 list_info->suffix = suffix;
3900 free(info);
3901 return node;
3904 /* If we reach a leaf node, then we have not found any outer tilable
3905 * band with parallel loops, so consider the leaf node as the outermost
3906 * tilable band.
3907 * Return a pointer to the leaf node.
3909 static __isl_give isl_schedule_node *leaf_select_outer_band(struct gpu_gen *gen,
3910 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
3912 info->gen = gen;
3913 info->tile_first = pos;
3914 info->tile_len = 0;
3915 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3916 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
3917 isl_union_map_foreach_map(info->prefix, &set_stmt_tile_len, info);
3919 node = group_statements(gen, node);
3921 return node;
3924 /* Select the outermost tilable band in the subtree that "node" points to and
3925 * return a pointer to the same node in a tree where all outermost tilable
3926 * bands in the current subtree have been removed.
3928 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
3929 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
3931 enum isl_schedule_node_type type;
3933 type = isl_schedule_node_get_type(node);
3934 switch (type) {
3935 case isl_schedule_node_domain:
3936 case isl_schedule_node_filter:
3937 node = isl_schedule_node_child(node, 0);
3938 node = select_outer_band(gen, node, pos, info);
3939 return isl_schedule_node_parent(node);
3940 case isl_schedule_node_leaf:
3941 return leaf_select_outer_band(gen, node, pos, info);
3942 case isl_schedule_node_band:
3943 return band_select_outer_band(gen, node, pos, info);
3944 case isl_schedule_node_set:
3945 case isl_schedule_node_sequence:
3946 return list_select_outer_band(gen, node, pos, info);
3947 default:
3948 isl_die(isl_schedule_node_get_ctx(node),
3949 isl_error_unsupported, "unhandled schedule node type",
3950 node = node);
3951 case isl_schedule_node_error:
3952 info->prefix = NULL;
3953 info->suffix = NULL;
3954 break;
3957 return isl_schedule_node_free(node);
3960 /* Select the outermost tilable band that (by construction)
3961 * has at least one parallel loop.
3962 * The starting position of the aligned band is stored in the pair
3963 * gen->tile_first.
3964 * The sizes and number of parallel loops may be different in different
3965 * parts of the band forest and are therefore stored in the gpu_stmts.
3967 * Return the complete schedule, with the tilable bands aligned
3968 * at gen->tile_first and padded with zero, if needed.
3969 * Store a schedule tree corresponding to the outer gen->tile_first
3970 * dimensions in gen->host_schedule.
3972 * We keep a copy of gen->kernel_id, since we will be temporarily
3973 * updating it inside group_statements.
3975 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
3976 __isl_keep isl_schedule *schedule)
3978 isl_schedule_node *node;
3979 struct band_info info;
3980 int kernel_id;
3982 gen->n_parallel = 0;
3983 gen->tile_len = -1;
3985 kernel_id = gen->kernel_id;
3987 node = isl_schedule_get_root(schedule);
3988 node = select_outer_band(gen, node, 0, &info);
3989 gen->host_schedule = isl_schedule_node_get_schedule(node);
3990 isl_schedule_node_free(node);
3992 gen->kernel_id = kernel_id;
3994 gen->tile_first = info.tile_first;
3995 info.suffix = align_range(info.suffix);
3997 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4000 /* Set gen->untiled_len to the number of scheduling dimensions
4001 * for the schedule of the first domain.
4002 * We assume here that this number is the same for all domains.
4004 static int set_untiled_len(__isl_take isl_map *map, void *user)
4006 unsigned *untiled_len = user;
4008 *untiled_len = isl_map_dim(map, isl_dim_out);
4010 isl_map_free(map);
4011 return -1;
4014 /* Compute an appropriate schedule based on the accesses in
4015 * gen->read and gen->write.
4017 * We use the dependences in gen->prog->scop to compute
4018 * a schedule that has a parallel loop in each tilable band.
4019 * Finally, we select the outermost tilable band.
4021 * If live range reordering is allowed, then we need to make sure
4022 * that live ranges on arrays are not run in parallel since doing
4023 * so would require array expansion. We therefore add the array
4024 * order dependences to the coincidence dependences. Non-zero array
4025 * order dependences will then prevent a schedule dimension from being
4026 * considered parallel.
4027 * Live ranges derived from scalars are allowed to be run in parallel
4028 * since we force the scalars to be mapped to private memory in
4029 * check_scalar_live_ranges.
4030 * If live range reordering is allowed, then the false dependences
4031 * are not added to the validity constraints as that would prevent
4032 * reordering. Instead, the external false dependences that enforce that reads
4033 * from potentially live-in data precede any later write and
4034 * that writes of potentially live-out data follow any other earlier write
4035 * are added to the validity and the coincidence constraints.
4036 * The false dependences are still added to the proximity constraints
4037 * for consistency with the case where live range reordering is not allowed.
4038 * The coincidence constraints then consist of flow dependences,
4039 * external false dependences and array order dependences.
4040 * The independences can be filtered out from the first two sets.
4041 * They have already been filtered out from the array order dependences
4042 * on a per array basis in collect_order_dependences.
4043 * There is no need for a per array handling of the other two sets
4044 * as there should be no flow or external false dependence on local
4045 * variables that can be filtered out.
4047 static void compute_schedule(struct gpu_gen *gen)
4049 isl_union_set *domain;
4050 isl_union_map *dep_raw, *dep;
4051 isl_union_map *validity, *proximity, *coincidence;
4052 isl_union_map *sched;
4053 isl_schedule_constraints *sc;
4054 isl_schedule *schedule;
4056 domain = isl_union_set_copy(gen->prog->scop->domain);
4057 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
4058 sc = isl_schedule_constraints_set_context(sc,
4059 isl_set_copy(gen->prog->scop->context));
4060 if (gen->options->live_range_reordering) {
4061 sc = isl_schedule_constraints_set_conditional_validity(sc,
4062 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
4063 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
4064 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
4065 validity = isl_union_map_copy(proximity);
4066 validity = isl_union_map_union(validity,
4067 isl_union_map_copy(gen->prog->scop->dep_external));
4068 proximity = isl_union_map_union(proximity,
4069 isl_union_map_copy(gen->prog->scop->dep_false));
4070 coincidence = isl_union_map_copy(validity);
4071 coincidence = isl_union_map_subtract(coincidence,
4072 isl_union_map_copy(gen->prog->scop->independence));
4073 coincidence = isl_union_map_union(coincidence,
4074 isl_union_map_copy(gen->prog->array_order));
4075 } else {
4076 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4077 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4078 dep = isl_union_map_union(dep, dep_raw);
4079 dep = isl_union_map_coalesce(dep);
4080 proximity = isl_union_map_copy(dep);
4081 coincidence = isl_union_map_copy(dep);
4082 validity = dep;
4084 sc = isl_schedule_constraints_set_validity(sc, validity);
4085 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4086 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4088 if (gen->options->debug->dump_schedule_constraints)
4089 isl_schedule_constraints_dump(sc);
4090 schedule = isl_schedule_constraints_compute_schedule(sc);
4091 if (gen->options->debug->dump_schedule)
4092 isl_schedule_dump(schedule);
4094 sched = select_outer_tilable_band(gen, schedule);
4096 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4097 sched = isl_union_map_intersect_domain(sched, domain);
4098 gen->sched = sched;
4100 isl_schedule_free(schedule);
4103 /* Compute the sets of outer array elements that need to be copied in and out.
4105 * In particular, for each array that is possibly written anywhere in
4106 * gen->prog and that is visible outside the corresponding scop,
4107 * we copy out its entire extent.
4109 * Any array elements that is read without first being written needs
4110 * to be copied in. Furthermore, if there are any array elements that
4111 * are copied out, but that may not be written inside gen->prog, then
4112 * they also need to be copied in to ensure that the value after execution
4113 * is the same as the value before execution, at least for those array
4114 * elements that may have their values preserved by the scop.
4115 * In case the array elements are structures, we need to take into
4116 * account that all members of the structures need to be written
4117 * by gen->prog before we can avoid copying the data structure in.
4119 * While computing the set of array elements that are copied out but
4120 * not necessarily written, we intersect both sets with the context.
4121 * This helps in those cases where the arrays are declared with a fixed size,
4122 * while the accesses are parametric and the context assigns a fixed value
4123 * to the parameters.
4125 * If an element from a local array is read without first being written,
4126 * then there is no point in copying it in since it cannot have been
4127 * written prior to the scop. Warn about the uninitialized read instead.
4129 static void compute_copy_in_and_out(struct gpu_gen *gen)
4131 int i;
4132 isl_union_set *local;
4133 isl_union_set *may_write, *must_write;
4134 isl_union_set *copy_in, *copy_out;
4135 isl_union_set *not_written;
4136 isl_union_map *uninitialized;
4137 isl_union_map *local_uninitialized;
4139 must_write = isl_union_map_range(
4140 isl_union_map_copy(gen->prog->must_write));
4141 must_write = isl_union_set_intersect_params(must_write,
4142 isl_set_copy(gen->prog->context));
4143 may_write = isl_union_map_range(
4144 isl_union_map_copy(gen->prog->may_write));
4145 may_write = isl_union_set_intersect_params(may_write,
4146 isl_set_copy(gen->prog->context));
4147 may_write = isl_union_set_universe(may_write);
4148 may_write = isl_union_set_apply(may_write,
4149 isl_union_map_copy(gen->prog->to_outer));
4150 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
4151 local = isl_union_set_copy(copy_out);
4153 for (i = 0; i < gen->prog->n_array; ++i) {
4154 isl_space *space;
4155 isl_set *write_i;
4156 int empty;
4158 space = isl_space_copy(gen->prog->array[i].space);
4160 if (gen->prog->array[i].local) {
4161 isl_set *set;
4163 set = isl_set_universe(space);
4164 local = isl_union_set_add_set(local, set);
4165 continue;
4168 write_i = isl_union_set_extract_set(may_write, space);
4169 empty = isl_set_plain_is_empty(write_i);
4170 isl_set_free(write_i);
4171 if (empty)
4172 continue;
4174 write_i = isl_set_copy(gen->prog->array[i].extent);
4175 copy_out = isl_union_set_add_set(copy_out, write_i);
4177 isl_union_set_free(may_write);
4179 copy_out = isl_union_set_intersect_params(copy_out,
4180 isl_set_copy(gen->prog->context));
4182 gen->prog->copy_out = isl_union_set_copy(copy_out);
4184 copy_out = isl_union_set_apply(copy_out,
4185 isl_union_map_copy(gen->prog->to_inner));
4186 copy_out = isl_union_set_intersect(copy_out,
4187 isl_union_set_copy(gen->prog->may_persist));
4188 not_written = isl_union_set_subtract(copy_out, must_write);
4190 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4191 local_uninitialized = isl_union_map_copy(uninitialized);
4193 local = isl_union_set_apply(local,
4194 isl_union_map_copy(gen->prog->to_inner));
4195 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4196 local);
4197 if (!isl_union_map_is_empty(local_uninitialized)) {
4198 fprintf(stderr,
4199 "possibly uninitialized reads (not copied in):\n");
4200 isl_union_map_dump(local_uninitialized);
4202 uninitialized = isl_union_map_subtract(uninitialized,
4203 local_uninitialized);
4204 copy_in = isl_union_map_range(uninitialized);
4205 copy_in = isl_union_set_union(copy_in, not_written);
4206 copy_in = isl_union_set_apply(copy_in,
4207 isl_union_map_copy(gen->prog->to_outer));
4209 gen->prog->copy_in = copy_in;
4212 /* Internal data structure for extract_access.
4213 * "next_access" points to the end of a linked list that is extended
4214 * by extract_access.
4215 * "single_expression" is set if the access expressions belong to
4216 * an expression statement (i.e., a statement without internal control).
4217 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4219 struct ppcg_extract_access_data {
4220 struct gpu_stmt_access **next_access;
4221 int single_expression;
4222 isl_union_map *any_to_outer;
4225 /* Given a tagged access relation to a single array "tagged", extract it
4226 * as a map, taking into account that the input may be empty.
4227 * If the access relation is empty, then it does not contain
4228 * any space information, so we try to recover it from the index
4229 * expression.
4230 * The space of the index expression is of the form I -> A,
4231 * with I the statement instances and A the array, or [I -> F] -> A,
4232 * with F the filters corresponding to arguments.
4233 * We first drop F, if present, obtaining I -> A.
4234 * Then we construct I -> R, with R the reference tag,
4235 * combine the two into I -> [R -> A] and uncurry to obtain
4236 * the final result [I -> R] -> A.
4237 * Note that the index expression may have a lower dimension
4238 * than that of the array, but this dimension is not used
4239 * if the access relation is empty.
4241 static __isl_give isl_map *extract_single_tagged_access(
4242 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4244 int empty;
4245 isl_id *id;
4246 isl_space *space, *space2;
4247 isl_multi_pw_aff *index;
4249 empty = isl_union_map_is_empty(tagged);
4250 if (empty < 0)
4251 goto error;
4252 if (!empty)
4253 return isl_map_from_union_map(tagged);
4254 isl_union_map_free(tagged);
4256 index = pet_expr_access_get_index(expr);
4257 space = isl_multi_pw_aff_get_space(index);
4258 isl_multi_pw_aff_free(index);
4259 if (isl_space_domain_is_wrapping(space))
4260 space = isl_space_domain_factor_domain(space);
4261 space2 = isl_space_copy(space);
4262 space2 = isl_space_from_domain(isl_space_domain(space));
4263 id = pet_expr_access_get_ref_id(expr);
4264 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4265 space = isl_space_range_product(space2, space);
4266 space = isl_space_uncurry(space);
4268 return isl_map_empty(space);
4269 error:
4270 isl_union_map_free(tagged);
4271 return NULL;
4274 /* Extract a gpu_stmt_access from "expr", append it to the list
4275 * that ends in *data->next_access and update the end of the list.
4276 * If the access expression performs a write, then it is considered
4277 * exact only if it appears in a single expression statement and
4278 * if its may access relation is equal to its must access relation.
4280 * The combined set of may accesses may be union if member accesses
4281 * are involved, but the entire set is derived from a single reference and
4282 * therefore from a single index expression. These accesses therefore
4283 * all map to the same outer array.
4285 static int extract_access(__isl_keep pet_expr *expr, void *user)
4287 struct ppcg_extract_access_data *data = user;
4288 isl_union_map *tagged;
4289 struct gpu_stmt_access *access;
4290 isl_ctx *ctx = pet_expr_get_ctx(expr);
4291 isl_multi_pw_aff *index;
4293 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4294 assert(access);
4295 access->next = NULL;
4296 access->read = pet_expr_access_is_read(expr);
4297 access->write = pet_expr_access_is_write(expr);
4298 tagged = pet_expr_access_get_tagged_may_read(expr);
4299 tagged = isl_union_map_union(tagged,
4300 pet_expr_access_get_tagged_may_write(expr));
4301 tagged = isl_union_map_apply_range(tagged,
4302 isl_union_map_copy(data->any_to_outer));
4303 if (!access->write) {
4304 access->exact_write = 1;
4305 } else if (!data->single_expression) {
4306 access->exact_write = 0;
4307 } else {
4308 isl_union_map *must, *may;
4309 may = isl_union_map_copy(tagged);
4310 may = isl_union_map_domain_factor_domain(may);
4311 must = pet_expr_access_get_must_write(expr);
4312 access->exact_write = isl_union_map_is_equal(must, may);
4313 isl_union_map_free(must);
4314 isl_union_map_free(may);
4316 index = pet_expr_access_get_index(expr);
4317 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4318 isl_multi_pw_aff_free(index);
4319 access->ref_id = pet_expr_access_get_ref_id(expr);
4320 access->tagged_access = extract_single_tagged_access(tagged, expr);
4321 access->access = isl_map_copy(access->tagged_access);
4322 access->access = isl_map_domain_factor_domain(access->access);
4324 *data->next_access = access;
4325 data->next_access = &(*data->next_access)->next;
4327 if (!access->access)
4328 return -1;
4330 return 0;
4333 /* Construct a linked list of gpu_stmt_access objects,
4334 * one for each access expression in the statement body.
4335 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4337 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4338 __isl_keep isl_union_map *any_to_outer)
4340 struct ppcg_extract_access_data data;
4342 stmt->accesses = NULL;
4343 data.next_access = &stmt->accesses;
4344 data.single_expression =
4345 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4346 data.any_to_outer = any_to_outer;
4347 return pet_tree_foreach_access_expr(stmt->stmt->body,
4348 &extract_access, &data);
4351 /* Return an array of gpu_stmt representing the statements in "scop".
4353 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4354 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4356 int i;
4357 struct gpu_stmt *stmts;
4359 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4360 if (!stmts)
4361 return NULL;
4363 for (i = 0; i < scop->pet->n_stmt; ++i) {
4364 struct gpu_stmt *s = &stmts[i];
4366 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4367 s->stmt = scop->pet->stmts[i];
4368 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4369 return free_stmts(stmts, i + 1);
4372 return stmts;
4375 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4377 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4379 struct gpu_gen *gen = user;
4381 return gen->print(p, gen->prog, gen->tree, &gen->types,
4382 gen->print_user);
4385 /* Generate CUDA code for "scop" and print it to "p".
4386 * After generating an AST for the transformed scop as explained below,
4387 * we call "gen->print" to print the AST in the desired output format
4388 * to "p".
4390 * If it turns out that it does not make sense to generate GPU code,
4391 * then we generate CPU code instead.
4393 * The GPU code is generated in a context where at least one
4394 * statement instance is executed. The corresponding guard (if any) is printed
4395 * around the entire generated GPU code, except for the declaration
4396 * of the arrays that are visible outside of the scop and that therefore
4397 * cannot be declared inside the body of any possible guard.
4399 * We first compute a schedule that respects the dependences
4400 * of the original program and select the outermost band
4401 * of tilable dimensions that has at least one parallel loop.
4402 * We then have three blocks of dimensions
4404 * H B G
4406 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4407 * in
4409 * H T P G
4411 * For each iteration of the T loop and for each array, we compute
4412 * the array elements accessed by that iteration, construct a rectangular
4413 * box around it and shift it to the origin. The result is used
4414 * as shared memory for the array.
4416 * We then split off at most 2 parallel loops from the T loops and
4417 * at most 3 parallel loops from the P loops
4419 * H T1 T2 P1 P2 G
4421 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4422 * according to "grid"/"block" sizes.
4424 * H T1T T1P T2 P1T P1P P2 G
4426 * Finally, the T1P and P1P iterators are equated to the block and
4427 * thread dimensions respectively and so are effectively removed.
4428 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4429 * are run on the GPU.
4431 * Code is generated in three stages. We first generate code for the
4432 * host (the H loops), with iterators h%d. Then, for each leaf node
4433 * of the resulting AST, we generate code for the shared loops (up to
4434 * and including T2), with iterators g%d and after equating the H loops
4435 * to h%d parameters and the T1P loops to the block dimensions.
4436 * Finally, we generate code for the remaining loops in a similar fashion.
4438 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4439 struct gpu_gen *gen, struct ppcg_scop *scop,
4440 struct ppcg_options *options)
4442 struct gpu_prog *prog;
4443 isl_ctx *ctx;
4444 isl_set *context, *guard;
4446 if (!scop)
4447 return isl_printer_free(p);
4449 ctx = isl_printer_get_ctx(p);
4450 prog = gpu_prog_alloc(ctx, scop);
4451 if (!prog)
4452 return isl_printer_free(p);
4454 context = isl_set_copy(prog->context);
4455 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
4456 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
4458 gen->prog = prog;
4459 gen->any_parallelism = 0;
4460 compute_schedule(gen);
4462 if (!gen->any_parallelism) {
4463 isl_set_free(context);
4464 isl_set_free(guard);
4465 p = print_cpu(p, scop, options);
4466 } else {
4467 compute_copy_in_and_out(gen);
4468 gen->tree = generate_host_code(gen);
4469 p = ppcg_print_exposed_declarations(p, prog->scop);
4470 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
4471 isl_ast_node_free(gen->tree);
4474 isl_union_map_free(gen->sched);
4475 isl_schedule_free(gen->host_schedule);
4477 gpu_prog_free(prog);
4479 return p;
4482 /* Wrapper around generate for use as a ppcg_transform callback.
4484 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
4485 struct ppcg_scop *scop, void *user)
4487 struct gpu_gen *gen = user;
4489 return generate(p, gen, scop, gen->options);
4492 /* Transform the code in the file called "input" by replacing
4493 * all scops by corresponding GPU code and write the results to "out".
4495 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4496 struct ppcg_options *options,
4497 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4498 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4499 struct gpu_types *types, void *user), void *user)
4501 struct gpu_gen gen;
4502 int r;
4503 int i;
4505 gen.ctx = ctx;
4506 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4507 gen.options = options;
4508 gen.kernel_id = 0;
4509 gen.print = print;
4510 gen.print_user = user;
4511 gen.types.n = 0;
4512 gen.types.name = NULL;
4514 if (options->debug->dump_sizes) {
4515 isl_space *space = isl_space_params_alloc(ctx, 0);
4516 gen.used_sizes = isl_union_map_empty(space);
4519 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
4521 if (options->debug->dump_sizes) {
4522 isl_union_map_dump(gen.used_sizes);
4523 isl_union_map_free(gen.used_sizes);
4526 isl_union_map_free(gen.sizes);
4527 for (i = 0; i < gen.types.n; ++i)
4528 free(gen.types.name[i]);
4529 free(gen.types.name);
4531 return r;
4534 /* Compute the set of inner array elements that may have their values
4535 * preserved by "prog". In particular, collect the array elements of
4536 * arrays that are not local to "prog" and remove those elements that
4537 * are definitely killed or definitely written by "prog".
4539 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
4541 int i;
4542 isl_union_set *may_persist, *killed;
4543 isl_union_map *must_kill;
4545 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
4546 for (i = 0; i < prog->n_array; ++i) {
4547 isl_set *extent;
4549 if (prog->array[i].local)
4550 continue;
4552 extent = isl_set_copy(prog->array[i].extent);
4553 may_persist = isl_union_set_add_set(may_persist, extent);
4556 may_persist = isl_union_set_intersect_params(may_persist,
4557 isl_set_copy(prog->context));
4558 may_persist = isl_union_set_apply(may_persist,
4559 isl_union_map_copy(prog->to_inner));
4560 must_kill = isl_union_map_copy(prog->tagged_must_kill);
4561 killed = isl_union_map_range(must_kill);
4562 must_kill = isl_union_map_copy(prog->must_write);
4563 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
4565 may_persist = isl_union_set_subtract(may_persist, killed);
4566 return may_persist;
4569 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4571 struct gpu_prog *prog;
4572 isl_space *space;
4573 isl_map *id;
4575 if (!scop)
4576 return NULL;
4578 prog = isl_calloc_type(ctx, struct gpu_prog);
4579 assert(prog);
4581 prog->ctx = ctx;
4582 prog->scop = scop;
4583 prog->context = isl_set_copy(scop->context);
4584 prog->n_stmts = scop->pet->n_stmt;
4585 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
4586 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
4587 space = isl_union_map_get_space(prog->any_to_outer);
4588 space = isl_space_set_from_params(space);
4589 space = isl_space_add_dims(space, isl_dim_set, 1);
4590 space = isl_space_map_from_set(space);
4591 id = isl_map_identity(space);
4592 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
4593 prog->stmts = extract_stmts(ctx, scop,
4594 prog->context, prog->any_to_outer);
4595 prog->read = isl_union_map_copy(scop->reads);
4596 prog->may_write = isl_union_map_copy(scop->may_writes);
4597 prog->must_write = isl_union_map_copy(scop->must_writes);
4598 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
4599 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
4600 prog->to_outer = isl_union_map_copy(prog->to_inner);
4601 prog->to_outer = isl_union_map_reverse(prog->to_outer);
4603 if (!prog->stmts)
4604 return gpu_prog_free(prog);
4606 if (collect_array_info(prog) < 0)
4607 return gpu_prog_free(prog);
4608 prog->may_persist = compute_may_persist(prog);
4610 return prog;
4613 void *gpu_prog_free(struct gpu_prog *prog)
4615 if (!prog)
4616 return NULL;
4617 free_array_info(prog);
4618 free_stmts(prog->stmts, prog->n_stmts);
4619 isl_union_map_free(prog->any_to_outer);
4620 isl_union_map_free(prog->to_outer);
4621 isl_union_map_free(prog->to_inner);
4622 isl_union_set_free(prog->copy_in);
4623 isl_union_set_free(prog->copy_out);
4624 isl_union_map_free(prog->read);
4625 isl_union_map_free(prog->may_write);
4626 isl_union_map_free(prog->must_write);
4627 isl_union_map_free(prog->tagged_must_kill);
4628 isl_union_map_free(prog->array_order);
4629 isl_union_set_free(prog->may_persist);
4630 isl_set_free(prog->context);
4631 free(prog);
4632 return NULL;