gpu.c: band_select_outer_band: extract out n_outer_coincidence
[ppcg.git] / gpu.c
blob471d41786d9ca6c02b2f8f4536b511e4a6d96dfe
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;
545 struct ppcg_kernel *kernel = gen->kernel;
547 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
548 assert(gen->tile_size);
549 for (n = 0; n < gen->tile_len; ++n)
550 gen->tile_size[n] = gen->options->tile_size;
552 size = extract_sizes(gen->sizes, "tile", kernel->id);
553 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
554 set_used_sizes(gen, "tile", kernel->id,
555 gen->tile_size, gen->tile_len);
557 if (gen->n_parallel > gen->tile_len)
558 gen->n_parallel = gen->tile_len;
561 /* Extract user specified "block" sizes from the "sizes" command line option,
562 * after filling in some potentially useful defaults.
563 * Add the effectively used sizes to gen->used_sizes.
565 static void read_block_sizes(struct gpu_gen *gen)
567 int n;
568 isl_set *size;
570 n = gen->n_parallel;
571 gen->n_block = (n <= 3) ? n : 3;
572 switch (gen->n_block) {
573 case 1:
574 gen->block_dim[0] = 512;
575 break;
576 case 2:
577 gen->block_dim[0] = 32;
578 gen->block_dim[1] = 16;
579 break;
580 default:
581 gen->block_dim[0] = 32;
582 gen->block_dim[1] = 4;
583 gen->block_dim[2] = 4;
584 break;
587 size = extract_sizes(gen->sizes, "block", gen->kernel->id);
588 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
589 set_used_sizes(gen, "block", gen->kernel->id,
590 gen->block_dim, gen->n_block);
593 /* Extract user specified "grid" sizes from the "sizes" command line option,
594 * after filling in some potentially useful defaults.
595 * Add the effectively used sizes to gen->used_sizes.
597 static void read_grid_sizes(struct gpu_gen *gen)
599 int n = gen->n_parallel;
600 isl_set *size;
602 gen->n_grid = (n <= 2) ? n : 2;
603 switch (gen->n_grid) {
604 case 1:
605 gen->grid_dim[0] = 32768;
606 break;
607 default:
608 gen->grid_dim[0] = 256;
609 gen->grid_dim[1] = 256;
610 break;
613 size = extract_sizes(gen->sizes, "grid", gen->kernel->id);
614 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
615 set_used_sizes(gen, "grid", gen->kernel->id,
616 gen->grid_dim, gen->n_grid);
619 /* Extract user specified sizes from the "sizes" command line option
620 * after filling in some potentially useful defaults.
622 static void read_sizes(struct gpu_gen *gen)
624 read_tile_sizes(gen);
625 read_block_sizes(gen);
626 read_grid_sizes(gen);
629 static void *free_stmts(struct gpu_stmt *stmts, int n)
631 int i;
633 if (!stmts)
634 return NULL;
636 for (i = 0; i < n; ++i) {
637 struct gpu_stmt_access *access, *next;
639 for (access = stmts[i].accesses; access; access = next) {
640 next = access->next;
641 isl_id_free(access->ref_id);
642 isl_map_free(access->access);
643 isl_map_free(access->tagged_access);
644 free(access);
647 isl_id_free(stmts[i].id);
649 free(stmts);
651 return NULL;
654 /* Construct a map from a domain of dimensionality "len"
655 * to a domain of dimensionality "len" + "tile_len" that tiles
656 * the "tile_len" coordinates starting at "first".
657 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
658 * "dim" prescribes the parameters.
660 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
661 int first, int tile_len, int *tile_size)
663 int i;
664 isl_basic_map *bmap;
665 isl_constraint *c;
666 isl_local_space *ls;
668 dim = isl_space_add_dims(dim, isl_dim_in, len);
669 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
670 bmap = isl_basic_map_universe(isl_space_copy(dim));
671 ls = isl_local_space_from_space(dim);
673 for (i = 0; i < len - tile_len; ++i) {
674 int j = i < first ? i : i + tile_len;
675 int k = i < first ? i : i + 2 * tile_len;
677 c = isl_equality_alloc(isl_local_space_copy(ls));
678 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
679 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
680 bmap = isl_basic_map_add_constraint(bmap, c);
683 for (i = 0; i < tile_len; ++i) {
684 c = isl_equality_alloc(isl_local_space_copy(ls));
685 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
686 first + i, -1);
687 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
688 first + i, tile_size[i]);
689 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
690 first + i + tile_len, 1);
691 bmap = isl_basic_map_add_constraint(bmap, c);
693 c = isl_inequality_alloc(isl_local_space_copy(ls));
694 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
695 first + i + tile_len, 1);
696 bmap = isl_basic_map_add_constraint(bmap, c);
698 c = isl_inequality_alloc(isl_local_space_copy(ls));
699 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
700 first + i + tile_len, -1);
701 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
702 bmap = isl_basic_map_add_constraint(bmap, c);
705 isl_local_space_free(ls);
707 return isl_map_from_basic_map(bmap);
710 /* Construct a map from a domain of dimensionality "len"
711 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
712 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
713 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
714 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
715 * that are projected out at the end.
716 * "dim" prescribes the parameters.
718 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
719 int first, int wrap_len, int *wrap_size)
721 int i;
722 isl_basic_map *bmap;
723 isl_constraint *c;
724 isl_local_space *ls;
726 dim = isl_space_add_dims(dim, isl_dim_in, len);
727 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
728 bmap = isl_basic_map_universe(isl_space_copy(dim));
729 ls = isl_local_space_from_space(dim);
731 for (i = 0; i < len; ++i) {
732 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
734 c = isl_equality_alloc(isl_local_space_copy(ls));
735 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
736 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
737 bmap = isl_basic_map_add_constraint(bmap, c);
740 for (i = 0; i < wrap_len; ++i) {
741 c = isl_equality_alloc(isl_local_space_copy(ls));
742 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
743 first + i, -1);
744 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
745 first + wrap_len + i, 1);
746 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
747 first + 2 * wrap_len + i, wrap_size[i]);
748 bmap = isl_basic_map_add_constraint(bmap, c);
750 c = isl_inequality_alloc(isl_local_space_copy(ls));
751 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
752 first + wrap_len + i, 1);
753 bmap = isl_basic_map_add_constraint(bmap, c);
755 c = isl_inequality_alloc(isl_local_space_copy(ls));
756 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
757 first + wrap_len + i, -1);
758 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
759 bmap = isl_basic_map_add_constraint(bmap, c);
762 isl_local_space_free(ls);
764 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
765 first + 2 * wrap_len, wrap_len);
767 return isl_map_from_basic_map(bmap);
770 /* Tile the B loops over the tile sizes and then tile/wrap
771 * the T1 loops over the blocks.
773 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
774 __isl_take isl_union_map *sched)
776 isl_space *dim;
777 isl_map *tiling, *block_tiling;
779 dim = isl_union_map_get_space(sched);
780 tiling = tile(isl_space_copy(dim), gen->untiled_len,
781 gen->tile_first, gen->tile_len, gen->tile_size);
783 if (gen->options->wrap)
784 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
785 gen->tile_first, gen->n_grid, gen->grid_dim);
786 else
787 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
788 gen->tile_first, gen->n_grid, gen->grid_dim);
790 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
792 tiling = isl_map_apply_range(tiling, block_tiling);
794 sched = isl_union_map_apply_range(sched,
795 isl_union_map_from_map(tiling));
797 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
799 return sched;
802 /* Equate the "T1P" iterators in the tiled schedule "sched"
803 * to the block dimensions.
805 static __isl_give isl_union_map *parametrize_tiled_schedule(
806 struct gpu_gen *gen, __isl_take isl_union_map *sched)
808 isl_space *dim;
809 isl_set *par;
811 dim = isl_union_map_get_space(sched);
812 par = parametrization(dim, gen->tiled_len,
813 gen->tile_first + gen->n_grid, gen->kernel->block_ids);
814 sched = isl_union_map_intersect_range(sched,
815 isl_union_set_from_set(par));
817 return sched;
820 /* Tile/wrap the P1 loops over the threads.
822 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
823 __isl_take isl_union_map *sched)
825 isl_space *dim;
826 isl_map *tiling;
827 isl_set *par;
829 dim = isl_union_map_get_space(sched);
831 if (gen->options->wrap)
832 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
833 gen->shared_len, gen->n_block, gen->block_dim);
834 else
835 tiling = tile(isl_space_copy(dim), gen->tiled_len,
836 gen->shared_len, gen->n_block, gen->block_dim);
837 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
839 sched = isl_union_map_apply_range(sched,
840 isl_union_map_from_map(tiling));
842 par = parametrization(dim, gen->thread_tiled_len,
843 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
844 gen->kernel->thread_ids);
845 sched = isl_union_map_intersect_range(sched,
846 isl_union_set_from_set(par));
848 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
850 return sched;
853 /* If the user asked for it, scale the shared memory tile loops
854 * (T1T and T2) of "sched" by gen->tile_size[i].
855 * If we are not performing "wrapping", then additionally scale the T1P
856 * loops by gen->grid_dim[i].
858 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
859 __isl_take isl_union_map *sched)
861 int i;
862 isl_space *dim;
863 isl_basic_map *scale;
864 isl_constraint *c;
865 isl_local_space *ls;
867 if (!gen->options->scale_tile_loops)
868 return sched;
870 dim = isl_union_map_get_space(sched);
871 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
872 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
873 scale = isl_basic_map_universe(isl_space_copy(dim));
874 ls = isl_local_space_from_space(dim);
876 for (i = 0; i < gen->tiled_len; ++i) {
877 int f = 1;
879 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
880 f = gen->tile_size[i - gen->tile_first];
881 if (!gen->options->wrap)
882 f *= gen->grid_dim[i - gen->tile_first];
883 } else if (i >= gen->tile_first + gen->n_grid &&
884 i < gen->tile_first + gen->n_grid + gen->tile_len) {
885 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
888 c = isl_equality_alloc(isl_local_space_copy(ls));
889 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
890 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
891 scale = isl_basic_map_add_constraint(scale, c);
894 isl_local_space_free(ls);
896 sched = isl_union_map_apply_range(sched,
897 isl_union_map_from_map(isl_map_from_basic_map(scale)));
899 return sched;
902 /* If we are not performing "wrapping" and if the user asked for it,
903 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
905 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
906 __isl_take isl_union_map *sched)
908 int i;
909 isl_space *dim;
910 isl_basic_map *scale;
911 isl_constraint *c;
912 isl_local_space *ls;
914 if (gen->options->wrap)
915 return sched;
916 if (!gen->options->scale_tile_loops)
917 return sched;
919 dim = isl_union_map_get_space(sched);
920 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
921 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
922 scale = isl_basic_map_universe(isl_space_copy(dim));
923 ls = isl_local_space_from_space(dim);
925 for (i = 0; i < gen->thread_tiled_len; ++i) {
926 int f = 1;
928 if (i >= gen->shared_len &&
929 i < gen->shared_len + gen->n_block)
930 f = gen->block_dim[i - gen->shared_len];
932 c = isl_equality_alloc(isl_local_space_copy(ls));
933 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
934 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
935 scale = isl_basic_map_add_constraint(scale, c);
938 isl_local_space_free(ls);
940 sched = isl_union_map_apply_range(sched,
941 isl_union_map_from_map(isl_map_from_basic_map(scale)));
943 return sched;
946 /* If we are not performing "wrapping" and if the user asked for it,
947 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
949 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
950 __isl_take isl_union_map *sched, int len, int first, int n_tile)
952 int i;
953 isl_space *dim;
954 isl_basic_map *scale;
955 isl_constraint *c;
956 isl_local_space *ls;
958 if (gen->options->wrap)
959 return sched;
960 if (!gen->options->scale_tile_loops)
961 return sched;
963 dim = isl_union_map_get_space(sched);
964 dim = isl_space_add_dims(dim, isl_dim_in, len);
965 dim = isl_space_add_dims(dim, isl_dim_out, len);
966 scale = isl_basic_map_universe(isl_space_copy(dim));
967 ls = isl_local_space_from_space(dim);
969 for (i = 0; i < len; ++i) {
970 int f = 1;
972 if (i >= first && i < first + n_tile)
973 f = gen->kernel->block_dim[i - first];
975 c = isl_equality_alloc(isl_local_space_copy(ls));
976 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
977 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
978 scale = isl_basic_map_add_constraint(scale, c);
981 isl_local_space_free(ls);
983 sched = isl_union_map_apply_range(sched,
984 isl_union_map_from_map(isl_map_from_basic_map(scale)));
986 return sched;
989 /* Add parameters p[i] with identifiers "ids" to "set",
990 * with bounds to 0 <= p[i] < size[i].
992 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
993 int *size, __isl_keep isl_id_list *ids)
995 int i, len;
996 unsigned nparam;
998 len = isl_id_list_n_id(ids);
999 nparam = isl_set_dim(set, isl_dim_param);
1000 set = isl_set_add_dims(set, isl_dim_param, len);
1002 for (i = 0; i < len; ++i) {
1003 isl_id *id;
1005 id = isl_id_list_get_id(ids, i);
1006 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1007 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
1008 set = isl_set_upper_bound_si(set, isl_dim_param,
1009 nparam + i, size[i] - 1);
1012 return set;
1015 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
1016 * with
1018 * { : 0 <= p[i] < size[i] }
1020 * or an overapproximation.
1022 static __isl_give isl_set *add_bounded_parameters_dynamic(
1023 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1024 __isl_keep isl_id_list *ids)
1026 int i, len;
1027 unsigned nparam;
1028 isl_space *space;
1029 isl_local_space *ls;
1031 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1032 nparam = isl_set_dim(set, isl_dim_param);
1033 set = isl_set_add_dims(set, isl_dim_param, len);
1035 for (i = 0; i < len; ++i) {
1036 isl_id *id;
1038 id = isl_id_list_get_id(ids, i);
1039 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1042 space = isl_space_params(isl_set_get_space(set));
1043 ls = isl_local_space_from_space(space);
1044 for (i = 0; i < len; ++i) {
1045 isl_pw_aff *param, *size_i, *zero;
1046 isl_set *bound;
1048 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1049 isl_dim_param, nparam + i);
1051 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1052 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1053 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1054 set = isl_set_intersect_params(set, bound);
1056 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1057 bound = isl_pw_aff_ge_set(param, zero);
1058 set = isl_set_intersect_params(set, bound);
1060 isl_local_space_free(ls);
1062 return set;
1065 /* Construct a map from an access to group->array to the corresponding
1066 * shared/private memory tile.
1067 * The map is of the form
1069 * { [D[i] -> A[a]] -> T[t] }
1071 * where D represents the initial shared_len dimensions
1072 * of the computed schedule.
1074 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1076 struct gpu_array_tile *tile;
1077 isl_multi_aff *tiling;
1079 tile = group->private_tile;
1080 if (!tile)
1081 tile = group->shared_tile;
1083 tiling = isl_multi_aff_copy(tile->tiling);
1085 return isl_map_from_multi_aff(tiling);
1088 /* Given a schedule that iterates over all elements in a piece of an array,
1089 * perform tiling/wrapping over the threads.
1091 * In particular, we tile the final iterators so that the final thread
1092 * dimension runs over the final array dimension.
1093 * However, if those final iterators have only a single iteration,
1094 * we try to tile earlier iterators instead.
1096 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1097 __isl_take isl_map *sched)
1099 isl_space *dim;
1100 isl_union_map *usched;
1101 isl_map *tiling;
1102 isl_set *par;
1103 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1104 int n_tile;
1105 int first;
1107 n_tile = gen->kernel->n_block;
1108 if (n_tile > nvar) {
1109 int i;
1110 sched = isl_map_insert_dims(sched,
1111 isl_dim_out, 0, n_tile - nvar);
1112 for (i = 0; i < n_tile - nvar; ++i)
1113 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1114 nvar = n_tile;
1117 first = nvar - n_tile;
1119 for (; first > 0; first --)
1120 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1121 break;
1123 dim = isl_map_get_space(sched);
1124 dim = isl_space_params(dim);
1125 if (gen->options->wrap)
1126 tiling = wrap(isl_space_copy(dim), nvar, first,
1127 n_tile, gen->kernel->block_dim);
1128 else
1129 tiling = tile(isl_space_copy(dim), nvar, first,
1130 n_tile, gen->kernel->block_dim);
1131 sched = isl_map_apply_range(sched, tiling);
1133 par = parametrization(dim, nvar + n_tile, first + n_tile,
1134 gen->kernel->thread_ids);
1135 sched = isl_map_intersect_range(sched, par);
1137 usched = isl_union_map_from_map(sched);
1138 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1139 first, n_tile);
1140 sched = isl_map_from_union_map(usched);
1142 return sched;
1145 /* Return the union of all tagged access relations in the group.
1147 static __isl_give isl_union_map *group_tagged_access_relation(
1148 struct gpu_array_ref_group *group)
1150 int i;
1151 isl_union_map *access;
1153 access = isl_union_map_empty(isl_map_get_space(group->access));
1154 for (i = 0; i < group->n_ref; ++i) {
1155 isl_map *map_i;
1157 map_i = isl_map_copy(group->refs[i]->tagged_access);
1158 access = isl_union_map_union(access,
1159 isl_union_map_from_map(map_i));
1162 return access;
1165 /* Return the extent of "array", recomputed from the bounds.
1166 * The recomputed extent may be simpler than the original extent.
1168 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1170 int i;
1171 isl_id *id;
1172 isl_space *space;
1173 isl_local_space *ls;
1174 isl_set *extent;
1176 id = isl_set_get_tuple_id(array->extent);
1177 space = isl_set_get_space(array->extent);
1178 extent = isl_set_universe(isl_space_copy(space));
1179 ls = isl_local_space_from_space(space);
1180 for (i = 0; i < array->n_index; ++i) {
1181 isl_pw_aff *bound;
1182 isl_aff *aff;
1183 isl_pw_aff *index;
1184 isl_set *lt;
1186 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1188 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1189 isl_dim_set, i);
1190 index = isl_pw_aff_from_aff(aff);
1191 bound = isl_pw_aff_copy(array->bound[i]);
1192 bound = isl_pw_aff_from_range(bound);
1193 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1194 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1195 isl_id_copy(id));
1196 lt = isl_pw_aff_lt_set(index, bound);
1197 extent = isl_set_intersect(extent, lt);
1199 isl_local_space_free(ls);
1200 isl_id_free(id);
1202 return extent;
1205 /* Return a map from the first shared_len dimensions of the computed
1206 * schedule to the array tile in
1207 * global memory that corresponds to the shared memory copy.
1209 * In particular, return a map
1211 * { D[i] -> A[a] }
1213 * with constraints
1215 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1217 * and
1219 * 0 <= a <= array_size - 1 (2)
1221 * Note that if some stride has been detected (i.e., when
1222 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1223 * to the shifted and scaled down version.
1225 * Constraints (1) are obtained by mapping the size constraints on the
1226 * shared/private memory tile back to the access relation.
1227 * Constraints (2) are obtained from the (recomputed) extent.
1229 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1231 int i;
1232 int n_index = group->array->n_index;
1233 isl_map *tile;
1234 isl_space *space;
1235 isl_set *local;
1236 isl_set *extent;
1238 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1239 space = isl_space_range(space);
1240 local = isl_set_universe(space);
1241 for (i = 0; i < n_index; ++i) {
1242 isl_val *bound;
1244 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1245 bound = isl_val_copy(group->shared_tile->bound[i].size);
1246 bound = isl_val_sub_ui(bound, 1);
1247 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1249 local = isl_set_preimage_multi_aff(local,
1250 isl_multi_aff_copy(group->shared_tile->tiling));
1251 tile = isl_set_unwrap(local);
1252 extent = array_extent(group->array);
1253 tile = isl_map_intersect_range(tile, extent);
1255 return tile;
1258 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1259 * return the corresponding mapping from the AST schedule to
1260 * to the first shared_len dimensions of the schedule computed by PPCG.
1262 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1263 __isl_take isl_pw_multi_aff *iterator_map)
1265 isl_union_map *umap;
1266 isl_space *space;
1267 isl_map *map, *sched;;
1269 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1270 space = isl_space_from_domain(space);
1271 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1273 umap = isl_union_map_copy(gen->shared_sched);
1274 umap = isl_union_map_apply_range(umap,
1275 isl_union_map_copy(gen->shared_proj));
1276 map = isl_union_map_extract_map(umap, space);
1277 isl_union_map_free(umap);
1279 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1280 sched = isl_map_detect_equalities(sched);
1282 return isl_pw_multi_aff_from_map(sched);
1285 /* Set unroll[j] if the input dimension j is involved in
1286 * the index expression represented by ma.
1288 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1289 void *user)
1291 int i, j;
1292 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1293 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1294 int *unroll = user;
1296 for (i = 0; i < n_out; ++i) {
1297 isl_aff *aff;
1299 aff = isl_multi_aff_get_aff(ma, i);
1300 for (j = 0; j < n_in; ++j)
1301 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1302 unroll[j] = 1;
1303 isl_aff_free(aff);
1306 isl_set_free(set);
1307 isl_multi_aff_free(ma);
1308 return 0;
1311 /* Given an array pos mapping input dimensions to the corresponding
1312 * output dimension, construct the corresponding map.
1314 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1315 int *pos, int len)
1317 int i;
1318 isl_constraint *c;
1319 isl_basic_map *bmap;
1320 isl_local_space *ls;
1322 dim = isl_space_add_dims(dim, isl_dim_in, len);
1323 dim = isl_space_add_dims(dim, isl_dim_out, len);
1324 bmap = isl_basic_map_universe(isl_space_copy(dim));
1325 ls = isl_local_space_from_space(dim);
1327 for (i = 0; i < len; ++i) {
1328 c = isl_equality_alloc(isl_local_space_copy(ls));
1329 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1330 -1);
1331 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1333 bmap = isl_basic_map_add_constraint(bmap, c);
1335 isl_local_space_free(ls);
1337 return isl_map_from_basic_map(bmap);
1340 /* Remove the private tiles from all array reference groups,
1341 * except for the groups of arrays that are marked force_private.
1343 static void remove_private_tiles(struct gpu_gen *gen)
1345 int i, j;
1347 for (i = 0; i < gen->kernel->n_array; ++i) {
1348 struct gpu_local_array_info *local = &gen->kernel->array[i];
1350 if (local->force_private)
1351 continue;
1353 for (j = 0; j < local->n_group; ++j) {
1354 struct gpu_array_ref_group *group = local->groups[j];
1356 group->private_tile =
1357 gpu_array_tile_free(group->private_tile);
1362 /* Find all loops involved in any of the index expressions for any of
1363 * the private accesses, move them innermost and then mark them as
1364 * requiring unrolling by setting gen->first_unroll.
1365 * The loops involved should all be parallel because of the checks
1366 * we performed in check_private_group_access. Moving them innermost
1367 * is therefore a valid transformation.
1369 * If any of the arrays are marked force_private, however, then
1370 * those loops may not be parallel with respect to the marked arrays.
1371 * If any of the loops would have to be moved innermost for the
1372 * (non forced) private accesses and if there are any force_private
1373 * arrays, then we revert the decision to map the selected arrays
1374 * to private memory. An alternative solution would be to expand
1375 * the force_private arrays.
1377 * Loops up to gen->shared_len are generated before the mapping to
1378 * threads is applied. They should therefore be ignored.
1380 * We compute the hidden equalities of the schedule first
1381 * since we will need them in our calls to isl_pw_multi_aff_from_map
1382 * and because we want to make sure that the same equalities
1383 * are also available to the code generator.
1385 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1386 __isl_take isl_union_map *sched)
1388 struct ppcg_kernel *kernel = gen->kernel;
1389 int i, j;
1390 int unroll[gen->thread_tiled_len];
1391 int perm[gen->thread_tiled_len];
1392 isl_space *dim;
1393 isl_map *permute;
1394 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1396 gen->first_unroll = -1;
1398 sched = isl_union_map_detect_equalities(sched);
1399 for (i = 0; i < gen->thread_tiled_len; ++i)
1400 unroll[i] = 0;
1401 for (i = 0; i < kernel->n_array; ++i) {
1402 struct gpu_local_array_info *array = &kernel->array[i];
1404 for (j = 0; j < array->n_group; ++j) {
1405 isl_union_map *access;
1406 isl_map *acc;
1407 isl_pw_multi_aff *pma;
1409 if (!array->groups[j]->private_tile)
1410 continue;
1412 access = gpu_array_ref_group_access_relation(
1413 array->groups[j], 1, 1);
1414 access = isl_union_map_apply_domain(access,
1415 isl_union_map_copy(sched));
1417 acc = isl_map_from_union_map(access);
1418 pma = isl_pw_multi_aff_from_map(acc);
1419 isl_pw_multi_aff_foreach_piece(pma,
1420 &check_unroll, unroll);
1422 isl_pw_multi_aff_free(pma);
1426 for (i = gen->shared_len; i < len; ++i)
1427 if (unroll[i])
1428 break;
1430 if (i >= len)
1431 return sched;
1433 for (i = len; i < gen->thread_tiled_len; ++i)
1434 if (unroll[i])
1435 return sched;
1437 if (kernel->any_force_private) {
1438 remove_private_tiles(gen);
1439 return sched;
1442 j = 0;
1443 for (i = 0; i < gen->shared_len; ++i)
1444 perm[i] = j++;
1445 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1446 if (!unroll[i])
1447 perm[i] = j++;
1448 gen->first_unroll = j - gen->shared_len;
1449 for (i = gen->shared_len; i < len; ++i)
1450 if (unroll[i])
1451 perm[i] = j++;
1453 dim = isl_union_map_get_space(sched);
1454 permute = permutation(dim, perm, gen->thread_tiled_len);
1455 sched = isl_union_map_apply_range(sched,
1456 isl_union_map_from_map(permute));
1458 return sched;
1461 /* Construct a map with input the shared tile loops and the loops that
1462 * will be wrapped around the threads that relates these later loops
1463 * to the thread indices and then projects them out.
1465 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1467 isl_map *priv;
1468 isl_map *tiling;
1469 isl_map *proj;
1470 isl_set *par;
1471 isl_space *dim;
1473 dim = isl_union_map_get_space(gen->shared_sched);
1475 if (gen->options->wrap)
1476 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
1477 gen->shared_len, gen->n_block, gen->block_dim);
1478 else
1479 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
1480 gen->shared_len, gen->n_block, gen->block_dim);
1482 priv = tiling;
1484 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
1485 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1486 gen->kernel->thread_ids);
1488 priv = isl_map_align_params(priv, isl_set_get_space(par));
1489 priv = isl_map_intersect_range(priv, par);
1491 dim = isl_map_get_space(priv);
1492 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1493 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1494 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
1495 gen->shared_len);
1497 priv = isl_map_apply_range(priv, proj);
1499 return priv;
1502 /* If max_shared_memory is not set to infinity (-1), then make
1503 * sure that the total amount of shared memory required by the
1504 * array reference groups mapped to shared memory is no larger
1505 * than this maximum.
1507 * We apply a greedy approach and discard (keep in global memory)
1508 * those groups that would result in a total memory size that
1509 * is larger than the maximum.
1511 * This function should be called after any function that may
1512 * affect the decision on whether to place a reference group
1513 * in private, shared or global memory.
1515 static void check_shared_memory_bound(struct gpu_gen *gen)
1517 int i, j;
1518 isl_val *left, *size;
1520 if (gen->options->max_shared_memory < 0)
1521 return;
1523 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
1525 for (i = 0; i < gen->kernel->n_array; ++i) {
1526 struct gpu_local_array_info *local = &gen->kernel->array[i];
1528 for (j = 0; j < local->n_group; ++j) {
1529 struct gpu_array_ref_group *group;
1531 group = local->groups[j];
1532 if (group->private_tile)
1533 continue;
1534 if (!group->shared_tile)
1535 continue;
1537 size = gpu_array_tile_size(group->shared_tile);
1538 size = isl_val_mul_ui(size, local->array->size);
1540 if (isl_val_le(size, left)) {
1541 left = isl_val_sub(left, size);
1542 continue;
1544 isl_val_free(size);
1546 group->shared_tile =
1547 gpu_array_tile_free(group->shared_tile);
1551 isl_val_free(left);
1554 /* Compute a tiling for all the array reference groups.
1556 static void compute_group_tilings(struct gpu_gen *gen)
1558 int i, j;
1560 for (i = 0; i < gen->kernel->n_array; ++i) {
1561 struct gpu_local_array_info *array = &gen->kernel->array[i];
1563 for (j = 0; j < array->n_group; ++j)
1564 gpu_array_ref_group_compute_tiling(array->groups[j]);
1568 /* Take tiled_sched, project it onto the shared tile loops and
1569 * the loops that will be wrapped over the threads and
1570 * store the result in gen->shared_sched.
1571 * Also compute a projection that projects out the loops that will be
1572 * wrapped over the threads and store this projection in gen->shared_proj.
1574 static void compute_shared_sched(struct gpu_gen *gen)
1576 isl_space *dim;
1577 isl_map *proj;
1578 isl_set *par;
1579 isl_union_map *sched;
1581 sched = isl_union_map_copy(gen->tiled_sched);
1583 dim = isl_union_map_get_space(sched);
1584 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
1585 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
1587 dim = isl_union_map_get_space(sched);
1588 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
1590 gen->shared_sched = sched;
1591 gen->shared_proj = isl_union_map_from_map(proj);
1594 /* Compute the size of a bounding box around the origin and "set",
1595 * where "set" is assumed to contain only non-negative elements.
1596 * In particular, compute the maximal value of "set" in each direction
1597 * and add one.
1599 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
1600 __isl_take isl_set *context)
1602 int i, n;
1603 isl_multi_pw_aff *mpa;
1605 context = isl_set_params(context);
1606 n = isl_set_dim(set, isl_dim_set);
1607 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
1608 for (i = 0; i < n; ++i) {
1609 isl_space *space;
1610 isl_aff *one;
1611 isl_pw_aff *bound;
1613 bound = isl_set_dim_max(isl_set_copy(set), i);
1614 bound = isl_pw_aff_coalesce(bound);
1615 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
1617 space = isl_pw_aff_get_domain_space(bound);
1618 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1619 one = isl_aff_add_constant_si(one, 1);
1620 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
1621 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
1623 isl_set_free(set);
1624 isl_set_free(context);
1626 return mpa;
1629 /* Compute the effective grid size as a list of the sizes in each dimension.
1631 * The grid size specified by the user or set by default
1632 * in read_grid_sizes() and applied in tile_schedule(),
1633 * may be too large for the given code in the sense that
1634 * it may contain blocks that don't need to execute anything.
1635 * We therefore don't return this grid size, but instead the
1636 * smallest grid size that ensures that all blocks that actually
1637 * execute code are included in the grid.
1639 * We first extract a description of the grid, i.e., the possible values
1640 * of the block ids, from gen->tiled_sched.
1641 * The block ids are parameters in gen->tiled_sched.
1642 * We simply need to change them into set dimensions.
1644 * Then, for each block dimension, we compute the maximal value of the block id
1645 * and add one.
1647 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
1648 struct ppcg_kernel *kernel)
1650 int i;
1651 isl_set *grid;
1653 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
1654 grid = isl_set_from_params(grid);
1655 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
1656 for (i = 0; i < gen->n_grid; ++i) {
1657 int pos;
1658 isl_id *id;
1660 id = isl_id_list_get_id(kernel->block_ids, i);
1661 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1662 isl_id_free(id);
1663 assert(pos >= 0);
1664 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1665 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1668 return extract_size(grid, isl_set_copy(kernel->context));
1671 /* Compute the size of a fixed bounding box around the origin and "set",
1672 * where "set" is assumed to contain only non-negative elements,
1673 * and store the results in "size".
1674 * In particular, compute the maximal value of "set" in each direction
1675 * and add one.
1677 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1679 int i, n;
1680 isl_local_space *ls;
1681 isl_aff *obj;
1683 n = isl_set_dim(set, isl_dim_set);
1684 ls = isl_local_space_from_space(isl_set_get_space(set));
1685 obj = isl_aff_zero_on_domain(ls);
1686 for (i = 0; i < n; ++i) {
1687 isl_val *max;
1689 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1690 max = isl_set_max_val(set, obj);
1691 size[i] = isl_val_get_num_si(max) + 1;
1692 isl_val_free(max);
1693 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1695 isl_aff_free(obj);
1696 isl_set_free(set);
1699 /* Compute the effective block size as a list of the sizes in each dimension
1700 * and store the sizes in kernel->block_dim.
1702 * The block size specified by the user or set by default
1703 * in read_block_sizes() and applied in thread_tile_schedule(),
1704 * may be too large for the given code in the sense that
1705 * it may contain threads that don't need to execute anything.
1706 * We therefore don't store this block size in kernel->block_dim,
1707 * but instead the smallest block size that ensures that all threads
1708 * that actually execute code are included in the block.
1710 * The current implementation eliminates all parameters, ensuring
1711 * that the size is a fixed constant in each dimension.
1712 * In principle we could also compute parametric sizes.
1713 * We would have to make sure to project out all b%d and t%d parameters,
1714 * however.
1716 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
1718 int i;
1719 int nparam;
1720 isl_set *block;
1721 isl_multi_pw_aff *mpa;
1723 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
1724 block = isl_set_from_params(block);
1725 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
1726 kernel->n_block = gen->n_block;
1727 for (i = 0; i < gen->n_block; ++i) {
1728 int pos;
1729 isl_id *id;
1731 id = isl_id_list_get_id(kernel->thread_ids, i);
1732 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1733 isl_id_free(id);
1734 assert(pos >= 0);
1735 block = isl_set_equate(block, isl_dim_param, pos,
1736 isl_dim_set, i);
1738 nparam = isl_set_dim(block, isl_dim_param);
1739 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1741 extract_fixed_size(block, kernel->block_dim);
1744 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1746 int i, j;
1748 if (!kernel)
1749 return NULL;
1751 isl_id_list_free(kernel->block_ids);
1752 isl_id_list_free(kernel->thread_ids);
1753 isl_multi_pw_aff_free(kernel->grid_size);
1754 isl_set_free(kernel->context);
1755 isl_union_set_free(kernel->arrays);
1756 isl_space_free(kernel->space);
1757 isl_ast_node_free(kernel->tree);
1759 for (i = 0; i < kernel->n_array; ++i) {
1760 struct gpu_local_array_info *array = &kernel->array[i];
1762 for (j = 0; j < array->n_group; ++j)
1763 gpu_array_ref_group_free(array->groups[j]);
1764 free(array->groups);
1766 isl_pw_aff_list_free(array->bound);
1768 free(kernel->array);
1770 for (i = 0; i < kernel->n_var; ++i) {
1771 free(kernel->var[i].name);
1772 isl_vec_free(kernel->var[i].size);
1774 free(kernel->var);
1776 free(kernel);
1778 return NULL;
1781 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1783 static void ppcg_kernel_free_wrap(void *user)
1785 struct ppcg_kernel *kernel = user;
1787 ppcg_kernel_free(kernel);
1790 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1791 struct ppcg_kernel_var *var)
1793 int j;
1794 struct gpu_array_tile *tile;
1795 isl_printer *p;
1796 char *name;
1798 var->array = group->array;
1800 tile = group->private_tile;
1801 var->type = ppcg_access_private;
1802 if (!tile) {
1803 tile = group->shared_tile;
1804 var->type = ppcg_access_shared;
1807 p = isl_printer_to_str(ctx);
1808 p = gpu_array_ref_group_print_name(group, p);
1809 var->name = isl_printer_get_str(p);
1810 isl_printer_free(p);
1812 var->size = isl_vec_alloc(ctx, group->array->n_index);
1814 for (j = 0; j < group->array->n_index; ++j)
1815 var->size = isl_vec_set_element_val(var->size, j,
1816 isl_val_copy(tile->bound[j].size));
1819 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
1821 int i, j, n;
1823 n = 0;
1824 for (i = 0; i < kernel->n_array; ++i) {
1825 struct gpu_local_array_info *array = &kernel->array[i];
1827 for (j = 0; j < array->n_group; ++j) {
1828 struct gpu_array_ref_group *group = array->groups[j];
1829 if (group->private_tile || group->shared_tile)
1830 ++n;
1834 kernel->n_var = n;
1835 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
1836 assert(kernel->var);
1838 n = 0;
1839 for (i = 0; i < kernel->n_array; ++i) {
1840 struct gpu_local_array_info *array = &kernel->array[i];
1842 for (j = 0; j < array->n_group; ++j) {
1843 struct gpu_array_ref_group *group = array->groups[j];
1844 if (!group->private_tile && !group->shared_tile)
1845 continue;
1846 create_kernel_var(gen->ctx, group, &kernel->var[n]);
1847 ++n;
1852 /* Replace "pa" by the zero function defined over the universe domain
1853 * in the space of "pa".
1855 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1857 isl_space *space;
1858 isl_aff *zero;
1860 space = isl_space_domain(isl_pw_aff_get_space(pa));
1861 isl_pw_aff_free(pa);
1862 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1864 return isl_pw_aff_from_aff(zero);
1867 /* The sizes of the arrays on the host that have been computed by
1868 * extract_array_info may depend on the parameters. Use the extra
1869 * constraints on the parameters that are valid at "host_domain"
1870 * to simplify these expressions and store the results in kernel->array.
1872 * We only need these localized bounds for arrays that are accessed
1873 * by the current kernel. If we have found at least one reference group
1874 * then the array is accessed by the kernel. If the array has compound
1875 * elements then we skipped the construction of array reference groups.
1877 * The resulting sizes may be functions that are nowhere defined
1878 * in case the access function cannot possibly access anything inside
1879 * the kernel for some reason. If so, they are replaced by the zero
1880 * function. Since the access function cannot actually access anything,
1881 * there is no harm in printing the array sizes as zero.
1883 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
1884 __isl_keep isl_set *host_domain)
1886 int i, j;
1887 isl_set *context;
1889 context = isl_set_copy(host_domain);
1890 context = isl_set_params(context);
1892 for (i = 0; i < kernel->n_array; ++i) {
1893 struct gpu_local_array_info *local = &kernel->array[i];
1894 isl_pw_aff_list *bound;
1895 int n_index;
1897 if (local->n_group == 0 && !local->array->has_compound_element)
1898 continue;
1900 n_index = local->array->n_index;
1901 bound = isl_pw_aff_list_alloc(gen->ctx, n_index);
1903 for (j = 0; j < n_index; ++j) {
1904 isl_pw_aff *pwaff;
1905 int empty;
1907 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1908 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1909 empty = isl_pw_aff_is_empty(pwaff);
1910 if (empty < 0)
1911 pwaff = isl_pw_aff_free(pwaff);
1912 else if (empty)
1913 pwaff = set_universally_zero(pwaff);
1914 bound = isl_pw_aff_list_add(bound, pwaff);
1917 local->n_index = n_index;
1918 local->bound = bound;
1920 isl_set_free(context);
1923 /* Create the array of gpu_local_array_info structures "array"
1924 * inside "kernel". The number of elements in this array is
1925 * the same as the number of arrays in "prog".
1926 * Initialize the "array" field of each local array to point
1927 * to the corresponding array in "prog".
1929 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1930 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1932 int i;
1933 isl_ctx *ctx;
1935 ctx = isl_set_get_ctx(prog->context);
1936 kernel->array = isl_calloc_array(ctx,
1937 struct gpu_local_array_info, prog->n_array);
1938 if (!kernel->array)
1939 return ppcg_kernel_free(kernel);
1940 kernel->n_array = prog->n_array;
1942 for (i = 0; i < prog->n_array; ++i)
1943 kernel->array[i].array = &prog->array[i];
1945 return kernel;
1948 /* Find the element in gen->stmt that has the given "id".
1949 * Return NULL if no such gpu_stmt can be found.
1951 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1953 int i;
1955 for (i = 0; i < prog->n_stmts; ++i) {
1956 if (id == prog->stmts[i].id)
1957 break;
1960 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1963 /* Set gen->tile_len and gen->n_parallel to those of the statement
1964 * affected by the first map (part of the schedule)
1965 * on which this function is called.
1966 * Because of the way the schedule is constructed, the other statements
1967 * in the list, if any, should have the same values for these properties.
1969 static int extract_tile_len(__isl_take isl_map *map, void *user)
1971 struct gpu_gen *gen = (struct gpu_gen *) user;
1972 isl_id *id;
1973 struct gpu_stmt *stmt;
1975 id = isl_map_get_tuple_id(map, isl_dim_in);
1976 stmt = find_stmt(gen->prog, id);
1977 isl_id_free(id);
1979 isl_map_free(map);
1981 if (!stmt)
1982 isl_die(gen->ctx, isl_error_unknown,
1983 "statement not found", return -1);
1985 gen->tile_len = stmt->tile_len;
1986 gen->n_parallel = stmt->n_parallel;
1988 return -1;
1991 void ppcg_kernel_stmt_free(void *user)
1993 int i;
1994 struct ppcg_kernel_stmt *stmt = user;
1996 if (!stmt)
1997 return;
1999 switch (stmt->type) {
2000 case ppcg_kernel_copy:
2001 isl_ast_expr_free(stmt->u.c.index);
2002 isl_ast_expr_free(stmt->u.c.local_index);
2003 break;
2004 case ppcg_kernel_domain:
2005 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
2006 break;
2007 case ppcg_kernel_sync:
2008 break;
2011 free(stmt);
2014 /* Set the options of "context" to
2016 * { space -> [x] : x >= first }
2018 static __isl_give isl_ast_build *set_unroll(
2019 __isl_take isl_ast_build *build, __isl_take isl_space *space,
2020 int first)
2022 isl_ctx *ctx;
2023 isl_map *unroll;
2024 isl_union_map *opt;
2026 ctx = isl_ast_build_get_ctx(build);
2028 space = isl_space_from_domain(space);
2029 space = isl_space_add_dims(space, isl_dim_out, 1);
2030 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
2031 unroll = isl_map_universe(space);
2032 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
2033 opt = isl_union_map_from_map(unroll);
2035 build = isl_ast_build_set_options(build, opt);
2037 return build;
2040 /* Extend the schedule "schedule" with the part of "extension"
2041 * starting at "first" up to "len".
2043 static __isl_give isl_union_map *extend_schedule(
2044 __isl_take isl_union_map *schedule,
2045 __isl_take isl_union_map *extension, int first, int len)
2047 isl_space *space;
2048 isl_map *proj;
2049 isl_union_map *umap;
2050 isl_set *set;
2052 space = isl_union_map_get_space(schedule);
2053 space = isl_space_set_from_params(space);
2054 space = isl_space_add_dims(space, isl_dim_set, len);
2055 proj = isl_set_identity(isl_set_universe(space));
2056 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
2057 extension = isl_union_map_apply_range(extension,
2058 isl_union_map_from_map(proj));
2060 schedule = isl_union_map_range_product(schedule, extension);
2062 return schedule;
2065 /* Return the gpu_stmt_access in the list "accesses" that corresponds
2066 * to "ref_id".
2068 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
2069 __isl_keep isl_id *ref_id)
2071 struct gpu_stmt_access *access;
2073 for (access = accesses; access; access = access->next)
2074 if (access->ref_id == ref_id)
2075 return access;
2077 return NULL;
2080 /* Return the index of the array called "name" in the list of arrays.
2082 static int find_array_index(struct gpu_gen *gen, const char *name)
2084 int i;
2086 for (i = 0; i < gen->prog->n_array; ++i)
2087 if (!strcmp(name, gen->prog->array[i].name))
2088 return i;
2090 return -1;
2093 /* Internal data structure for the index and AST expression transformation
2094 * callbacks for pet_stmt_build_ast_exprs.
2096 * "accesses" is the list of gpu_stmt_access in the statement.
2097 * "iterator_map" expresses the statement iterators in terms of
2098 * the AST loop iterators.
2099 * "sched2shared" expresses the first shared_len dimensions of
2100 * the computed schedule in terms of the AST loop iterators.
2102 * The following fields are set in transform_index and used in transform_expr.
2103 * "array" is the array that is being accessed.
2104 * "global" is set if the global array is accessed (rather than
2105 * shared/private memory).
2106 * "local_array" refers to information on the array specialized
2107 * to the current kernel.
2109 struct ppcg_transform_data {
2110 struct gpu_gen *gen;
2111 struct gpu_stmt_access *accesses;
2112 isl_pw_multi_aff *iterator_map;
2113 isl_pw_multi_aff *sched2shared;
2115 struct gpu_array_info *array;
2116 int global;
2117 struct gpu_local_array_info *local_array;
2120 /* Return the name of the outer array (of structs) accessed by "access".
2122 static const char *get_outer_array_name(__isl_keep isl_map *access)
2124 isl_space *space;
2125 const char *name;
2127 space = isl_space_range(isl_map_get_space(access));
2128 while (space && isl_space_is_wrapping(space))
2129 space = isl_space_domain(isl_space_unwrap(space));
2130 name = isl_space_get_tuple_name(space, isl_dim_set);
2131 isl_space_free(space);
2133 return name;
2136 /* Return a pointer to the gpu_array_ref_group in "local"
2137 * that contains the reference "access".
2138 * Return NULL if no such group can be found.
2140 static struct gpu_array_ref_group *find_ref_group(
2141 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
2143 int i, j;
2145 for (i = 0; i < local->n_group; ++i) {
2146 struct gpu_array_ref_group *group = local->groups[i];
2148 for (j = 0; j < group->n_ref; ++j)
2149 if (group->refs[j] == access)
2150 return group;
2153 return NULL;
2156 /* Index transformation callback for pet_stmt_build_ast_exprs.
2158 * "index" expresses the array indices in terms of statement iterators
2160 * We first reformulate "index" in terms of the AST loop iterators.
2161 * Then we check if we are accessing the global array or
2162 * a shared/private copy. In the former case, we simply return
2163 * the updated index. If "index" is an affine expression rather
2164 * than an array access, then we also return the updated index here.
2166 * If no reference groups have been computed for the array,
2167 * then we can only be accessing the global array.
2169 * Otherwise, we apply the tiling to the index.
2170 * This tiling is of the form
2172 * [D -> A] -> T
2174 * The index is of the form
2176 * L -> A
2178 * We update the tiling to refer to the AST loop iterators
2180 * [L -> A] -> T
2182 * and modify index to keep track of those iterators
2184 * L -> [L -> A]
2186 * Combining these two yields a tiled index expression in terms
2187 * of the AST loop iterators
2189 * L -> T
2191 static __isl_give isl_multi_pw_aff *transform_index(
2192 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
2193 void *user)
2195 struct ppcg_transform_data *data = user;
2196 struct gpu_stmt_access *access;
2197 struct gpu_array_ref_group *group;
2198 struct gpu_array_tile *tile;
2199 isl_pw_multi_aff *iterator_map;
2200 int i;
2201 const char *name;
2202 isl_space *space;
2203 isl_multi_pw_aff *tiling;
2204 isl_pw_multi_aff *pma;
2205 isl_multi_pw_aff *mpa;
2207 data->array = NULL;
2209 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
2210 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
2212 access = find_access(data->accesses, ref_id);
2213 if (!access)
2214 return index;
2215 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
2216 return index;
2218 name = get_outer_array_name(access->access);
2219 i = find_array_index(data->gen, name);
2220 if (i < 0)
2221 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
2222 "cannot find array",
2223 return isl_multi_pw_aff_free(index));
2224 data->array = &data->gen->prog->array[i];
2225 data->local_array = &data->gen->kernel->array[i];
2227 group = find_ref_group(data->local_array, access);
2228 if (!group) {
2229 data->global = 1;
2230 return index;
2233 tile = group->private_tile;
2234 if (!tile)
2235 tile = group->shared_tile;
2236 data->global = !tile;
2237 if (!tile)
2238 return index;
2240 space = isl_space_range(isl_multi_pw_aff_get_space(index));
2241 space = isl_space_map_from_set(space);
2242 pma = isl_pw_multi_aff_identity(space);
2243 pma = isl_pw_multi_aff_product(
2244 isl_pw_multi_aff_copy(data->sched2shared), pma);
2245 tiling = isl_multi_pw_aff_from_multi_aff(
2246 isl_multi_aff_copy(tile->tiling));
2247 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
2249 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
2250 space = isl_space_map_from_set(space);
2251 mpa = isl_multi_pw_aff_identity(space);
2252 index = isl_multi_pw_aff_range_product(mpa, index);
2253 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
2255 return index;
2258 /* Dereference "expr" by adding an index [0].
2259 * The original "expr" is assumed not to have any indices.
2261 * If "expr" is a member access, then the dereferencing needs
2262 * to be applied to the structure argument of this member access.
2264 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
2266 isl_ctx *ctx;
2267 isl_ast_expr *arg0, *res;
2268 isl_ast_expr_list *list;
2270 arg0 = isl_ast_expr_get_op_arg(expr, 0);
2271 if (!arg0)
2272 return isl_ast_expr_free(expr);
2273 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
2274 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
2275 isl_ast_expr *arg;
2277 arg = isl_ast_expr_get_op_arg(arg0, 0);
2278 arg = dereference(arg);
2279 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
2280 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
2282 return expr;
2284 isl_ast_expr_free(arg0);
2286 ctx = isl_ast_expr_get_ctx(expr);
2287 res = isl_ast_expr_from_val(isl_val_zero(ctx));
2288 list = isl_ast_expr_list_from_ast_expr(res);
2289 res = isl_ast_expr_get_op_arg(expr, 0);
2290 res = isl_ast_expr_access(res, list);
2291 isl_ast_expr_free(expr);
2293 return res;
2296 /* Linearize the index expression "expr" based on the array bounds
2297 * of "array".
2299 * That is, transform expression
2301 * A[i_0][i_1]...[i_n]
2303 * to
2305 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
2307 * where b_0, b_1, ..., b_n are the bounds on the array.
2309 * If the base of "expr" is a member access, then the linearization needs
2310 * to be applied to the structure argument of this member access.
2312 * In the base case, if "expr" has no arguments (other than the name of
2313 * the array), then we are passing an entire array to a function.
2314 * In this case, there is nothing to linearize.
2315 * Note that at this point an expression with no arguments can
2316 * only be an entire array because the scalar case and
2317 * the case of single struct are handled by the caller.
2319 * If the number of specified index expressions in "expr"
2320 * is smaller than the dimension of the accessed array,
2321 * then the missing i_j also do not appear in the linearized expression.
2322 * Furthermore, since such an expression does not refer to a single
2323 * element while the default linearized expression would refer to
2324 * a single element, we return the expression
2326 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
2328 * instead. Note that because of the special case handling above,
2329 * we can assume here that here that there is at least one index expression.
2331 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
2332 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
2334 int i, n;
2335 isl_ctx *ctx;
2336 isl_set *context;
2337 isl_ast_expr *arg0;
2338 isl_ast_expr *res;
2339 isl_ast_expr_list *list;
2340 isl_ast_build *build;
2342 arg0 = isl_ast_expr_get_op_arg(expr, 0);
2343 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
2344 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
2345 isl_ast_expr *arg;
2347 arg = isl_ast_expr_get_op_arg(arg0, 0);
2348 arg = gpu_local_array_info_linearize_index(array, arg);
2349 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
2350 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
2352 return expr;
2354 isl_ast_expr_free(arg0);
2356 if (isl_ast_expr_get_op_n_arg(expr) == 1)
2357 return expr;
2359 ctx = isl_ast_expr_get_ctx(expr);
2360 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
2361 build = isl_ast_build_from_context(context);
2363 n = isl_ast_expr_get_op_n_arg(expr);
2364 res = isl_ast_expr_get_op_arg(expr, 1);
2365 for (i = 1; i < array->n_index; ++i) {
2366 isl_pw_aff *bound_i;
2367 isl_ast_expr *expr_i;
2369 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
2370 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
2371 res = isl_ast_expr_mul(res, expr_i);
2373 if (i + 1 >= n)
2374 continue;
2375 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
2376 res = isl_ast_expr_add(res, expr_i);
2379 isl_ast_build_free(build);
2381 if (1 + array->n_index > n) {
2382 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
2383 } else {
2384 list = isl_ast_expr_list_from_ast_expr(res);
2385 res = isl_ast_expr_get_op_arg(expr, 0);
2386 res = isl_ast_expr_access(res, list);
2389 isl_ast_expr_free(expr);
2391 return res;
2394 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
2396 * If the AST expression refers to an array that is not accessed
2397 * at all, then this means the value of the expression is not used,
2398 * so we might as well print zero (NULL pointer) instead.
2400 * If the AST expression refers to a global scalar that is not
2401 * a read-only scalar, then its address was passed to the kernel and
2402 * we need to dereference it.
2404 * If the AST expression refers to an access to a global array,
2405 * then we linearize the access exploiting the bounds in data->local_array.
2407 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
2408 __isl_keep isl_id *id, void *user)
2410 struct ppcg_transform_data *data = user;
2412 if (!data->array)
2413 return expr;
2414 if (!data->array->accessed) {
2415 isl_ctx *ctx;
2417 ctx = isl_ast_expr_get_ctx(expr);
2418 isl_ast_expr_free(expr);
2419 return isl_ast_expr_from_val(isl_val_zero(ctx));
2421 if (gpu_array_is_read_only_scalar(data->array))
2422 return expr;
2423 if (!data->global)
2424 return expr;
2425 if (data->array->n_index == 0)
2426 return dereference(expr);
2427 if (!data->array->linearize)
2428 return expr;
2430 return gpu_local_array_info_linearize_index(data->local_array, expr);
2433 /* This function is called for each instance of a user statement
2434 * in the kernel.
2436 * We attach a struct ppcg_kernel_stmt to the "node", containing
2437 * a computed AST expression for each access.
2438 * These AST expressions are computed from iterator_map,
2439 * which expresses the domain
2440 * elements in terms of the generated loops, and sched2shared,
2441 * which expresses the first shared_len dimensions of the schedule
2442 * computed by PPCG in terms of the generated loops.
2444 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
2445 __isl_keep isl_ast_build *build, void *user)
2447 struct ppcg_transform_data data;
2448 struct gpu_gen *gen = (struct gpu_gen *) user;
2449 struct ppcg_kernel_stmt *stmt;
2450 isl_id *id;
2451 isl_pw_multi_aff *sched2shared;
2452 isl_map *map;
2453 isl_pw_multi_aff *iterator_map;
2454 isl_ast_expr *expr, *arg;
2455 isl_union_map *schedule;
2457 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2458 if (!stmt)
2459 return isl_ast_node_free(node);
2461 expr = isl_ast_node_user_get_expr(node);
2462 arg = isl_ast_expr_get_op_arg(expr, 0);
2463 id = isl_ast_expr_get_id(arg);
2465 schedule = isl_ast_build_get_schedule(build);
2466 map = isl_map_reverse(isl_map_from_union_map(schedule));
2467 iterator_map = isl_pw_multi_aff_from_map(map);
2468 sched2shared = compute_sched_to_shared(gen,
2469 isl_pw_multi_aff_copy(iterator_map));
2471 stmt->type = ppcg_kernel_domain;
2472 stmt->u.d.stmt = find_stmt(gen->prog, id);
2473 if (!stmt->u.d.stmt)
2474 isl_die(gen->ctx, isl_error_internal,
2475 "statement not found", goto error);
2477 data.gen = gen;
2478 data.accesses = stmt->u.d.stmt->accesses;
2479 data.iterator_map = iterator_map;
2480 data.sched2shared = sched2shared;
2481 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
2482 build, &transform_index, &data,
2483 &transform_expr, &data);
2485 isl_id_free(id);
2486 isl_pw_multi_aff_free(iterator_map);
2487 isl_pw_multi_aff_free(sched2shared);
2488 isl_ast_expr_free(arg);
2489 isl_ast_expr_free(expr);
2491 id = isl_id_alloc(gen->ctx, NULL, stmt);
2492 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2493 return isl_ast_node_set_annotation(node, id);
2494 error:
2495 isl_id_free(id);
2496 isl_pw_multi_aff_free(iterator_map);
2497 ppcg_kernel_stmt_free(stmt);
2498 isl_pw_multi_aff_free(sched2shared);
2499 return isl_ast_node_free(node);
2502 /* This function is called when code has been generated for the shared
2503 * tile loops. The "schedule" refers only to the original statements.
2505 * We extend the schedule with that part of gen->local_sched that hasn't
2506 * been taken into account yet. This introduces parameters referring
2507 * to thread ids in the schedule, so we add them (with the appropriate
2508 * bounds to the context as well).
2509 * Finally, we set the appropriate unrolling options
2510 * if gen->first_unroll is set.
2512 static __isl_give isl_ast_node *create_domain_leaf(
2513 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
2514 void *user)
2516 struct gpu_gen *gen = (struct gpu_gen *) user;
2517 isl_space *space;
2518 isl_union_map *sched;
2519 isl_ast_node *tree;
2520 isl_set *set;
2521 isl_id_list *iterators;
2522 int n;
2524 schedule = extend_schedule(schedule,
2525 isl_union_map_copy(gen->local_sched),
2526 gen->shared_len, gen->thread_tiled_len);
2528 space = isl_ast_build_get_schedule_space(build);
2529 set = isl_set_universe(space);
2530 set = add_bounded_parameters(set, gen->kernel->block_dim,
2531 gen->kernel->thread_ids);
2532 build = isl_ast_build_restrict(build, set);
2534 n = gen->thread_tiled_len - gen->shared_len;
2536 if (gen->first_unroll >= 0) {
2537 space = isl_space_set_alloc(gen->ctx, 0, n);
2538 build = set_unroll(build, space, gen->first_unroll);
2540 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
2541 build = isl_ast_build_set_iterators(build, iterators);
2542 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
2543 tree = isl_ast_build_node_from_schedule_map(build, schedule);
2544 isl_ast_build_free(build);
2546 return tree;
2549 /* This function is called for each statement node in the AST of the code
2550 * for copying to or from shared/private memory.
2551 * Attach a pointer to a ppcg_kernel_stmt representing the copy
2552 * statement to the node.
2553 * The statement name is "read" or "write", depending on whether we are
2554 * reading from global memory or writing to global memory.
2555 * The name of the T space is {shared,private}_<array>.
2557 * The schedule is of the form
2559 * type[A -> T] -> L
2561 * where A refers to a piece of an array and T to the corresponding
2562 * shifted tile. We split this schedule into mappings L -> A and L -> T
2563 * and store the corresponding expressions in stmt->index and stmt->local_index,
2564 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
2566 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
2567 __isl_keep isl_ast_build *build, void *user)
2569 struct gpu_gen *gen = (struct gpu_gen *) user;
2570 struct ppcg_kernel_stmt *stmt;
2571 isl_id *id;
2572 isl_ast_expr *expr;
2573 isl_space *space;
2574 isl_map *access, *local_access, *map;
2575 isl_pw_multi_aff *pma;
2576 const char *type;
2577 int array_index;
2579 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2580 if (!stmt)
2581 return isl_ast_node_free(node);
2583 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
2584 type = isl_map_get_tuple_name(access, isl_dim_in);
2585 stmt->u.c.read = !strcmp(type, "read");
2586 access = isl_map_reverse(access);
2587 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
2588 local_access = isl_map_copy(access);
2590 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
2591 id = isl_map_get_tuple_id(access, isl_dim_out);
2592 map = isl_map_set_tuple_id(map, isl_dim_in, id);
2593 access = isl_map_apply_range(access, map);
2594 pma = isl_pw_multi_aff_from_map(access);
2595 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
2596 stmt->u.c.index = expr;
2598 map = isl_map_range_map(isl_map_universe(space));
2599 id = isl_map_get_tuple_id(local_access, isl_dim_out);
2600 map = isl_map_set_tuple_id(map, isl_dim_in, id);
2601 local_access = isl_map_apply_range(local_access, map);
2602 pma = isl_pw_multi_aff_from_map(local_access);
2603 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
2604 stmt->u.c.local_index = expr;
2606 stmt->u.c.array = gen->copy_group->array;
2607 array_index = stmt->u.c.array - gen->prog->array;
2608 stmt->u.c.local_array = &gen->kernel->array[array_index];
2609 stmt->type = ppcg_kernel_copy;
2611 id = isl_id_alloc(gen->ctx, NULL, stmt);
2612 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2613 return isl_ast_node_set_annotation(node, id);
2616 /* Given a schedule of the form
2618 * [S -> A] -> L
2620 * (with S the first shared_len dimensions of the computed schedule,
2621 * A the array and L the schedule correponding to the generated loops),
2622 * indicating where to copy the array elements that need to be copied,
2623 * construct code for performing the copying.
2625 * "group" is the array reference group that is being copied
2626 * "type" is either "read" or "write"
2627 * private is set if copying needs to be performed to/from registers
2629 * We first construct a mapping to a shifted tile of the array,
2631 * [S -> A] -> T(S,A) (1)
2633 * If private is set, then we also use this mapping as a schedule
2634 * (which is already thread-specific and will be completely unrolled).
2635 * Otherwise, we wrap/tile the range over the threads.
2636 * The result is
2638 * [S -> A] -> T'(S,A)
2640 * Combined with the given schedule, we have
2642 * [S -> A] -> [L -> T'(S,A)] (2)
2644 * From the shifted tile mapping, we construct a mapping
2646 * [S -> A] -> [A -> T(S,A)]
2648 * and apply it to the schedule (2), obtaining
2650 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
2652 * Note that we can project out S because it is uniquely defined by L.
2654 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
2655 __isl_take isl_map *sched,
2656 const char *type, struct gpu_array_ref_group *group,
2657 __isl_take isl_ast_build *build, int private)
2659 isl_space *space;
2660 isl_ast_node *tree;
2661 isl_map *schedule, *shift, *map;
2662 isl_set *set;
2663 isl_id_list *iterators;
2664 int n;
2666 shift = shift_access(group);
2668 schedule = isl_map_copy(shift);
2669 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
2670 if (!private)
2671 schedule = tile_access_schedule(gen, schedule);
2673 n = isl_map_dim(schedule, isl_dim_out);
2674 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
2675 set = add_bounded_parameters(set, gen->kernel->block_dim,
2676 gen->kernel->thread_ids);
2678 schedule = isl_map_range_product(sched, schedule);
2680 space = isl_space_domain(isl_map_get_space(shift));
2681 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
2682 map = isl_map_range_product(map, shift);
2684 schedule = isl_map_apply_domain(schedule, map);
2686 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
2688 build = isl_ast_build_restrict(build, set);
2690 gen->copy_group = group;
2692 if (private) {
2693 space = isl_space_range(isl_map_get_space(schedule));
2694 space = isl_space_range(isl_space_unwrap(space));
2695 build = set_unroll(build, space, 0);
2697 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
2698 build = isl_ast_build_set_iterators(build, iterators);
2699 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
2700 tree = isl_ast_build_node_from_schedule_map(build,
2701 isl_union_map_from_map(schedule));
2702 isl_ast_build_free(build);
2704 return tree;
2707 /* Return code for reading into or writing from shared memory
2708 * the given array reference group.
2710 * If we are performing a read from global memory to shared memory and
2711 * if the array involved is not a scalar, then we copy
2712 * the entire tile to shared memory. This may result in some extra
2713 * elements getting copied, but it should lead to simpler code
2714 * (which means that fewer registers may be needed) and less divergence.
2716 * Otherwise, we only copy the elements that will be read or have been written
2717 * in the kernel.
2720 * The input "sched" is of the form.
2722 * type[S -> A] -> L
2724 * with S the first shared_len dimensions of the computed schedule,
2725 * A the array and L the schedule correponding to the generated loops.
2727 * We first drop "type",
2729 * [S -> A] -> L
2731 * If the above conditions are satisfied, we project out A,
2732 * resulting in
2734 * S -> L
2736 * and then introduce the group tile [S -> T], resulting in
2738 * [S -> T] -> L
2740 static __isl_give isl_ast_node *copy_group_shared_accesses(
2741 struct gpu_gen *gen, struct gpu_array_ref_group *group,
2742 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
2744 const char *type;
2745 int read;
2746 isl_union_map *access;
2748 type = isl_map_get_tuple_name(sched, isl_dim_in);
2749 read = !strcmp(type, "read");
2751 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
2753 if (read && !gpu_array_is_scalar(group->array)) {
2754 isl_space *space;
2755 isl_map *map;
2757 space = isl_space_domain(isl_map_get_space(sched));
2758 space = isl_space_unwrap(space);
2759 map = isl_map_domain_map(isl_map_universe(space));
2760 sched = isl_map_apply_domain(sched, map);
2762 map = group_tile(group);
2763 map = isl_map_reverse(isl_map_domain_map(map));
2764 sched = isl_map_apply_domain(sched, map);
2767 return copy_access(gen, sched, type, group, build, 0);
2770 /* Return code for reading into or writing from private memory
2771 * the given array reference group.
2773 * Let S be the first shared_len dimensions of the computed schedule,
2774 * D the iteration domains, A the array and L the schedule correponding
2775 * to the generated loops.
2776 * "sched" is of the form
2778 * type[S -> A] -> L
2780 * where type is either "read" or "write".
2781 * We apply the privatization D -> S(t), with t the thread ids,
2782 * to the access relation D -> A to obtain the privatized access relation
2784 * S(t) -> A
2786 * We drop the type from "sched" and intersect with the privatized access
2787 * relation to obtain
2789 * [S(t) -> A] -> L
2791 static __isl_give isl_ast_node *copy_group_private_accesses(
2792 struct gpu_gen *gen, struct gpu_array_ref_group *group,
2793 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
2795 const char *type;
2796 int read;
2797 isl_union_map *priv;
2798 isl_union_map *access;
2799 isl_map *access_map;
2801 type = isl_map_get_tuple_name(sched, isl_dim_in);
2802 read = !strcmp(type, "read");
2804 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2805 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2806 priv);
2808 access = gpu_array_ref_group_access_relation(group, read, !read);
2809 access = isl_union_map_apply_domain(access, priv);
2810 access_map = isl_map_from_union_map(access);
2812 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
2813 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
2815 return copy_access(gen, sched, type, group, build, 1);
2818 /* Return code for reading into or writing from shared or private memory.
2820 * "schedule" is of the form
2822 * type[S -> A] -> L
2824 * with S be the first shared_len dimensions of the computed schedule,
2825 * A the array and L the schedule correponding to the generated loops.
2826 * The array reference group is attached to "type".
2828 static __isl_give isl_ast_node *create_access_leaf(
2829 struct gpu_gen *gen, __isl_take isl_map *schedule,
2830 __isl_take isl_ast_build *build)
2832 struct gpu_array_ref_group *group;
2833 isl_id *id;
2835 id = isl_map_get_tuple_id(schedule, isl_dim_in);
2836 group = isl_id_get_user(id);
2837 isl_id_free(id);
2839 if (group->private_tile)
2840 return copy_group_private_accesses(gen, group, schedule,
2841 build);
2842 else
2843 return copy_group_shared_accesses(gen, group, schedule,
2844 build);
2847 /* Create a domain node representing a synchronization.
2849 static __isl_give isl_ast_node *create_sync_leaf(
2850 struct gpu_gen *gen, __isl_take isl_map *schedule,
2851 __isl_take isl_ast_build *build)
2853 struct ppcg_kernel_stmt *stmt;
2854 isl_id *id;
2855 isl_space *space;
2856 isl_ast_node *node;
2857 isl_ast_expr *expr;
2859 isl_map_free(schedule);
2861 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2862 if (!stmt)
2863 return NULL;
2865 stmt->type = ppcg_kernel_sync;
2867 space = isl_ast_build_get_schedule_space(build);
2868 space = isl_space_from_domain(space);
2869 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
2870 expr = isl_ast_build_call_from_pw_multi_aff(build,
2871 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
2872 node = isl_ast_node_alloc_user(expr);
2873 isl_ast_build_free(build);
2875 id = isl_id_alloc(gen->ctx, NULL, stmt);
2876 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2877 return isl_ast_node_set_annotation(node, id);
2880 /* This function is called during the code generation at the point
2881 * where the schedule domain element is completely determined by
2882 * the generated code. The input schedule contains the original
2883 * statements as well as synchronization and copy "statements".
2884 * The latter are scheduled at different points than any of the original
2885 * statements, so they will only arrive here in isolation.
2887 * If the current schedule only refers to a single statement,
2888 * we check if it is a copy or synchronization statement and
2889 * call the appropriate functions.
2890 * Otherwise, we assume we are dealing with the original statements
2891 * and we call create_domain_leaf.
2893 static __isl_give isl_ast_node *create_kernel_leaf(
2894 __isl_take isl_ast_build *build, void *user)
2896 struct gpu_gen *gen = (struct gpu_gen *) user;
2897 isl_map *map;
2898 isl_union_map *schedule;
2899 const char *name;
2901 schedule = isl_ast_build_get_schedule(build);
2903 if (isl_union_map_n_map(schedule) != 1)
2904 return create_domain_leaf(schedule, build, user);
2906 map = isl_map_from_union_map(schedule);
2907 name = isl_map_get_tuple_name(map, isl_dim_in);
2908 if (!strcmp(name, "read") || !strcmp(name, "write"))
2909 return create_access_leaf(gen, map, build);
2910 if (!strcmp(name, "sync"))
2911 return create_sync_leaf(gen, map, build);
2913 return create_domain_leaf(isl_union_map_from_map(map), build, user);
2916 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
2917 * have value 0) and all even schedule dimensions as "unroll".
2919 * That is, the options look as follows
2921 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
2922 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
2924 * The even positions are used to be able to schedule copying blocks
2925 * and synchronization before or after each level of the shared memory
2926 * tile loops and we want to make sure that code for these is generated
2927 * separately (within each level).
2929 static __isl_give isl_ast_build *set_atomic_and_unroll(
2930 __isl_take isl_ast_build *build,
2931 __isl_take isl_space *space, int sched_len)
2933 isl_ctx *ctx;
2934 isl_map *map;
2935 isl_constraint *c;
2936 isl_union_map *opt;
2937 isl_local_space *ls;
2938 int i, n;
2940 ctx = isl_ast_build_get_ctx(build);
2942 space = isl_space_params(space);
2943 space = isl_space_add_dims(space, isl_dim_set, sched_len);
2944 space = isl_space_from_domain(space);
2945 space = isl_space_add_dims(space, isl_dim_out, 2);
2946 map = isl_map_universe(isl_space_copy(space));
2947 for (i = 0; i < sched_len; i += 2)
2948 map = isl_map_fix_si(map, isl_dim_in, i, 0);
2949 ls = isl_local_space_from_space(isl_map_get_space(map));
2950 c = isl_equality_alloc(ls);
2951 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
2952 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
2953 c = isl_constraint_set_constant_si(c, 1);
2954 map = isl_map_add_constraint(map, c);
2955 map = isl_map_project_out(map, isl_dim_out, 1, 1);
2956 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
2957 opt = isl_union_map_from_map(map);
2959 map = isl_map_universe(space);
2960 ls = isl_local_space_from_space(isl_map_get_space(map));
2961 c = isl_equality_alloc(ls);
2962 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
2963 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
2964 map = isl_map_add_constraint(map, c);
2965 map = isl_map_project_out(map, isl_dim_out, 1, 1);
2966 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
2967 opt = isl_union_map_add_map(opt, map);
2969 build = isl_ast_build_set_options(build, opt);
2971 return build;
2974 /* Return a map that maps a space of dimension gen->shared_len
2975 * to its last dimensions starting at gen->tile_first.
2976 * The range is of dimension
2978 * 2 * (gen->shared_len - gen->tile_first) + 1
2980 * The input dimensions are mapped to the odd dimensions in the output,
2981 * while the even dimensions (except 2*pos) are fixed to 0.
2982 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
2983 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
2984 * are mapped to the output. The remaining input dimensions are projected
2985 * out and the corresponding output dimensions are fixed to 0.
2987 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
2988 __isl_take isl_space *space, int pos, int val)
2990 int i, n;
2991 isl_map *proj;
2993 space = isl_space_set_from_params(space);
2994 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
2995 space = isl_space_map_from_set(space);
2996 proj = isl_map_identity(space);
2997 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
2998 n = gen->shared_len - gen->tile_first;
2999 for (i = 0; i <= n; ++i) {
3000 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
3001 if (i == pos)
3002 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
3003 else
3004 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
3007 if (pos < 0)
3008 return proj;
3010 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
3011 gen->shared_len - (gen->tile_first + pos));
3012 for (i = pos; i < n; ++i)
3013 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
3015 return proj;
3018 /* Given the AST context schedule "schedule" and the mapping from
3019 * domains to the shared tile loops "shared_sched", add a schedule
3020 * for a synchronization operation at position "val" of loop level "pos".
3022 * schedule is of the form
3024 * D -> L
3026 * (with D the iteration domains and L the already generated loops),
3027 * while shared_sched is of the form
3029 * D -> S
3031 * We combine them into
3033 * L -> S
3035 * apply a mapping
3037 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3039 * and use the result as a schedule for "sync".
3041 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
3042 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3043 __isl_keep isl_union_map *shared_sched, int pos, int val)
3045 isl_space *space;
3046 isl_map *proj, *map;
3048 shared_sched = isl_union_map_copy(shared_sched);
3049 schedule = isl_union_map_copy(schedule);
3051 space = isl_union_map_get_space(shared_sched);
3052 schedule = isl_union_map_apply_domain(shared_sched, schedule);
3053 map = isl_map_from_union_map(schedule);
3055 proj = insert_even(gen, space, pos, val);
3056 map = isl_map_apply_range(map, proj);
3057 map = isl_map_from_range(isl_map_wrap(map));
3058 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
3060 res = isl_union_map_add_map(res, map);
3062 return res;
3065 /* Given a set of wrapped references "ref", return the corresponding
3066 * access relations based on the tagged access relations "tagged".
3068 * The elements of "ref" are of the form
3070 * [D -> R]
3072 * with D an iteration domains and R a reference.
3073 * The elements of "tagged" are of the form
3075 * [D -> R] -> A
3077 * with A an array.
3079 * Extend "tagged" to include the iteration domain in the range, i.e.,
3081 * [D -> R] -> [D -> A]
3083 * apply the result to "ref" and then unwrap the resulting set
3084 * to obtain relations of the form
3086 * D -> A
3088 static __isl_give isl_union_map *wrapped_reference_to_access(
3089 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
3091 isl_union_map *tag2access;
3093 tag2access = isl_union_map_copy(tagged);
3094 tag2access = isl_union_map_universe(tag2access);
3095 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
3096 tag2access = isl_union_map_domain_map(tag2access);
3097 tag2access = isl_union_map_range_product(tag2access, tagged);
3099 ref = isl_union_set_coalesce(ref);
3100 ref = isl_union_set_apply(ref, tag2access);
3102 return isl_union_set_unwrap(ref);
3105 /* Given an access relation "access" from "group", remove those reads
3106 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
3107 * communicate data within the same iteration of the last_shared dimension
3108 * of the group.
3110 * If the access is a read then it is either an element of
3112 * live_in union (range flow)
3114 * where live_in and flow may be overapproximations, or
3115 * it reads an uninitialized value (that is not live-in because
3116 * there is an intermediate kill) or it reads a value that was
3117 * written within the same (compound) statement instance.
3118 * If the access is a write then it is either an element of
3120 * live_out union (domain flow)
3122 * or it writes a value that is never read (and is not live-out
3123 * because of an intermediate kill) or only
3124 * within the same (compound) statement instance.
3125 * In both cases, the access relation is also a subset of
3126 * the group access relation.
3128 * The cases where an uninitialized value is read or a value is written
3129 * that is never read or where the dataflow occurs within a statement
3130 * instance are also considered local and may also be removed.
3132 * Essentially, we compute the intersection of "access" with either
3134 * live_in union (range non-local-flow)
3136 * or
3138 * live_out union (domain non-local-flow)
3140 * We first construct a relation "local"
3142 * [[D -> R] -> [D' -> R']]
3144 * of pairs of domain iterations accessing the reference group
3145 * and references in the group that are scheduled to the same iteration
3146 * of the last_shared dimension.
3148 * If this relation does not intersect the dataflow dependences,
3149 * then there is nothing we can possibly remove, unless the dataflow
3150 * dependences themselves only relate a subset of the accesses.
3151 * In particular, the accesses may not be involved in any dataflow
3152 * dependences, either because they are uninitialized reads/dead writes
3153 * or because the dataflow occurs inside a statement instance.
3155 * Since the computation below may break up the access relation
3156 * into smaller pieces, we only perform the intersection with
3157 * the non-local dependent accesses if the local pairs
3158 * intersect the dataflow dependences. Otherwise, we intersect
3159 * with the universe of the non-local dependent accesses.
3160 * This should at least remove accesses from statements that
3161 * do not participate in any dependences.
3163 * In particular, we remove the "local" dataflow dependences from
3164 * the set of all dataflow dependences.
3165 * Note that if the potential dataflow dependences are an overapproximation
3166 * of the actual dataflow dependences, then the result remains an
3167 * overapproximation of the non-local dataflow dependences.
3168 * Copying to/from global memory is only needed for the references
3169 * in the domain/range of the result or for accesses that are live out/in
3170 * for the entire scop.
3172 * We therefore map the domain/range of the "external" relation
3173 * to the corresponding access relation and take the union with
3174 * the live out/in relation.
3176 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
3177 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
3178 int read)
3180 int empty;
3181 isl_union_pw_multi_aff *tagger;
3182 isl_union_set *domain;
3183 isl_space *space;
3184 isl_union_map *sched, *local, *tagged, *external;
3185 isl_union_set *tag_set;
3186 isl_map *proj;
3188 if (isl_union_map_is_empty(access))
3189 return access;
3191 tagged = group_tagged_access_relation(group);
3193 sched = isl_union_map_copy(gen->sched);
3195 space = isl_union_map_get_space(sched);
3196 proj = projection(space, gen->untiled_len, group->last_shared + 1);
3197 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3199 tagger = isl_union_pw_multi_aff_copy(gen->prog->scop->tagger);
3200 domain = isl_union_map_domain(isl_union_map_copy(tagged));
3201 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
3202 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
3204 local = isl_union_map_apply_range(sched,
3205 isl_union_map_reverse(isl_union_map_copy(sched)));
3206 local = isl_union_map_intersect(local,
3207 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
3209 empty = isl_union_map_is_empty(local);
3211 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
3212 external = isl_union_map_intersect_params(external,
3213 isl_set_copy(gen->prog->scop->context));
3214 external = isl_union_map_subtract(external, local);
3216 if (read) {
3217 tag_set = isl_union_map_range(external);
3218 external = wrapped_reference_to_access(tag_set, tagged);
3219 external = isl_union_map_union(external,
3220 isl_union_map_copy(gen->prog->scop->live_in));
3221 } else {
3222 tag_set = isl_union_map_domain(external);
3223 external = wrapped_reference_to_access(tag_set, tagged);
3224 external = isl_union_map_union(external,
3225 isl_union_map_copy(gen->prog->scop->live_out));
3228 if (empty < 0)
3229 external = isl_union_map_free(external);
3230 else if (empty)
3231 external = isl_union_map_universe(external);
3233 access = isl_union_map_intersect(access, external);
3235 return access;
3238 /* Given the AST context schedule "schedule" and the mapping from
3239 * domains to the shared tile loops "shared_sched", add a schedule
3240 * for copying an array reference group to/from shared/private memory.
3241 * "read" is set if data should be copied from global memory
3242 * to shared/private memory.
3243 * "k" represents the current group
3244 * "s" is the total number of groups
3246 * We schedule an operation before or after the innermost loop
3247 * of "shared_sched" that affects the tile of the array reference group.
3249 * schedule is of the form
3251 * D -> L
3253 * (with D the iteration domains and L the already generated loops),
3254 * while shared_sched is of the form
3256 * D -> S
3258 * We first compute the access relation for the reference group
3260 * D -> A
3262 * and remove from this access relation those reads or writes
3263 * that only needed to communicate data within the same iteration
3264 * of the last_shared dimension of the group.
3265 * We then combine what is left with shared_sched into
3267 * D -> [S -> A]
3269 * If this results in an empty relation, no copying needs to be performed
3270 * at this point.
3271 * Otherwise, we invert the relation and combine it with "schedule" into
3273 * [S -> A] -> L
3275 * The actual additional piece of the schedule is obtained from combining
3277 * [S -> A] -> S
3279 * with a mapping
3281 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3283 * The position of "val" corresponds to the innermost loop that affects
3284 * the tile and the value indicates where the copying is scheduled
3285 * with respect to the actual kernel code (at value 0).
3286 * Reads are schedule before the code, writes to global memory from
3287 * private memory are scheduled at values 1 to s, writes to global
3288 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
3290 * If we are scheduling a read from global memory to shared memory,
3291 * we insert a synchronization before the kernel code (at the innermost
3292 * level).
3293 * If we are scheduling a write to global memory, then we add
3294 * a synchronization after all writes (at value 2 *s + 2).
3295 * However, there is no need for a synchronization after the outermost loop.
3296 * A write to global memory from private memory at the innermost level
3297 * does not require a synchronization, because it is covered by
3298 * the synchronization after the kernel inserted by body_schedule.
3300 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
3301 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3302 __isl_keep isl_union_map *shared_sched,
3303 struct gpu_array_ref_group *group, int read, int k, int s)
3305 int n;
3306 int pos, val;
3307 isl_space *space;
3308 isl_union_map *access;
3309 isl_map *map, *proj, *access_map;
3310 isl_id *id;
3312 access = gpu_array_ref_group_access_relation(group, read, !read);
3313 access = remove_local_accesses(gen, group, access, read);
3314 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
3315 access);
3317 if (isl_union_map_is_empty(access)) {
3318 isl_union_map_free(access);
3319 return res;
3322 access = isl_union_map_reverse(access);
3323 access = isl_union_map_apply_range(access,
3324 isl_union_map_copy(schedule));
3325 access_map = isl_map_from_union_map(access);
3327 space = isl_space_copy(group->array->space);
3328 space = isl_space_from_range(space);
3329 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
3330 map = isl_map_domain_map(isl_map_universe(space));
3332 space = isl_union_map_get_space(schedule);
3333 pos = group->last_shared + 1 - gen->tile_first;
3334 assert(pos >= 0);
3335 if (read)
3336 val = -2 - k;
3337 else if (group->private_tile)
3338 val = 1 + k;
3339 else
3340 val = 1 + s + 1 + k;
3341 proj = insert_even(gen, space, pos, val);
3342 map = isl_map_apply_range(map, proj);
3344 access_map = isl_map_range_product(access_map, map);
3346 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
3347 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
3349 res = isl_union_map_add_map(res, access_map);
3351 n = gen->shared_len - gen->tile_first;
3352 if (read) {
3353 if (!group->private_tile)
3354 res = add_sync_schedule(gen, res, schedule,
3355 shared_sched, n, -1);
3356 } else {
3357 if (pos == 0)
3358 return res;
3359 if (pos == n && group->private_tile)
3360 return res;
3361 res = add_sync_schedule(gen, res, schedule, shared_sched,
3362 pos, 2 * s + 2);
3365 return res;
3368 /* Return a schedule for the shared tile loops based on the current
3369 * AST context schedule.
3371 * We create a "shared_sched" that maps the domains to the first
3372 * shared_len dimensions of the computed schedule, project out the
3373 * first tile_first dimensions (as these are already covered by
3374 * the host code) and insert "statement-level" dimensions at even
3375 * positions so that we can schedule copy blocks and synchronization
3376 * before/after each level.
3378 * In particular, copy blocks are inserted inside the innermost
3379 * level that affect the tile. For the copying to global memory,
3380 * those from private memory are scheduled before those from shared
3381 * memory such that synchronization can be inserted between the two
3382 * at the innermost level.
3383 * Synchronization is inserted at the innermost level before the
3384 * actual kernel code if there is any copying from global memory
3385 * to shared memory. It is inserted unconditionally at the innermost
3386 * level after the actual kernel code and the copying to global memory
3387 * from private memory (if any). Finally, it is inserted after
3388 * any copying to global memory, except at the outermost level
3389 * and at the innermost level if there is no copying from shared
3390 * memory. The copying from private memory is covered by the unconditional
3391 * synchronization at the innermost level.
3393 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
3394 __isl_take isl_union_map *schedule)
3396 isl_space *space;
3397 isl_union_map *res;
3398 isl_union_map *shared_sched;
3399 isl_union_map *sched;
3400 isl_map *proj, *map;
3401 int i, j, k, s;
3403 shared_sched = isl_union_map_copy(gen->tiled_sched);
3404 proj = projection(isl_union_map_get_space(shared_sched),
3405 gen->tiled_len, gen->shared_len);
3406 shared_sched = isl_union_map_apply_range(shared_sched,
3407 isl_union_map_from_map(proj));
3408 space = isl_union_map_get_space(shared_sched);
3409 proj = insert_even(gen, space, -1, 0);
3410 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
3411 isl_union_map_from_map(proj));
3413 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
3415 s = 0;
3416 for (i = 0; i < gen->kernel->n_array; ++i)
3417 s += gen->kernel->array[i].n_group;
3419 k = 0;
3420 for (i = 0; i < gen->kernel->n_array; ++i) {
3421 struct gpu_local_array_info *array = &gen->kernel->array[i];
3423 for (j = 0; j < array->n_group; ++j) {
3424 struct gpu_array_ref_group *group;
3426 group = array->groups[j];
3427 if (!group->private_tile && !group->shared_tile)
3428 continue;
3429 res = add_group_schedule(gen, res, schedule,
3430 shared_sched, group, 0, k, s);
3431 res = add_group_schedule(gen, res, schedule,
3432 shared_sched, group, 1, k, s);
3433 ++k;
3437 res = add_sync_schedule(gen, res, schedule, shared_sched,
3438 gen->shared_len - gen->tile_first, 1 + s);
3440 isl_union_map_free(shared_sched);
3441 isl_union_map_free(schedule);
3443 return res;
3446 /* Generate code for "kernel" in the given "context".
3448 * We first generate code for the shared tile loops (T1T, T1P and T2)
3449 * in a context that includes the block ids.
3450 * Within each iteration of these loops an additional code generation
3451 * is performed (within create_kernel_leaf) for the rest of the schedule
3452 * in a context that includes the thread ids.
3454 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
3455 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
3456 __isl_keep isl_multi_pw_aff *grid_size)
3458 isl_space *space;
3459 isl_set *set;
3460 isl_id_list *iterators;
3461 isl_union_map *schedule;
3462 isl_ast_node *tree;
3463 int sched_len;
3465 schedule = isl_ast_build_get_schedule(build);
3467 build = isl_ast_build_copy(build);
3468 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
3469 space = isl_ast_build_get_schedule_space(build);
3470 set = isl_set_universe(isl_space_copy(space));
3471 set = add_bounded_parameters_dynamic(set, grid_size,
3472 gen->kernel->block_ids);
3473 build = isl_ast_build_restrict(build, set);
3475 schedule = body_schedule(gen, schedule);
3477 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
3479 build = set_atomic_and_unroll(build, space, sched_len);
3480 iterators = ppcg_scop_generate_names(gen->prog->scop, sched_len, "g");
3481 build = isl_ast_build_set_iterators(build, iterators);
3482 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
3483 tree = isl_ast_build_node_from_schedule_map(build, schedule);
3484 isl_ast_build_free(build);
3486 return tree;
3489 /* Attach "id" to the given node.
3491 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
3492 __isl_keep isl_ast_build *build, void *user)
3494 isl_id *id = user;
3496 node = isl_ast_node_set_annotation(node, id);
3498 return node;
3501 /* Construct an AST node for performing a kernel launch and attach
3502 * the information about the kernel to that node.
3503 * "kernel_id" has name "kernel" and contains a pointer
3504 * to the ppcg_kernel structure.
3506 * The kernel AST has been constructed in the context of the range
3507 * of "schedule". In particular, the grid size has been computed
3508 * in the context. We therefore still need to make sure that these
3509 * constraints are expressed in the code. We do this by creating a schedule
3511 * kernel[] -> [S -> []]
3513 * where S is the schedule domain, i.e., the range of "schedule".
3514 * The AST generation will then create a single call surrounded by
3515 * all the condition in "S" that have not been expressed yet.
3517 * The kernel information is attached to this node in attach_id.
3519 static __isl_give isl_ast_node *construct_launch(
3520 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
3521 __isl_take isl_id *kernel_id)
3523 isl_ctx *ctx;
3524 isl_union_set *domain;
3525 isl_set *set;
3526 isl_map *map;
3527 isl_ast_node *node;
3529 ctx = isl_ast_build_get_ctx(build);
3531 domain = isl_union_map_range(schedule);
3532 set = isl_set_from_union_set(domain);
3533 map = isl_map_from_domain(set);
3534 map = isl_map_from_range(isl_map_wrap(map));
3535 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
3536 schedule = isl_union_map_from_map(map);
3538 build = isl_ast_build_set_at_each_domain(build, &attach_id, kernel_id);
3539 node = isl_ast_build_node_from_schedule_map(build, schedule);
3540 isl_ast_build_free(build);
3542 return node;
3545 /* This function is called for each leaf in the AST of the host code.
3546 * We first specialize the schedule to the site of the leaf, compute
3547 * the size of shared memory and then construct the body of the host code
3548 * and the associated kernel.
3550 * The necessary information for printing the kernel launch is
3551 * stored in the struct ppcg_kernel that was created in create_kernel and
3552 * attached to an outer mark node in the schedule tree.
3553 * Note that this assumes that a kernel is only launched once.
3554 * The kernel pointer itself is stored in gen->kernel by before_mark,
3555 * while the isl_id containing this pointer is stored in gen->kernel_mark.
3556 * The latter is attached to the leaf AST node created to represent the launch.
3558 static __isl_give isl_ast_node *create_host_leaf(
3559 __isl_take isl_ast_build *build, void *user)
3561 struct gpu_gen *gen = (struct gpu_gen *) user;
3562 isl_id *id;
3563 isl_ast_node *node;
3564 struct ppcg_kernel *kernel;
3565 isl_set *host_domain;
3566 isl_union_map *schedule;
3567 isl_union_map *local_sched;
3568 isl_union_set *domain;
3569 int i;
3571 schedule = isl_ast_build_get_schedule(build);
3573 kernel = gen->kernel;
3574 if (!kernel)
3575 goto error;
3577 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
3578 read_sizes(gen);
3580 domain = isl_union_map_domain(isl_union_map_copy(schedule));
3582 local_sched = isl_union_map_copy(gen->sched);
3583 local_sched = isl_union_map_intersect_domain(local_sched, domain);
3585 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3586 gen->n_grid, "b");
3587 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3588 gen->n_block, "t");
3590 gen->tiled_sched = tile_schedule(gen, local_sched);
3591 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
3592 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
3594 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
3595 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
3596 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
3598 kernel->grid_size = extract_grid_size(gen, kernel);
3599 extract_block_size(gen, kernel);
3600 kernel->space = isl_ast_build_get_schedule_space(build);
3602 compute_shared_sched(gen);
3603 gen->privatization = compute_privatization(gen);
3604 if (gpu_group_references(gen) < 0)
3605 schedule = isl_union_map_free(schedule);
3606 host_domain = isl_set_from_union_set(isl_union_map_range(
3607 isl_union_map_copy(schedule)));
3608 localize_bounds(gen, kernel, host_domain);
3610 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
3611 check_shared_memory_bound(gen);
3612 compute_group_tilings(gen);
3614 kernel->tree = generate_kernel(gen, build, host_domain,
3615 kernel->grid_size);
3616 create_kernel_vars(gen, kernel);
3618 isl_map_free(gen->privatization);
3619 isl_union_map_free(gen->local_sched);
3620 isl_union_map_free(gen->tiled_sched);
3621 isl_union_map_free(gen->shared_sched);
3622 isl_union_map_free(gen->shared_proj);
3623 isl_set_free(host_domain);
3624 free(gen->tile_size);
3626 node = construct_launch(build, schedule, isl_id_copy(gen->kernel_mark));
3628 return node;
3629 error:
3630 isl_union_map_free(schedule);
3631 return NULL;
3634 /* This function is called before the AST generator starts traversing
3635 * the schedule subtree of a node with mark "mark".
3637 * If the mark is called "kernel", store the mark itself in gen->kernel_mark
3638 * and the kernel pointer in gen->kernel for use in create_host_leaf.
3640 static int before_mark(__isl_keep isl_id *mark,
3641 __isl_keep isl_ast_build *build, void *user)
3643 struct gpu_gen *gen = user;
3645 if (!mark)
3646 return -1;
3647 if (!strcmp(isl_id_get_name(mark), "kernel")) {
3648 gen->kernel_mark = isl_id_copy(mark);
3649 gen->kernel = isl_id_get_user(mark);
3651 return 0;
3654 /* This function is called after the AST generator has finished traversing
3655 * the schedule subtree of a mark node. "node" points to the corresponding
3656 * mark AST node.
3658 * If the mark is called "kernel", then clear kernel and gen->kernel_mark.
3660 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
3661 __isl_keep isl_ast_build *build, void *user)
3663 struct gpu_gen *gen = user;
3664 isl_id *id;
3666 id = isl_ast_node_mark_get_id(node);
3667 if (!id)
3668 return isl_ast_node_free(node);
3669 if (!strcmp(isl_id_get_name(id), "kernel") && gen->kernel) {
3670 gen->kernel_mark = isl_id_free(gen->kernel_mark);
3671 gen->kernel = NULL;
3674 isl_id_free(id);
3675 return node;
3678 /* Use isl to generate host code from gen->host_schedule, which corresponds to
3679 * the outer gen->tile_first loops of the global schedule in gen->sched.
3680 * Within each iteration of this partial schedule, i.e., for each kernel
3681 * launch, create_host_leaf takes care of generating the kernel code.
3682 * The ppcg_kernel objects are stored in mark nodes in the schedule
3683 * tree and are extracted in before_mark.
3685 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
3687 isl_ast_build *build;
3688 isl_ast_node *tree;
3689 isl_schedule *schedule;
3690 isl_id_list *iterators;
3692 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
3693 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
3694 iterators = ppcg_scop_generate_names(gen->prog->scop,
3695 gen->tile_first, "h");
3696 build = isl_ast_build_set_iterators(build, iterators);
3697 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
3698 build = isl_ast_build_set_before_each_mark(build, &before_mark, gen);
3699 build = isl_ast_build_set_after_each_mark(build, &after_mark, gen);
3700 schedule = isl_schedule_copy(gen->host_schedule);
3701 tree = isl_ast_build_node_from_schedule(build, schedule);
3702 isl_ast_build_free(build);
3704 return tree;
3707 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
3709 if (!str)
3710 return NULL;
3711 return isl_union_map_read_from_str(ctx, str);
3714 /* Information about the outermost tilable bands in the forest of bands.
3716 * tile_len and n_parallel are only sets on band_info structures
3717 * that correspond to outermost bands. For other bands (in particular,
3718 * ancestors of the outermost bands), n_parallal is set to 0.
3720 * prefix is the (padded) schedule leading up to the outermost tilable bands.
3722 * tile_first is the number of schedule dimensions in prefix.
3724 * suffix is the schedule of the outermost tilable bands and their descendants.
3726 struct band_info {
3727 struct gpu_gen *gen;
3728 int tile_first;
3729 int tile_len;
3730 int n_parallel;
3731 isl_union_map *prefix;
3732 isl_union_map *suffix;
3735 /* Set tile_len and n_parallel of the statement to that of
3736 * their outermost band, recorded in the band_info.
3738 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
3740 struct band_info *info = user;
3741 struct gpu_stmt *stmt;
3742 isl_id *id;
3744 id = isl_map_get_tuple_id(map, isl_dim_in);
3745 stmt = find_stmt(info->gen->prog, id);
3746 isl_id_free(id);
3748 stmt->tile_len = info->tile_len;
3749 stmt->n_parallel = info->n_parallel;
3751 isl_map_free(map);
3753 return 0;
3756 /* Extract the set of parameter values and outer schedule dimensions
3757 * for which any statement instance
3758 * in the kernel inserted at "node" needs to be executed.
3759 * Intersect the set of parameter values derived from the host schedule
3760 * relation with the context of "prog".
3762 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
3763 struct gpu_prog *prog)
3765 isl_union_map *schedule;
3766 isl_union_set *schedule_domain;
3767 isl_set *context;
3768 int empty;
3770 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
3771 schedule_domain = isl_union_map_range(schedule);
3772 empty = isl_union_set_is_empty(schedule_domain);
3773 if (empty < 0) {
3774 isl_union_set_free(schedule_domain);
3775 return NULL;
3777 if (empty) {
3778 int depth;
3779 isl_space *space;
3781 space = isl_union_set_get_space(schedule_domain);
3782 isl_union_set_free(schedule_domain);
3783 space = isl_space_set_from_params(space);
3784 depth = isl_schedule_node_get_schedule_depth(node);
3785 space = isl_space_add_dims(space, isl_dim_set, depth);
3786 context = isl_set_empty(space);
3787 } else {
3788 context = isl_set_from_union_set(schedule_domain);
3790 context = isl_set_intersect_params(context,
3791 isl_set_copy(prog->context));
3793 return context;
3796 /* Return the set of outer array elements accessed by
3797 * by the statement instance in "domain" in "prog".
3799 static __isl_give isl_union_set *accessed_by_domain(
3800 __isl_take isl_union_set *domain, struct gpu_prog *prog)
3802 isl_union_map *access;
3803 isl_union_set *arrays;
3805 access = isl_union_map_union(isl_union_map_copy(prog->read),
3806 isl_union_map_copy(prog->may_write));
3807 access = isl_union_map_intersect_domain(access, domain);
3808 arrays = isl_union_map_range(access);
3809 arrays = isl_union_set_apply(arrays,
3810 isl_union_map_copy(prog->to_outer));
3812 return arrays;
3815 /* Return the number of outer band members of the band node "node"
3816 * that are marked coincident.
3818 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
3820 int i, n;
3822 n = isl_schedule_node_band_n_member(node);
3824 for (i = 0; i < n; ++i)
3825 if (!isl_schedule_node_band_member_get_coincident(node, i))
3826 break;
3828 return i;
3831 /* Mark all dimensions in the current band node atomic.
3833 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3835 int i, n;
3837 n = isl_schedule_node_band_n_member(node);
3838 for (i = 0; i < n; ++i)
3839 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3840 isl_ast_loop_atomic);
3842 return node;
3845 /* Mark "node" atomic, if it is a band node.
3846 * Do the same for all ancestors.
3847 * Return a pointer to "node" (in the updated schedule tree).
3849 static __isl_give isl_schedule_node *atomic_ancestors(
3850 __isl_take isl_schedule_node *node)
3852 int pos;
3854 if (!node)
3855 return NULL;
3856 if (!isl_schedule_node_has_parent(node))
3857 return node;
3859 pos = isl_schedule_node_get_child_position(node);
3860 node = isl_schedule_node_parent(node);
3861 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3862 node = atomic(node);
3863 node = atomic_ancestors(node);
3864 node = isl_schedule_node_child(node, pos);
3866 return node;
3869 /* Group the domain elements into a single space, named kernelX,
3870 * with X the kernel sequence number "kernel_id".
3872 static __isl_give isl_schedule_node *group_statements(
3873 __isl_take isl_schedule_node *node, int kernel_id)
3875 char buffer[20];
3876 isl_id *id;
3878 if (!node)
3879 return NULL;
3881 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3882 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3883 return isl_schedule_node_group(node, id);
3886 /* Create a ppcg_kernel representing the domain instances that reach "node"
3887 * and replace the subtree at "node" by a mark node pointing
3888 * to the ppcg_kernel.
3889 * Mark all outer band nodes as atomic to ensure each kernel is only
3890 * scheduled once.
3891 * If the domain elements that reach "node" live in more than one space,
3892 * then group the domain elements into a single space, named kernelX,
3893 * with X the kernel sequence number.
3895 * We keep a copy of the isl_id that points to the kernel to ensure
3896 * that the kernel does not get destroyed if the schedule node
3897 * is freed due to some error condition.
3899 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3900 __isl_take isl_schedule_node *node)
3902 struct ppcg_kernel *kernel;
3903 isl_id *id;
3904 isl_union_set *domain;
3905 int single_statement;
3907 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3908 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3909 if (!kernel)
3910 return isl_schedule_node_free(node);
3912 domain = isl_schedule_node_get_domain(node);
3913 single_statement = isl_union_set_n_set(domain) == 1;
3915 kernel->ctx = gen->ctx;
3916 kernel->options = gen->options;
3917 kernel->context = extract_context(node, gen->prog);
3918 kernel->arrays = accessed_by_domain(domain, gen->prog);
3919 kernel->id = gen->kernel_id++;
3921 node = atomic_ancestors(node);
3923 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3924 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3925 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3927 if (!single_statement)
3928 node = group_statements(node, kernel->id);
3930 node = isl_schedule_node_child(node, 0);
3931 node = isl_schedule_node_cut(node);
3932 node = isl_schedule_node_parent(node);
3934 if (!single_statement)
3935 node = isl_schedule_node_parent(node);
3937 isl_id_free(id);
3938 return node;
3941 /* Insert a zero-dimensional permutable band at "node".
3943 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3944 __isl_take isl_schedule_node *node)
3946 isl_space *space;
3947 isl_schedule *schedule;
3948 isl_union_set *domain;
3949 isl_multi_union_pw_aff *mupa;
3951 schedule = isl_schedule_node_get_schedule(node);
3952 domain = isl_schedule_get_domain(schedule);
3953 space = isl_union_set_get_space(domain);
3954 isl_union_set_free(domain);
3955 isl_schedule_free(schedule);
3957 space = isl_space_set_from_params(space);
3958 mupa = isl_multi_union_pw_aff_zero(space);
3959 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3960 node = isl_schedule_node_band_set_permutable(node, 1);
3962 return node;
3965 /* Mark "node" as outer permutable.
3967 * If "node" originally points to a leaf, then insert a zero-dimensional
3968 * permutable band such that we can assume that "node" always
3969 * points to a band node.
3971 * Create a kernel representing the domain instances that reach "node" and
3972 * replace the band node with a mark node pointing to the kernel.
3974 static __isl_give isl_schedule_node *mark_outer_permutable(
3975 struct gpu_gen *gen, __isl_take isl_schedule_node *node)
3977 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3978 node = insert_empty_permutable_band(node);
3980 node = create_kernel(gen, node);
3982 return node;
3985 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
3986 __isl_take isl_schedule_node *node, int pos, struct band_info *info);
3988 /* Check if this band node is tilable and has any parallel loops. If so,
3989 * take it as the outermost tilable band. If not, continue looking for the
3990 * outermost tilable band in the children of the current band.
3991 * Return a pointer to the same node in a tree where all outermost tilable
3992 * bands in the current subtree have been replaced by mark nodes
3993 * containing a pointer to a ppcg_kernel object.
3995 static __isl_give isl_schedule_node *band_select_outer_band(struct gpu_gen *gen,
3996 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
3998 int n = isl_schedule_node_band_n_member(node);
3999 int n_parallel;
4001 n_parallel = n_outer_coincidence(node);
4003 if (!isl_schedule_node_band_get_permutable(node) || n_parallel == 0) {
4004 node = isl_schedule_node_child(node, 0);
4005 node = select_outer_band(gen, node, pos + n, info);
4006 return isl_schedule_node_parent(node);
4009 info->n_parallel = n_parallel;
4010 gen->any_parallelism = 1;
4011 info->gen = gen;
4012 info->tile_first = pos;
4013 info->tile_len = n;
4014 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4015 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
4016 isl_union_map_foreach_map(info->prefix, &set_stmt_tile_len, info);
4018 node = mark_outer_permutable(gen, node);
4020 return node;
4023 /* Extend "umap" with coordinates with fixed value "val"
4024 * to a total length of "dst_len", assuming the original dimension is "src_len".
4026 static __isl_give isl_union_map *extend_range(
4027 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4029 isl_space *dim;
4030 isl_map *map;
4031 int i;
4033 dim = isl_union_map_get_space(umap);
4034 map = isl_map_reverse(projection(dim, dst_len, src_len));
4035 for (i = src_len; i < dst_len; ++i)
4036 map = isl_map_fix_si(map, isl_dim_out, i, val);
4038 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4040 return umap;
4043 /* Select the outermost bands in the elements of the sequence or set
4044 * node "node", align their prefix schedules and combine the resulting
4045 * prefix and suffix schedules into a single pair of prefix and
4046 * suffix schedules for the entire list.
4047 * Return a pointer to the same node in a tree where all outermost tilable
4048 * bands in the current subtree have been replaced by mark nodes
4049 * containing a pointer to a ppcg_kernel object.
4051 static __isl_give isl_schedule_node *list_select_outer_band(
4052 struct gpu_gen *gen, __isl_take isl_schedule_node *node, int pos,
4053 struct band_info *list_info)
4055 int i;
4056 int n = isl_schedule_node_n_children(node);
4057 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
4058 struct band_info *info;
4059 int max_tile_first;
4060 isl_union_map *prefix;
4061 isl_union_map *suffix;
4063 assert(n >= 1);
4064 info = isl_calloc_array(ctx, struct band_info, n);
4065 assert(info);
4067 max_tile_first = 0;
4068 for (i = 0; i < n; ++i) {
4069 node = isl_schedule_node_child(node, i);
4070 node = select_outer_band(gen, node, pos, &info[i]);
4071 if (info[i].tile_first > max_tile_first)
4072 max_tile_first = info[i].tile_first;
4073 node = isl_schedule_node_parent(node);
4076 for (i = 0; i < n; ++i) {
4077 if (info[i].tile_first == max_tile_first)
4078 continue;
4079 info[i].prefix = extend_range(info[i].prefix,
4080 info[i].tile_first, max_tile_first, 0);
4081 info[i].tile_first = max_tile_first;
4084 prefix = info[0].prefix;
4085 suffix = info[0].suffix;
4087 for (i = 1; i < n; ++i) {
4088 prefix = isl_union_map_union(prefix, info[i].prefix);
4089 suffix = isl_union_map_union(suffix, info[i].suffix);
4092 list_info->tile_first = info[0].tile_first;
4093 list_info->tile_len = -1;
4094 list_info->prefix = prefix;
4095 list_info->suffix = suffix;
4097 free(info);
4098 return node;
4101 /* If we reach a leaf node, then we have not found any outer tilable
4102 * band with parallel loops, so consider the leaf node as the outermost
4103 * tilable band.
4104 * Return a pointer to a mark node containing a pointer
4105 * to a ppcg_kernel object inserted at the original leaf node.
4107 static __isl_give isl_schedule_node *leaf_select_outer_band(struct gpu_gen *gen,
4108 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
4110 info->gen = gen;
4111 info->tile_first = pos;
4112 info->tile_len = 0;
4113 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4114 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
4115 isl_union_map_foreach_map(info->prefix, &set_stmt_tile_len, info);
4117 node = mark_outer_permutable(gen, node);
4119 return node;
4122 /* Select the outermost tilable band in the subtree that "node" points to and
4123 * return a pointer to the same node in a tree where all outermost tilable
4124 * bands in the current subtree have been replaced by mark nodes
4125 * containing a pointer to a ppcg_kernel object.
4127 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
4128 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
4130 enum isl_schedule_node_type type;
4132 type = isl_schedule_node_get_type(node);
4133 switch (type) {
4134 case isl_schedule_node_domain:
4135 case isl_schedule_node_filter:
4136 node = isl_schedule_node_child(node, 0);
4137 node = select_outer_band(gen, node, pos, info);
4138 return isl_schedule_node_parent(node);
4139 case isl_schedule_node_leaf:
4140 return leaf_select_outer_band(gen, node, pos, info);
4141 case isl_schedule_node_band:
4142 return band_select_outer_band(gen, node, pos, info);
4143 case isl_schedule_node_set:
4144 case isl_schedule_node_sequence:
4145 return list_select_outer_band(gen, node, pos, info);
4146 default:
4147 isl_die(isl_schedule_node_get_ctx(node),
4148 isl_error_unsupported, "unhandled schedule node type",
4149 node = node);
4150 case isl_schedule_node_error:
4151 info->prefix = NULL;
4152 info->suffix = NULL;
4153 break;
4156 return isl_schedule_node_free(node);
4159 /* Select the outermost tilable band that (by construction)
4160 * has at least one parallel loop.
4161 * The starting position of the aligned band is stored in the pair
4162 * gen->tile_first.
4163 * The sizes and number of parallel loops may be different in different
4164 * parts of the band forest and are therefore stored in the gpu_stmts.
4166 * Return the complete schedule, with the tilable bands aligned
4167 * at gen->tile_first and padded with zero, if needed.
4168 * Store a schedule tree corresponding to the outer gen->tile_first
4169 * dimensions, with mark nodes containing pointers to ppcg_kernel objects,
4170 * in gen->host_schedule.
4172 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4173 __isl_keep isl_schedule *schedule)
4175 isl_schedule_node *node;
4176 struct band_info info;
4178 gen->n_parallel = 0;
4179 gen->tile_len = -1;
4181 node = isl_schedule_get_root(schedule);
4182 node = select_outer_band(gen, node, 0, &info);
4183 gen->host_schedule = isl_schedule_node_get_schedule(node);
4184 isl_schedule_node_free(node);
4186 gen->tile_first = info.tile_first;
4187 info.suffix = align_range(info.suffix);
4189 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4192 /* Set gen->untiled_len to the number of scheduling dimensions
4193 * for the schedule of the first domain.
4194 * We assume here that this number is the same for all domains.
4196 static int set_untiled_len(__isl_take isl_map *map, void *user)
4198 unsigned *untiled_len = user;
4200 *untiled_len = isl_map_dim(map, isl_dim_out);
4202 isl_map_free(map);
4203 return -1;
4206 /* Compute an appropriate schedule based on the accesses in
4207 * gen->read and gen->write.
4209 * We use the dependences in gen->prog->scop to compute
4210 * a schedule that has a parallel loop in each tilable band.
4211 * Finally, we select the outermost tilable band.
4213 * If live range reordering is allowed, then we need to make sure
4214 * that live ranges on arrays are not run in parallel since doing
4215 * so would require array expansion. We therefore add the array
4216 * order dependences to the coincidence dependences. Non-zero array
4217 * order dependences will then prevent a schedule dimension from being
4218 * considered parallel.
4219 * Live ranges derived from scalars are allowed to be run in parallel
4220 * since we force the scalars to be mapped to private memory in
4221 * check_scalar_live_ranges.
4222 * If live range reordering is allowed, then the false dependences
4223 * are not added to the validity constraints as that would prevent
4224 * reordering. Instead, the external false dependences that enforce that reads
4225 * from potentially live-in data precede any later write and
4226 * that writes of potentially live-out data follow any other earlier write
4227 * are added to the validity and the coincidence constraints.
4228 * The false dependences are still added to the proximity constraints
4229 * for consistency with the case where live range reordering is not allowed.
4230 * The coincidence constraints then consist of flow dependences,
4231 * external false dependences and array order dependences.
4232 * The independences can be filtered out from the first two sets.
4233 * They have already been filtered out from the array order dependences
4234 * on a per array basis in collect_order_dependences.
4235 * There is no need for a per array handling of the other two sets
4236 * as there should be no flow or external false dependence on local
4237 * variables that can be filtered out.
4239 static void compute_schedule(struct gpu_gen *gen)
4241 isl_union_set *domain;
4242 isl_union_map *dep_raw, *dep;
4243 isl_union_map *validity, *proximity, *coincidence;
4244 isl_union_map *sched;
4245 isl_schedule_constraints *sc;
4246 isl_schedule *schedule;
4248 domain = isl_union_set_copy(gen->prog->scop->domain);
4249 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
4250 sc = isl_schedule_constraints_set_context(sc,
4251 isl_set_copy(gen->prog->scop->context));
4252 if (gen->options->live_range_reordering) {
4253 sc = isl_schedule_constraints_set_conditional_validity(sc,
4254 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
4255 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
4256 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
4257 validity = isl_union_map_copy(proximity);
4258 validity = isl_union_map_union(validity,
4259 isl_union_map_copy(gen->prog->scop->dep_forced));
4260 proximity = isl_union_map_union(proximity,
4261 isl_union_map_copy(gen->prog->scop->dep_false));
4262 coincidence = isl_union_map_copy(validity);
4263 coincidence = isl_union_map_subtract(coincidence,
4264 isl_union_map_copy(gen->prog->scop->independence));
4265 coincidence = isl_union_map_union(coincidence,
4266 isl_union_map_copy(gen->prog->array_order));
4267 } else {
4268 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4269 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4270 dep = isl_union_map_union(dep, dep_raw);
4271 dep = isl_union_map_coalesce(dep);
4272 proximity = isl_union_map_copy(dep);
4273 coincidence = isl_union_map_copy(dep);
4274 validity = dep;
4276 sc = isl_schedule_constraints_set_validity(sc, validity);
4277 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4278 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4280 if (gen->options->debug->dump_schedule_constraints)
4281 isl_schedule_constraints_dump(sc);
4282 schedule = isl_schedule_constraints_compute_schedule(sc);
4283 if (gen->options->debug->dump_schedule)
4284 isl_schedule_dump(schedule);
4286 sched = select_outer_tilable_band(gen, schedule);
4288 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4289 sched = isl_union_map_intersect_domain(sched, domain);
4290 gen->sched = sched;
4292 isl_schedule_free(schedule);
4295 /* Compute the sets of outer array elements that need to be copied in and out.
4297 * In particular, for each array that is possibly written anywhere in
4298 * gen->prog and that is visible outside the corresponding scop,
4299 * we copy out its entire extent.
4301 * Any array elements that is read without first being written needs
4302 * to be copied in. Furthermore, if there are any array elements that
4303 * are copied out, but that may not be written inside gen->prog, then
4304 * they also need to be copied in to ensure that the value after execution
4305 * is the same as the value before execution, at least for those array
4306 * elements that may have their values preserved by the scop.
4307 * In case the array elements are structures, we need to take into
4308 * account that all members of the structures need to be written
4309 * by gen->prog before we can avoid copying the data structure in.
4311 * While computing the set of array elements that are copied out but
4312 * not necessarily written, we intersect both sets with the context.
4313 * This helps in those cases where the arrays are declared with a fixed size,
4314 * while the accesses are parametric and the context assigns a fixed value
4315 * to the parameters.
4317 * If an element from a local array is read without first being written,
4318 * then there is no point in copying it in since it cannot have been
4319 * written prior to the scop. Warn about the uninitialized read instead.
4321 static void compute_copy_in_and_out(struct gpu_gen *gen)
4323 int i;
4324 isl_union_set *local;
4325 isl_union_set *may_write, *must_write;
4326 isl_union_set *copy_in, *copy_out;
4327 isl_union_set *not_written;
4328 isl_union_map *uninitialized;
4329 isl_union_map *local_uninitialized;
4331 must_write = isl_union_map_range(
4332 isl_union_map_copy(gen->prog->must_write));
4333 must_write = isl_union_set_intersect_params(must_write,
4334 isl_set_copy(gen->prog->context));
4335 may_write = isl_union_map_range(
4336 isl_union_map_copy(gen->prog->may_write));
4337 may_write = isl_union_set_intersect_params(may_write,
4338 isl_set_copy(gen->prog->context));
4339 may_write = isl_union_set_universe(may_write);
4340 may_write = isl_union_set_apply(may_write,
4341 isl_union_map_copy(gen->prog->to_outer));
4342 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
4343 local = isl_union_set_copy(copy_out);
4345 for (i = 0; i < gen->prog->n_array; ++i) {
4346 isl_space *space;
4347 isl_set *write_i;
4348 int empty;
4350 space = isl_space_copy(gen->prog->array[i].space);
4352 if (gen->prog->array[i].local) {
4353 isl_set *set;
4355 set = isl_set_universe(space);
4356 local = isl_union_set_add_set(local, set);
4357 continue;
4360 write_i = isl_union_set_extract_set(may_write, space);
4361 empty = isl_set_plain_is_empty(write_i);
4362 isl_set_free(write_i);
4363 if (empty)
4364 continue;
4366 write_i = isl_set_copy(gen->prog->array[i].extent);
4367 copy_out = isl_union_set_add_set(copy_out, write_i);
4369 isl_union_set_free(may_write);
4371 copy_out = isl_union_set_intersect_params(copy_out,
4372 isl_set_copy(gen->prog->context));
4374 gen->prog->copy_out = isl_union_set_copy(copy_out);
4376 copy_out = isl_union_set_apply(copy_out,
4377 isl_union_map_copy(gen->prog->to_inner));
4378 copy_out = isl_union_set_intersect(copy_out,
4379 isl_union_set_copy(gen->prog->may_persist));
4380 not_written = isl_union_set_subtract(copy_out, must_write);
4382 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4383 local_uninitialized = isl_union_map_copy(uninitialized);
4385 local = isl_union_set_apply(local,
4386 isl_union_map_copy(gen->prog->to_inner));
4387 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4388 local);
4389 if (!isl_union_map_is_empty(local_uninitialized)) {
4390 fprintf(stderr,
4391 "possibly uninitialized reads (not copied in):\n");
4392 isl_union_map_dump(local_uninitialized);
4394 uninitialized = isl_union_map_subtract(uninitialized,
4395 local_uninitialized);
4396 copy_in = isl_union_map_range(uninitialized);
4397 copy_in = isl_union_set_union(copy_in, not_written);
4398 copy_in = isl_union_set_apply(copy_in,
4399 isl_union_map_copy(gen->prog->to_outer));
4401 gen->prog->copy_in = copy_in;
4404 /* Internal data structure for extract_access.
4405 * "next_access" points to the end of a linked list that is extended
4406 * by extract_access.
4407 * "single_expression" is set if the access expressions belong to
4408 * an expression statement (i.e., a statement without internal control).
4409 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4411 struct ppcg_extract_access_data {
4412 struct gpu_stmt_access **next_access;
4413 int single_expression;
4414 isl_union_map *any_to_outer;
4417 /* Given a tagged access relation to a single array "tagged", extract it
4418 * as a map, taking into account that the input may be empty.
4419 * If the access relation is empty, then it does not contain
4420 * any space information, so we try to recover it from the index
4421 * expression.
4422 * The space of the index expression is of the form I -> A,
4423 * with I the statement instances and A the array, or [I -> F] -> A,
4424 * with F the filters corresponding to arguments.
4425 * We first drop F, if present, obtaining I -> A.
4426 * Then we construct I -> R, with R the reference tag,
4427 * combine the two into I -> [R -> A] and uncurry to obtain
4428 * the final result [I -> R] -> A.
4429 * Note that the index expression may have a lower dimension
4430 * than that of the array, but this dimension is not used
4431 * if the access relation is empty.
4433 static __isl_give isl_map *extract_single_tagged_access(
4434 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4436 int empty;
4437 isl_id *id;
4438 isl_space *space, *space2;
4439 isl_multi_pw_aff *index;
4441 empty = isl_union_map_is_empty(tagged);
4442 if (empty < 0)
4443 goto error;
4444 if (!empty)
4445 return isl_map_from_union_map(tagged);
4446 isl_union_map_free(tagged);
4448 index = pet_expr_access_get_index(expr);
4449 space = isl_multi_pw_aff_get_space(index);
4450 isl_multi_pw_aff_free(index);
4451 if (isl_space_domain_is_wrapping(space))
4452 space = isl_space_domain_factor_domain(space);
4453 space2 = isl_space_copy(space);
4454 space2 = isl_space_from_domain(isl_space_domain(space));
4455 id = pet_expr_access_get_ref_id(expr);
4456 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4457 space = isl_space_range_product(space2, space);
4458 space = isl_space_uncurry(space);
4460 return isl_map_empty(space);
4461 error:
4462 isl_union_map_free(tagged);
4463 return NULL;
4466 /* Extract a gpu_stmt_access from "expr", append it to the list
4467 * that ends in *data->next_access and update the end of the list.
4468 * If the access expression performs a write, then it is considered
4469 * exact only if it appears in a single expression statement and
4470 * if its may access relation is equal to its must access relation.
4472 * The combined set of may accesses may be union if member accesses
4473 * are involved, but the entire set is derived from a single reference and
4474 * therefore from a single index expression. These accesses therefore
4475 * all map to the same outer array.
4477 static int extract_access(__isl_keep pet_expr *expr, void *user)
4479 struct ppcg_extract_access_data *data = user;
4480 isl_union_map *tagged;
4481 struct gpu_stmt_access *access;
4482 isl_ctx *ctx = pet_expr_get_ctx(expr);
4483 isl_multi_pw_aff *index;
4485 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4486 assert(access);
4487 access->next = NULL;
4488 access->read = pet_expr_access_is_read(expr);
4489 access->write = pet_expr_access_is_write(expr);
4490 tagged = pet_expr_access_get_tagged_may_read(expr);
4491 tagged = isl_union_map_union(tagged,
4492 pet_expr_access_get_tagged_may_write(expr));
4493 tagged = isl_union_map_apply_range(tagged,
4494 isl_union_map_copy(data->any_to_outer));
4495 if (!access->write) {
4496 access->exact_write = 1;
4497 } else if (!data->single_expression) {
4498 access->exact_write = 0;
4499 } else {
4500 isl_union_map *must, *may;
4501 may = isl_union_map_copy(tagged);
4502 may = isl_union_map_domain_factor_domain(may);
4503 must = pet_expr_access_get_must_write(expr);
4504 access->exact_write = isl_union_map_is_equal(must, may);
4505 isl_union_map_free(must);
4506 isl_union_map_free(may);
4508 index = pet_expr_access_get_index(expr);
4509 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4510 isl_multi_pw_aff_free(index);
4511 access->ref_id = pet_expr_access_get_ref_id(expr);
4512 access->tagged_access = extract_single_tagged_access(tagged, expr);
4513 access->access = isl_map_copy(access->tagged_access);
4514 access->access = isl_map_domain_factor_domain(access->access);
4516 *data->next_access = access;
4517 data->next_access = &(*data->next_access)->next;
4519 if (!access->access)
4520 return -1;
4522 return 0;
4525 /* Construct a linked list of gpu_stmt_access objects,
4526 * one for each access expression in the statement body.
4527 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4529 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4530 __isl_keep isl_union_map *any_to_outer)
4532 struct ppcg_extract_access_data data;
4534 stmt->accesses = NULL;
4535 data.next_access = &stmt->accesses;
4536 data.single_expression =
4537 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4538 data.any_to_outer = any_to_outer;
4539 return pet_tree_foreach_access_expr(stmt->stmt->body,
4540 &extract_access, &data);
4543 /* Return an array of gpu_stmt representing the statements in "scop".
4545 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4546 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4548 int i;
4549 struct gpu_stmt *stmts;
4551 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4552 if (!stmts)
4553 return NULL;
4555 for (i = 0; i < scop->pet->n_stmt; ++i) {
4556 struct gpu_stmt *s = &stmts[i];
4558 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4559 s->stmt = scop->pet->stmts[i];
4560 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4561 return free_stmts(stmts, i + 1);
4564 return stmts;
4567 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4569 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4571 struct gpu_gen *gen = user;
4573 return gen->print(p, gen->prog, gen->tree, &gen->types,
4574 gen->print_user);
4577 /* Generate CUDA code for "scop" and print it to "p".
4578 * After generating an AST for the transformed scop as explained below,
4579 * we call "gen->print" to print the AST in the desired output format
4580 * to "p".
4582 * If it turns out that it does not make sense to generate GPU code,
4583 * then we generate CPU code instead.
4585 * The GPU code is generated in a context where at least one
4586 * statement instance is executed. The corresponding guard (if any) is printed
4587 * around the entire generated GPU code, except for the declaration
4588 * of the arrays that are visible outside of the scop and that therefore
4589 * cannot be declared inside the body of any possible guard.
4591 * We first compute a schedule that respects the dependences
4592 * of the original program and select the outermost band
4593 * of tilable dimensions that has at least one parallel loop.
4594 * We then have three blocks of dimensions
4596 * H B G
4598 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4599 * in
4601 * H T P G
4603 * For each iteration of the T loop and for each array, we compute
4604 * the array elements accessed by that iteration, construct a rectangular
4605 * box around it and shift it to the origin. The result is used
4606 * as shared memory for the array.
4608 * We then split off at most 2 parallel loops from the T loops and
4609 * at most 3 parallel loops from the P loops
4611 * H T1 T2 P1 P2 G
4613 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4614 * according to "grid"/"block" sizes.
4616 * H T1T T1P T2 P1T P1P P2 G
4618 * Finally, the T1P and P1P iterators are equated to the block and
4619 * thread dimensions respectively and so are effectively removed.
4620 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4621 * are run on the GPU.
4623 * Code is generated in three stages. We first generate code for the
4624 * host (the H loops), with iterators h%d. Then, for each leaf node
4625 * of the resulting AST, we generate code for the shared loops (up to
4626 * and including T2), with iterators g%d and after equating the H loops
4627 * to h%d parameters and the T1P loops to the block dimensions.
4628 * Finally, we generate code for the remaining loops in a similar fashion.
4630 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4631 struct gpu_gen *gen, struct ppcg_scop *scop,
4632 struct ppcg_options *options)
4634 struct gpu_prog *prog;
4635 isl_ctx *ctx;
4636 isl_set *context, *guard;
4638 if (!scop)
4639 return isl_printer_free(p);
4641 ctx = isl_printer_get_ctx(p);
4642 prog = gpu_prog_alloc(ctx, scop);
4643 if (!prog)
4644 return isl_printer_free(p);
4646 context = isl_set_copy(prog->context);
4647 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
4648 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
4650 gen->prog = prog;
4651 gen->any_parallelism = 0;
4652 compute_schedule(gen);
4654 if (!gen->any_parallelism) {
4655 isl_set_free(context);
4656 isl_set_free(guard);
4657 p = print_cpu(p, scop, options);
4658 } else {
4659 compute_copy_in_and_out(gen);
4660 gen->tree = generate_host_code(gen);
4661 p = ppcg_print_exposed_declarations(p, prog->scop);
4662 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
4663 isl_ast_node_free(gen->tree);
4666 isl_union_map_free(gen->sched);
4667 isl_schedule_free(gen->host_schedule);
4669 gpu_prog_free(prog);
4671 return p;
4674 /* Wrapper around generate for use as a ppcg_transform callback.
4676 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
4677 struct ppcg_scop *scop, void *user)
4679 struct gpu_gen *gen = user;
4681 return generate(p, gen, scop, gen->options);
4684 /* Transform the code in the file called "input" by replacing
4685 * all scops by corresponding GPU code and write the results to "out".
4687 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4688 struct ppcg_options *options,
4689 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4690 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4691 struct gpu_types *types, void *user), void *user)
4693 struct gpu_gen gen;
4694 int r;
4695 int i;
4697 gen.ctx = ctx;
4698 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4699 gen.options = options;
4700 gen.kernel_id = 0;
4701 gen.print = print;
4702 gen.print_user = user;
4703 gen.types.n = 0;
4704 gen.types.name = NULL;
4706 if (options->debug->dump_sizes) {
4707 isl_space *space = isl_space_params_alloc(ctx, 0);
4708 gen.used_sizes = isl_union_map_empty(space);
4711 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
4713 if (options->debug->dump_sizes) {
4714 isl_union_map_dump(gen.used_sizes);
4715 isl_union_map_free(gen.used_sizes);
4718 isl_union_map_free(gen.sizes);
4719 for (i = 0; i < gen.types.n; ++i)
4720 free(gen.types.name[i]);
4721 free(gen.types.name);
4723 return r;
4726 /* Compute the set of inner array elements that may have their values
4727 * preserved by "prog". In particular, collect the array elements of
4728 * arrays that are not local to "prog" and remove those elements that
4729 * are definitely killed or definitely written by "prog".
4731 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
4733 int i;
4734 isl_union_set *may_persist, *killed;
4735 isl_union_map *must_kill;
4737 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
4738 for (i = 0; i < prog->n_array; ++i) {
4739 isl_set *extent;
4741 if (prog->array[i].local)
4742 continue;
4744 extent = isl_set_copy(prog->array[i].extent);
4745 may_persist = isl_union_set_add_set(may_persist, extent);
4748 may_persist = isl_union_set_intersect_params(may_persist,
4749 isl_set_copy(prog->context));
4750 may_persist = isl_union_set_apply(may_persist,
4751 isl_union_map_copy(prog->to_inner));
4752 must_kill = isl_union_map_copy(prog->tagged_must_kill);
4753 killed = isl_union_map_range(must_kill);
4754 must_kill = isl_union_map_copy(prog->must_write);
4755 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
4757 may_persist = isl_union_set_subtract(may_persist, killed);
4758 return may_persist;
4761 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4763 struct gpu_prog *prog;
4764 isl_space *space;
4765 isl_map *id;
4767 if (!scop)
4768 return NULL;
4770 prog = isl_calloc_type(ctx, struct gpu_prog);
4771 assert(prog);
4773 prog->ctx = ctx;
4774 prog->scop = scop;
4775 prog->context = isl_set_copy(scop->context);
4776 prog->n_stmts = scop->pet->n_stmt;
4777 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
4778 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
4779 space = isl_union_map_get_space(prog->any_to_outer);
4780 space = isl_space_set_from_params(space);
4781 space = isl_space_add_dims(space, isl_dim_set, 1);
4782 space = isl_space_map_from_set(space);
4783 id = isl_map_identity(space);
4784 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
4785 prog->stmts = extract_stmts(ctx, scop,
4786 prog->context, prog->any_to_outer);
4787 prog->read = isl_union_map_copy(scop->reads);
4788 prog->may_write = isl_union_map_copy(scop->may_writes);
4789 prog->must_write = isl_union_map_copy(scop->must_writes);
4790 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
4791 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
4792 prog->to_outer = isl_union_map_copy(prog->to_inner);
4793 prog->to_outer = isl_union_map_reverse(prog->to_outer);
4795 if (!prog->stmts)
4796 return gpu_prog_free(prog);
4798 if (collect_array_info(prog) < 0)
4799 return gpu_prog_free(prog);
4800 prog->may_persist = compute_may_persist(prog);
4802 return prog;
4805 void *gpu_prog_free(struct gpu_prog *prog)
4807 if (!prog)
4808 return NULL;
4809 free_array_info(prog);
4810 free_stmts(prog->stmts, prog->n_stmts);
4811 isl_union_map_free(prog->any_to_outer);
4812 isl_union_map_free(prog->to_outer);
4813 isl_union_map_free(prog->to_inner);
4814 isl_union_set_free(prog->copy_in);
4815 isl_union_set_free(prog->copy_out);
4816 isl_union_map_free(prog->read);
4817 isl_union_map_free(prog->may_write);
4818 isl_union_map_free(prog->must_write);
4819 isl_union_map_free(prog->tagged_must_kill);
4820 isl_union_map_free(prog->array_order);
4821 isl_union_set_free(prog->may_persist);
4822 isl_set_free(prog->context);
4823 free(prog);
4824 return NULL;