update isl for change in isl_map_gist
[ppcg.git] / gpu.c
blobd038f15cd6b2389f7ec3ba2342ad300aedd210bb
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 "gpu_tree.h"
32 #include "schedule.h"
33 #include "ppcg_options.h"
34 #include "print.h"
35 #include "util.h"
37 struct gpu_array_info;
39 /* Return the name of the outer array (of structs) accessed by "access".
41 static const char *get_outer_array_name(__isl_keep isl_map *access)
43 isl_space *space;
44 const char *name;
46 space = isl_space_range(isl_map_get_space(access));
47 while (space && isl_space_is_wrapping(space))
48 space = isl_space_domain(isl_space_unwrap(space));
49 name = isl_space_get_tuple_name(space, isl_dim_set);
50 isl_space_free(space);
52 return name;
55 /* Collect all references to the given array and store pointers to them
56 * in array->refs.
58 static void collect_references(struct gpu_prog *prog,
59 struct gpu_array_info *array)
61 int i;
62 int n;
64 n = 0;
65 for (i = 0; i < prog->n_stmts; ++i) {
66 struct gpu_stmt *stmt = &prog->stmts[i];
67 struct gpu_stmt_access *access;
69 for (access = stmt->accesses; access; access = access->next) {
70 const char *name;
71 name = get_outer_array_name(access->access);
72 if (name && !strcmp(array->name, name))
73 n++;
77 array->n_ref = n;
78 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
79 assert(array->refs);
81 n = 0;
82 for (i = 0; i < prog->n_stmts; ++i) {
83 struct gpu_stmt *stmt = &prog->stmts[i];
84 struct gpu_stmt_access *access;
86 for (access = stmt->accesses; access; access = access->next) {
87 const char *name;
88 name = get_outer_array_name(access->access);
89 if (!name || strcmp(array->name, name))
90 continue;
92 array->refs[n++] = access;
97 /* Compute and return the extent of "array", taking into account the set of
98 * accessed elements.
100 * In particular, the extent in the outer dimension is taken
101 * from "accessed", while the extents in the remaining dimensions
102 * are taken from array->extent.
104 * The extent in the outer dimension cannot be taken from array->extent
105 * because that may be unbounded. Furthermore, even if it is bounded,
106 * it may be larger than the piece of the array that is being accessed.
108 static __isl_give isl_set *compute_extent(struct pet_array *array,
109 __isl_keep isl_set *accessed)
111 int n_index;
112 isl_id *id;
113 isl_set *outer;
114 isl_set *extent;
116 extent = isl_set_copy(array->extent);
118 n_index = isl_set_dim(accessed, isl_dim_set);
119 if (n_index == 0)
120 return extent;
122 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
123 outer = isl_set_copy(accessed);
124 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
125 extent = isl_set_flat_product(outer, extent);
126 id = isl_set_get_tuple_id(accessed);
127 extent = isl_set_set_tuple_id(extent, id);
129 return extent;
132 /* Is the array "array" being extracted a read-only scalar?
134 * That is, is "array" a scalar that is never possibly written to.
135 * An array containing structures is never considered to be a scalar.
137 static int is_read_only_scalar(struct gpu_array_info *array,
138 struct gpu_prog *prog)
140 isl_set *space;
141 isl_union_map *write;
142 int empty;
144 if (array->has_compound_element)
145 return 0;
146 if (array->n_index != 0)
147 return 0;
149 write = isl_union_map_copy(prog->may_write);
150 space = isl_set_universe(isl_space_copy(array->space));
151 write = isl_union_map_intersect_range(write,
152 isl_union_set_from_set(space));
153 empty = isl_union_map_is_empty(write);
154 isl_union_map_free(write);
156 return empty;
159 /* Compute bounds on the host array "pa" based on the corresponding
160 * accessed elements in "arrays"
161 * and collect all references to the array.
162 * Store the results in "info".
164 * If the array is zero-dimensional and does not contain structures,
165 * i.e., if the array is a scalar, we check whether it is read-only.
166 * We also check whether the array is accessed at all.
168 static int extract_array_info(struct gpu_prog *prog,
169 struct gpu_array_info *info, struct pet_array *pa,
170 __isl_keep isl_union_set *arrays)
172 int i, empty;
173 const char *name;
174 int n_index;
175 isl_pw_aff **bounds;
176 isl_set *accessed, *extent;
178 n_index = isl_set_dim(pa->extent, isl_dim_set);
179 name = isl_set_get_tuple_name(pa->extent);
180 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index);
181 if (!bounds)
182 return -1;
184 info->space = isl_set_get_space(pa->extent);
185 info->name = strdup(name);
186 info->n_index = n_index;
187 info->bound = bounds;
188 info->linearize = prog->scop->options->linearize_device_arrays;
190 info->type = strdup(pa->element_type);
191 info->size = pa->element_size;
192 info->local = pa->declared && !pa->exposed;
193 info->has_compound_element = pa->element_is_record;
194 info->read_only_scalar = is_read_only_scalar(info, prog);
196 accessed = isl_union_set_extract_set(arrays,
197 isl_space_copy(info->space));
198 empty = isl_set_is_empty(accessed);
199 extent = compute_extent(pa, accessed);
200 isl_set_free(accessed);
201 info->extent = extent;
202 if (empty < 0)
203 return -1;
204 info->accessed = !empty;
205 for (i = 0; i < n_index; ++i) {
206 isl_set *dom;
207 isl_local_space *ls;
208 isl_aff *one;
209 isl_pw_aff *bound;
211 dom = isl_set_copy(extent);
212 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
213 n_index - (i + 1));
214 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
215 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
216 fprintf(stderr, "unable to determine extent of '%s' "
217 "in dimension %d\n", info->name, i);
218 dom = isl_set_free(dom);
220 bound = isl_set_dim_max(dom, 0);
221 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
222 ls = isl_local_space_from_space(isl_set_get_space(dom));
223 one = isl_aff_zero_on_domain(ls);
224 one = isl_aff_add_constant_si(one, 1);
225 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
226 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
228 bounds[i] = bound;
229 if (!isl_pw_aff_is_cst(bound))
230 info->linearize = 1;
233 collect_references(prog, info);
235 return 0;
238 /* Remove independence from the order constraints "order" on array "array".
239 * Since the pairs of iterations in the filter relation of an independence
240 * are guaranteed to be completely independent by the user, there is
241 * no need to ensure that live ranges are ordered along thong pairs.
242 * We make an exception for local variables, though, as the independence
243 * guarantee does not apply to those.
245 * The order constraints are used in two places.
246 * Those on scalars are used in check_scalar_live_ranges to check if
247 * we need to force the scalar to be private. Any non-local scalar
248 * should not be forced scalar if it only appears in independent loops.
249 * Those on non-scalars are added to the coincidence constraints
250 * in compute_schedule because we do not support any array expansion.
251 * Accesses to non-local arrays should not prevent a loop from being
252 * considered coincident so we should indeed remove those constraints
253 * from the order constraints.
255 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
256 struct gpu_array_info *array, __isl_take isl_union_map *order)
258 int i;
260 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
261 struct pet_independence *pi = prog->scop->pet->independences[i];
262 if (isl_union_set_contains(pi->local, array->space))
263 continue;
265 order = isl_union_map_subtract(order,
266 isl_union_map_copy(pi->filter));
269 return order;
272 /* For each array in "prog", store the (untagged) order dependences
273 * derived from the array in array->dep_order.
274 * In particular, consider all references that access the given array
275 * and take the order dependences that have one of these references
276 * as source. (Since an order dependence relates two references to
277 * the same array, the target of these order dependences will also
278 * be one of these references.)
279 * Additionally, store the union of these array->dep_order relations
280 * for all non-scalar arrays in prog->array_order.
282 void collect_order_dependences(struct gpu_prog *prog)
284 int i;
285 isl_space *space;
286 isl_union_map *accesses;
288 space = isl_union_map_get_space(prog->read);
289 prog->array_order = isl_union_map_empty(space);
291 accesses = isl_union_map_copy(prog->scop->tagged_reads);
292 accesses = isl_union_map_union(accesses,
293 isl_union_map_copy(prog->scop->tagged_may_writes));
294 accesses = isl_union_map_universe(accesses);
295 accesses = isl_union_map_apply_range(accesses,
296 isl_union_map_copy(prog->to_outer));
298 for (i = 0; i < prog->n_array; ++i) {
299 struct gpu_array_info *array = &prog->array[i];
300 isl_set *set;
301 isl_union_set *uset;
302 isl_union_map *order;
304 set = isl_set_universe(isl_space_copy(array->space));
305 uset = isl_union_set_from_set(set);
306 uset = isl_union_map_domain(
307 isl_union_map_intersect_range(isl_union_map_copy(accesses),
308 uset));
309 order = isl_union_map_copy(prog->scop->tagged_dep_order);
310 order = isl_union_map_intersect_domain(order, uset);
311 order = isl_union_map_zip(order);
312 order = isl_union_set_unwrap(isl_union_map_domain(order));
313 order = remove_independences(prog, array, order);
314 array->dep_order = order;
316 if (gpu_array_is_scalar(array) && !array->has_compound_element)
317 continue;
319 prog->array_order = isl_union_map_union(prog->array_order,
320 isl_union_map_copy(array->dep_order));
323 isl_union_map_free(accesses);
326 /* Construct a gpu_array_info for each array referenced by prog->scop and
327 * collect them in prog->array.
329 * The sizes are based on the extents and the set of possibly accessed
330 * elements by "prog".
331 * If there are any member accesses involved, then they are first mapped
332 * to the outer arrays of structs.
334 * If we are allowing live range reordering, then also set
335 * the dep_order field. Otherwise leave it NULL.
337 static int collect_array_info(struct gpu_prog *prog)
339 int i;
340 int r = 0;
341 isl_union_set *arrays;
343 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
344 arrays = isl_union_set_union(arrays,
345 isl_union_map_range(isl_union_map_copy(prog->may_write)));
347 arrays = isl_union_set_apply(arrays,
348 isl_union_map_copy(prog->to_outer));
350 arrays = isl_union_set_coalesce(arrays);
352 prog->n_array = prog->scop->pet->n_array;
353 prog->array = isl_calloc_array(prog->ctx,
354 struct gpu_array_info, prog->n_array);
355 assert(prog->array);
356 for (i = 0; i < prog->scop->pet->n_array; ++i)
357 if (extract_array_info(prog, &prog->array[i],
358 prog->scop->pet->arrays[i], arrays) < 0)
359 r = -1;
361 isl_union_set_free(arrays);
363 if (prog->scop->options->live_range_reordering)
364 collect_order_dependences(prog);
366 return r;
369 static void free_array_info(struct gpu_prog *prog)
371 int i, j;
373 for (i = 0; i < prog->n_array; ++i) {
374 int n_index = prog->array[i].n_index;
375 free(prog->array[i].type);
376 free(prog->array[i].name);
377 for (j = 0; j < n_index; ++j)
378 isl_pw_aff_free(prog->array[i].bound[j]);
379 isl_space_free(prog->array[i].space);
380 isl_set_free(prog->array[i].extent);
381 free(prog->array[i].bound);
382 free(prog->array[i].refs);
383 isl_union_map_free(prog->array[i].dep_order);
385 free(prog->array);
388 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
389 * as an array or through a pointer reference, but as a single data element.
390 * At the moment, scalars are represented as zero-dimensional arrays.
391 * Note that the single data element may be an entire structure.
393 int gpu_array_is_scalar(struct gpu_array_info *array)
395 return array->n_index == 0;
398 /* Is "array" a read-only scalar?
400 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
402 return array->read_only_scalar;
405 /* Does "array" need to be allocated on the device?
406 * If it is a read-only scalar, then it will be passed as an argument
407 * to the kernel and therefore does not require any allocation.
408 * If this device memory is not accessed at all, then it does not
409 * need to be allocated either.
411 int gpu_array_requires_device_allocation(struct gpu_array_info *array)
413 if (gpu_array_is_read_only_scalar(array))
414 return 0;
415 if (!array->global)
416 return 0;
417 return 1;
420 /* Return the set of parameter values for which the array has a positive
421 * size in all dimensions.
422 * If the sizes are only valid for some parameter values, then those
423 * constraints are also taken into account.
425 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
427 int i;
428 isl_space *space;
429 isl_set *guard;
431 if (!array)
432 return NULL;
434 space = isl_space_params(isl_space_copy(array->space));
435 guard = isl_set_universe(space);
437 for (i = 0; i < array->n_index; ++i) {
438 isl_pw_aff *bound;
439 isl_set *guard_i, *zero;
441 bound = isl_pw_aff_copy(array->bound[i]);
442 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
443 zero = isl_pw_aff_zero_set(bound);
444 guard_i = isl_set_subtract(guard_i, zero);
445 guard = isl_set_intersect(guard, guard_i);
448 return guard;
451 /* Internal data structure for extract_size_of_type.
452 * "type" specifies the name of the space that we want to extract.
453 * "res" is used to store the subset of that space.
455 struct ppcg_extract_size_data {
456 const char *type;
457 isl_set *res;
460 /* This function is called for each set in a union_set.
461 * If the name of the set matches data->type, we store the
462 * set in data->res.
464 static isl_stat extract_size_of_type(__isl_take isl_set *size, void *user)
466 struct ppcg_extract_size_data *data = user;
467 const char *name;
469 name = isl_set_get_tuple_name(size);
470 if (name && !strcmp(name, data->type)) {
471 data->res = size;
472 return isl_stat_error;
475 isl_set_free(size);
476 return isl_stat_ok;
479 /* Given a union map { kernel[i] -> *[...] },
480 * return the range in the space called "type" for the kernel with
481 * sequence number "id".
483 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
484 const char *type, int id)
486 isl_space *space;
487 isl_set *dom;
488 isl_union_set *local_sizes;
489 struct ppcg_extract_size_data data = { type, NULL };
491 if (!sizes)
492 return NULL;
494 space = isl_union_map_get_space(sizes);
495 space = isl_space_set_from_params(space);
496 space = isl_space_add_dims(space, isl_dim_set, 1);
497 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
498 dom = isl_set_universe(space);
499 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
501 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
502 isl_union_map_copy(sizes));
503 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
504 isl_union_set_free(local_sizes);
505 return data.res;
508 /* Given a singleton set, extract the first (at most *len) elements
509 * of the single integer tuple into *sizes and update *len if needed.
511 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
513 int i;
514 int dim;
516 if (!set)
517 return;
519 dim = isl_set_dim(set, isl_dim_set);
520 if (dim < *len)
521 *len = dim;
523 for (i = 0; i < *len; ++i) {
524 isl_val *v;
526 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
527 assert(v);
529 sizes[i] = isl_val_get_num_si(v);
530 isl_val_free(v);
533 isl_set_free(set);
536 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
537 * if the option debug->dump_sizes is set.
539 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
540 int *sizes, int len)
542 int i;
543 isl_space *space;
544 isl_map *map;
546 if (!gen->options->debug->dump_sizes)
547 return;
549 space = isl_union_map_get_space(gen->used_sizes);
550 space = isl_space_set_from_params(space);
551 space = isl_space_add_dims(space, isl_dim_set, 1);
552 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
553 space = isl_space_from_domain(space);
554 space = isl_space_add_dims(space, isl_dim_out, len);
555 space = isl_space_set_tuple_name(space, isl_dim_out, type);
557 map = isl_map_universe(space);
558 map = isl_map_fix_si(map, isl_dim_in, 0, id);
559 for (i = 0; i < len; ++i)
560 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
562 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
565 /* Extract user specified "tile" sizes from the "sizes" command line option,
566 * defaulting to option->tile_size in each dimension.
567 * *tile_len contains the maximum number of tile sizes needed.
568 * Update *tile_len to the number of specified tile sizes, if any, and
569 * return a pointer to the tile sizes (or NULL on error).
570 * Add the effectively used sizes to gen->used_sizes.
572 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
574 int n;
575 int *tile_size;
576 isl_set *size;
578 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
579 if (!tile_size)
580 return NULL;
581 for (n = 0; n < *tile_len; ++n)
582 tile_size[n] = gen->options->tile_size;
584 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
585 read_sizes_from_set(size, tile_size, tile_len);
586 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
588 return tile_size;
591 /* Extract user specified "block" sizes from the "sizes" command line option,
592 * after filling in some potentially useful defaults.
594 static void read_block_sizes(struct ppcg_kernel *kernel,
595 __isl_keep isl_union_map *sizes)
597 isl_set *size;
599 if (kernel->n_block > 3)
600 kernel->n_block = 3;
601 switch (kernel->n_block) {
602 case 1:
603 kernel->block_dim[0] = 512;
604 break;
605 case 2:
606 kernel->block_dim[0] = 32;
607 kernel->block_dim[1] = 16;
608 break;
609 default:
610 kernel->block_dim[0] = 32;
611 kernel->block_dim[1] = 4;
612 kernel->block_dim[2] = 4;
613 break;
616 size = extract_sizes(sizes, "block", kernel->id);
617 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
620 /* Extract user specified "grid" sizes from the "sizes" command line option,
621 * after filling in some potentially useful defaults.
623 static void read_grid_sizes(struct ppcg_kernel *kernel,
624 __isl_keep isl_union_map *sizes)
626 isl_set *size;
628 if (kernel->n_grid > 2)
629 kernel->n_grid = 2;
630 switch (kernel->n_grid) {
631 case 1:
632 kernel->grid_dim[0] = 32768;
633 break;
634 default:
635 kernel->grid_dim[0] = 256;
636 kernel->grid_dim[1] = 256;
637 break;
640 size = extract_sizes(sizes, "grid", kernel->id);
641 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
644 /* Extract user specified grid and block sizes from the gen->sizes
645 * command line option after filling in some potentially useful defaults.
646 * Store the extracted sizes in "kernel".
647 * Add the effectively used sizes to gen->used_sizes.
649 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
650 struct gpu_gen *gen)
652 read_block_sizes(kernel, gen->sizes);
653 read_grid_sizes(kernel, gen->sizes);
654 set_used_sizes(gen, "block", kernel->id,
655 kernel->block_dim, kernel->n_block);
656 set_used_sizes(gen, "grid", kernel->id,
657 kernel->grid_dim, kernel->n_grid);
660 static void *free_stmts(struct gpu_stmt *stmts, int n)
662 int i;
664 if (!stmts)
665 return NULL;
667 for (i = 0; i < n; ++i) {
668 struct gpu_stmt_access *access, *next;
670 for (access = stmts[i].accesses; access; access = next) {
671 next = access->next;
672 isl_id_free(access->ref_id);
673 isl_map_free(access->access);
674 isl_map_free(access->tagged_access);
675 free(access);
678 isl_id_free(stmts[i].id);
680 free(stmts);
682 return NULL;
685 /* Add parameters p[i] with identifiers "ids" to "set",
686 * with bounds to 0 <= p[i] < size[i].
688 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
689 int *size, __isl_keep isl_id_list *ids)
691 int i, len;
692 unsigned nparam;
694 len = isl_id_list_n_id(ids);
695 nparam = isl_set_dim(set, isl_dim_param);
696 set = isl_set_add_dims(set, isl_dim_param, len);
698 for (i = 0; i < len; ++i) {
699 isl_id *id;
701 id = isl_id_list_get_id(ids, i);
702 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
703 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
704 set = isl_set_upper_bound_si(set, isl_dim_param,
705 nparam + i, size[i] - 1);
708 return set;
711 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
712 * with
714 * { : 0 <= p[i] < size[i] }
716 * or an overapproximation.
718 static __isl_give isl_set *add_bounded_parameters_dynamic(
719 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
720 __isl_keep isl_id_list *ids)
722 int i, len;
723 unsigned nparam;
724 isl_space *space;
725 isl_local_space *ls;
727 len = isl_multi_pw_aff_dim(size, isl_dim_out);
728 nparam = isl_set_dim(set, isl_dim_param);
729 set = isl_set_add_dims(set, isl_dim_param, len);
731 for (i = 0; i < len; ++i) {
732 isl_id *id;
734 id = isl_id_list_get_id(ids, i);
735 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
738 space = isl_space_params(isl_set_get_space(set));
739 ls = isl_local_space_from_space(space);
740 for (i = 0; i < len; ++i) {
741 isl_pw_aff *param, *size_i, *zero;
742 isl_set *bound;
744 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
745 isl_dim_param, nparam + i);
747 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
748 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
749 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
750 set = isl_set_intersect_params(set, bound);
752 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
753 bound = isl_pw_aff_ge_set(param, zero);
754 set = isl_set_intersect_params(set, bound);
756 isl_local_space_free(ls);
758 return set;
761 /* Return the union of all tagged access relations in the group.
763 static __isl_give isl_union_map *group_tagged_access_relation(
764 struct gpu_array_ref_group *group)
766 int i;
767 isl_union_map *access;
769 access = isl_union_map_empty(isl_map_get_space(group->access));
770 for (i = 0; i < group->n_ref; ++i) {
771 isl_map *map_i;
773 map_i = isl_map_copy(group->refs[i]->tagged_access);
774 access = isl_union_map_union(access,
775 isl_union_map_from_map(map_i));
778 return access;
781 /* Return the extent of "array", recomputed from the bounds.
782 * The recomputed extent may be simpler than the original extent.
784 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
786 int i;
787 isl_id *id;
788 isl_space *space;
789 isl_local_space *ls;
790 isl_set *extent;
792 id = isl_set_get_tuple_id(array->extent);
793 space = isl_set_get_space(array->extent);
794 extent = isl_set_universe(isl_space_copy(space));
795 ls = isl_local_space_from_space(space);
796 for (i = 0; i < array->n_index; ++i) {
797 isl_pw_aff *bound;
798 isl_aff *aff;
799 isl_pw_aff *index;
800 isl_set *lt;
802 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
804 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
805 isl_dim_set, i);
806 index = isl_pw_aff_from_aff(aff);
807 bound = isl_pw_aff_copy(array->bound[i]);
808 bound = isl_pw_aff_from_range(bound);
809 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
810 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
811 isl_id_copy(id));
812 lt = isl_pw_aff_lt_set(index, bound);
813 extent = isl_set_intersect(extent, lt);
815 isl_local_space_free(ls);
816 isl_id_free(id);
818 return extent;
821 /* Return a map from the first group->depth dimensions of the computed
822 * schedule to the array tile in
823 * global memory that corresponds to the shared memory copy.
825 * In particular, return a map
827 * { D[i] -> A[a] }
829 * with constraints
831 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
833 * and
835 * 0 <= a <= array_size - 1 (2)
837 * Note that if some stride has been detected (i.e., when
838 * group->shared_tile->bound[i].shift is set), then a in (1) refers
839 * to the shifted and scaled down version.
841 * Constraints (1) are obtained by mapping the size constraints on the
842 * shared/private memory tile back to the access relation.
843 * Constraints (2) are obtained from the (recomputed) extent.
845 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
847 int i;
848 int n_index = group->array->n_index;
849 isl_map *tile;
850 isl_space *space;
851 isl_set *local;
852 isl_set *extent;
854 space = isl_multi_aff_get_space(group->shared_tile->tiling);
855 space = isl_space_range(space);
856 local = isl_set_universe(space);
857 for (i = 0; i < n_index; ++i) {
858 isl_val *bound;
860 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
861 bound = isl_val_copy(group->shared_tile->bound[i].size);
862 bound = isl_val_sub_ui(bound, 1);
863 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
865 local = isl_set_preimage_multi_aff(local,
866 isl_multi_aff_copy(group->shared_tile->tiling));
867 tile = isl_set_unwrap(local);
868 extent = array_extent(group->array);
869 tile = isl_map_intersect_range(tile, extent);
871 return tile;
874 /* Given a mapping "iterator_map" from the AST schedule to a domain,
875 * return the corresponding mapping from the AST schedule to
876 * to the outer kernel->shared_schedule_dim dimensions of
877 * the schedule computed by PPCG for this kernel.
879 * Note that kernel->shared_schedule_dim is at least as large as
880 * the largest depth of any array reference group associated to the kernel.
881 * This is needed as the returned schedule is used to extract a mapping
882 * to the outer group->depth dimensions in transform_index.
884 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
885 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
887 isl_union_pw_multi_aff *upma;
888 isl_pw_multi_aff *pma;
889 isl_space *space;
891 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
892 space = isl_space_from_domain(space);
893 space = isl_space_add_dims(space, isl_dim_out,
894 kernel->shared_schedule_dim);
896 upma = isl_union_pw_multi_aff_copy(kernel->shared_schedule);
897 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
898 isl_union_pw_multi_aff_free(upma);
900 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
903 /* If max_shared_memory is not set to infinity (-1), then make
904 * sure that the total amount of shared memory required by the
905 * array reference groups mapped to shared memory by "kernel"
906 * is no larger than this maximum.
908 * We apply a greedy approach and discard (keep in global memory)
909 * those groups that would result in a total memory size that
910 * is larger than the maximum.
912 * This function should be called after any function that may
913 * affect the decision on whether to place a reference group
914 * in private, shared or global memory.
916 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
918 int i, j;
919 isl_val *left, *size;
921 if (kernel->options->max_shared_memory < 0)
922 return;
924 left = isl_val_int_from_si(kernel->ctx,
925 kernel->options->max_shared_memory);
927 for (i = 0; i < kernel->n_array; ++i) {
928 struct gpu_local_array_info *local = &kernel->array[i];
930 for (j = 0; j < local->n_group; ++j) {
931 struct gpu_array_ref_group *group;
933 group = local->groups[j];
934 if (group->private_tile)
935 continue;
936 if (!group->shared_tile)
937 continue;
939 size = gpu_array_tile_size(group->shared_tile);
940 size = isl_val_mul_ui(size, local->array->size);
942 if (isl_val_le(size, left)) {
943 left = isl_val_sub(left, size);
944 continue;
946 isl_val_free(size);
948 group->shared_tile =
949 gpu_array_tile_free(group->shared_tile);
953 isl_val_free(left);
956 /* Mark all arrays of "kernel" that have an array reference group
957 * that is not mapped to private or shared memory as
958 * accessing the corresponding global device memory.
960 static void mark_global_arrays(struct ppcg_kernel *kernel)
962 int i, j;
964 for (i = 0; i < kernel->n_array; ++i) {
965 struct gpu_local_array_info *local = &kernel->array[i];
967 if (local->global)
968 continue;
969 for (j = 0; j < local->n_group; ++j) {
970 if (gpu_array_ref_group_tile(local->groups[j]))
971 continue;
973 local->global = 1;
974 local->array->global = 1;
975 break;
980 /* Compute a tiling for all the array reference groups in "kernel".
982 static void compute_group_tilings(struct ppcg_kernel *kernel)
984 int i, j;
986 for (i = 0; i < kernel->n_array; ++i) {
987 struct gpu_local_array_info *array = &kernel->array[i];
989 for (j = 0; j < array->n_group; ++j)
990 gpu_array_ref_group_compute_tiling(array->groups[j]);
994 /* Compute the size of a bounding box around the origin and "set",
995 * where "set" is assumed to contain only non-negative elements.
996 * In particular, compute the maximal value of "set" in each direction
997 * and add one.
999 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
1000 __isl_take isl_set *context)
1002 int i, n;
1003 isl_multi_pw_aff *mpa;
1005 context = isl_set_params(context);
1006 n = isl_set_dim(set, isl_dim_set);
1007 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
1008 for (i = 0; i < n; ++i) {
1009 isl_space *space;
1010 isl_aff *one;
1011 isl_pw_aff *bound;
1013 bound = isl_set_dim_max(isl_set_copy(set), i);
1014 bound = isl_pw_aff_coalesce(bound);
1015 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
1017 space = isl_pw_aff_get_domain_space(bound);
1018 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1019 one = isl_aff_add_constant_si(one, 1);
1020 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
1021 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
1023 isl_set_free(set);
1024 isl_set_free(context);
1026 return mpa;
1029 /* Compute the effective grid size as a list of the sizes in each dimension.
1031 * The grid size specified by the user or set by default
1032 * in read_grid_sizes() and applied by the block filter,
1033 * may be too large for the given code in the sense that
1034 * it may contain blocks that don't need to execute anything.
1035 * We therefore don't return this grid size, but instead the
1036 * smallest grid size that ensures that all blocks that actually
1037 * execute code are included in the grid.
1039 * We first extract a description of the grid, i.e., the possible values
1040 * of the block ids, from the domain elements in "domain" and
1041 * kernel->block_filter.
1042 * The block ids are parameters in kernel->block_filter.
1043 * We simply need to change them into set dimensions.
1045 * Then, for each block dimension, we compute the maximal value of the block id
1046 * and add one.
1048 static __isl_give isl_multi_pw_aff *extract_grid_size(
1049 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1051 int i;
1052 isl_set *grid;
1054 domain = isl_union_set_intersect(domain,
1055 isl_union_set_copy(kernel->block_filter));
1056 grid = isl_union_set_params(domain);
1057 grid = isl_set_from_params(grid);
1058 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1059 for (i = 0; i < kernel->n_grid; ++i) {
1060 int pos;
1061 isl_id *id;
1063 id = isl_id_list_get_id(kernel->block_ids, i);
1064 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1065 isl_id_free(id);
1066 assert(pos >= 0);
1067 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1068 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1071 return extract_size(grid, isl_set_copy(kernel->context));
1074 /* Compute the size of a fixed bounding box around the origin and "set",
1075 * where "set" is assumed to contain only non-negative elements,
1076 * and store the results in "size".
1077 * In particular, compute the maximal value of "set" in each direction
1078 * and add one.
1080 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1082 int i, n;
1083 isl_local_space *ls;
1084 isl_aff *obj;
1086 n = isl_set_dim(set, isl_dim_set);
1087 ls = isl_local_space_from_space(isl_set_get_space(set));
1088 obj = isl_aff_zero_on_domain(ls);
1089 for (i = 0; i < n; ++i) {
1090 isl_val *max;
1092 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1093 max = isl_set_max_val(set, obj);
1094 size[i] = isl_val_get_num_si(max) + 1;
1095 isl_val_free(max);
1096 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1098 isl_aff_free(obj);
1099 isl_set_free(set);
1102 /* Compute the effective block size as a list of the sizes in each dimension
1103 * and store the sizes in kernel->block_dim.
1105 * The block size specified by the user or set by default
1106 * in read_block_sizes() and applied by the thread filter,
1107 * may be too large for the given code in the sense that
1108 * it may contain threads that don't need to execute anything.
1109 * We therefore update this block size in kernel->block_dim
1110 * to the smallest block size that ensures that all threads
1111 * that actually execute code are included in the block.
1113 * The possible values of the thread ids is obtained from
1114 * the domain elements "domain" and kernel->thread_filter.
1115 * The current implementation eliminates all parameters, ensuring
1116 * that the size is a fixed constant in each dimension.
1117 * In principle we could also compute parametric sizes.
1118 * We would have to make sure to project out all b%d and t%d parameters,
1119 * however.
1121 static isl_stat extract_block_size(struct ppcg_kernel *kernel,
1122 __isl_take isl_union_set *domain)
1124 int i;
1125 int nparam;
1126 isl_set *block;
1128 domain = isl_union_set_intersect(domain,
1129 isl_union_set_copy(kernel->thread_filter));
1130 block = isl_union_set_params(domain);
1131 block = isl_set_from_params(block);
1132 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1133 for (i = 0; i < kernel->n_block; ++i) {
1134 int pos;
1135 isl_id *id;
1137 if (!block)
1138 return isl_stat_error;
1140 id = isl_id_list_get_id(kernel->thread_ids, i);
1141 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1142 isl_id_free(id);
1143 if (pos < 0)
1144 isl_die(isl_set_get_ctx(block), isl_error_internal,
1145 "missing constraints on thread identifier",
1146 block = isl_set_free(block));
1147 block = isl_set_equate(block, isl_dim_param, pos,
1148 isl_dim_set, i);
1150 nparam = isl_set_dim(block, isl_dim_param);
1151 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1153 if (!block)
1154 return isl_stat_error;
1156 extract_fixed_size(block, kernel->block_dim);
1158 return isl_stat_ok;
1161 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1163 int i, j;
1165 if (!kernel)
1166 return NULL;
1168 isl_id_list_free(kernel->block_ids);
1169 isl_id_list_free(kernel->thread_ids);
1170 isl_multi_pw_aff_free(kernel->grid_size);
1171 isl_set_free(kernel->context);
1172 isl_union_set_free(kernel->core);
1173 isl_union_set_free(kernel->arrays);
1174 isl_space_free(kernel->space);
1175 isl_ast_node_free(kernel->tree);
1176 isl_union_set_free(kernel->block_filter);
1177 isl_union_set_free(kernel->thread_filter);
1178 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1179 isl_union_set_free(kernel->sync_writes);
1181 for (i = 0; i < kernel->n_array; ++i) {
1182 struct gpu_local_array_info *array = &kernel->array[i];
1184 for (j = 0; j < array->n_group; ++j)
1185 gpu_array_ref_group_free(array->groups[j]);
1186 free(array->groups);
1188 isl_pw_aff_list_free(array->bound);
1190 free(kernel->array);
1192 for (i = 0; i < kernel->n_var; ++i) {
1193 free(kernel->var[i].name);
1194 isl_vec_free(kernel->var[i].size);
1196 free(kernel->var);
1198 free(kernel);
1200 return NULL;
1203 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1205 static void ppcg_kernel_free_wrap(void *user)
1207 struct ppcg_kernel *kernel = user;
1209 ppcg_kernel_free(kernel);
1212 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1213 struct ppcg_kernel_var *var)
1215 int j;
1216 struct gpu_array_tile *tile;
1217 isl_printer *p;
1218 char *name;
1220 var->array = group->array;
1222 tile = group->private_tile;
1223 var->type = ppcg_access_private;
1224 if (!tile) {
1225 tile = group->shared_tile;
1226 var->type = ppcg_access_shared;
1229 p = isl_printer_to_str(ctx);
1230 p = gpu_array_ref_group_print_name(group, p);
1231 var->name = isl_printer_get_str(p);
1232 isl_printer_free(p);
1234 var->size = isl_vec_alloc(ctx, group->array->n_index);
1236 for (j = 0; j < group->array->n_index; ++j)
1237 var->size = isl_vec_set_element_val(var->size, j,
1238 isl_val_copy(tile->bound[j].size));
1241 static int create_kernel_vars(struct ppcg_kernel *kernel)
1243 int i, j, n;
1245 n = 0;
1246 for (i = 0; i < kernel->n_array; ++i) {
1247 struct gpu_local_array_info *array = &kernel->array[i];
1249 for (j = 0; j < array->n_group; ++j) {
1250 struct gpu_array_ref_group *group = array->groups[j];
1251 if (group->private_tile || group->shared_tile)
1252 ++n;
1256 kernel->n_var = n;
1257 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1258 if (!kernel->var)
1259 return -1;
1261 n = 0;
1262 for (i = 0; i < kernel->n_array; ++i) {
1263 struct gpu_local_array_info *array = &kernel->array[i];
1265 for (j = 0; j < array->n_group; ++j) {
1266 struct gpu_array_ref_group *group = array->groups[j];
1267 if (!group->private_tile && !group->shared_tile)
1268 continue;
1269 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1270 ++n;
1274 return 0;
1277 /* Replace "pa" by the zero function defined over the universe domain
1278 * in the space of "pa".
1280 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1282 isl_space *space;
1283 isl_aff *zero;
1285 space = isl_space_domain(isl_pw_aff_get_space(pa));
1286 isl_pw_aff_free(pa);
1287 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1289 return isl_pw_aff_from_aff(zero);
1292 /* The sizes of the arrays on the host that have been computed by
1293 * extract_array_info may depend on the parameters. Use the extra
1294 * constraints on the parameters that are valid at "host_domain"
1295 * to simplify these expressions and store the results in kernel->array.
1297 * We only need these localized bounds for arrays that are accessed
1298 * by the current kernel. If we have found at least one reference group
1299 * then the array is accessed by the kernel.
1301 * The resulting sizes may be functions that are nowhere defined
1302 * in case the access function cannot possibly access anything inside
1303 * the kernel for some reason. If so, they are replaced by the zero
1304 * function. Since the access function cannot actually access anything,
1305 * there is no harm in printing the array sizes as zero.
1307 static void localize_bounds(struct ppcg_kernel *kernel,
1308 __isl_keep isl_set *host_domain)
1310 int i, j;
1311 isl_set *context;
1313 context = isl_set_copy(host_domain);
1314 context = isl_set_params(context);
1316 for (i = 0; i < kernel->n_array; ++i) {
1317 struct gpu_local_array_info *local = &kernel->array[i];
1318 isl_pw_aff_list *bound;
1319 int n_index;
1321 if (local->n_group == 0)
1322 continue;
1324 n_index = local->array->n_index;
1325 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1327 for (j = 0; j < n_index; ++j) {
1328 isl_pw_aff *pwaff;
1329 int empty;
1331 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1332 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1333 empty = isl_pw_aff_is_empty(pwaff);
1334 if (empty < 0)
1335 pwaff = isl_pw_aff_free(pwaff);
1336 else if (empty)
1337 pwaff = set_universally_zero(pwaff);
1338 bound = isl_pw_aff_list_add(bound, pwaff);
1341 local->n_index = n_index;
1342 local->bound = bound;
1344 isl_set_free(context);
1347 /* Create the array of gpu_local_array_info structures "array"
1348 * inside "kernel". The number of elements in this array is
1349 * the same as the number of arrays in "prog".
1350 * Initialize the "array" field of each local array to point
1351 * to the corresponding array in "prog".
1353 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1354 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1356 int i;
1357 isl_ctx *ctx;
1359 ctx = isl_set_get_ctx(prog->context);
1360 kernel->array = isl_calloc_array(ctx,
1361 struct gpu_local_array_info, prog->n_array);
1362 if (!kernel->array)
1363 return ppcg_kernel_free(kernel);
1364 kernel->n_array = prog->n_array;
1366 for (i = 0; i < prog->n_array; ++i)
1367 kernel->array[i].array = &prog->array[i];
1369 return kernel;
1372 /* Does "kernel" need to be passed an argument corresponding to array "i"?
1374 * The argument is only needed if the kernel accesses this device memory.
1376 int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1378 return kernel->array[i].global;
1381 /* Find the element in gen->stmt that has the given "id".
1382 * Return NULL if no such gpu_stmt can be found.
1384 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1386 int i;
1388 for (i = 0; i < prog->n_stmts; ++i) {
1389 if (id == prog->stmts[i].id)
1390 break;
1393 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1396 void ppcg_kernel_stmt_free(void *user)
1398 int i;
1399 struct ppcg_kernel_stmt *stmt = user;
1401 if (!stmt)
1402 return;
1404 switch (stmt->type) {
1405 case ppcg_kernel_copy:
1406 isl_ast_expr_free(stmt->u.c.index);
1407 isl_ast_expr_free(stmt->u.c.local_index);
1408 break;
1409 case ppcg_kernel_domain:
1410 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1411 break;
1412 case ppcg_kernel_sync:
1413 break;
1416 free(stmt);
1419 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1420 * to "ref_id".
1422 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1423 __isl_keep isl_id *ref_id)
1425 struct gpu_stmt_access *access;
1427 for (access = accesses; access; access = access->next)
1428 if (access->ref_id == ref_id)
1429 return access;
1431 return NULL;
1434 /* Return the index of the array called "name" in the list of arrays.
1436 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1438 int i;
1440 for (i = 0; i < kernel->n_array; ++i)
1441 if (!strcmp(name, kernel->array[i].array->name))
1442 return i;
1444 return -1;
1447 /* Internal data structure for the index and AST expression transformation
1448 * callbacks for pet_stmt_build_ast_exprs.
1450 * "kernel" is the kernel for which are computing AST expressions and
1451 * may be NULL if we are not inside a kernel.
1452 * "accesses" is the list of gpu_stmt_access in the statement.
1453 * "iterator_map" expresses the statement iterators in terms of
1454 * the AST loop iterators.
1455 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1456 * the kernel schedule in terms of the AST loop iterators and
1457 * may be NULL if we are not inside a kernel.
1459 * The following fields are set in transform_index and used in transform_expr.
1460 * "array" is the array that is being accessed.
1461 * "global" is set if the global array is accessed (rather than
1462 * shared/private memory).
1463 * "local_array" refers to information on the array specialized
1464 * to the current kernel.
1466 struct ppcg_transform_data {
1467 struct ppcg_kernel *kernel;
1468 struct gpu_stmt_access *accesses;
1469 isl_pw_multi_aff *iterator_map;
1470 isl_pw_multi_aff *sched2shared;
1472 struct gpu_array_info *array;
1473 int global;
1474 struct gpu_local_array_info *local_array;
1477 /* Return a pointer to the gpu_array_ref_group in "local"
1478 * that contains the reference "access".
1479 * Return NULL if no such group can be found.
1481 static struct gpu_array_ref_group *find_ref_group(
1482 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1484 int i, j;
1486 for (i = 0; i < local->n_group; ++i) {
1487 struct gpu_array_ref_group *group = local->groups[i];
1489 for (j = 0; j < group->n_ref; ++j)
1490 if (group->refs[j] == access)
1491 return group;
1494 return NULL;
1497 /* Index transformation callback for pet_stmt_build_ast_exprs.
1499 * "index" expresses the array indices in terms of statement iterators
1501 * We first reformulate "index" in terms of the AST loop iterators.
1502 * Then we check if we are accessing the global array or
1503 * a shared/private copy. In particular, if we are not inside a kernel
1504 * then we must be accessing a global array.
1505 * In the former case, we simply return
1506 * the updated index. If "index" is an affine expression rather
1507 * than an array access, then we also return the updated index here.
1509 * If no reference groups have been computed for the array,
1510 * then we can only be accessing the global array.
1512 * Otherwise, we apply the tiling to the index.
1513 * This tiling is of the form
1515 * [D -> A] -> T
1517 * where D corresponds to the outer group->depth dimensions of
1518 * the kernel schedule.
1519 * The index is of the form
1521 * L -> A
1523 * We update the tiling to refer to the AST loop iterators
1525 * [L -> A] -> T
1527 * and modify index to keep track of those iterators
1529 * L -> [L -> A]
1531 * Combining these two yields a tiled index expression in terms
1532 * of the AST loop iterators
1534 * L -> T
1536 static __isl_give isl_multi_pw_aff *transform_index(
1537 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1538 void *user)
1540 struct ppcg_transform_data *data = user;
1541 struct gpu_stmt_access *access;
1542 struct gpu_array_ref_group *group;
1543 struct gpu_array_tile *tile;
1544 isl_pw_multi_aff *iterator_map;
1545 int i;
1546 int dim;
1547 const char *name;
1548 isl_space *space;
1549 isl_multi_pw_aff *tiling;
1550 isl_pw_multi_aff *pma;
1551 isl_multi_pw_aff *mpa;
1552 isl_pw_multi_aff *sched2depth;
1554 data->array = NULL;
1556 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1557 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1559 if (!data->kernel)
1560 return index;
1562 access = find_access(data->accesses, ref_id);
1563 if (!access)
1564 return index;
1565 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1566 return index;
1568 name = get_outer_array_name(access->access);
1569 i = find_array_index(data->kernel, name);
1570 if (i < 0)
1571 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1572 "cannot find array",
1573 return isl_multi_pw_aff_free(index));
1574 data->local_array = &data->kernel->array[i];
1575 data->array = data->local_array->array;
1577 group = find_ref_group(data->local_array, access);
1578 if (!group) {
1579 data->global = 1;
1580 return index;
1583 tile = group->private_tile;
1584 if (!tile)
1585 tile = group->shared_tile;
1586 data->global = !tile;
1587 if (!tile)
1588 return index;
1590 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1591 space = isl_space_map_from_set(space);
1592 pma = isl_pw_multi_aff_identity(space);
1593 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1594 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1595 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1596 group->depth, dim - group->depth);
1597 pma = isl_pw_multi_aff_product(sched2depth, pma);
1598 tiling = isl_multi_pw_aff_from_multi_aff(
1599 isl_multi_aff_copy(tile->tiling));
1600 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1602 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1603 space = isl_space_map_from_set(space);
1604 mpa = isl_multi_pw_aff_identity(space);
1605 index = isl_multi_pw_aff_range_product(mpa, index);
1606 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1608 return index;
1611 /* Dereference "expr" by adding an index [0].
1612 * The original "expr" is assumed not to have any indices.
1614 * If "expr" is a member access, then the dereferencing needs
1615 * to be applied to the structure argument of this member access.
1617 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1619 isl_ctx *ctx;
1620 isl_ast_expr *arg0, *res;
1621 isl_ast_expr_list *list;
1623 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1624 if (!arg0)
1625 return isl_ast_expr_free(expr);
1626 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1627 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1628 isl_ast_expr *arg;
1630 arg = isl_ast_expr_get_op_arg(arg0, 0);
1631 arg = dereference(arg);
1632 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1633 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1635 return expr;
1637 isl_ast_expr_free(arg0);
1639 ctx = isl_ast_expr_get_ctx(expr);
1640 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1641 list = isl_ast_expr_list_from_ast_expr(res);
1642 res = isl_ast_expr_get_op_arg(expr, 0);
1643 res = isl_ast_expr_access(res, list);
1644 isl_ast_expr_free(expr);
1646 return res;
1649 /* Linearize the index expression "expr" based on the array bounds
1650 * of "array".
1652 * That is, transform expression
1654 * A[i_0][i_1]...[i_n]
1656 * to
1658 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1660 * where b_0, b_1, ..., b_n are the bounds on the array.
1662 * If the base of "expr" is a member access, then the linearization needs
1663 * to be applied to the structure argument of this member access.
1665 * In the base case, if "expr" has no arguments (other than the name of
1666 * the array), then we are passing an entire array to a function.
1667 * In this case, there is nothing to linearize.
1668 * Note that at this point an expression with no arguments can
1669 * only be an entire array because the scalar case and
1670 * the case of single struct are handled by the caller.
1672 * If the number of specified index expressions in "expr"
1673 * is smaller than the dimension of the accessed array,
1674 * then the missing i_j also do not appear in the linearized expression.
1675 * Furthermore, since such an expression does not refer to a single
1676 * element while the default linearized expression would refer to
1677 * a single element, we return the expression
1679 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1681 * instead. Note that because of the special case handling above,
1682 * we can assume here that here that there is at least one index expression.
1684 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1685 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1687 int i, n;
1688 isl_ctx *ctx;
1689 isl_set *context;
1690 isl_ast_expr *arg0;
1691 isl_ast_expr *res;
1692 isl_ast_expr_list *list;
1693 isl_ast_build *build;
1695 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1696 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1697 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1698 isl_ast_expr *arg;
1700 arg = isl_ast_expr_get_op_arg(arg0, 0);
1701 arg = gpu_local_array_info_linearize_index(array, arg);
1702 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1703 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1705 return expr;
1707 isl_ast_expr_free(arg0);
1709 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1710 return expr;
1712 ctx = isl_ast_expr_get_ctx(expr);
1713 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1714 build = isl_ast_build_from_context(context);
1716 n = isl_ast_expr_get_op_n_arg(expr);
1717 res = isl_ast_expr_get_op_arg(expr, 1);
1718 for (i = 1; i < array->n_index; ++i) {
1719 isl_pw_aff *bound_i;
1720 isl_ast_expr *expr_i;
1722 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1723 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1724 res = isl_ast_expr_mul(res, expr_i);
1726 if (i + 1 >= n)
1727 continue;
1728 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1729 res = isl_ast_expr_add(res, expr_i);
1732 isl_ast_build_free(build);
1734 if (1 + array->n_index > n) {
1735 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1736 } else {
1737 list = isl_ast_expr_list_from_ast_expr(res);
1738 res = isl_ast_expr_get_op_arg(expr, 0);
1739 res = isl_ast_expr_access(res, list);
1742 isl_ast_expr_free(expr);
1744 return res;
1747 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1749 * If the AST expression refers to an array that is not accessed
1750 * at all, then this means the value of the expression is not used,
1751 * so we might as well print zero (NULL pointer) instead.
1753 * If the AST expression refers to a global scalar that is not
1754 * a read-only scalar, then its address was passed to the kernel and
1755 * we need to dereference it.
1757 * If the AST expression refers to an access to a global array,
1758 * then we linearize the access exploiting the bounds in data->local_array.
1760 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1761 __isl_keep isl_id *id, void *user)
1763 struct ppcg_transform_data *data = user;
1765 if (!data->array)
1766 return expr;
1767 if (!data->array->accessed) {
1768 isl_ctx *ctx;
1770 ctx = isl_ast_expr_get_ctx(expr);
1771 isl_ast_expr_free(expr);
1772 return isl_ast_expr_from_val(isl_val_zero(ctx));
1774 if (gpu_array_is_read_only_scalar(data->array))
1775 return expr;
1776 if (!data->global)
1777 return expr;
1778 if (data->array->n_index == 0)
1779 return dereference(expr);
1780 if (!data->array->linearize)
1781 return expr;
1783 return gpu_local_array_info_linearize_index(data->local_array, expr);
1786 /* This function is called for each instance of a user statement
1787 * in the kernel "kernel", identified by "gpu_stmt".
1788 * "kernel" may be NULL if we are not inside a kernel.
1790 * We attach a struct ppcg_kernel_stmt to the "node", containing
1791 * a computed AST expression for each access, through an annotation
1792 * with name "user".
1793 * These AST expressions are computed from iterator_map,
1794 * which expresses the domain
1795 * elements in terms of the generated loops, and sched2shared,
1796 * which expresses the outer shared_schedule_dim dimensions of
1797 * the kernel schedule computed by PPCG in terms of the generated loops.
1799 static __isl_give isl_ast_node *create_domain_leaf(
1800 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1801 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1803 struct ppcg_transform_data data;
1804 struct ppcg_kernel_stmt *stmt;
1805 isl_ctx *ctx;
1806 isl_id *id;
1807 isl_pw_multi_aff *sched2shared;
1808 isl_map *map;
1809 isl_pw_multi_aff *iterator_map;
1810 isl_union_map *schedule;
1812 if (!node)
1813 return NULL;
1814 ctx = isl_ast_node_get_ctx(node);
1816 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1817 if (!stmt)
1818 return isl_ast_node_free(node);
1820 schedule = isl_ast_build_get_schedule(build);
1821 map = isl_map_reverse(isl_map_from_union_map(schedule));
1822 iterator_map = isl_pw_multi_aff_from_map(map);
1823 if (kernel)
1824 sched2shared = compute_sched_to_shared(kernel,
1825 isl_pw_multi_aff_copy(iterator_map));
1826 else
1827 sched2shared = NULL;
1829 stmt->type = ppcg_kernel_domain;
1830 stmt->u.d.stmt = gpu_stmt;
1832 data.kernel = kernel;
1833 data.accesses = stmt->u.d.stmt->accesses;
1834 data.iterator_map = iterator_map;
1835 data.sched2shared = sched2shared;
1836 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1837 build, &transform_index, &data,
1838 &transform_expr, &data);
1840 isl_pw_multi_aff_free(iterator_map);
1841 isl_pw_multi_aff_free(sched2shared);
1843 id = isl_id_alloc(ctx, "user", stmt);
1844 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1845 return isl_ast_node_set_annotation(node, id);
1848 /* This function is called for each statement node in the AST
1849 * for copying to or from shared/private memory.
1850 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1851 * statement to the node.
1852 * The statement name is "read" or "write", depending on whether we are
1853 * reading from global memory or writing to global memory.
1855 * The schedule is of the form
1857 * type[D -> A] -> L
1859 * where D corresponds to the outer group->depth dimensions of
1860 * the kernel schedule, A to the global array and L to the outer
1861 * generated AST schedule.
1862 * We compute the inverse and strip off the type, resulting in
1864 * L -> [D -> A]
1866 * We combine this mapping with on the one hand the projection
1868 * [D -> A] -> A
1870 * and on the other hand the group tiling
1872 * [D -> A] -> T
1874 * resulting in
1876 * L -> A and L -> T
1878 * and store the corresponding expressions in stmt->index and stmt->local_index,
1879 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1881 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1882 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1883 __isl_keep isl_ast_build *build)
1885 struct ppcg_kernel_stmt *stmt;
1886 struct gpu_array_tile *tile;
1887 isl_id *id;
1888 isl_ast_expr *expr;
1889 isl_space *space;
1890 isl_map *access;
1891 isl_pw_multi_aff *pma, *pma2;
1892 const char *type;
1894 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1895 if (!stmt)
1896 return isl_ast_node_free(node);
1898 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1899 type = isl_map_get_tuple_name(access, isl_dim_in);
1900 stmt->u.c.read = !strcmp(type, "read");
1901 access = isl_map_reverse(access);
1902 pma = isl_pw_multi_aff_from_map(access);
1903 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1905 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1906 space = isl_space_unwrap(space);
1907 pma2 = isl_pw_multi_aff_range_map(space);
1908 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1909 isl_pw_multi_aff_copy(pma));
1910 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1911 stmt->u.c.index = expr;
1913 tile = gpu_array_ref_group_tile(group);
1914 pma2 = isl_pw_multi_aff_from_multi_aff(
1915 isl_multi_aff_copy(tile->tiling));
1916 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1917 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1918 stmt->u.c.local_index = expr;
1920 stmt->u.c.array = group->array;
1921 stmt->u.c.local_array = group->local_array;
1922 stmt->type = ppcg_kernel_copy;
1924 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1925 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1926 return isl_ast_node_set_annotation(node, id);
1929 /* Create a synchronization ppcg_kernel_stmt and
1930 * attach it to the node "node" representing the synchronization.
1932 static __isl_give isl_ast_node *create_sync_leaf(
1933 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1934 __isl_keep isl_ast_build *build)
1936 struct ppcg_kernel_stmt *stmt;
1937 isl_id *id;
1939 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1940 if (!stmt)
1941 return isl_ast_node_free(node);
1943 stmt->type = ppcg_kernel_sync;
1944 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1945 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1946 return isl_ast_node_set_annotation(node, id);
1949 /* Internal data structure for at_domain.
1951 * "prog" represents the entire scop.
1952 * "kernel" points to the kernel to which the current schedule node
1953 * belongs. It is set by before_mark and reset by after_mark.
1954 * It may be NULL if we are outside any kernel.
1956 struct ppcg_at_domain_data {
1957 struct gpu_prog *prog;
1958 struct ppcg_kernel *kernel;
1961 /* This function is called for each instance of a user statement
1962 * in the kernel. This may be one of the original user statements
1963 * or a statement introduced by PPCG.
1965 * We first check if the statement id corresponds to a gpu statement,
1966 * which indicates the statement is an original user statement. Any statement
1967 * that is not an original user statement has been introduced by PPCG and
1968 * requires special handling.
1970 * If the user statement is one of the original user statements, then we call
1971 * create_domain_leaf. Otherwise, we check if it is a copy or synchronization
1972 * statement and call the appropriate functions. Statements that copy an array
1973 * to/from the device do not need any further treatment.
1975 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1976 __isl_keep isl_ast_build *build, void *user)
1978 struct ppcg_at_domain_data *data = user;
1979 struct gpu_stmt *gpu_stmt;
1980 isl_ast_expr *expr, *arg;
1981 isl_id *id;
1982 int is_sync;
1983 const char *name;
1984 void *p;
1986 expr = isl_ast_node_user_get_expr(node);
1987 arg = isl_ast_expr_get_op_arg(expr, 0);
1988 id = isl_ast_expr_get_id(arg);
1989 name = isl_id_get_name(id);
1990 p = isl_id_get_user(id);
1991 isl_ast_expr_free(expr);
1992 isl_ast_expr_free(arg);
1994 gpu_stmt = find_stmt(data->prog, id);
1995 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1996 isl_id_free(id);
1998 if (gpu_stmt)
1999 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
2001 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
2002 return node;
2003 if (is_sync < 0)
2004 return isl_ast_node_free(node);
2005 if (!strcmp(name, "read") || !strcmp(name, "write")) {
2006 struct gpu_array_ref_group *group = p;
2007 return create_access_leaf(data->kernel, group, node, build);
2009 if (!is_sync)
2010 isl_die(data->prog->ctx, isl_error_internal,
2011 "unknown statement type",
2012 return isl_ast_node_free(node));
2013 return create_sync_leaf(data->kernel, node, build);
2016 /* Given a set of wrapped references "ref", return the corresponding
2017 * access relations based on the tagged access relations "tagged".
2019 * The elements of "ref" are of the form
2021 * [D -> R]
2023 * with D an iteration domains and R a reference.
2024 * The elements of "tagged" are of the form
2026 * [D -> R] -> A
2028 * with A an array.
2030 * Extend "tagged" to include the iteration domain in the range, i.e.,
2032 * [D -> R] -> [D -> A]
2034 * apply the result to "ref" and then unwrap the resulting set
2035 * to obtain relations of the form
2037 * D -> A
2039 static __isl_give isl_union_map *wrapped_reference_to_access(
2040 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2042 isl_union_map *tag2access;
2044 tag2access = isl_union_map_copy(tagged);
2045 tag2access = isl_union_map_universe(tag2access);
2046 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2047 tag2access = isl_union_map_domain_map(tag2access);
2048 tag2access = isl_union_map_range_product(tag2access, tagged);
2050 ref = isl_union_set_coalesce(ref);
2051 ref = isl_union_set_apply(ref, tag2access);
2053 return isl_union_set_unwrap(ref);
2056 /* Given an access relation "access" from one or more array reference groups,
2057 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2058 * that are only needed to communicate data within
2059 * the same iteration of "sched".
2060 * "tagged" contains all tagged access relations to all
2061 * the array reference groups accessed by "access" from statement
2062 * instances scheduled by "sched".
2064 * If the access is a read then it is either an element of
2066 * live_in union (range flow)
2068 * where live_in and flow may be overapproximations, or
2069 * it reads an uninitialized value (that is not live-in because
2070 * there is an intermediate kill) or it reads a value that was
2071 * written within the same (compound) statement instance.
2072 * If the access is a write then it is either an element of
2074 * live_out union (domain flow)
2076 * or it writes a value that is never read (and is not live-out
2077 * because of an intermediate kill) or only
2078 * within the same (compound) statement instance.
2079 * In both cases, the access relation is also a subset of
2080 * the group access relation.
2082 * The cases where an uninitialized value is read or a value is written
2083 * that is never read or where the dataflow occurs within a statement
2084 * instance are also considered local and may also be removed.
2086 * Essentially, we compute the intersection of "access" with either
2088 * live_in union (range non-local-flow)
2090 * or
2092 * live_out union (domain non-local-flow)
2094 * We first construct a relation "local"
2096 * [[D -> R] -> [D' -> R']]
2098 * of pairs of domain iterations accessing the reference group
2099 * and references in the group that are coscheduled by "sched".
2101 * If this relation does not intersect the dataflow dependences,
2102 * then there is nothing we can possibly remove, unless the dataflow
2103 * dependences themselves only relate a subset of the accesses.
2104 * In particular, the accesses may not be involved in any dataflow
2105 * dependences, either because they are uninitialized reads/dead writes
2106 * or because the dataflow occurs inside a statement instance.
2108 * Since the computation below may break up the access relation
2109 * into smaller pieces, we only perform the intersection with
2110 * the non-local dependent accesses if the local pairs
2111 * intersect the dataflow dependences. Otherwise, we intersect
2112 * with the universe of the non-local dependent accesses.
2113 * This should at least remove accesses from statements that
2114 * do not participate in any dependences.
2116 * In particular, we remove the "local" dataflow dependences from
2117 * the set of all dataflow dependences, or at least those
2118 * that may contribute to a domain/range that intersects
2119 * the domain of "access".
2120 * Note that if the potential dataflow dependences are an overapproximation
2121 * of the actual dataflow dependences, then the result remains an
2122 * overapproximation of the non-local dataflow dependences.
2123 * Copying to/from global memory is only needed for the references
2124 * in the domain/range of the result or for accesses that are live out/in
2125 * for the entire scop.
2127 * We therefore map the domain/range of the "external" relation
2128 * to the corresponding access relation and take the union with
2129 * the live out/in relation.
2131 static __isl_give isl_union_map *remove_local_accesses(
2132 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2133 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2134 int read)
2136 int empty;
2137 isl_union_pw_multi_aff *tagger;
2138 isl_union_set *domain, *access_domain;
2139 isl_union_map *local, *external, *universe;
2140 isl_union_set *tag_set;
2142 if (isl_union_map_is_empty(access)) {
2143 isl_union_map_free(sched);
2144 isl_union_map_free(tagged);
2145 return access;
2148 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2149 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2150 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2151 isl_union_set_copy(domain));
2152 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2154 local = isl_union_map_apply_range(sched,
2155 isl_union_map_reverse(isl_union_map_copy(sched)));
2156 local = isl_union_map_intersect(local,
2157 isl_union_map_copy(prog->scop->tagged_dep_flow));
2159 empty = isl_union_map_is_empty(local);
2161 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2162 universe = isl_union_map_universe(isl_union_map_copy(access));
2163 access_domain = isl_union_map_domain(universe);
2164 domain = isl_union_set_universe(domain);
2165 universe = isl_union_set_unwrap(domain);
2166 universe = isl_union_map_intersect_domain(universe, access_domain);
2167 domain = isl_union_map_wrap(universe);
2168 if (read)
2169 external = isl_union_map_intersect_range(external, domain);
2170 else
2171 external = isl_union_map_intersect_domain(external, domain);
2172 external = isl_union_map_intersect_params(external,
2173 isl_set_copy(prog->scop->context));
2174 external = isl_union_map_subtract(external, local);
2176 if (read) {
2177 tag_set = isl_union_map_range(external);
2178 external = wrapped_reference_to_access(tag_set, tagged);
2179 external = isl_union_map_union(external,
2180 isl_union_map_copy(prog->scop->live_in));
2181 } else {
2182 tag_set = isl_union_map_domain(external);
2183 external = wrapped_reference_to_access(tag_set, tagged);
2184 external = isl_union_map_union(external,
2185 isl_union_map_copy(prog->scop->live_out));
2188 if (empty < 0)
2189 external = isl_union_map_free(external);
2190 else if (empty)
2191 external = isl_union_map_universe(external);
2193 access = isl_union_map_intersect(access, external);
2195 return access;
2198 /* Given an access relation "access" from "group", remove those reads
2199 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2200 * communicate data within the same iteration of the schedule at the
2201 * position where the copying of the group is inserted.
2202 * "node" points to this position, i.e., the depth at "node"
2203 * is equal to group->depth.
2205 * We extract a schedule that picks out the iterations of the outer
2206 * group->depth dimensions and call remove_local_accesses.
2208 static __isl_give isl_union_map *remove_local_accesses_group(
2209 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2210 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2211 int read)
2213 isl_union_map *sched, *tagged;
2215 if (isl_union_map_is_empty(access))
2216 return access;
2218 tagged = group_tagged_access_relation(group);
2219 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2221 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2224 /* This function is called before the AST generator starts traversing
2225 * the schedule subtree of a node with mark "mark".
2227 * If the mark is called "kernel", store the kernel pointer in data->kernel
2228 * for use in at_domain.
2230 static int before_mark(__isl_keep isl_id *mark,
2231 __isl_keep isl_ast_build *build, void *user)
2233 struct ppcg_at_domain_data *data = user;
2235 if (!mark)
2236 return -1;
2237 if (!strcmp(isl_id_get_name(mark), "kernel"))
2238 data->kernel = isl_id_get_user(mark);
2239 return 0;
2242 /* This function is called after the AST generator has finished traversing
2243 * the schedule subtree of a mark node. "node" points to the corresponding
2244 * mark AST node.
2246 * If the mark is called "kernel", then replace "node" by a user node
2247 * that "calls" the kernel, representing the launch of the kernel.
2248 * The original "node" is stored inside the kernel object so that
2249 * it can be used to print the device code.
2250 * Note that this assumes that a kernel is only launched once.
2251 * Also clear data->kernel.
2253 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2254 __isl_keep isl_ast_build *build, void *user)
2256 isl_ctx *ctx;
2257 isl_id *id;
2258 isl_ast_expr *expr;
2259 isl_ast_expr_list *list;
2260 struct ppcg_kernel *kernel;
2261 struct ppcg_at_domain_data *data = user;
2263 ctx = isl_ast_node_get_ctx(node);
2264 id = isl_ast_node_mark_get_id(node);
2265 if (!id)
2266 return isl_ast_node_free(node);
2267 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2268 isl_id_free(id);
2269 return node;
2271 kernel = data->kernel;
2272 data->kernel = NULL;
2273 kernel->space = isl_ast_build_get_schedule_space(build);
2274 kernel->tree = isl_ast_node_mark_get_node(node);
2275 isl_ast_node_free(node);
2277 expr = isl_ast_expr_from_id(isl_id_copy(id));
2278 list = isl_ast_expr_list_alloc(ctx, 0);
2279 expr = isl_ast_expr_call(expr, list);
2280 node = isl_ast_node_alloc_user(expr);
2281 node = isl_ast_node_set_annotation(node, id);
2283 return node;
2286 static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2288 int *depth = user;
2289 int node_depth;
2291 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2292 return isl_bool_true;
2293 node_depth = isl_schedule_node_get_schedule_depth(node);
2294 if (node_depth > *depth)
2295 *depth = node_depth;
2297 return isl_bool_false;
2300 /* Use isl to generate code for both the host and the device
2301 * from "schedule".
2302 * The device code is marked by "kernel" mark nodes in the schedule tree,
2303 * containing a pointer to a ppcg_kernel object.
2304 * The returned AST only contains the AST for the host code.
2305 * The ASTs for the device code are embedded in ppcg_kernel objects
2306 * attached to the leaf nodes that call "kernel".
2308 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2309 __isl_take isl_schedule *schedule)
2311 struct ppcg_at_domain_data data;
2312 isl_ast_build *build;
2313 isl_ast_node *tree;
2314 isl_id_list *iterators;
2315 int depth;
2317 data.prog = gen->prog;
2318 data.kernel = NULL;
2320 depth = 0;
2321 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2322 &depth) < 0)
2323 return NULL;
2324 build = isl_ast_build_alloc(gen->prog->ctx);
2325 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2326 build = isl_ast_build_set_iterators(build, iterators);
2327 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2328 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2329 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2330 if (gen->prog->scop->options->debug->dump_final_schedule)
2331 isl_schedule_dump(schedule);
2332 tree = isl_ast_build_node_from_schedule(build, schedule);
2333 isl_ast_build_free(build);
2335 return tree;
2338 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2340 if (!str)
2341 return NULL;
2342 return isl_union_map_read_from_str(ctx, str);
2345 /* Can "node" be tiled and then mapped to block and thread identifiers?
2346 * That is, is it permutable with at least one coincident dimension?
2348 static int is_permutable(__isl_keep isl_schedule_node *node)
2350 if (!node)
2351 return -1;
2353 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2354 return 0;
2355 if (!isl_schedule_node_band_get_permutable(node))
2356 return 0;
2357 if (isl_schedule_node_band_n_member(node) < 1)
2358 return 0;
2359 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2360 return 0;
2362 return 1;
2365 /* A isl_schedule_foreach_schedule_node_top_down callback
2366 * for setting *any_permutable and aborting the search
2367 * if "node" is a permutable band with coincident dimensions.
2368 * Otherwise, continue searching.
2370 static isl_bool set_permutable(__isl_keep isl_schedule_node *node, void *user)
2372 int *any_permutable = user;
2373 int permutable;
2375 permutable = is_permutable(node);
2376 if (permutable < 0)
2377 return isl_bool_error;
2378 if (!permutable)
2379 return isl_bool_true;
2381 *any_permutable = 1;
2383 return isl_bool_error;
2386 /* Does "schedule" contain any permutable band with at least one coincident
2387 * member?
2389 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2391 int any_permutable = 0;
2393 if (isl_schedule_foreach_schedule_node_top_down(schedule,
2394 &set_permutable, &any_permutable) < 0 &&
2395 !any_permutable)
2396 return -1;
2398 return any_permutable;
2401 /* Is "node" a leaf or can it be tiled and then mapped to
2402 * block and thread identifiers?
2404 static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2406 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2407 return 1;
2408 return is_permutable(node);
2411 /* Is "node" the outermost node in its branch that can be tiled
2412 * and then mapped to block and thread identifiers?
2413 * If there are no such nodes in the branch and if "node" is a leaf,
2414 * then it is accepted too.
2416 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2418 int tilable;
2419 isl_schedule_node *ancestor;
2421 tilable = is_leaf_or_tilable(node);
2422 if (tilable < 0)
2423 return -1;
2424 if (!tilable)
2425 return 0;
2427 tilable = 0;
2428 ancestor = isl_schedule_node_copy(node);
2429 while (isl_schedule_node_has_parent(ancestor)) {
2430 ancestor = isl_schedule_node_parent(ancestor);
2432 tilable = is_permutable(ancestor);
2433 if (tilable < 0 || tilable)
2434 break;
2437 isl_schedule_node_free(ancestor);
2438 return tilable < 0 ? -1 : !tilable;
2441 /* Collect the references to all writes in "group".
2442 * Each reference is represented by a universe set in a space
2444 * [S[i,j] -> R[]]
2446 * with S[i,j] the statement instance space and R[] the array reference.
2448 static __isl_give isl_union_set *group_tagged_writes(
2449 struct gpu_array_ref_group *group)
2451 int i;
2452 isl_space *space;
2453 isl_union_set *writes;
2455 space = isl_map_get_space(group->access);
2456 writes = isl_union_set_empty(space);
2457 for (i = 0; i < group->n_ref; ++i) {
2458 isl_space *space;
2459 isl_set *writes_i;
2461 if (!group->refs[i]->write)
2462 continue;
2464 space = isl_map_get_space(group->refs[i]->tagged_access);
2465 space = isl_space_domain(space);
2466 writes_i = isl_set_universe(space);
2467 writes = isl_union_set_add_set(writes, writes_i);
2470 return writes;
2473 /* Is there any write access in "group" that requires synchronization
2474 * on a write to global memory?
2475 * We currently take into account all writes that would require
2476 * synchronization at the thread level depth, but if the copying
2477 * for this group is performed at an outer level, then we do not
2478 * actually need to take into account dependences at intermediate levels.
2480 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2481 struct gpu_array_ref_group *group)
2483 isl_union_set *writes;
2484 int empty, disjoint;
2486 empty = isl_union_set_is_empty(kernel->sync_writes);
2487 if (empty < 0)
2488 return -1;
2489 if (empty)
2490 return 0;
2492 writes = group_tagged_writes(group);
2493 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2494 isl_union_set_free(writes);
2496 return disjoint < 0 ? -1 : !disjoint;
2499 /* Collect the references to all writes in "kernel" that write directly
2500 * to global or shared memory, i.e., that are not mapped to private memory.
2501 * Each reference is represented by a universe set in a space
2503 * [S[i,j] -> R[]]
2505 * with S[i,j] the statement instance space and R[] the array reference.
2507 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2508 struct ppcg_kernel *kernel)
2510 isl_union_set *writes;
2511 int i, j;
2513 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2515 for (i = 0; i < kernel->n_array; ++i) {
2516 struct gpu_local_array_info *array = &kernel->array[i];
2518 for (j = 0; j < array->n_group; ++j) {
2519 struct gpu_array_ref_group *group = array->groups[j];
2520 isl_union_set *writes_ij;
2522 if (!group->write)
2523 continue;
2524 if (group->private_tile)
2525 continue;
2526 writes_ij = group_tagged_writes(group);
2527 writes = isl_union_set_union(writes, writes_ij);
2531 return writes;
2534 /* Are there any direct writes to global memory that require
2535 * synchronization?
2537 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2539 isl_union_set *writes;
2540 int empty, disjoint;
2542 empty = isl_union_set_is_empty(kernel->sync_writes);
2543 if (empty < 0)
2544 return -1;
2545 if (empty)
2546 return 0;
2548 writes = collect_non_private_tagged_writes(kernel);
2549 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2550 isl_union_set_free(writes);
2552 return disjoint < 0 ? -1 : !disjoint;
2555 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2556 * from the elements in "tile_size".
2558 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2559 __isl_keep isl_schedule_node *node, int *tile_size)
2561 int i, n;
2562 isl_ctx *ctx;
2563 isl_space *space;
2564 isl_multi_val *mv;
2566 if (!node)
2567 return NULL;
2569 ctx = isl_schedule_node_get_ctx(node);
2570 space = isl_schedule_node_band_get_space(node);
2571 n = isl_schedule_node_band_n_member(node);
2572 mv = isl_multi_val_zero(space);
2573 for (i = 0; i < n; ++i) {
2574 isl_val *v;
2576 v = isl_val_int_from_si(ctx, tile_size[i]);
2577 mv = isl_multi_val_set_val(mv, i, v);
2580 return mv;
2583 /* Replace the partial schedule S of the band node "node" by
2585 * floor(S/f)
2587 * or
2589 * f * floor(S/f)
2591 * if scale_tile_loops is set, with f the integers in "factor".
2592 * The list that "factor" points to is assumed to contain at least
2593 * as many elements as the number of members in the band.
2595 static __isl_give isl_schedule_node *snap_band_to_sizes(
2596 __isl_take isl_schedule_node *node, int *factor,
2597 struct ppcg_options *options)
2599 isl_multi_val *mv;
2601 mv = construct_band_tiles_sizes(node, factor);
2602 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2603 if (options->scale_tile_loops)
2604 node = isl_schedule_node_band_scale(node,
2605 isl_multi_val_copy(mv));
2606 isl_multi_val_free(mv);
2608 return node;
2611 /* Tile "band" with tile size specified by "sizes".
2613 * Since the tile loops will be mapped to block ids, we forcibly
2614 * turn off tile loop scaling. We may want to enable tile loop scaling
2615 * at some later point, but then we would have to support the detection
2616 * of strides during the mapping to block ids.
2617 * Similarly, since the point loops will be mapped to thread ids,
2618 * we forcibly shift the point loops so that they start at zero.
2620 static __isl_give isl_schedule_node *tile_band(
2621 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2623 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2624 int scale_tile;
2625 int shift_point;
2627 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2628 isl_options_set_tile_scale_tile_loops(ctx, 0);
2629 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2630 isl_options_set_tile_shift_point_loops(ctx, 1);
2632 node = isl_schedule_node_band_tile(node, sizes);
2634 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2635 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2637 return node;
2640 /* Extract the set of parameter values and outer schedule dimensions
2641 * for which any statement instance
2642 * in the kernel inserted at "node" needs to be executed.
2643 * Intersect the set of parameter values derived from the host schedule
2644 * relation with the context of "prog".
2646 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2647 struct gpu_prog *prog)
2649 isl_union_map *schedule;
2650 isl_union_set *schedule_domain;
2651 isl_set *context;
2652 int empty;
2654 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2655 schedule_domain = isl_union_map_range(schedule);
2656 empty = isl_union_set_is_empty(schedule_domain);
2657 if (empty < 0) {
2658 isl_union_set_free(schedule_domain);
2659 return NULL;
2661 if (empty) {
2662 int depth;
2663 isl_space *space;
2665 space = isl_union_set_get_space(schedule_domain);
2666 isl_union_set_free(schedule_domain);
2667 space = isl_space_set_from_params(space);
2668 depth = isl_schedule_node_get_schedule_depth(node);
2669 space = isl_space_add_dims(space, isl_dim_set, depth);
2670 context = isl_set_empty(space);
2671 } else {
2672 context = isl_set_from_union_set(schedule_domain);
2674 context = isl_set_intersect_params(context,
2675 isl_set_copy(prog->context));
2677 return context;
2680 /* Return the set of outer array elements accessed by
2681 * by the statement instance in "domain" in "prog".
2683 static __isl_give isl_union_set *accessed_by_domain(
2684 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2686 isl_union_map *access;
2687 isl_union_set *arrays;
2689 access = isl_union_map_union(isl_union_map_copy(prog->read),
2690 isl_union_map_copy(prog->may_write));
2691 access = isl_union_map_intersect_domain(access, domain);
2692 arrays = isl_union_map_range(access);
2693 arrays = isl_union_set_apply(arrays,
2694 isl_union_map_copy(prog->to_outer));
2696 return arrays;
2699 /* Return the number of outer band members of the band node "node"
2700 * that are marked coincident.
2702 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2704 int i, n;
2706 n = isl_schedule_node_band_n_member(node);
2708 for (i = 0; i < n; ++i)
2709 if (!isl_schedule_node_band_member_get_coincident(node, i))
2710 break;
2712 return i;
2715 /* If the band node "node" has more than "n" members, then split off
2716 * the first "n" of them.
2718 static __isl_give isl_schedule_node *split_band(
2719 __isl_take isl_schedule_node *node, int n)
2721 int dim;
2723 dim = isl_schedule_node_band_n_member(node);
2724 if (n < dim)
2725 node = isl_schedule_node_band_split(node, n);
2727 return node;
2730 /* Scale a band node that may have been split by split_band.
2731 * "sizes" are the scaling factors for the original node.
2732 * "node" either points to the original band node, or the outer
2733 * of the two pieces after splitting.
2735 * If the number of elements in "node" is smaller than the number of
2736 * elements in "sizes", then some splitting has occurred and we split
2737 * "sizes" in the same way.
2739 static __isl_give isl_schedule_node *scale_band(
2740 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2742 int n, dim;
2744 n = isl_multi_val_dim(sizes, isl_dim_set);
2745 dim = isl_schedule_node_band_n_member(node);
2746 if (n > dim) {
2747 isl_multi_val *sizes2;
2749 sizes2 = isl_multi_val_copy(sizes);
2750 sizes = isl_multi_val_drop_dims(sizes,
2751 isl_dim_set, dim, n - dim);
2752 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2753 node = isl_schedule_node_child(node, 0);
2754 node = isl_schedule_node_band_scale(node, sizes2);
2755 node = isl_schedule_node_parent(node);
2758 return isl_schedule_node_band_scale(node, sizes);
2761 /* Return an isl_multi_aff, with as elements the parameters in "space"
2762 * that have the names specified by the elements in "names".
2763 * If (some of) these parameters do not already appear in "space",
2764 * then they are added first.
2766 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2767 __isl_keep isl_id_list *names)
2769 int i, n;
2770 isl_local_space *ls;
2771 isl_multi_aff *ma;
2773 if (!names)
2774 space = isl_space_free(space);
2776 n = isl_id_list_n_id(names);
2777 for (i = 0; i < n; ++i) {
2778 int pos;
2779 isl_id *id;
2781 id = isl_id_list_get_id(names, i);
2782 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2783 if (pos >= 0) {
2784 isl_id_free(id);
2785 continue;
2787 pos = isl_space_dim(space, isl_dim_param);
2788 space = isl_space_add_dims(space, isl_dim_param, 1);
2789 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2791 ma = isl_multi_aff_zero(isl_space_copy(space));
2792 ls = isl_local_space_from_space(isl_space_domain(space));
2793 for (i = 0; i < n; ++i) {
2794 int pos;
2795 isl_id *id;
2796 isl_aff *aff;
2798 id = isl_id_list_get_id(names, i);
2799 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2800 isl_id_free(id);
2801 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2802 isl_dim_param, pos);
2803 ma = isl_multi_aff_set_aff(ma, i, aff);
2805 isl_local_space_free(ls);
2807 return ma;
2810 /* Return constraints on the domain elements that equate a sequence of
2811 * parameters called "names", to the partial schedule
2812 * of "node" modulo the integers in "size".
2813 * The number of elements in the array "size" should be equal
2814 * to the number of elements in "names".
2815 * The number of members of the band node "node" should be smaller
2816 * than or equal to this number. If it is smaller, then the first
2817 * elements of "names" are equated to zero.
2819 static __isl_give isl_union_set *set_schedule_modulo(
2820 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2821 int *size)
2823 int n, n_zero;
2824 isl_space *space;
2825 isl_multi_aff *ma;
2826 isl_multi_union_pw_aff *mupa, *mupa2;
2827 isl_multi_val *mv;
2828 isl_union_set *domain;
2830 if (!node)
2831 return NULL;
2832 n = isl_id_list_n_id(names);
2833 if (n == 0)
2834 return isl_schedule_node_get_universe_domain(node);
2835 n_zero = n - isl_schedule_node_band_n_member(node);
2837 mupa = isl_schedule_node_band_get_partial_schedule(node);
2838 mv = construct_band_tiles_sizes(node, size + n_zero);
2839 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2841 space = isl_multi_union_pw_aff_get_space(mupa);
2842 space = isl_space_params(space);
2843 space = isl_space_set_from_params(space);
2844 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2845 ma = isl_multi_aff_zero(space);
2847 domain = isl_schedule_node_get_universe_domain(node);
2848 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2849 isl_union_set_copy(domain), ma);
2850 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2852 space = isl_multi_union_pw_aff_get_space(mupa);
2853 ma = parameter_vector(space, names);
2855 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2856 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2858 return isl_multi_union_pw_aff_zero_union_set(mupa);
2861 /* Insert a context node at "node" introducing the block and thread
2862 * identifiers along with their bounds, which are stored in kernel->grid_size
2863 * and kernel->block_dim.
2864 * Note that the bounds on the block identifiers may implicitly impose
2865 * constraints on the parameters. A guard needs to be inserted
2866 * in the schedule tree to ensure that those bounds hold at "node".
2867 * This guard is inserted in insert_guard.
2869 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2870 __isl_take isl_schedule_node *node)
2872 isl_set *context;
2874 context = isl_set_universe(isl_set_get_space(kernel->context));
2876 context = add_bounded_parameters_dynamic(context,
2877 kernel->grid_size, kernel->block_ids);
2878 context = add_bounded_parameters(context,
2879 kernel->block_dim, kernel->thread_ids);
2881 node = isl_schedule_node_insert_context(node, context);
2883 return node;
2886 /* Insert a guard that eliminates kernel launches where the kernel
2887 * obviously does not have any work to do.
2889 * In particular, eliminate kernel launches where there are obviously
2890 * zero blocks.
2891 * Use the same block size constraints that are used to create the context
2892 * to ensure that all constraints implicit in the constructed context
2893 * are imposed by the guard.
2895 * Additionally, add other constraints that are valid
2896 * for each executed instance ("context"), as long as this does not result
2897 * in a disjunction.
2899 static __isl_give isl_schedule_node *insert_guard(
2900 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2901 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2903 unsigned nparam, n;
2904 isl_set *guard;
2905 isl_id_list *ids;
2907 guard = isl_set_copy(context);
2908 guard = isl_set_compute_divs(guard);
2909 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2911 nparam = isl_set_dim(guard, isl_dim_param);
2912 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2913 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2914 guard = add_bounded_parameters_dynamic(guard, size, ids);
2915 isl_id_list_free(ids);
2916 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2918 node = isl_schedule_node_insert_guard(node, guard);
2920 return node;
2923 /* Does any array reference group mapping require the band that is mapped
2924 * to threads to be unrolled?
2926 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2928 int i, j;
2930 for (i = 0; i < kernel->n_array; ++i) {
2931 struct gpu_local_array_info *array = &kernel->array[i];
2933 for (j = 0; j < array->n_group; ++j) {
2934 struct gpu_array_ref_group *group = array->groups[j];
2935 if (gpu_array_ref_group_requires_unroll(group))
2936 return 1;
2940 return 0;
2943 /* Mark the given band node "node" for unrolling by the AST generator and
2944 * then sink it to the leaves of the schedule tree.
2945 * All dimensions of "node" are assumed to be coincident, such that this
2946 * sinking is a valid operation.
2948 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2950 int i, n;
2952 n = isl_schedule_node_band_n_member(node);
2953 for (i = 0; i < n; ++i)
2954 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2955 isl_ast_loop_unroll);
2957 node = isl_schedule_node_band_sink(node);
2959 return node;
2962 /* Insert a synchronization node in the schedule tree of "node"
2963 * after the core computation of "kernel" at the level of the band
2964 * that is mapped to threads, except if that level is equal to
2965 * that of the band that is mapped to blocks or if there are no writes
2966 * to global or shared memory in the core computation that require
2967 * synchronization.
2968 * If there are any writes to shared memory and the shared memory
2969 * copying is performed at the same level, then synchronization
2970 * is needed between the core and the copying anyway, so we might
2971 * as well add it here. If the copying is performed at a higher
2972 * level, then different iterations of intermediate schedule dimensions
2973 * may have a different mapping from between shared memory elements and
2974 * threads, such that synchronization is required after the core.
2975 * "node" is assumed to point to the kernel node.
2977 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2978 __isl_take isl_schedule_node *node)
2980 int kernel_depth;
2981 int need_sync;
2983 need_sync = any_global_or_shared_sync_writes(kernel);
2984 if (need_sync < 0)
2985 return isl_schedule_node_free(node);
2986 if (!need_sync)
2987 return node;
2989 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2991 node = gpu_tree_move_down_to_thread(node, kernel->core);
2992 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2993 return gpu_tree_move_up_to_kernel(node);
2995 node = gpu_tree_ensure_following_sync(node, kernel);
2997 node = gpu_tree_move_up_to_kernel(node);
2999 return node;
3002 /* Return a read ("read" is 1) or write access relation for "group"
3003 * with those accesses removed that are only needed to communicate data
3004 * within the subtree of the schedule rooted at "node".
3005 * Furthermore, include the prefix schedule at "node".
3006 * That is, return a relation of the form
3008 * S -> [D -> A]
3010 * with D the outer schedule dimensions at "node".
3012 static __isl_give isl_union_map *anchored_non_local_accesses(
3013 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3014 __isl_take isl_schedule_node *node, int read)
3016 isl_union_map *access;
3017 isl_union_map *prefix;
3019 access = gpu_array_ref_group_access_relation(group, read, !read);
3020 access = remove_local_accesses_group(kernel, group, access, node, read);
3021 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3022 access = isl_union_map_range_product(prefix, access);
3024 return access;
3027 /* Given an array reference group "group", create a mapping
3029 * read[D -> A] -> [D -> A]
3031 * if "read" is set or
3033 * write[D -> A] -> [D -> A]
3035 * if "read" is not set.
3036 * D corresponds to the outer group->depth dimensions of
3037 * the kernel schedule.
3039 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3040 struct gpu_array_ref_group *group, int read)
3042 isl_space *space;
3043 isl_id *id;
3045 space = isl_space_copy(group->array->space);
3046 space = isl_space_from_range(space);
3047 space = isl_space_add_dims(space, isl_dim_in, group->depth);
3048 space = isl_space_wrap(space);
3049 space = isl_space_map_from_set(space);
3051 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3052 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3054 return isl_multi_aff_identity(space);
3057 /* If any writes in "group" require synchronization, then make sure
3058 * that there is a synchronization node for "kernel" after the node
3059 * following "node" in a sequence.
3061 * If "shared" is set and no synchronization is needed for
3062 * the writes to global memory, then add synchronization before
3063 * the kernel to protect shared memory from being overwritten
3064 * by the next iteration of the core computation.
3065 * No additional synchronization is needed to protect against
3066 * the next copy into shared memory because each element of
3067 * the shared memory tile is always copied by the same thread.
3069 static __isl_give isl_schedule_node *add_group_write_sync(
3070 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3071 struct gpu_array_ref_group *group, int shared)
3073 int need_sync;
3075 need_sync = any_sync_writes_in_group(kernel, group);
3076 if (need_sync < 0)
3077 return isl_schedule_node_free(node);
3078 if (need_sync) {
3079 node = isl_schedule_node_parent(node);
3080 node = isl_schedule_node_next_sibling(node);
3081 node = isl_schedule_node_child(node, 0);
3082 node = gpu_tree_ensure_following_sync(node, kernel);
3083 } else if (shared) {
3084 node = isl_schedule_node_parent(node);
3085 node = isl_schedule_node_parent(node);
3086 node = gpu_tree_move_down_to_depth(node, group->depth,
3087 kernel->core);
3088 node = gpu_tree_move_left_to_sync(node, kernel);
3091 return node;
3094 /* Add copy statements to the schedule tree of "node"
3095 * for reading from global memory to private memory (if "read" is set) or
3096 * for writing back from private memory to global memory
3097 * (if "read" is not set) for the array reference group "group" that
3098 * is mapped to private memory.
3099 * On input, "node" points to the kernel node, and it is moved
3100 * back there on output.
3102 * The copies are performed in the order of the array elements.
3103 * The copy statement instances include a reference to the outer
3104 * group->depth dimensions of the kernel schedule for ease of
3105 * combining them with the group tiling.
3107 * That is, the extra schedule is of the form
3109 * type[D -> A] -> A
3111 * where D corresponds to the outer group->depth dimensions of
3112 * the kernel schedule and A to the global array.
3113 * This schedule is unrolled because registers are not addressable.
3115 * The copying is inserted in the schedule tree through an extension
3116 * of the form
3118 * D -> type[D -> A]
3120 * where the extra domain elements type[D -> A] are those accessed
3121 * by the group.
3122 * A filter is inserted on type[D -> A] to ensure that the element
3123 * is read/written by the same thread that needs the element.
3124 * This filter is obtained by applying
3126 * S -> type[D -> A]
3128 * to the thread filter for the core statements.
3130 * The extension is inserted before the core computation in case of a read
3131 * and after the core computation in case of a write.
3132 * In the latter case, we also make sure that there is a synchronization
3133 * node after the write to global memory, unless this write is performed
3134 * at the outer level of the kernel.
3135 * In principle, this synchronization could be inserted higher
3136 * in the schedule tree depending on where the corresponding reads
3137 * from global memory are performed.
3139 static __isl_give isl_schedule_node *add_copies_group_private(
3140 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3141 __isl_take isl_schedule_node *node, int read)
3143 isl_union_map *access;
3144 isl_union_map *prefix;
3145 isl_union_set *domain;
3146 isl_space *space;
3147 isl_multi_aff *from_access;
3148 isl_multi_pw_aff *mpa;
3149 isl_multi_union_pw_aff *mupa;
3150 isl_schedule_node *graft;
3151 isl_union_set *filter;
3152 int kernel_depth;
3153 int empty;
3155 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3156 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3158 access = anchored_non_local_accesses(kernel, group, node, read);
3159 empty = isl_union_map_is_empty(access);
3160 if (empty < 0 || empty) {
3161 isl_union_map_free(access);
3162 if (empty < 0)
3163 return isl_schedule_node_free(node);
3164 return gpu_tree_move_up_to_kernel(node);
3167 group->array->global = 1;
3168 group->local_array->global = 1;
3170 from_access = create_from_access(kernel->ctx, group, read);
3171 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3172 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3174 filter = isl_union_set_copy(kernel->thread_filter);
3175 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3176 filter = isl_union_set_detect_equalities(filter);
3177 filter = isl_union_set_coalesce(filter);
3179 domain = isl_union_map_range(access);
3180 access = isl_union_set_wrapped_domain_map(domain);
3181 access = isl_union_map_reverse(access);
3182 access = isl_union_map_coalesce(access);
3183 graft = isl_schedule_node_from_extension(access);
3185 space = isl_space_map_from_set(space);
3186 mpa = isl_multi_pw_aff_identity(space);
3187 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3188 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3190 graft = isl_schedule_node_child(graft, 0);
3191 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3192 graft = unroll(graft);
3194 graft = isl_schedule_node_insert_filter(graft, filter);
3196 graft = isl_schedule_node_parent(graft);
3198 if (read)
3199 node = isl_schedule_node_graft_before(node, graft);
3200 else {
3201 node = isl_schedule_node_graft_after(node, graft);
3202 if (kernel_depth < group->depth)
3203 node = add_group_write_sync(node, kernel, group, 0);
3206 node = gpu_tree_move_up_to_kernel(node);
3208 return node;
3211 /* Add copy statements to the schedule tree of "node"
3212 * for reading from global memory to shared memory (if "read" is set) or
3213 * for writing back from shared memory to global memory
3214 * (if "read" is not set) for the array reference group "group" that
3215 * is mapped to shared memory.
3216 * On input, "node" points to the kernel node, and it is moved
3217 * back there on output.
3219 * The copies are performed in the order of the corresponding shared
3220 * memory tile.
3221 * The copy statement instances include a reference to the outer
3222 * group->depth dimensions of the kernel schedule for ease of
3223 * combining them with the group tiling.
3225 * If we are performing a read from global memory to shared memory and
3226 * if the array involved is not a scalar, then we copy
3227 * the entire tile to shared memory. This may result in some extra
3228 * elements getting copied, but it should lead to simpler code
3229 * (which means that fewer registers may be needed) and less divergence.
3231 * Otherwise, we only copy the elements that will be read or have been written
3232 * in the kernel.
3234 * That is, the extra schedule is of the form
3236 * type[D -> A] -> T
3238 * where D corresponds to the outer group->depth dimensions of
3239 * the kernel schedule, A to the global array and T is the corresponding
3240 * shared memory tile.
3242 * The copying is inserted in the schedule tree through an extension
3243 * of the form
3245 * D -> type[D -> A]
3247 * where the extra domain elements type[D -> A] are those accessed
3248 * by the group. In the case of read from a non-scalar, this set
3249 * is replaced by the entire shared memory tile.
3251 * A filter is inserted on type[D -> A] to map the copy instances
3252 * to the threads. In particular, the thread identifiers are
3253 * equated to the position inside the shared memory tile (T)
3254 * modulo the block size.
3255 * We try to align the innermost tile dimension with the innermost
3256 * thread identifier (x) as a heuristic to improve coalescing.
3257 * In particular, if the dimension of the tile is greater than
3258 * the dimension of the block, then the schedule mapping to the tile
3259 * is broken up into two pieces and the filter is applied to the inner part.
3260 * If, on the other hand, the dimension of the tile is smaller than
3261 * the dimension of the block, then the initial thread identifiers
3262 * are equated to zero and the remaining thread identifiers are
3263 * matched to the memory tile.
3265 * The extension is inserted before the core computation in case of a read
3266 * and after the core computation in case of a write.
3267 * In the case of a read, we first need to make sure there is some
3268 * synchronization before the core computation such that we can put the read
3269 * from global memory to shared memory before that synchronization.
3270 * This ensures that all threads have finished copying into shared memory
3271 * before the shared memory is used.
3272 * We also need to make sure that there is a synchronization node after
3273 * the core computation to ensure that the next load into shared memory
3274 * only happens after all data has been used. There is no need for
3275 * this synchronization if we are at the outer level since then there
3276 * won't be a next load.
3277 * In the case of a write, we need to make sure there is some synchronization
3278 * after the core computation such taht we can put the write from shared
3279 * memory to global memory after that synchronization.
3280 * Unless we are at the outer level, we also need a synchronization node
3281 * after the write to ensure the data is saved to global memory
3282 * before the next iteration write to the same shared memory.
3283 * It also makes sure the data has arrived in global memory before
3284 * it is read in a subsequent iteration.
3286 static __isl_give isl_schedule_node *add_copies_group_shared(
3287 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3288 __isl_take isl_schedule_node *node, int read)
3290 struct gpu_array_tile *tile;
3291 isl_union_map *access;
3292 isl_union_set *domain;
3293 isl_union_set *sync;
3294 isl_multi_aff *ma;
3295 isl_multi_aff *from_access;
3296 isl_multi_pw_aff *mpa;
3297 isl_multi_union_pw_aff *mupa;
3298 isl_schedule_node *graft;
3299 isl_union_set *filter;
3300 int skip;
3301 int kernel_depth;
3302 int empty;
3304 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3305 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3307 access = anchored_non_local_accesses(kernel, group, node, read);
3308 empty = isl_union_map_is_empty(access);
3309 if (empty < 0 || empty) {
3310 isl_union_map_free(access);
3311 if (empty < 0)
3312 return isl_schedule_node_free(node);
3313 return gpu_tree_move_up_to_kernel(node);
3316 group->array->global = 1;
3317 group->local_array->global = 1;
3319 from_access = create_from_access(kernel->ctx, group, read);
3321 tile = gpu_array_ref_group_tile(group);
3322 ma = isl_multi_aff_copy(tile->tiling);
3323 ma = isl_multi_aff_pullback_multi_aff(ma,
3324 isl_multi_aff_copy(from_access));
3325 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3326 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3328 domain = isl_union_map_range(access);
3330 if (read && !gpu_array_is_scalar(group->array)) {
3331 isl_map *map;
3332 isl_union_set_free(domain);
3333 map = group_tile(group);
3334 domain = isl_union_set_from_set(isl_map_wrap(map));
3337 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3338 access = isl_union_set_wrapped_domain_map(domain);
3339 access = isl_union_map_reverse(access);
3340 access = isl_union_map_coalesce(access);
3341 graft = isl_schedule_node_from_extension(access);
3343 graft = isl_schedule_node_child(graft, 0);
3345 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3347 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3348 graft = isl_schedule_node_band_split(graft,
3349 tile->n - kernel->n_block);
3350 graft = isl_schedule_node_child(graft, 0);
3352 if (tile->n < kernel->n_block)
3353 skip = kernel->n_block - tile->n;
3354 else
3355 skip = 0;
3356 filter = set_schedule_modulo(graft, kernel->thread_ids,
3357 kernel->block_dim);
3358 if (!kernel->options->wrap)
3359 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3360 kernel->options);
3361 if (tile->n > kernel->n_block && kernel->n_block > 0)
3362 graft = isl_schedule_node_parent(graft);
3363 graft = isl_schedule_node_insert_filter(graft, filter);
3365 while (graft && isl_schedule_node_has_parent(graft))
3366 graft = isl_schedule_node_parent(graft);
3368 if (read) {
3369 if (kernel_depth < group->depth)
3370 node = gpu_tree_ensure_sync_after_core(node, kernel);
3371 node = gpu_tree_move_left_to_sync(node, kernel);
3372 node = isl_schedule_node_graft_before(node, graft);
3373 } else {
3374 node = gpu_tree_move_right_to_sync(node, kernel);
3375 node = isl_schedule_node_graft_after(node, graft);
3376 if (kernel_depth < group->depth)
3377 node = add_group_write_sync(node, kernel, group, 1);
3380 node = gpu_tree_move_up_to_kernel(node);
3382 return node;
3385 /* Check whether the array reference group "group" is mapped to
3386 * private or shared memory and, if so,
3387 * add copy statements to the schedule tree of "node"
3388 * for reading from global memory to private or shared memory
3389 * (if "read" is set) or for writing back from private or shared memory
3390 * to global memory (if "read" is not set) for this group.
3391 * On input, "node" points to the kernel node, and it is moved
3392 * back there on output.
3394 static __isl_give isl_schedule_node *add_copies_group(
3395 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3396 __isl_take isl_schedule_node *node, int read)
3398 if (group->private_tile)
3399 return add_copies_group_private(kernel, group, node, read);
3400 if (group->shared_tile)
3401 return add_copies_group_shared(kernel, group, node, read);
3402 return node;
3405 /* For each array reference group that is mapped to private or shared memory,
3406 * add copy statements to the schedule tree of "node"
3407 * for reading from global memory to private or shared memory
3408 * and for writing back.
3409 * On input, "node" points to the kernel node, and it is moved
3410 * back there on output.
3412 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3413 __isl_take isl_schedule_node *node)
3415 int i, j;
3417 for (i = 0; i < kernel->n_array; ++i) {
3418 struct gpu_local_array_info *array = &kernel->array[i];
3420 for (j = 0; j < array->n_group; ++j) {
3421 struct gpu_array_ref_group *group = array->groups[j];
3423 node = add_copies_group(kernel, group, node, 1);
3424 if (!node)
3425 return NULL;
3426 node = add_copies_group(kernel, group, node, 0);
3427 if (!node)
3428 return NULL;
3432 return node;
3435 /* Mark all dimensions in the current band node atomic.
3437 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3439 int i, n;
3441 n = isl_schedule_node_band_n_member(node);
3442 for (i = 0; i < n; ++i)
3443 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3444 isl_ast_loop_atomic);
3446 return node;
3449 /* Mark "node" atomic, if it is a band node.
3450 * Do the same for all ancestors.
3451 * Return a pointer to "node" (in the updated schedule tree).
3453 static __isl_give isl_schedule_node *atomic_ancestors(
3454 __isl_take isl_schedule_node *node)
3456 int pos;
3458 if (!node)
3459 return NULL;
3460 if (!isl_schedule_node_has_parent(node))
3461 return node;
3463 pos = isl_schedule_node_get_child_position(node);
3464 node = isl_schedule_node_parent(node);
3465 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3466 node = atomic(node);
3467 node = atomic_ancestors(node);
3468 node = isl_schedule_node_child(node, pos);
3470 return node;
3473 /* Collect all write references that require synchronization.
3474 * "node" is assumed to point to the kernel node.
3475 * Each reference is represented by a universe set in a space
3477 * [S[i,j] -> R[]]
3479 * with S[i,j] the statement instance space and R[] the array reference.
3481 * This function should be called before block and thread filters are added.
3483 * Synchronization is needed after a write if there is a subsequent read
3484 * within the same block that may not be performed by the same thread.
3485 * There should not be any dependences between different blocks,
3486 * so we start with the flow dependences within the same kernel invocation
3487 * and we subtract from these those dependences that are mapped
3488 * to the same iteration of the bands where synchronization is inserted.
3489 * We do not remove pairs of instances that are known to map to
3490 * the same thread across different iterations of the intermediate
3491 * bands because the read may be performed by a different thread
3492 * than the one that needs the value if shared memory is involved.
3494 * We also consider all pairs of possible writes that access the same
3495 * memory location and that may be mapped to the same block but not
3496 * to the same iteration of the intermediate bands.
3497 * In theory, it would be possible for one thread to still be in
3498 * a previous iteration of a loop in these bands.
3499 * A write to global memory in this delayed thread could then overwrite
3500 * a write from another thread that has already moved on to
3501 * the next iteration.
3503 * After computing the above writes paired off with reads or writes
3504 * that depend on them, we project onto the domain writes.
3505 * Sychronization is needed after writes to global memory
3506 * through these references.
3508 static __isl_give isl_union_set *compute_sync_writes(
3509 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3511 isl_union_map *local;
3512 isl_union_map *may_writes, *shared_access;
3513 isl_union_map *kernel_prefix, *thread_prefix;
3514 isl_union_map *equal;
3515 isl_union_set *wrap;
3516 isl_union_set *domain;
3518 domain = isl_schedule_node_get_universe_domain(node);
3519 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3520 node = isl_schedule_node_copy(node);
3521 node = gpu_tree_move_down_to_thread(node, kernel->core);
3522 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3523 isl_schedule_node_free(node);
3525 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3526 may_writes = isl_union_map_curry(may_writes);
3527 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3528 may_writes = isl_union_map_uncurry(may_writes);
3529 shared_access = isl_union_map_copy(may_writes);
3530 shared_access = isl_union_map_apply_range(shared_access,
3531 isl_union_map_reverse(may_writes));
3533 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3534 local = isl_union_map_union(local, shared_access);
3535 local = isl_union_map_zip(local);
3537 equal = isl_union_map_apply_range(kernel_prefix,
3538 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3539 wrap = isl_union_map_wrap(equal);
3540 local = isl_union_map_intersect_domain(local, wrap);
3541 equal = isl_union_map_apply_range(thread_prefix,
3542 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3543 wrap = isl_union_map_wrap(equal);
3544 local = isl_union_map_subtract_domain(local, wrap);
3546 local = isl_union_map_zip(local);
3547 local = isl_union_map_universe(local);
3549 return isl_union_map_domain(local);
3552 /* Group the domain elements into a single space, named kernelX,
3553 * with X the kernel sequence number "kernel_id".
3555 static __isl_give isl_schedule_node *group_statements(
3556 __isl_take isl_schedule_node *node, int kernel_id)
3558 char buffer[20];
3559 isl_id *id;
3561 if (!node)
3562 return NULL;
3564 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3565 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3566 return isl_schedule_node_group(node, id);
3569 /* Create a ppcg_kernel representing the domain instances that reach "node"
3570 * and insert a mark node pointing to the ppcg_kernel before "node".
3571 * The band that "node" points to is the band that needs to be mapped
3572 * to block identifiers. The band that needs to be mapped to thread
3573 * identifiers should be marked by a "thread" mark by the caller.
3574 * This mark is removed by this function.
3575 * If "scale" is set, then the band that "node" points to is scaled
3576 * by "sizes".
3578 * Mark all outer band nodes as atomic to ensure each kernel is only
3579 * scheduled once.
3580 * If the domain elements that reach "node" live in more than one space,
3581 * then group the domain elements into a single space, named kernelX,
3582 * with X the kernel sequence number.
3584 * Insert a guard node governing the kernel node to ensure that
3585 * no kernels with zero blocks are launched.
3587 * Insert a context node describing the block and thread
3588 * identifiers inside the kernel mark.
3589 * The context node needs to be inserted after the effective block size
3590 * has been determined such that the bounds on the thread identifiers
3591 * would reflect the effective block size.
3592 * Insert a filter node inside the context node mapping the statement
3593 * instances to block identifiers. In particular, the block identifiers
3594 * are equated to the partial schedule of band that was marked for mapping
3595 * to blocks modulo the grid size.
3596 * Insert a filter node inside the "thread" mark mapping the statement
3597 * instances to thread identifiers. In particular, the thread identifiers
3598 * are equated to the partial schedule of band that was marked for mapping
3599 * to threads modulo the block size.
3601 * Compute array reference groups for all arrays, set the local
3602 * array bounds based on the set of domain instances that reach
3603 * the kernel node, check the total amount of shared memory used
3604 * and compute all group tilings.
3605 * The array reference groups are computed after the block filter
3606 * has been inserted because it affects the mapping to shared or
3607 * private memory. This computation also requires the thread filter
3608 * (in the ppcg_kernel object), but this thread filter should not
3609 * have been added to the schedule tree yet since the computation
3610 * requires the schedule of the band that needs to be mapped to
3611 * threads before the privatization is applied.
3613 * If any array reference group requires the band mapped to threads
3614 * to be unrolled, then we perform the required unrolling.
3616 * We save a copy of the schedule that may influence the mappings
3617 * to shared or private memory in kernel->shared_schedule.
3619 * Finally, we add synchronization and copy statements to the schedule tree,
3620 * remove the "thread" mark and create representations for the local
3621 * variables in the kernel.
3623 * We keep a copy of the isl_id that points to the kernel to ensure
3624 * that the kernel does not get destroyed if the schedule node
3625 * is freed due to some error condition.
3627 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3628 __isl_take isl_schedule_node *node, int scale,
3629 __isl_keep isl_multi_val *sizes)
3631 struct ppcg_kernel *kernel;
3632 isl_id *id;
3633 isl_schedule_node *node_thread;
3634 isl_union_map *host_schedule;
3635 isl_set *host_domain;
3636 isl_union_set *domain;
3637 int single_statement;
3639 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3640 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3641 if (!kernel)
3642 return isl_schedule_node_free(node);
3644 domain = isl_schedule_node_get_domain(node);
3645 single_statement = isl_union_set_n_set(domain) == 1;
3647 kernel->ctx = gen->ctx;
3648 kernel->prog = gen->prog;
3649 kernel->options = gen->options;
3650 kernel->context = extract_context(node, gen->prog);
3651 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3652 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3653 gen->prog);
3654 kernel->n_grid = n_outer_coincidence(node);
3655 node_thread = isl_schedule_node_copy(node);
3656 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3657 node_thread = isl_schedule_node_child(node_thread, 0);
3658 kernel->n_block = n_outer_coincidence(node_thread);
3659 isl_schedule_node_free(node_thread);
3660 kernel->id = gen->kernel_id++;
3661 read_grid_and_block_sizes(kernel, gen);
3663 kernel->sync_writes = compute_sync_writes(kernel, node);
3665 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3666 host_domain = isl_set_from_union_set(isl_union_map_range(
3667 host_schedule));
3669 node = atomic_ancestors(node);
3671 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3672 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3673 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3675 if (!single_statement)
3676 node = group_statements(node, kernel->id);
3678 node = isl_schedule_node_child(node, 0);
3679 node = split_band(node, kernel->n_grid);
3680 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3681 kernel->n_grid, "b");
3682 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3683 kernel->grid_dim);
3684 kernel->grid_size = extract_grid_size(kernel,
3685 isl_union_set_copy(domain));
3686 if (!kernel->options->wrap)
3687 node = snap_band_to_sizes(node, kernel->grid_dim,
3688 kernel->options);
3689 if (scale)
3690 node = scale_band(node, isl_multi_val_copy(sizes));
3691 node = isl_schedule_node_parent(node);
3692 if (!single_statement)
3693 node = isl_schedule_node_parent(node);
3694 node = insert_guard(node, kernel->context, kernel->grid_size,
3695 gen->prog->scop);
3696 node = gpu_tree_move_down_to_thread(node, kernel->core);
3697 node = isl_schedule_node_child(node, 0);
3698 node = split_band(node, kernel->n_block);
3699 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3700 kernel->n_block, "t");
3701 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3702 kernel->block_dim);
3703 if (extract_block_size(kernel, domain) < 0)
3704 node = isl_schedule_node_free(node);
3706 node = gpu_tree_move_up_to_kernel(node);
3707 node = isl_schedule_node_child(node, 0);
3708 node = insert_context(kernel, node);
3709 node = isl_schedule_node_child(node, 0);
3710 node = isl_schedule_node_insert_filter(node,
3711 isl_union_set_copy(kernel->block_filter));
3713 node = gpu_tree_move_up_to_kernel(node);
3715 if (gpu_group_references(kernel, node) < 0)
3716 node = isl_schedule_node_free(node);
3717 localize_bounds(kernel, host_domain);
3718 isl_set_free(host_domain);
3720 check_shared_memory_bound(kernel);
3721 mark_global_arrays(kernel);
3722 compute_group_tilings(kernel);
3724 node = gpu_tree_move_down_to_thread(node, kernel->core);
3725 node = isl_schedule_node_child(node, 0);
3726 if (!kernel->options->wrap)
3727 node = snap_band_to_sizes(node, kernel->block_dim,
3728 kernel->options);
3729 node = isl_schedule_node_insert_filter(node,
3730 isl_union_set_copy(kernel->thread_filter));
3731 if (kernel_requires_unroll(kernel)) {
3732 node = isl_schedule_node_child(node, 0);
3733 node = unroll(node);
3736 node = gpu_tree_move_up_to_thread(node);
3737 kernel->shared_schedule_dim =
3738 isl_schedule_node_get_schedule_depth(node);
3739 kernel->shared_schedule =
3740 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3742 node = gpu_tree_move_up_to_kernel(node);
3744 node = add_sync(kernel, node);
3745 node = add_copies(kernel, node);
3747 node = gpu_tree_move_down_to_thread(node, kernel->core);
3748 node = isl_schedule_node_delete(node);
3750 node = gpu_tree_move_up_to_kernel(node);
3752 if (create_kernel_vars(kernel) < 0)
3753 node = isl_schedule_node_free(node);
3755 if (!single_statement)
3756 node = isl_schedule_node_parent(node);
3757 node = isl_schedule_node_parent(node);
3759 isl_id_free(id);
3760 return node;
3763 /* Insert a zero-dimensional permutable band at "node".
3765 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3766 __isl_take isl_schedule_node *node)
3768 isl_space *space;
3769 isl_schedule *schedule;
3770 isl_union_set *domain;
3771 isl_multi_union_pw_aff *mupa;
3773 schedule = isl_schedule_node_get_schedule(node);
3774 domain = isl_schedule_get_domain(schedule);
3775 space = isl_union_set_get_space(domain);
3776 isl_union_set_free(domain);
3777 isl_schedule_free(schedule);
3779 space = isl_space_set_from_params(space);
3780 mupa = isl_multi_union_pw_aff_zero(space);
3781 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3782 node = isl_schedule_node_band_set_permutable(node, 1);
3784 return node;
3787 /* If "node" is the outermost permutable band that can be mapped to block and
3788 * thread identifiers in its branch (or a leaf with no such outer bands),
3789 * then mark the band as such, attaching a ppcg_kernel to the mark.
3791 * If "node" originally points to a leaf, then insert a zero-dimensional
3792 * permutable band such that we can assume that "node" always
3793 * points to a band node.
3795 * Tile "node" using user specified tile sizes, after splitting the band
3796 * if the number of specified tile sizes is smaller than the dimension
3797 * of the band. Mark the point band of this tiling as the band that
3798 * needs to be mapped to threads.
3799 * Create a kernel representing the domain instances that reach "node" and
3800 * insert a mark node pointing to the ppcg_kernel before the band node.
3802 static __isl_give isl_schedule_node *mark_outer_permutable(
3803 __isl_take isl_schedule_node *node, void *user)
3805 struct gpu_gen *gen = user;
3806 int outer;
3807 int scale;
3808 int tile_len;
3809 int *tile_size;
3810 isl_id *id;
3811 isl_multi_val *sizes;
3813 outer = is_outer_tilable(node);
3814 if (outer < 0)
3815 return isl_schedule_node_free(node);
3816 if (!outer)
3817 return node;
3819 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3820 node = insert_empty_permutable_band(node);
3822 tile_len = isl_schedule_node_band_n_member(node);
3823 tile_size = read_tile_sizes(gen, &tile_len);
3824 if (!tile_size)
3825 return isl_schedule_node_free(node);
3826 if (tile_len < isl_schedule_node_band_n_member(node))
3827 node = isl_schedule_node_band_split(node, tile_len);
3828 sizes = construct_band_tiles_sizes(node, tile_size);
3829 node = tile_band(node, isl_multi_val_copy(sizes));
3830 node = isl_schedule_node_child(node, 0);
3831 id = isl_id_alloc(gen->ctx, "thread", NULL);
3832 node = isl_schedule_node_insert_mark(node, id);
3833 node = isl_schedule_node_parent(node);
3835 scale = gen->options->scale_tile_loops;
3836 node = create_kernel(gen, node, scale, sizes);
3837 isl_multi_val_free(sizes);
3838 free(tile_size);
3840 return node;
3843 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
3844 * That is, does it have any nodes that are permutable and that
3845 * have a least one coincident dimension?
3847 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
3849 int any_parallelism = 0;
3851 if (isl_schedule_node_foreach_descendant_top_down(node, &set_permutable,
3852 &any_parallelism) < 0 &&
3853 !any_parallelism)
3854 return -1;
3856 return any_parallelism;
3859 /* Mark all variables that are accessed by the statement instances in "domain"
3860 * and that are local to "prog" as requiring a declaration in the host code.
3862 static int declare_accessed_local_variables(struct gpu_prog *prog,
3863 __isl_keep isl_union_set *domain)
3865 isl_union_set *arrays;
3866 int i;
3868 if (!ppcg_scop_any_hidden_declarations(prog->scop))
3869 return 0;
3870 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
3872 for (i = 0; i < prog->n_array; ++i) {
3873 isl_space *space;
3874 isl_set *set;
3875 int empty;
3877 if (!prog->array[i].local)
3878 continue;
3879 space = isl_set_get_space(prog->array[i].extent);
3880 set = isl_union_set_extract_set(arrays, space);
3881 empty = isl_set_plain_is_empty(set);
3882 isl_set_free(set);
3883 if (empty < 0)
3884 goto error;
3885 if (!empty)
3886 prog->array[i].declare_local = 1;
3889 isl_union_set_free(arrays);
3890 return 0;
3891 error:
3892 isl_union_set_free(arrays);
3893 return -1;
3896 /* If "node" points to a set node, then separate its children
3897 * into subtrees that have suitably permutable bands and
3898 * those that do not.
3899 * Adjust the schedule tree in order to execute the second group
3900 * after the first group and return a pointer to the first group,
3901 * assuming there are any such subtrees.
3902 * Mark all local variables in "prog" that are accessed by
3903 * the second group as requiring a declaration on the host.
3905 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
3906 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
3908 isl_space *space;
3909 isl_union_set *filter;
3910 int i, n;
3912 if (!node)
3913 return NULL;
3914 if (isl_schedule_node_get_type(node) != isl_schedule_node_set)
3915 return node;
3917 n = isl_schedule_node_n_children(node);
3918 if (n < 0)
3919 return isl_schedule_node_free(node);
3921 node = isl_schedule_node_child(node, 0);
3922 filter = isl_schedule_node_filter_get_filter(node);
3923 node = isl_schedule_node_parent(node);
3924 space = isl_union_set_get_space(filter);
3925 isl_union_set_free(filter);
3926 filter = isl_union_set_empty(space);
3928 for (i = 0; i < n; ++i) {
3929 int parallelism;
3931 node = isl_schedule_node_child(node, i);
3932 parallelism = subtree_has_permutable_bands(node);
3933 if (parallelism < 0) {
3934 node = isl_schedule_node_free(node);
3935 } else if (!parallelism) {
3936 isl_union_set *filter_i;
3937 filter_i = isl_schedule_node_filter_get_filter(node);
3938 filter = isl_union_set_union(filter, filter_i);
3940 node = isl_schedule_node_parent(node);
3943 if (declare_accessed_local_variables(prog, filter) < 0)
3944 node = isl_schedule_node_free(node);
3945 node = isl_schedule_node_order_after(node, filter);
3947 return node;
3950 /* Replace any reference to an array element in the range of "copy"
3951 * by a reference to all array elements (defined by the extent of the array).
3953 static __isl_give isl_union_map *approximate_copy_out(
3954 __isl_take isl_union_map *copy, struct gpu_prog *prog)
3956 int i;
3957 isl_union_map *res;
3959 res = isl_union_map_empty(isl_union_map_get_space(copy));
3961 for (i = 0; i < prog->n_array; ++i) {
3962 isl_space *space;
3963 isl_set *set;
3964 isl_union_map *copy_i;
3965 isl_union_set *extent, *domain;
3967 space = isl_space_copy(prog->array[i].space);
3968 extent = isl_union_set_from_set(isl_set_universe(space));
3969 copy_i = isl_union_map_copy(copy);
3970 copy_i = isl_union_map_intersect_range(copy_i, extent);
3971 set = isl_set_copy(prog->array[i].extent);
3972 extent = isl_union_set_from_set(set);
3973 domain = isl_union_map_domain(copy_i);
3974 copy_i = isl_union_map_from_domain_and_range(domain, extent);
3975 res = isl_union_map_union(res, copy_i);
3978 isl_union_map_free(copy);
3980 return res;
3983 /* Insert "kernel" marks that point to a ppcg_kernel structure
3984 * in front of all outermost tilable band that (by construction)
3985 * have at least one parallel loop.
3987 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3988 __isl_take isl_schedule_node *node)
3990 return isl_schedule_node_map_descendant_bottom_up(node,
3991 &mark_outer_permutable, gen);
3994 /* Save the schedule "schedule" to a file called "filename".
3995 * The schedule is printed in block style.
3997 static void save_schedule(__isl_keep isl_schedule *schedule,
3998 const char *filename)
4000 FILE *file;
4001 isl_ctx *ctx;
4002 isl_printer *p;
4004 if (!schedule)
4005 return;
4007 file = fopen(filename, "w");
4008 if (!file) {
4009 fprintf(stderr, "Unable to open '%s' for writing\n", filename);
4010 return;
4012 ctx = isl_schedule_get_ctx(schedule);
4013 p = isl_printer_to_file(ctx, file);
4014 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
4015 p = isl_printer_print_schedule(p, schedule);
4016 isl_printer_free(p);
4017 fclose(file);
4020 /* Load and return a schedule from a file called "filename".
4022 static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
4023 const char *filename)
4025 FILE *file;
4026 isl_schedule *schedule;
4028 file = fopen(filename, "r");
4029 if (!file) {
4030 fprintf(stderr, "Unable to open '%s' for reading\n", filename);
4031 return NULL;
4033 schedule = isl_schedule_read_from_file(ctx, file);
4034 fclose(file);
4036 return schedule;
4039 /* Construct schedule constraints from the dependences in prog->scop and
4040 * the array order dependences in prog->array_order.
4042 * If live range reordering is allowed, then we need to make sure
4043 * that live ranges on arrays are not run in parallel since doing
4044 * so would require array expansion. We therefore add the array
4045 * order dependences to the coincidence dependences. Non-zero array
4046 * order dependences will then prevent a schedule dimension from being
4047 * considered parallel.
4048 * Live ranges derived from scalars are allowed to be run in parallel
4049 * since we force the scalars to be mapped to private memory in
4050 * check_scalar_live_ranges.
4051 * If live range reordering is allowed, then the false dependences
4052 * are not added to the validity constraints as that would prevent
4053 * reordering. Instead, the external false dependences that enforce that reads
4054 * from potentially live-in data precede any later write and
4055 * that writes of potentially live-out data follow any other earlier write
4056 * are added to the validity and the coincidence constraints.
4057 * The false dependences are still added to the proximity constraints
4058 * for consistency with the case where live range reordering is not allowed.
4059 * The coincidence constraints then consist of flow dependences,
4060 * external false dependences and array order dependences.
4061 * The independences can be filtered out from the first two sets.
4062 * They have already been filtered out from the array order dependences
4063 * on a per array basis in collect_order_dependences.
4064 * There is no need for a per array handling of the other two sets
4065 * as there should be no flow or external false dependence on local
4066 * variables that can be filtered out.
4068 static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4069 struct gpu_prog *prog)
4071 isl_union_set *domain;
4072 isl_union_map *dep_raw, *dep;
4073 isl_union_map *validity, *proximity, *coincidence;
4074 isl_schedule_constraints *sc;
4076 domain = isl_union_set_copy(prog->scop->domain);
4077 sc = isl_schedule_constraints_on_domain(domain);
4078 sc = isl_schedule_constraints_set_context(sc,
4079 isl_set_copy(prog->scop->context));
4080 if (prog->scop->options->live_range_reordering) {
4081 sc = isl_schedule_constraints_set_conditional_validity(sc,
4082 isl_union_map_copy(prog->scop->tagged_dep_flow),
4083 isl_union_map_copy(prog->scop->tagged_dep_order));
4084 proximity = isl_union_map_copy(prog->scop->dep_flow);
4085 validity = isl_union_map_copy(proximity);
4086 validity = isl_union_map_union(validity,
4087 isl_union_map_copy(prog->scop->dep_forced));
4088 proximity = isl_union_map_union(proximity,
4089 isl_union_map_copy(prog->scop->dep_false));
4090 coincidence = isl_union_map_copy(validity);
4091 coincidence = isl_union_map_subtract(coincidence,
4092 isl_union_map_copy(prog->scop->independence));
4093 coincidence = isl_union_map_union(coincidence,
4094 isl_union_map_copy(prog->array_order));
4095 } else {
4096 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4097 dep = isl_union_map_copy(prog->scop->dep_false);
4098 dep = isl_union_map_union(dep, dep_raw);
4099 dep = isl_union_map_coalesce(dep);
4100 proximity = isl_union_map_copy(dep);
4101 coincidence = isl_union_map_copy(dep);
4102 validity = dep;
4104 sc = isl_schedule_constraints_set_validity(sc, validity);
4105 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4106 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4108 if (prog->scop->options->debug->dump_schedule_constraints)
4109 isl_schedule_constraints_dump(sc);
4110 return sc;
4113 /* Compute an appropriate schedule based on the accesses in
4114 * gen->read and gen->write.
4116 * We derive schedule constraints from the dependences in gen->prog->scop
4117 * and then use isl to compute a schedule that has a parallel loop
4118 * in each tilable band.
4120 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4122 isl_schedule_constraints *sc;
4123 isl_schedule *schedule;
4125 sc = construct_schedule_constraints(gen->prog);
4126 schedule = isl_schedule_constraints_compute_schedule(sc);
4128 return schedule;
4131 /* If the band node "node" has exactly one member then mark it permutable.
4133 static __isl_give isl_schedule_node *band_set_permutable(
4134 __isl_take isl_schedule_node *node,
4135 __isl_keep isl_schedule_constraints *sc)
4137 if (isl_schedule_node_band_n_member(node) == 1)
4138 node = isl_schedule_node_band_set_permutable(node, 1);
4140 return node;
4143 /* Return the coincidence constraints between pairs of instances
4144 * that are scheduled together by the ancestors of "node".
4145 * That is, select those coincidence constraints that relate
4146 * pairs of instances that have the same value for the prefix schedule.
4147 * If the schedule depth is zero, then the prefix schedule does not
4148 * contain any information, so we intersect domain and range
4149 * of the schedule constraints with the reaching domain elements instead.
4151 static __isl_give isl_union_map *get_local_coincidence(
4152 __isl_keep isl_schedule_node *node,
4153 __isl_keep isl_schedule_constraints *sc)
4155 isl_union_map *coincidence;
4156 isl_multi_union_pw_aff *prefix;
4157 isl_union_pw_multi_aff *contraction;
4159 coincidence = isl_schedule_constraints_get_coincidence(sc);
4160 contraction = isl_schedule_node_get_subtree_contraction(node);
4161 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4162 isl_union_set *domain;
4164 domain = isl_schedule_node_get_domain(node);
4165 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4166 contraction);
4167 coincidence = isl_union_map_intersect_domain(coincidence,
4168 isl_union_set_copy(domain));
4169 coincidence = isl_union_map_intersect_range(coincidence,
4170 domain);
4171 return coincidence;
4174 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4175 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4176 contraction);
4177 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4180 /* For each member in the band node "node", determine whether
4181 * it is coincident with respect to the outer nodes and mark
4182 * it accordingly.
4184 * That is, for each coincidence constraint between pairs
4185 * of instances that are scheduled together by the outer nodes,
4186 * check that domain and range are assigned the same value
4187 * by the band member. This test is performed by checking
4188 * that imposing the same value for the band member does not
4189 * remove any elements from the set of coincidence constraints.
4191 static __isl_give isl_schedule_node *band_set_coincident(
4192 __isl_take isl_schedule_node *node,
4193 __isl_keep isl_schedule_constraints *sc)
4195 isl_union_map *coincidence;
4196 isl_union_pw_multi_aff *contraction;
4197 isl_multi_union_pw_aff *partial;
4198 int i, n;
4200 coincidence = get_local_coincidence(node, sc);
4202 partial = isl_schedule_node_band_get_partial_schedule(node);
4203 contraction = isl_schedule_node_get_subtree_contraction(node);
4204 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4205 contraction);
4206 n = isl_schedule_node_band_n_member(node);
4207 for (i = 0; i < n; ++i) {
4208 isl_union_map *coincidence_i;
4209 isl_union_pw_aff *upa;
4210 isl_multi_union_pw_aff *partial_i;
4211 int subset;
4213 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4214 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4215 coincidence_i = isl_union_map_copy(coincidence);
4216 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4217 coincidence_i, partial_i);
4218 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4219 isl_union_map_free(coincidence_i);
4221 if (subset < 0)
4222 break;
4223 node = isl_schedule_node_band_member_set_coincident(node, i,
4224 subset);
4226 if (i < n)
4227 node = isl_schedule_node_free(node);
4228 isl_multi_union_pw_aff_free(partial);
4229 isl_union_map_free(coincidence);
4231 return node;
4234 /* If "node" is a band, then set its properties.
4236 * In particular, if the band has exactly one member, then mark it permutable.
4237 * Mark the band member coincident based on the coincidence constraints
4238 * of "sc".
4240 static __isl_give isl_schedule_node *set_band_properties(
4241 __isl_take isl_schedule_node *node, void *user)
4243 isl_schedule_constraints *sc = user;
4245 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4246 return node;
4247 if (isl_schedule_node_band_n_member(node) == 0)
4248 return node;
4250 node = band_set_permutable(node, sc);
4251 node = band_set_coincident(node, sc);
4253 return node;
4256 /* Return the original schedule with all bands marked permutable and
4257 * all band members marked coincident based on the coincidence constraints.
4258 * The bands are explicitly marked permutable so that they will be considered
4259 * by mark_outer_permutable.
4261 static __isl_give isl_schedule *determine_properties_original_schedule(
4262 struct gpu_gen *gen)
4264 isl_schedule *schedule;
4265 isl_schedule_constraints *sc;
4267 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4268 sc = construct_schedule_constraints(gen->prog);
4269 schedule = isl_schedule_map_schedule_node_bottom_up(schedule,
4270 &set_band_properties, sc);
4271 isl_schedule_constraints_free(sc);
4273 return schedule;
4276 /* Obtain a schedule for the scop, by reading it from
4277 * a file, by computing one or by determining the properties
4278 * of the original schedule.
4280 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4282 isl_schedule *schedule;
4284 if (gen->options->load_schedule_file) {
4285 schedule = load_schedule(gen->ctx,
4286 gen->options->load_schedule_file);
4287 } else {
4288 if (gen->options->reschedule)
4289 schedule = compute_schedule(gen);
4290 else
4291 schedule = determine_properties_original_schedule(gen);
4292 if (gen->options->save_schedule_file)
4293 save_schedule(schedule,
4294 gen->options->save_schedule_file);
4296 if (gen->options->debug->dump_schedule)
4297 isl_schedule_dump(schedule);
4299 return schedule;
4302 /* Construct the string "<a>_<b>".
4304 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4306 isl_printer *p;
4307 char *s;
4309 p = isl_printer_to_str(ctx);
4310 p = isl_printer_print_str(p, a);
4311 p = isl_printer_print_str(p, "_");
4312 p = isl_printer_print_str(p, b);
4313 s = isl_printer_get_str(p);
4314 isl_printer_free(p);
4316 return s;
4319 /* For each array in "prog" of which an element appears in "accessed" and
4320 * that is not a read only scalar, create a zero-dimensional universe set
4321 * of which the tuple id has name "<prefix>_<name of array>" and a user
4322 * pointer pointing to the array (gpu_array_info).
4324 * If the array is local to "prog", then make sure it will be declared
4325 * in the host code.
4327 * Return the list of these universe sets.
4329 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4330 const char *prefix, __isl_take isl_union_set *accessed)
4332 int i;
4333 isl_ctx *ctx;
4334 isl_union_set_list *filters;
4336 ctx = prog->ctx;
4337 filters = isl_union_set_list_alloc(ctx, 0);
4338 for (i = 0; i < prog->n_array; ++i) {
4339 struct gpu_array_info *array = &prog->array[i];
4340 isl_space *space;
4341 isl_set *accessed_i;
4342 int empty;
4343 char *name;
4344 isl_id *id;
4345 isl_union_set *uset;
4347 if (gpu_array_is_read_only_scalar(array))
4348 continue;
4350 space = isl_space_copy(array->space);
4351 accessed_i = isl_union_set_extract_set(accessed, space);
4352 empty = isl_set_plain_is_empty(accessed_i);
4353 isl_set_free(accessed_i);
4354 if (empty < 0) {
4355 filters = isl_union_set_list_free(filters);
4356 break;
4358 if (empty)
4359 continue;
4361 array->global = 1;
4362 if (array->local)
4363 array->declare_local = 1;
4365 name = concat(ctx, prefix, array->name);
4366 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4367 free(name);
4368 space = isl_space_set_alloc(ctx, 0, 0);
4369 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4370 uset = isl_union_set_from_set(isl_set_universe(space));
4372 filters = isl_union_set_list_add(filters, uset);
4374 isl_union_set_free(accessed);
4376 return filters;
4379 /* Make sure that code for the statements in "filters" that
4380 * copy arrays to or from the device is only generated when
4381 * the size of the corresponding array is positive.
4382 * That is, add a set node underneath "graft" with "filters" as children
4383 * and for each child add a guard that the selects the parameter
4384 * values for which the corresponding array has a positive size.
4385 * The array is available in the user pointer of the statement identifier.
4386 * "depth" is the schedule depth of the position where "graft"
4387 * will be added.
4389 static __isl_give isl_schedule_node *insert_positive_size_guards(
4390 __isl_take isl_schedule_node *graft,
4391 __isl_take isl_union_set_list *filters, int depth)
4393 int i, n;
4395 graft = isl_schedule_node_child(graft, 0);
4396 graft = isl_schedule_node_insert_set(graft, filters);
4397 n = isl_schedule_node_n_children(graft);
4398 for (i = 0; i < n; ++i) {
4399 isl_union_set *filter;
4400 isl_set *domain, *guard;
4401 isl_id *id;
4402 struct gpu_array_info *array;
4404 graft = isl_schedule_node_child(graft, i);
4405 filter = isl_schedule_node_filter_get_filter(graft);
4406 domain = isl_set_from_union_set(filter);
4407 id = isl_set_get_tuple_id(domain);
4408 array = isl_id_get_user(id);
4409 isl_id_free(id);
4410 isl_set_free(domain);
4411 guard = gpu_array_positive_size_guard(array);
4412 guard = isl_set_from_params(guard);
4413 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4414 graft = isl_schedule_node_child(graft, 0);
4415 graft = isl_schedule_node_insert_guard(graft, guard);
4416 graft = isl_schedule_node_parent(graft);
4417 graft = isl_schedule_node_parent(graft);
4419 graft = isl_schedule_node_parent(graft);
4421 return graft;
4424 /* Create a graft for copying arrays to or from the device,
4425 * whenever the size of the array is strictly positive.
4426 * Each statement is called "<prefix>_<name of array>" and
4427 * the identifier has a user pointer pointing to the array.
4428 * The graft will be added at the position specified by "node".
4429 * "copy" contains the array elements that need to be copied.
4430 * Only arrays of which some elements need to be copied
4431 * will have a corresponding statement in the graph.
4432 * Note though that each such statement will copy the entire array.
4434 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4435 __isl_keep isl_schedule_node *node, const char *prefix,
4436 __isl_take isl_union_set *copy)
4438 int depth;
4439 isl_ctx *ctx;
4440 isl_space *space;
4441 isl_union_set *all, *domain;
4442 isl_union_set_list *filters;
4443 isl_union_map *extension;
4444 isl_schedule_node *graft;
4446 ctx = prog->ctx;
4447 depth = isl_schedule_node_get_schedule_depth(node);
4448 filters = create_copy_filters(prog, prefix, copy);
4449 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4451 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4452 domain = isl_union_set_from_set(isl_set_universe(space));
4453 extension = isl_union_map_from_domain_and_range(domain, all);
4454 graft = isl_schedule_node_from_extension(extension);
4456 if (!filters)
4457 return isl_schedule_node_free(graft);
4458 if (isl_union_set_list_n_union_set(filters) == 0) {
4459 isl_union_set_list_free(filters);
4460 return graft;
4463 return insert_positive_size_guards(graft, filters, depth);
4466 /* Return (the universe spaces of) the arrays that are declared
4467 * inside the scop corresponding to "prog" and for which all
4468 * potential writes inside the scop form a subset of "domain".
4470 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4471 __isl_keep isl_union_set *domain)
4473 int i;
4474 isl_union_set *local;
4476 local = isl_union_set_empty(isl_union_set_get_space(domain));
4478 for (i = 0; i < prog->n_array; ++i) {
4479 isl_set *set;
4480 isl_union_map *to_outer;
4481 isl_union_map *may_write;
4482 isl_union_set *write_domain;
4483 isl_union_set *fields;
4484 int subset;
4486 if (!prog->array[i].local)
4487 continue;
4489 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4490 to_outer = isl_union_map_copy(prog->to_outer);
4491 to_outer = isl_union_map_intersect_range(to_outer,
4492 isl_union_set_from_set(isl_set_copy(set)));
4493 fields = isl_union_map_domain(to_outer);
4494 may_write = isl_union_map_copy(prog->may_write);
4495 may_write = isl_union_map_intersect_range(may_write, fields);
4496 write_domain = isl_union_map_domain(may_write);
4497 subset = isl_union_set_is_subset(write_domain, domain);
4498 isl_union_set_free(write_domain);
4500 if (subset < 0) {
4501 isl_set_free(set);
4502 return isl_union_set_free(local);
4503 } else if (subset) {
4504 local = isl_union_set_add_set(local, set);
4505 } else {
4506 isl_set_free(set);
4510 return local;
4513 /* Internal data structure for node_may_persist.
4515 * "tagger" maps tagged iteration domains to the corresponding untagged
4516 * iteration domain.
4518 * "may_persist_flow" is the set of all tagged dataflow dependences
4519 * with those dependences removed that either precede or follow
4520 * the kernel launch in a sequence.
4521 * "inner_band_flow" is the set of all tagged dataflow dependences
4522 * that are local to a given iteration of the outer band nodes
4523 * with respect to the current node.
4524 * "local_flow" is equal to "inner_band_flow", except that the domain
4525 * and the range have been intersected with intermediate filters
4526 * on children of sets or sequences.
4528 struct ppcg_may_persist_data {
4529 isl_union_pw_multi_aff *tagger;
4531 isl_union_map *local_flow;
4532 isl_union_map *inner_band_flow;
4533 isl_union_map *may_persist_flow;
4536 /* Update the information in "data" based on the band ancestor "node".
4538 * In particular, we restrict the dependences in data->local_flow
4539 * to those dependence where the source and the sink occur in
4540 * the same iteration of the given band node.
4541 * We also update data->inner_band_flow to the new value of
4542 * data->local_flow.
4544 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4545 struct ppcg_may_persist_data *data)
4547 isl_multi_union_pw_aff *partial;
4548 isl_union_pw_multi_aff *contraction;
4549 isl_union_map *flow;
4551 if (isl_schedule_node_band_n_member(node) == 0)
4552 return 0;
4554 partial = isl_schedule_node_band_get_partial_schedule(node);
4555 contraction = isl_schedule_node_get_subtree_contraction(node);
4556 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4557 contraction);
4558 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4559 isl_union_pw_multi_aff_copy(data->tagger));
4561 flow = data->local_flow;
4562 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4563 data->local_flow = flow;
4565 isl_union_map_free(data->inner_band_flow);
4566 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4568 return 0;
4571 /* Given a set of local reaching domain elements "domain",
4572 * expand them to the corresponding leaf domain elements using "contraction"
4573 * and insert the array references tags using data->tagger.
4575 static __isl_give isl_union_set *expand_and_tag(
4576 __isl_take isl_union_set *domain,
4577 __isl_take isl_union_pw_multi_aff *contraction,
4578 struct ppcg_may_persist_data *data)
4580 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4581 contraction);
4582 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4583 isl_union_pw_multi_aff_copy(data->tagger));
4584 return domain;
4587 /* Given a filter node that is the child of a set or sequence node,
4588 * restrict data->local_flow to refer only to those elements
4589 * in the filter of the node.
4590 * "contraction" maps the leaf domain elements of the schedule tree
4591 * to the corresponding domain elements at (the parent of) "node".
4593 static int filter_flow(__isl_keep isl_schedule_node *node,
4594 struct ppcg_may_persist_data *data,
4595 __isl_take isl_union_pw_multi_aff *contraction)
4597 isl_union_set *filter;
4598 isl_union_map *flow;
4600 flow = data->local_flow;
4601 filter = isl_schedule_node_filter_get_filter(node);
4602 filter = expand_and_tag(filter, contraction, data);
4603 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4604 flow = isl_union_map_intersect_range(flow, filter);
4605 data->local_flow = flow;
4607 return 0;
4610 /* Given a filter node "node", collect the filters on all preceding siblings
4611 * (which are also filter nodes), add them to "filters" and return the result.
4613 static __isl_give isl_union_set *add_previous_filters(
4614 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4616 isl_schedule_node *sibling;
4618 sibling = isl_schedule_node_copy(node);
4619 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4620 isl_union_set *filter;
4622 sibling = isl_schedule_node_previous_sibling(sibling);
4623 filter = isl_schedule_node_filter_get_filter(sibling);
4624 filters = isl_union_set_union(filters, filter);
4626 isl_schedule_node_free(sibling);
4627 if (!sibling)
4628 return isl_union_set_free(filters);
4630 return filters;
4633 /* Given a filter node "node", collect the filters on all following siblings
4634 * (which are also filter nodes), add them to "filters" and return the result.
4636 static __isl_give isl_union_set *add_next_filters(
4637 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4639 isl_schedule_node *sibling;
4641 sibling = isl_schedule_node_copy(node);
4642 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4643 isl_union_set *filter;
4645 sibling = isl_schedule_node_next_sibling(sibling);
4646 filter = isl_schedule_node_filter_get_filter(sibling);
4647 filters = isl_union_set_union(filters, filter);
4649 isl_schedule_node_free(sibling);
4650 if (!sibling)
4651 return isl_union_set_free(filters);
4653 return filters;
4656 /* Remove those flow dependences from data->may_persist_flow
4657 * that flow between elements of "domain" within the same iteration
4658 * of all outer band nodes.
4659 * "contraction" maps the leaf domain elements of the schedule tree
4660 * to the corresponding elements "domain".
4662 static void remove_external_flow(struct ppcg_may_persist_data *data,
4663 __isl_take isl_union_set *domain,
4664 __isl_keep isl_union_pw_multi_aff *contraction)
4666 isl_union_map *flow;
4668 contraction = isl_union_pw_multi_aff_copy(contraction);
4669 domain = expand_and_tag(domain, contraction, data);
4670 flow = isl_union_map_copy(data->local_flow);
4671 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4672 flow = isl_union_map_intersect_range(flow, domain);
4674 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4675 flow);
4678 /* Update the information in "data" based on the filter ancestor "node".
4679 * We only need to modify anything if the filter is the child
4680 * of a set or sequence node.
4682 * In the case of a sequence, we remove the dependences between
4683 * statement instances that are both executed either before or
4684 * after the subtree that will be mapped to a kernel, within
4685 * the same iteration of outer bands.
4687 * In both cases, we restrict data->local_flow to the current child.
4689 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4690 struct ppcg_may_persist_data *data)
4692 enum isl_schedule_node_type type;
4693 isl_schedule_node *parent;
4694 isl_space *space;
4695 isl_union_pw_multi_aff *contraction;
4696 isl_union_set *before, *after, *filter;
4697 isl_union_map *flow;
4699 type = isl_schedule_node_get_parent_type(node);
4700 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4701 return 0;
4703 parent = isl_schedule_node_copy(node);
4704 parent = isl_schedule_node_parent(parent);
4705 contraction = isl_schedule_node_get_subtree_contraction(parent);
4706 isl_schedule_node_free(parent);
4708 if (type == isl_schedule_node_set)
4709 return filter_flow(node, data, contraction);
4711 filter = isl_schedule_node_filter_get_filter(node);
4712 space = isl_union_set_get_space(filter);
4713 isl_union_set_free(filter);
4714 before = isl_union_set_empty(space);
4715 after = isl_union_set_copy(before);
4716 before = add_previous_filters(before, node);
4717 after = add_next_filters(after, node);
4719 remove_external_flow(data, before, contraction);
4720 remove_external_flow(data, after, contraction);
4722 return filter_flow(node, data, contraction);
4725 /* Update the information in "data" based on the ancestor "node".
4727 static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
4728 void *user)
4730 struct ppcg_may_persist_data *data = user;
4732 switch (isl_schedule_node_get_type(node)) {
4733 case isl_schedule_node_error:
4734 return isl_stat_error;
4735 case isl_schedule_node_context:
4736 case isl_schedule_node_domain:
4737 case isl_schedule_node_expansion:
4738 case isl_schedule_node_extension:
4739 case isl_schedule_node_guard:
4740 case isl_schedule_node_leaf:
4741 case isl_schedule_node_mark:
4742 case isl_schedule_node_sequence:
4743 case isl_schedule_node_set:
4744 break;
4745 case isl_schedule_node_band:
4746 if (update_may_persist_at_band(node, data) < 0)
4747 return isl_stat_error;
4748 break;
4749 case isl_schedule_node_filter:
4750 if (update_may_persist_at_filter(node, data) < 0)
4751 return isl_stat_error;
4752 break;
4755 return isl_stat_ok;
4758 /* Determine the set of array elements that may need to be perserved
4759 * by a kernel constructed from the subtree at "node".
4760 * This includes the set of array elements that may need to be preserved
4761 * by the entire scop (prog->may_persist) and the elements for which
4762 * there is a potential flow dependence that may cross a kernel launch.
4764 * To determine the second set, we start from all flow dependences.
4765 * From this set of dependences, we remove those that cannot possibly
4766 * require data to be preserved by a kernel launch.
4767 * In particular, we consider the following sets of dependences.
4768 * - dependences of which the write occurs inside the kernel.
4769 * If the data is needed outside the kernel, then it will
4770 * be copied out immediately after the kernel launch, so there
4771 * is no need for any special care.
4772 * - dependences of which the read occurs inside the kernel and the
4773 * corresponding write occurs inside the same iteration of the
4774 * outer band nodes. This means that the data is needed in
4775 * the first kernel launch after the write, which is already
4776 * taken care of by the standard copy-in. That is, the data
4777 * do not need to be preserved by any intermediate call to
4778 * the same kernel.
4779 * - dependences of which the write and the read either both occur
4780 * before the kernel launch or both occur after the kernel launch,
4781 * within the same iteration of the outer band nodes with respect
4782 * to the sequence that determines the ordering of the dependence
4783 * and the kernel launch. Such flow dependences cannot cross
4784 * any kernel launch.
4786 * For the remaining (tagged) dependences, we take the domain
4787 * (i.e., the tagged writes) and apply the tagged access relation
4788 * to obtain the accessed data elements.
4789 * These are then combined with the elements that may need to be
4790 * preserved by the entire scop.
4792 static __isl_give isl_union_set *node_may_persist(
4793 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4795 struct ppcg_may_persist_data data;
4796 isl_schedule_node *root;
4797 isl_union_pw_multi_aff *contraction;
4798 isl_union_set *domain;
4799 isl_union_set *persist;
4800 isl_union_map *flow, *local_flow;
4802 data.tagger = prog->scop->tagger;
4804 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4805 data.local_flow = isl_union_map_copy(flow);
4806 data.inner_band_flow = isl_union_map_copy(flow);
4807 data.may_persist_flow = flow;
4808 if (isl_schedule_node_foreach_ancestor_top_down(node,
4809 &update_may_persist_at, &data) < 0)
4810 data.may_persist_flow =
4811 isl_union_map_free(data.may_persist_flow);
4812 flow = data.may_persist_flow;
4813 isl_union_map_free(data.local_flow);
4815 domain = isl_schedule_node_get_domain(node);
4816 contraction = isl_schedule_node_get_subtree_contraction(node);
4817 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4818 contraction);
4819 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4820 isl_union_pw_multi_aff_copy(data.tagger));
4821 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4822 local_flow = data.inner_band_flow;
4823 local_flow = isl_union_map_intersect_range(local_flow, domain);
4824 flow = isl_union_map_subtract(flow, local_flow);
4826 persist = isl_union_map_domain(flow);
4827 persist = isl_union_set_apply(persist,
4828 isl_union_map_copy(prog->scop->tagged_may_writes));
4829 persist = isl_union_set_union(persist,
4830 isl_union_set_copy(prog->may_persist));
4832 return persist;
4835 /* Add nodes for copying outer arrays in and out of the device
4836 * before and after the subtree "node", which contains one or more kernels.
4837 * "domain" contains the original reaching domain elements before
4838 * the kernels were created, i.e., before the contraction that
4839 * may have been performed in creating the kernels has been applied.
4840 * "prefix" contains the prefix schedule at that point, in terms
4841 * of the same original reaching domain elements.
4843 * We first compute the sets of outer array elements that need
4844 * to be copied in and out and then graft in the nodes for
4845 * performing this copying.
4847 * In particular, for each array that is possibly written anywhere in
4848 * the subtree "node" and that may be used after "node"
4849 * or that may be visible outside the corresponding scop,
4850 * we copy out its entire extent.
4852 * Any array elements that is read without first being written inside
4853 * the subtree "node" needs to be copied in.
4854 * Furthermore, if there are any array elements that
4855 * are copied out, but that may not be written inside "node, then
4856 * they also need to be copied in to ensure that the value after execution
4857 * is the same as the value before execution, at least for those array
4858 * elements that may have their values preserved by the scop or that
4859 * may be written before "node" and read after "node".
4860 * In case the array elements are structures, we need to take into
4861 * account that all members of the structures need to be written
4862 * by "node" before we can avoid copying the data structure in.
4864 * Note that the may_write relation is intersected with the domain,
4865 * which has been intersected with the context.
4866 * This helps in those cases where the arrays are declared with a fixed size,
4867 * while the accesses are parametric and the context assigns a fixed value
4868 * to the parameters.
4870 * If an element from a local array is read without first being written,
4871 * then there is no point in copying it in since it cannot have been
4872 * written prior to the scop. Warn about the uninitialized read instead.
4874 static __isl_give isl_schedule_node *add_to_from_device(
4875 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4876 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4878 isl_union_set *local;
4879 isl_union_set *to_device, *from_device, *may_persist;
4880 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4881 isl_union_map *read, *copy_in;
4882 isl_union_map *tagged;
4883 isl_union_map *local_uninitialized;
4884 isl_schedule_node *graft;
4886 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4887 tagged = isl_union_map_union(tagged,
4888 isl_union_map_copy(prog->scop->tagged_may_writes));
4890 may_write = isl_union_map_copy(prog->may_write);
4891 may_write = isl_union_map_intersect_domain(may_write,
4892 isl_union_set_copy(domain));
4893 may_write = remove_local_accesses(prog,
4894 isl_union_map_copy(tagged), may_write,
4895 isl_union_map_copy(prefix), 0);
4896 may_write = isl_union_map_apply_range(may_write,
4897 isl_union_map_copy(prog->to_outer));
4898 may_write = isl_union_map_apply_domain(may_write,
4899 isl_union_map_copy(prefix));
4900 may_write = approximate_copy_out(may_write, prog);
4901 copy_out = isl_union_map_copy(may_write);
4902 may_write = isl_union_map_apply_range(may_write,
4903 isl_union_map_copy(prog->to_inner));
4904 must_write = isl_union_map_copy(prog->must_write);
4905 must_write = isl_union_map_apply_domain(must_write,
4906 isl_union_map_copy(prefix));
4907 may_persist = node_may_persist(node, prog);
4908 may_write = isl_union_map_intersect_range(may_write, may_persist);
4909 not_written = isl_union_map_subtract(may_write, must_write);
4911 local = extract_local_accesses(prog, domain);
4912 read = isl_union_map_copy(prog->read);
4913 read = isl_union_map_intersect_domain(read, domain);
4914 read = remove_local_accesses(prog, tagged, read,
4915 isl_union_map_copy(prefix), 1);
4916 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4917 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4918 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4919 local);
4920 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4921 isl_union_map_copy(read));
4922 if (!isl_union_map_is_empty(local_uninitialized)) {
4923 fprintf(stderr,
4924 "possibly uninitialized reads (not copied in):\n");
4925 isl_union_map_dump(local_uninitialized);
4927 read = isl_union_map_subtract(read, local_uninitialized);
4928 read = isl_union_map_apply_domain(read, prefix);
4929 copy_in = isl_union_map_union(read, not_written);
4930 copy_in = isl_union_map_apply_range(copy_in,
4931 isl_union_map_copy(prog->to_outer));
4933 graft = create_copy_device(prog, node, "to_device",
4934 isl_union_map_range(copy_in));
4935 node = isl_schedule_node_graft_before(node, graft);
4936 graft = create_copy_device(prog, node, "from_device",
4937 isl_union_map_range(copy_out));
4938 node = isl_schedule_node_graft_after(node, graft);
4940 return node;
4943 /* Update "schedule" for mapping to a GPU device.
4945 * In particular, insert a context node, create kernels for
4946 * each outermost tilable band and introduce node for copying array
4947 * in and out of the device.
4948 * If the child of the initial root points to a set node,
4949 * then children of this node that do not contain any tilable bands
4950 * are separated from the other children and are not mapped to
4951 * the device.
4953 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4954 __isl_take isl_schedule *schedule)
4956 isl_schedule_node *node;
4957 isl_set *context;
4958 isl_union_set *domain;
4959 isl_union_map *prefix;
4961 context = isl_set_copy(gen->prog->context);
4962 context = isl_set_from_params(context);
4963 schedule = isl_schedule_insert_context(schedule, context);
4965 node = isl_schedule_get_root(schedule);
4966 isl_schedule_free(schedule);
4967 node = isl_schedule_node_child(node, 0);
4968 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4969 node = isl_schedule_node_child(node, 0);
4970 node = isolate_permutable_subtrees(node, gen->prog);
4971 domain = isl_schedule_node_get_domain(node);
4972 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4973 node = mark_kernels(gen, node);
4974 node = add_to_from_device(node, domain, prefix, gen->prog);
4975 schedule = isl_schedule_node_get_schedule(node);
4976 isl_schedule_node_free(node);
4978 return schedule;
4981 /* Internal data structure for extract_access.
4982 * "next_access" points to the end of a linked list that is extended
4983 * by extract_access.
4984 * "single_expression" is set if the access expressions belong to
4985 * an expression statement (i.e., a statement without internal control).
4986 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4988 struct ppcg_extract_access_data {
4989 struct gpu_stmt_access **next_access;
4990 int single_expression;
4991 isl_union_map *any_to_outer;
4994 /* Given a tagged access relation to a single array "tagged", extract it
4995 * as a map, taking into account that the input may be empty.
4996 * If the access relation is empty, then it does not contain
4997 * any space information, so we try to recover it from the index
4998 * expression.
4999 * The space of the index expression is of the form I -> A,
5000 * with I the statement instances and A the array, or [I -> F] -> A,
5001 * with F the filters corresponding to arguments.
5002 * We first drop F, if present, obtaining I -> A.
5003 * Then we construct I -> R, with R the reference tag,
5004 * combine the two into I -> [R -> A] and uncurry to obtain
5005 * the final result [I -> R] -> A.
5006 * Note that the index expression may have a lower dimension
5007 * than that of the array, but this dimension is not used
5008 * if the access relation is empty.
5010 static __isl_give isl_map *extract_single_tagged_access(
5011 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5013 int empty;
5014 isl_id *id;
5015 isl_space *space, *space2;
5016 isl_multi_pw_aff *index;
5018 empty = isl_union_map_is_empty(tagged);
5019 if (empty < 0)
5020 goto error;
5021 if (!empty)
5022 return isl_map_from_union_map(tagged);
5023 isl_union_map_free(tagged);
5025 index = pet_expr_access_get_index(expr);
5026 space = isl_multi_pw_aff_get_space(index);
5027 isl_multi_pw_aff_free(index);
5028 if (isl_space_domain_is_wrapping(space))
5029 space = isl_space_domain_factor_domain(space);
5030 space2 = isl_space_copy(space);
5031 space2 = isl_space_from_domain(isl_space_domain(space));
5032 id = pet_expr_access_get_ref_id(expr);
5033 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5034 space = isl_space_range_product(space2, space);
5035 space = isl_space_uncurry(space);
5037 return isl_map_empty(space);
5038 error:
5039 isl_union_map_free(tagged);
5040 return NULL;
5043 /* Extract a gpu_stmt_access from "expr", append it to the list
5044 * that ends in *data->next_access and update the end of the list.
5045 * If the access expression performs a write, then it is considered
5046 * exact only if it appears in a single expression statement and
5047 * if its may access relation is equal to its must access relation.
5049 * The combined set of may accesses may be union if member accesses
5050 * are involved, but the entire set is derived from a single reference and
5051 * therefore from a single index expression. These accesses therefore
5052 * all map to the same outer array.
5054 static int extract_access(__isl_keep pet_expr *expr, void *user)
5056 struct ppcg_extract_access_data *data = user;
5057 isl_union_map *tagged;
5058 struct gpu_stmt_access *access;
5059 isl_ctx *ctx = pet_expr_get_ctx(expr);
5060 isl_multi_pw_aff *index;
5062 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5063 assert(access);
5064 access->next = NULL;
5065 access->read = pet_expr_access_is_read(expr);
5066 access->write = pet_expr_access_is_write(expr);
5067 tagged = pet_expr_access_get_tagged_may_read(expr);
5068 tagged = isl_union_map_union(tagged,
5069 pet_expr_access_get_tagged_may_write(expr));
5070 tagged = isl_union_map_apply_range(tagged,
5071 isl_union_map_copy(data->any_to_outer));
5072 if (!access->write) {
5073 access->exact_write = 1;
5074 } else if (!data->single_expression) {
5075 access->exact_write = 0;
5076 } else {
5077 isl_union_map *must, *may;
5078 may = isl_union_map_copy(tagged);
5079 may = isl_union_map_domain_factor_domain(may);
5080 must = pet_expr_access_get_must_write(expr);
5081 access->exact_write = isl_union_map_is_equal(must, may);
5082 isl_union_map_free(must);
5083 isl_union_map_free(may);
5085 index = pet_expr_access_get_index(expr);
5086 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5087 isl_multi_pw_aff_free(index);
5088 access->ref_id = pet_expr_access_get_ref_id(expr);
5089 access->tagged_access = extract_single_tagged_access(tagged, expr);
5090 access->access = isl_map_copy(access->tagged_access);
5091 access->access = isl_map_domain_factor_domain(access->access);
5093 *data->next_access = access;
5094 data->next_access = &(*data->next_access)->next;
5096 if (!access->access)
5097 return -1;
5099 return 0;
5102 /* Construct a linked list of gpu_stmt_access objects,
5103 * one for each access expression in the statement body.
5104 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5106 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5107 __isl_keep isl_union_map *any_to_outer)
5109 struct ppcg_extract_access_data data;
5111 stmt->accesses = NULL;
5112 data.next_access = &stmt->accesses;
5113 data.single_expression =
5114 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5115 data.any_to_outer = any_to_outer;
5116 return pet_tree_foreach_access_expr(stmt->stmt->body,
5117 &extract_access, &data);
5120 /* Return an array of gpu_stmt representing the statements in "scop".
5122 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5123 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5125 int i;
5126 struct gpu_stmt *stmts;
5128 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5129 if (!stmts)
5130 return NULL;
5132 for (i = 0; i < scop->pet->n_stmt; ++i) {
5133 struct gpu_stmt *s = &stmts[i];
5135 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5136 s->stmt = scop->pet->stmts[i];
5137 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5138 return free_stmts(stmts, i + 1);
5141 return stmts;
5144 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5146 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5148 struct gpu_gen *gen = user;
5150 return gen->print(p, gen->prog, gen->tree, &gen->types,
5151 gen->print_user);
5154 /* Generate CUDA code for "scop" and print it to "p".
5155 * After generating an AST for the transformed scop as explained below,
5156 * we call "gen->print" to print the AST in the desired output format
5157 * to "p".
5159 * If it turns out that it does not make sense to generate GPU code,
5160 * then we generate CPU code instead.
5162 * The GPU code is generated in a context where at least one
5163 * statement instance is executed. The corresponding guard (if any) is printed
5164 * around the entire generated GPU code, except for the declaration
5165 * of the arrays that are visible outside of the scop and that therefore
5166 * cannot be declared inside the body of any possible guard.
5168 * We first compute a schedule that respects the dependences
5169 * of the original program and select the outermost bands
5170 * of tilable dimensions that have at least one parallel loop.
5171 * If the --load-schedule is specified, then the loaded schedule
5172 * is used instead of a computed schedule.
5174 * Each of these bands B is then tiled according to "tile" sizes, resulting
5175 * in two nested bands, with a kernel marker on top
5183 * We then split off at most 2 parallel dimensions from the T band and
5184 * at most 3 parallel dimension from the P band
5189 * T1
5191 * T2
5193 * P1
5195 * P2
5197 * A filter is introduced in front of T1 that maps the domain instances
5198 * to block identifiers. Similarly, a filter is introduced in front of P1
5199 * that maps the domain instances to thread identifiers.
5201 * For each iteration of the T2 band and for each array, we compute
5202 * the array elements accessed by that iteration, construct a rectangular
5203 * box around it and shift it to the origin. The result is used
5204 * as shared memory for the array.
5206 * Copying and synchronization statements are added to this schedule tree.
5207 * In principle, these are added in front of the P1 band, but some of
5208 * them may get hoisted up to higher levels.
5210 * The entire AST is then generated from the single resulting schedule tree.
5211 * During the generation the subtrees at kernel nodes (K) are saved
5212 * aside and replaced by kernel calls. The result is printed as host code
5213 * while the saved subtrees are printed as device code.
5215 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5216 struct gpu_gen *gen, struct ppcg_scop *scop,
5217 struct ppcg_options *options)
5219 struct gpu_prog *prog;
5220 isl_ctx *ctx;
5221 isl_set *context, *guard;
5222 isl_schedule *schedule;
5223 int any_permutable;
5225 if (!scop)
5226 return isl_printer_free(p);
5228 ctx = isl_printer_get_ctx(p);
5229 prog = gpu_prog_alloc(ctx, scop);
5230 if (!prog)
5231 return isl_printer_free(p);
5233 context = isl_set_copy(prog->context);
5234 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5235 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5237 gen->prog = prog;
5238 schedule = get_schedule(gen);
5240 any_permutable = has_any_permutable_node(schedule);
5241 if (any_permutable < 0 || !any_permutable) {
5242 isl_set_free(context);
5243 isl_set_free(guard);
5244 if (any_permutable < 0)
5245 p = isl_printer_free(p);
5246 else
5247 p = print_cpu(p, scop, options);
5248 isl_schedule_free(schedule);
5249 } else {
5250 schedule = map_to_device(gen, schedule);
5251 gen->tree = generate_code(gen, schedule);
5252 p = isl_ast_op_type_print_macro(isl_ast_op_fdiv_q, p);
5253 p = ppcg_print_exposed_declarations(p, prog->scop);
5254 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5255 isl_ast_node_free(gen->tree);
5258 gpu_prog_free(prog);
5260 return p;
5263 /* Wrapper around generate for use as a ppcg_transform callback.
5265 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5266 struct ppcg_scop *scop, void *user)
5268 struct gpu_gen *gen = user;
5270 return generate(p, gen, scop, gen->options);
5273 /* Transform the code in the file called "input" by replacing
5274 * all scops by corresponding GPU code and write the results to "out".
5276 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5277 struct ppcg_options *options,
5278 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5279 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5280 struct gpu_types *types, void *user), void *user)
5282 struct gpu_gen gen;
5283 int r;
5284 int i;
5286 gen.ctx = ctx;
5287 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5288 gen.options = options;
5289 gen.kernel_id = 0;
5290 gen.print = print;
5291 gen.print_user = user;
5292 gen.types.n = 0;
5293 gen.types.name = NULL;
5295 if (options->debug->dump_sizes) {
5296 isl_space *space = isl_space_params_alloc(ctx, 0);
5297 gen.used_sizes = isl_union_map_empty(space);
5300 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5302 if (options->debug->dump_sizes) {
5303 isl_union_map_dump(gen.used_sizes);
5304 isl_union_map_free(gen.used_sizes);
5307 isl_union_map_free(gen.sizes);
5308 for (i = 0; i < gen.types.n; ++i)
5309 free(gen.types.name[i]);
5310 free(gen.types.name);
5312 return r;
5315 /* Compute the set of inner array elements that may have their values
5316 * preserved by "prog". In particular, collect the array elements of
5317 * arrays that are not local to "prog" and remove those elements that
5318 * are definitely killed or definitely written by "prog".
5320 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5322 int i;
5323 isl_union_set *may_persist, *killed;
5324 isl_union_map *must_kill;
5326 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5327 for (i = 0; i < prog->n_array; ++i) {
5328 isl_set *extent;
5330 if (prog->array[i].local)
5331 continue;
5333 extent = isl_set_copy(prog->array[i].extent);
5334 may_persist = isl_union_set_add_set(may_persist, extent);
5337 may_persist = isl_union_set_intersect_params(may_persist,
5338 isl_set_copy(prog->context));
5339 may_persist = isl_union_set_apply(may_persist,
5340 isl_union_map_copy(prog->to_inner));
5341 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5342 killed = isl_union_map_range(must_kill);
5343 must_kill = isl_union_map_copy(prog->must_write);
5344 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5346 may_persist = isl_union_set_subtract(may_persist, killed);
5347 return may_persist;
5350 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5352 struct gpu_prog *prog;
5353 isl_space *space;
5354 isl_map *id;
5356 if (!scop)
5357 return NULL;
5359 prog = isl_calloc_type(ctx, struct gpu_prog);
5360 assert(prog);
5362 prog->ctx = ctx;
5363 prog->scop = scop;
5364 prog->context = isl_set_copy(scop->context);
5365 prog->n_stmts = scop->pet->n_stmt;
5366 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5367 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5368 space = isl_union_map_get_space(prog->any_to_outer);
5369 space = isl_space_set_from_params(space);
5370 space = isl_space_add_dims(space, isl_dim_set, 1);
5371 space = isl_space_map_from_set(space);
5372 id = isl_map_identity(space);
5373 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5374 prog->stmts = extract_stmts(ctx, scop,
5375 prog->context, prog->any_to_outer);
5376 prog->read = isl_union_map_copy(scop->reads);
5377 prog->may_write = isl_union_map_copy(scop->may_writes);
5378 prog->must_write = isl_union_map_copy(scop->must_writes);
5379 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5380 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5381 prog->to_outer = isl_union_map_copy(prog->to_inner);
5382 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5384 if (!prog->stmts)
5385 return gpu_prog_free(prog);
5387 if (collect_array_info(prog) < 0)
5388 return gpu_prog_free(prog);
5389 prog->may_persist = compute_may_persist(prog);
5391 return prog;
5394 void *gpu_prog_free(struct gpu_prog *prog)
5396 if (!prog)
5397 return NULL;
5398 free_array_info(prog);
5399 free_stmts(prog->stmts, prog->n_stmts);
5400 isl_union_map_free(prog->any_to_outer);
5401 isl_union_map_free(prog->to_outer);
5402 isl_union_map_free(prog->to_inner);
5403 isl_union_map_free(prog->read);
5404 isl_union_map_free(prog->may_write);
5405 isl_union_map_free(prog->must_write);
5406 isl_union_map_free(prog->tagged_must_kill);
5407 isl_union_map_free(prog->array_order);
5408 isl_union_set_free(prog->may_persist);
5409 isl_set_free(prog->context);
5410 free(prog);
5411 return NULL;