update isl to version 0.17.1
[ppcg.git] / gpu.c
blob8357d0c298ffc2a59ad0373c22f1255a9d9247aa
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
4 * Copyright 2016 Sven Verdoolaege
6 * Use of this software is governed by the MIT license
8 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
9 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
10 * 91893 Orsay, France
11 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
14 #include <assert.h>
15 #include <stdlib.h>
16 #include <string.h>
18 #include <isl/polynomial.h>
19 #include <isl/union_set.h>
20 #include <isl/aff.h>
21 #include <isl/ilp.h>
22 #include <isl/flow.h>
23 #include <isl/schedule.h>
24 #include <isl/schedule_node.h>
25 #include <isl/options.h>
26 #include <isl/ast_build.h>
28 #include "cpu.h"
29 #include "gpu.h"
30 #include "gpu_array_tile.h"
31 #include "gpu_group.h"
32 #include "gpu_tree.h"
33 #include "schedule.h"
34 #include "ppcg_options.h"
35 #include "print.h"
36 #include "util.h"
38 struct gpu_array_info;
40 /* Return the name of the outer array (of structs) accessed by "access".
42 static const char *get_outer_array_name(__isl_keep isl_map *access)
44 isl_space *space;
45 const char *name;
47 space = isl_space_range(isl_map_get_space(access));
48 while (space && isl_space_is_wrapping(space))
49 space = isl_space_domain(isl_space_unwrap(space));
50 name = isl_space_get_tuple_name(space, isl_dim_set);
51 isl_space_free(space);
53 return name;
56 /* Collect all references to the given array and store pointers to them
57 * in array->refs.
59 static void collect_references(struct gpu_prog *prog,
60 struct gpu_array_info *array)
62 int i;
63 int n;
65 n = 0;
66 for (i = 0; i < prog->n_stmts; ++i) {
67 struct gpu_stmt *stmt = &prog->stmts[i];
68 struct gpu_stmt_access *access;
70 for (access = stmt->accesses; access; access = access->next) {
71 const char *name;
72 name = get_outer_array_name(access->access);
73 if (name && !strcmp(array->name, name))
74 n++;
78 array->n_ref = n;
79 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
80 assert(array->refs);
82 n = 0;
83 for (i = 0; i < prog->n_stmts; ++i) {
84 struct gpu_stmt *stmt = &prog->stmts[i];
85 struct gpu_stmt_access *access;
87 for (access = stmt->accesses; access; access = access->next) {
88 const char *name;
89 name = get_outer_array_name(access->access);
90 if (!name || strcmp(array->name, name))
91 continue;
93 array->refs[n++] = access;
98 /* Compute and return the extent of "array", taking into account the set of
99 * accessed elements.
101 * In particular, the extent in the outer dimension is taken
102 * from "accessed", while the extents in the remaining dimensions
103 * are taken from array->extent.
105 * The extent in the outer dimension cannot be taken from array->extent
106 * because that may be unbounded. Furthermore, even if it is bounded,
107 * it may be larger than the piece of the array that is being accessed.
109 static __isl_give isl_set *compute_extent(struct pet_array *array,
110 __isl_keep isl_set *accessed)
112 int n_index;
113 isl_id *id;
114 isl_set *outer;
115 isl_set *extent;
117 extent = isl_set_copy(array->extent);
119 n_index = isl_set_dim(accessed, isl_dim_set);
120 if (n_index == 0)
121 return extent;
123 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
124 outer = isl_set_copy(accessed);
125 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
126 extent = isl_set_flat_product(outer, extent);
127 id = isl_set_get_tuple_id(accessed);
128 extent = isl_set_set_tuple_id(extent, id);
130 return extent;
133 /* Is the array "array" being extracted a read-only scalar?
135 * That is, is "array" a scalar that is never possibly written to.
136 * An array containing structures is never considered to be a scalar.
138 static int is_read_only_scalar(struct gpu_array_info *array,
139 struct gpu_prog *prog)
141 isl_set *space;
142 isl_union_map *write;
143 int empty;
145 if (array->has_compound_element)
146 return 0;
147 if (array->n_index != 0)
148 return 0;
150 write = isl_union_map_copy(prog->may_write);
151 space = isl_set_universe(isl_space_copy(array->space));
152 write = isl_union_map_intersect_range(write,
153 isl_union_set_from_set(space));
154 empty = isl_union_map_is_empty(write);
155 isl_union_map_free(write);
157 return empty;
160 /* Is "array" only accessed as individual, fixed elements?
161 * That is, does each access to "array" access a single, fixed element?
163 static isl_bool only_fixed_element_accessed(struct gpu_array_info *array)
165 int i;
167 for (i = 0; i < array->n_ref; ++i)
168 if (!array->refs[i]->fixed_element)
169 return isl_bool_false;
171 return isl_bool_true;
174 /* Compute bounds on the host array "pa" based on the corresponding
175 * accessed elements in "arrays"
176 * and collect all references to the array.
177 * Store the results in "info".
179 * If the array is zero-dimensional and does not contain structures,
180 * i.e., if the array is a scalar, we check whether it is read-only.
181 * We also check whether the array is accessed at all.
183 static int extract_array_info(struct gpu_prog *prog,
184 struct gpu_array_info *info, struct pet_array *pa,
185 __isl_keep isl_union_set *arrays)
187 int empty;
188 const char *name;
189 int n_index;
190 isl_multi_pw_aff *bounds;
191 isl_set *accessed, *extent;
193 n_index = isl_set_dim(pa->extent, isl_dim_set);
194 name = isl_set_get_tuple_name(pa->extent);
196 info->space = isl_set_get_space(pa->extent);
197 info->name = strdup(name);
198 info->n_index = n_index;
199 info->linearize = prog->scop->options->linearize_device_arrays;
201 info->type = strdup(pa->element_type);
202 info->size = pa->element_size;
203 info->local = pa->declared && !pa->exposed;
204 info->has_compound_element = pa->element_is_record;
205 info->read_only_scalar = is_read_only_scalar(info, prog);
207 info->declared_extent = isl_set_copy(pa->extent);
208 accessed = isl_union_set_extract_set(arrays,
209 isl_space_copy(info->space));
210 empty = isl_set_is_empty(accessed);
211 extent = compute_extent(pa, accessed);
212 isl_set_free(accessed);
213 info->extent = extent;
214 if (empty < 0)
215 return -1;
216 info->accessed = !empty;
217 bounds = ppcg_size_from_extent(isl_set_copy(extent));
218 bounds = isl_multi_pw_aff_gist(bounds, isl_set_copy(prog->context));
219 if (!bounds)
220 return -1;
221 if (!isl_multi_pw_aff_is_cst(bounds))
222 info->linearize = 1;
223 info->bound = bounds;
225 collect_references(prog, info);
226 info->only_fixed_element = only_fixed_element_accessed(info);
228 return 0;
231 /* Remove independence from the order constraints "order" on array "array".
232 * Since the pairs of iterations in the filter relation of an independence
233 * are guaranteed to be completely independent by the user, there is
234 * no need to ensure that live ranges are ordered along thong pairs.
235 * We make an exception for local variables, though, as the independence
236 * guarantee does not apply to those.
238 * The order constraints are used in two places.
239 * Those on scalars are used in check_scalar_live_ranges to check if
240 * we need to force the scalar to be private. Any non-local scalar
241 * should not be forced scalar if it only appears in independent loops.
242 * Those on non-scalars are added to the coincidence constraints
243 * in compute_schedule because we do not support any array expansion.
244 * Accesses to non-local arrays should not prevent a loop from being
245 * considered coincident so we should indeed remove those constraints
246 * from the order constraints.
248 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
249 struct gpu_array_info *array, __isl_take isl_union_map *order)
251 int i;
253 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
254 struct pet_independence *pi = prog->scop->pet->independences[i];
255 if (isl_union_set_contains(pi->local, array->space))
256 continue;
258 order = isl_union_map_subtract(order,
259 isl_union_map_copy(pi->filter));
262 return order;
265 /* For each array in "prog", store the (untagged) order dependences
266 * derived from the array in array->dep_order.
267 * In particular, consider all references that access the given array
268 * and take the order dependences that have one of these references
269 * as source. (Since an order dependence relates two references to
270 * the same array, the target of these order dependences will also
271 * be one of these references.)
272 * Additionally, store the union of these array->dep_order relations
273 * for all arrays that cannot be mapped to private memory in prog->array_order.
275 void collect_order_dependences(struct gpu_prog *prog)
277 int i;
278 isl_space *space;
279 isl_union_map *accesses;
281 space = isl_union_map_get_space(prog->read);
282 prog->array_order = isl_union_map_empty(space);
284 accesses = isl_union_map_copy(prog->scop->tagged_reads);
285 accesses = isl_union_map_union(accesses,
286 isl_union_map_copy(prog->scop->tagged_may_writes));
287 accesses = isl_union_map_universe(accesses);
288 accesses = isl_union_map_apply_range(accesses,
289 isl_union_map_copy(prog->to_outer));
291 for (i = 0; i < prog->n_array; ++i) {
292 struct gpu_array_info *array = &prog->array[i];
293 isl_set *set;
294 isl_union_set *uset;
295 isl_union_map *order;
297 set = isl_set_universe(isl_space_copy(array->space));
298 uset = isl_union_set_from_set(set);
299 uset = isl_union_map_domain(
300 isl_union_map_intersect_range(isl_union_map_copy(accesses),
301 uset));
302 order = isl_union_map_copy(prog->scop->tagged_dep_order);
303 order = isl_union_map_intersect_domain(order, uset);
304 order = isl_union_map_zip(order);
305 order = isl_union_set_unwrap(isl_union_map_domain(order));
306 order = remove_independences(prog, array, order);
307 array->dep_order = order;
309 if (gpu_array_can_be_private(array))
310 continue;
312 prog->array_order = isl_union_map_union(prog->array_order,
313 isl_union_map_copy(array->dep_order));
316 isl_union_map_free(accesses);
319 /* Construct a gpu_array_info for each array referenced by prog->scop and
320 * collect them in prog->array.
322 * The sizes are based on the extents and the set of possibly accessed
323 * elements by "prog".
324 * If there are any member accesses involved, then they are first mapped
325 * to the outer arrays of structs.
326 * Only extract gpu_array_info entries for these outer arrays.
328 * If we are allowing live range reordering, then also set
329 * the dep_order field. Otherwise leave it NULL.
331 static int collect_array_info(struct gpu_prog *prog)
333 int i;
334 int r = 0;
335 isl_union_set *arrays;
337 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
338 arrays = isl_union_set_union(arrays,
339 isl_union_map_range(isl_union_map_copy(prog->may_write)));
341 arrays = isl_union_set_apply(arrays,
342 isl_union_map_copy(prog->to_outer));
344 arrays = isl_union_set_coalesce(arrays);
346 prog->n_array = prog->scop->pet->n_array;
347 prog->array = isl_calloc_array(prog->ctx,
348 struct gpu_array_info, prog->n_array);
349 assert(prog->array);
350 prog->n_array = 0;
351 for (i = 0; i < prog->scop->pet->n_array; ++i) {
352 isl_bool field;
354 field = isl_set_is_wrapping(prog->scop->pet->arrays[i]->extent);
355 if (field < 0)
356 break;
357 if (field)
358 continue;
359 if (extract_array_info(prog, &prog->array[prog->n_array++],
360 prog->scop->pet->arrays[i], arrays) < 0)
361 r = -1;
363 if (i < prog->scop->pet->n_array)
364 r = -1;
366 isl_union_set_free(arrays);
368 if (prog->scop->options->live_range_reordering)
369 collect_order_dependences(prog);
371 return r;
374 static void free_array_info(struct gpu_prog *prog)
376 int i;
378 for (i = 0; i < prog->n_array; ++i) {
379 free(prog->array[i].type);
380 free(prog->array[i].name);
381 isl_multi_pw_aff_free(prog->array[i].bound);
382 isl_ast_expr_free(prog->array[i].bound_expr);
383 isl_space_free(prog->array[i].space);
384 isl_set_free(prog->array[i].declared_extent);
385 isl_set_free(prog->array[i].extent);
386 isl_ast_expr_free(prog->array[i].declared_size);
387 free(prog->array[i].refs);
388 isl_union_map_free(prog->array[i].dep_order);
390 free(prog->array);
393 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
394 * as an array or through a pointer reference, but as a single data element.
395 * At the moment, scalars are represented as zero-dimensional arrays.
396 * Note that the single data element may be an entire structure.
398 int gpu_array_is_scalar(struct gpu_array_info *array)
400 return array->n_index == 0;
403 /* Can "array" be mapped to private memory?
404 * That is, is it only accessed as individual elements with
405 * constant index expressions?
407 isl_bool gpu_array_can_be_private(struct gpu_array_info *array)
409 if (!array)
410 return isl_bool_error;
411 return array->only_fixed_element;
414 /* Is "array" a read-only scalar?
416 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
418 return array->read_only_scalar;
421 /* Does "array" need to be allocated on the device?
422 * If it is a read-only scalar, then it will be passed as an argument
423 * to the kernel and therefore does not require any allocation.
424 * If this device memory is not accessed at all, then it does not
425 * need to be allocated either.
427 int gpu_array_requires_device_allocation(struct gpu_array_info *array)
429 if (gpu_array_is_read_only_scalar(array))
430 return 0;
431 if (!array->global)
432 return 0;
433 return 1;
436 /* Return the set of parameter values for which the array has a positive
437 * size in all dimensions.
438 * If the sizes are only valid for some parameter values, then those
439 * constraints are also taken into account.
441 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
443 int i;
444 isl_space *space;
445 isl_set *guard;
447 if (!array)
448 return NULL;
450 space = isl_space_params(isl_space_copy(array->space));
451 guard = isl_set_universe(space);
453 for (i = 0; i < array->n_index; ++i) {
454 isl_pw_aff *bound;
455 isl_set *guard_i, *zero;
457 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
458 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
459 zero = isl_pw_aff_zero_set(bound);
460 guard_i = isl_set_subtract(guard_i, zero);
461 guard = isl_set_intersect(guard, guard_i);
464 return guard;
467 /* Internal data structure for extract_size_of_type.
468 * "type" specifies the name of the space that we want to extract.
469 * "res" is used to store the subset of that space.
471 struct ppcg_extract_size_data {
472 const char *type;
473 isl_set *res;
476 /* This function is called for each set in a union_set.
477 * If the name of the set matches data->type, we store the
478 * set in data->res.
480 static isl_stat extract_size_of_type(__isl_take isl_set *size, void *user)
482 struct ppcg_extract_size_data *data = user;
483 const char *name;
485 name = isl_set_get_tuple_name(size);
486 if (name && !strcmp(name, data->type)) {
487 data->res = size;
488 return isl_stat_error;
491 isl_set_free(size);
492 return isl_stat_ok;
495 /* Given a union map { kernel[i] -> *[...] },
496 * return the range in the space called "type" for the kernel with
497 * sequence number "id".
499 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
500 const char *type, int id)
502 isl_space *space;
503 isl_set *dom;
504 isl_union_set *local_sizes;
505 struct ppcg_extract_size_data data = { type, NULL };
507 if (!sizes)
508 return NULL;
510 space = isl_union_map_get_space(sizes);
511 space = isl_space_set_from_params(space);
512 space = isl_space_add_dims(space, isl_dim_set, 1);
513 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
514 dom = isl_set_universe(space);
515 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
517 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
518 isl_union_map_copy(sizes));
519 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
520 isl_union_set_free(local_sizes);
521 return data.res;
524 /* Given a singleton set, extract the first (at most *len) elements
525 * of the single integer tuple into *sizes and update *len if needed.
527 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
529 int i;
530 int dim;
532 if (!set)
533 return;
535 dim = isl_set_dim(set, isl_dim_set);
536 if (dim < *len)
537 *len = dim;
539 for (i = 0; i < *len; ++i) {
540 isl_val *v;
542 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
543 assert(v);
545 sizes[i] = isl_val_get_num_si(v);
546 isl_val_free(v);
549 isl_set_free(set);
552 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
553 * if the option debug->dump_sizes is set.
555 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
556 int *sizes, int len)
558 int i;
559 isl_space *space;
560 isl_map *map;
562 if (!gen->options->debug->dump_sizes)
563 return;
565 space = isl_union_map_get_space(gen->used_sizes);
566 space = isl_space_set_from_params(space);
567 space = isl_space_add_dims(space, isl_dim_set, 1);
568 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
569 space = isl_space_from_domain(space);
570 space = isl_space_add_dims(space, isl_dim_out, len);
571 space = isl_space_set_tuple_name(space, isl_dim_out, type);
573 map = isl_map_universe(space);
574 map = isl_map_fix_si(map, isl_dim_in, 0, id);
575 for (i = 0; i < len; ++i)
576 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
578 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
581 /* Extract user specified "tile" sizes from the "sizes" command line option,
582 * defaulting to option->tile_size in each dimension.
583 * *tile_len contains the maximum number of tile sizes needed.
584 * Update *tile_len to the number of specified tile sizes, if any, and
585 * return a pointer to the tile sizes (or NULL on error).
586 * Add the effectively used sizes to gen->used_sizes.
588 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
590 int n;
591 int *tile_size;
592 isl_set *size;
594 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
595 if (!tile_size)
596 return NULL;
597 for (n = 0; n < *tile_len; ++n)
598 tile_size[n] = gen->options->tile_size;
600 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
601 read_sizes_from_set(size, tile_size, tile_len);
602 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
604 return tile_size;
607 /* Extract user specified "block" sizes from the "sizes" command line option,
608 * after filling in some potentially useful defaults.
610 static void read_block_sizes(struct ppcg_kernel *kernel,
611 __isl_keep isl_union_map *sizes)
613 isl_set *size;
615 if (kernel->n_block > 3)
616 kernel->n_block = 3;
617 switch (kernel->n_block) {
618 case 1:
619 kernel->block_dim[0] = 512;
620 break;
621 case 2:
622 kernel->block_dim[0] = 32;
623 kernel->block_dim[1] = 16;
624 break;
625 default:
626 kernel->block_dim[0] = 32;
627 kernel->block_dim[1] = 4;
628 kernel->block_dim[2] = 4;
629 break;
632 size = extract_sizes(sizes, "block", kernel->id);
633 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
636 /* Extract user specified "grid" sizes from the "sizes" command line option,
637 * after filling in some potentially useful defaults.
639 static void read_grid_sizes(struct ppcg_kernel *kernel,
640 __isl_keep isl_union_map *sizes)
642 isl_set *size;
644 if (kernel->n_grid > 2)
645 kernel->n_grid = 2;
646 switch (kernel->n_grid) {
647 case 1:
648 kernel->grid_dim[0] = 32768;
649 break;
650 default:
651 kernel->grid_dim[0] = 256;
652 kernel->grid_dim[1] = 256;
653 break;
656 size = extract_sizes(sizes, "grid", kernel->id);
657 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
660 /* Extract user specified grid and block sizes from the gen->sizes
661 * command line option after filling in some potentially useful defaults.
662 * Store the extracted sizes in "kernel".
663 * Add the effectively used sizes to gen->used_sizes.
665 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
666 struct gpu_gen *gen)
668 read_block_sizes(kernel, gen->sizes);
669 read_grid_sizes(kernel, gen->sizes);
670 set_used_sizes(gen, "block", kernel->id,
671 kernel->block_dim, kernel->n_block);
672 set_used_sizes(gen, "grid", kernel->id,
673 kernel->grid_dim, kernel->n_grid);
676 static void *free_stmts(struct gpu_stmt *stmts, int n)
678 int i;
680 if (!stmts)
681 return NULL;
683 for (i = 0; i < n; ++i) {
684 struct gpu_stmt_access *access, *next;
686 for (access = stmts[i].accesses; access; access = next) {
687 next = access->next;
688 isl_id_free(access->ref_id);
689 isl_map_free(access->access);
690 isl_map_free(access->tagged_access);
691 free(access);
694 isl_id_free(stmts[i].id);
696 free(stmts);
698 return NULL;
701 /* Add parameters p[i] with identifiers "ids" to "set",
702 * with bounds to 0 <= p[i] < size[i].
704 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
705 int *size, __isl_keep isl_id_list *ids)
707 int i, len;
708 unsigned nparam;
710 len = isl_id_list_n_id(ids);
711 nparam = isl_set_dim(set, isl_dim_param);
712 set = isl_set_add_dims(set, isl_dim_param, len);
714 for (i = 0; i < len; ++i) {
715 isl_id *id;
717 id = isl_id_list_get_id(ids, i);
718 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
719 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
720 set = isl_set_upper_bound_si(set, isl_dim_param,
721 nparam + i, size[i] - 1);
724 return set;
727 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
728 * with
730 * { : 0 <= p[i] < size[i] }
732 * or an overapproximation.
734 static __isl_give isl_set *add_bounded_parameters_dynamic(
735 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
736 __isl_keep isl_id_list *ids)
738 int i, len;
739 unsigned nparam;
740 isl_space *space;
741 isl_local_space *ls;
743 len = isl_multi_pw_aff_dim(size, isl_dim_out);
744 nparam = isl_set_dim(set, isl_dim_param);
745 set = isl_set_add_dims(set, isl_dim_param, len);
747 for (i = 0; i < len; ++i) {
748 isl_id *id;
750 id = isl_id_list_get_id(ids, i);
751 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
754 space = isl_space_params(isl_set_get_space(set));
755 ls = isl_local_space_from_space(space);
756 for (i = 0; i < len; ++i) {
757 isl_pw_aff *param, *size_i, *zero;
758 isl_set *bound;
760 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
761 isl_dim_param, nparam + i);
763 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
764 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
765 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
766 set = isl_set_intersect_params(set, bound);
768 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
769 bound = isl_pw_aff_ge_set(param, zero);
770 set = isl_set_intersect_params(set, bound);
772 isl_local_space_free(ls);
774 return set;
777 /* Return the union of all tagged access relations in the group.
779 static __isl_give isl_union_map *group_tagged_access_relation(
780 struct gpu_array_ref_group *group)
782 int i;
783 isl_union_map *access;
785 access = isl_union_map_empty(isl_map_get_space(group->access));
786 for (i = 0; i < group->n_ref; ++i) {
787 isl_map *map_i;
789 map_i = isl_map_copy(group->refs[i]->tagged_access);
790 access = isl_union_map_union(access,
791 isl_union_map_from_map(map_i));
794 return access;
797 /* Return the extent of "array", recomputed from the bounds.
798 * The recomputed extent may be simpler than the original extent.
800 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
802 int i;
803 isl_id *id;
804 isl_space *space;
805 isl_local_space *ls;
806 isl_set *extent;
808 id = isl_set_get_tuple_id(array->extent);
809 space = isl_set_get_space(array->extent);
810 extent = isl_set_universe(isl_space_copy(space));
811 ls = isl_local_space_from_space(space);
812 for (i = 0; i < array->n_index; ++i) {
813 isl_pw_aff *bound;
814 isl_aff *aff;
815 isl_pw_aff *index;
816 isl_set *lt;
818 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
820 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
821 isl_dim_set, i);
822 index = isl_pw_aff_from_aff(aff);
823 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
824 bound = isl_pw_aff_from_range(bound);
825 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
826 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
827 isl_id_copy(id));
828 lt = isl_pw_aff_lt_set(index, bound);
829 extent = isl_set_intersect(extent, lt);
831 isl_local_space_free(ls);
832 isl_id_free(id);
834 return extent;
837 /* Return a map from the first group->shared_tile->depth dimensions
838 * of the computed schedule to the array tile in
839 * global memory that corresponds to the shared memory copy.
841 * In particular, return a map
843 * { D[i] -> A[a] }
845 * with constraints
847 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
849 * and
851 * 0 <= a <= array_size - 1 (2)
853 * Note that if some stride has been detected (i.e., when
854 * group->shared_tile->bound[i].shift is set), then a in (1) refers
855 * to the shifted and scaled down version.
857 * Constraints (1) are obtained by mapping the size constraints on the
858 * shared/private memory tile back to the access relation.
859 * Constraints (2) are obtained from the (recomputed) extent.
861 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
863 int i;
864 int n_index = group->array->n_index;
865 isl_map *tile;
866 isl_space *space;
867 isl_set *local;
868 isl_set *extent;
870 space = isl_multi_aff_get_space(group->shared_tile->tiling);
871 space = isl_space_range(space);
872 local = isl_set_universe(space);
873 for (i = 0; i < n_index; ++i) {
874 isl_val *bound;
876 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
877 bound = isl_val_copy(group->shared_tile->bound[i].size);
878 bound = isl_val_sub_ui(bound, 1);
879 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
881 local = isl_set_preimage_multi_aff(local,
882 isl_multi_aff_copy(group->shared_tile->tiling));
883 tile = isl_set_unwrap(local);
884 extent = array_extent(group->array);
885 tile = isl_map_intersect_range(tile, extent);
887 return tile;
890 /* Given a mapping "iterator_map" from the AST schedule to a domain,
891 * return the corresponding mapping from the AST schedule to
892 * to the outer kernel->copy_schedule_dim dimensions of
893 * the schedule computed by PPCG for this kernel.
895 * Note that kernel->copy_schedule_dim is at least as large as
896 * the largest depth of any array reference group associated to the kernel.
897 * This is needed as the returned schedule is used to extract a mapping
898 * to the outer tile->depth dimensions in transform_index.
900 static __isl_give isl_pw_multi_aff *compute_sched_to_copy(
901 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
903 isl_union_pw_multi_aff *upma;
904 isl_pw_multi_aff *pma;
905 isl_space *space;
907 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
908 space = isl_space_from_domain(space);
909 space = isl_space_add_dims(space, isl_dim_out,
910 kernel->copy_schedule_dim);
912 upma = isl_union_pw_multi_aff_copy(kernel->copy_schedule);
913 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
914 isl_union_pw_multi_aff_free(upma);
916 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
919 /* If max_shared_memory is not set to infinity (-1), then make
920 * sure that the total amount of shared memory required by the
921 * array reference groups mapped to shared memory by "kernel"
922 * is no larger than this maximum.
924 * We apply a greedy approach and discard (keep in global memory)
925 * those groups that would result in a total memory size that
926 * is larger than the maximum.
928 * This function should be called after any function that may
929 * affect the decision on whether to place a reference group
930 * in private, shared or global memory.
932 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
934 int i, j;
935 isl_val *left, *size;
937 if (kernel->options->max_shared_memory < 0)
938 return;
940 left = isl_val_int_from_si(kernel->ctx,
941 kernel->options->max_shared_memory);
943 for (i = 0; i < kernel->n_array; ++i) {
944 struct gpu_local_array_info *local = &kernel->array[i];
946 for (j = 0; j < local->n_group; ++j) {
947 struct gpu_array_ref_group *group;
948 enum ppcg_group_access_type type;
950 group = local->groups[j];
951 type = gpu_array_ref_group_type(group);
952 if (type != ppcg_access_shared)
953 continue;
955 size = gpu_array_tile_size(group->shared_tile);
956 size = isl_val_mul_ui(size, local->array->size);
958 if (isl_val_le(size, left)) {
959 left = isl_val_sub(left, size);
960 continue;
962 isl_val_free(size);
964 group->shared_tile =
965 gpu_array_tile_free(group->shared_tile);
969 isl_val_free(left);
972 /* Mark all arrays of "kernel" that have an array reference group
973 * that is not mapped to private or shared memory as
974 * accessing the corresponding global device memory.
976 static void mark_global_arrays(struct ppcg_kernel *kernel)
978 int i, j;
980 for (i = 0; i < kernel->n_array; ++i) {
981 struct gpu_local_array_info *local = &kernel->array[i];
983 if (local->global)
984 continue;
985 for (j = 0; j < local->n_group; ++j) {
986 if (gpu_array_ref_group_tile(local->groups[j]))
987 continue;
989 local->global = 1;
990 local->array->global = 1;
991 break;
996 /* Compute a tiling for all the array reference groups in "kernel".
998 static void compute_group_tilings(struct ppcg_kernel *kernel)
1000 int i, j;
1002 for (i = 0; i < kernel->n_array; ++i) {
1003 struct gpu_local_array_info *array = &kernel->array[i];
1005 for (j = 0; j < array->n_group; ++j)
1006 gpu_array_ref_group_compute_tiling(array->groups[j]);
1010 /* Compute the effective grid size as a list of the sizes in each dimension.
1012 * The grid size specified by the user or set by default
1013 * in read_grid_sizes() and applied by the block filter,
1014 * may be too large for the given code in the sense that
1015 * it may contain blocks that don't need to execute anything.
1016 * We therefore don't return this grid size, but instead the
1017 * smallest grid size that ensures that all blocks that actually
1018 * execute code are included in the grid.
1020 * We first extract a description of the grid, i.e., the possible values
1021 * of the block ids, from the domain elements in "domain" and
1022 * kernel->block_filter.
1023 * The block ids are parameters in kernel->block_filter.
1024 * We simply need to change them into set dimensions.
1026 * Then, for each block dimension, we compute the maximal value of the block id
1027 * and add one.
1029 static __isl_give isl_multi_pw_aff *extract_grid_size(
1030 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1032 int i;
1033 isl_set *grid;
1034 isl_set *context;
1035 isl_multi_pw_aff *size;
1037 domain = isl_union_set_intersect(domain,
1038 isl_union_set_copy(kernel->block_filter));
1039 grid = isl_union_set_params(domain);
1040 grid = isl_set_from_params(grid);
1041 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1042 for (i = 0; i < kernel->n_grid; ++i) {
1043 int pos;
1044 isl_id *id;
1046 id = isl_id_list_get_id(kernel->block_ids, i);
1047 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1048 isl_id_free(id);
1049 assert(pos >= 0);
1050 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1051 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1054 grid = isl_set_coalesce(grid);
1055 size = ppcg_size_from_extent(grid);
1056 context = isl_set_params(isl_set_copy(kernel->context));
1057 return isl_multi_pw_aff_gist(size, context);
1060 /* Compute the size of a fixed bounding box around the origin and "set",
1061 * where "set" is assumed to contain only non-negative elements,
1062 * and store the results in "size".
1063 * In particular, compute the maximal value of "set" in each direction
1064 * and add one.
1066 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1068 int i, n;
1069 isl_local_space *ls;
1070 isl_aff *obj;
1072 n = isl_set_dim(set, isl_dim_set);
1073 ls = isl_local_space_from_space(isl_set_get_space(set));
1074 obj = isl_aff_zero_on_domain(ls);
1075 for (i = 0; i < n; ++i) {
1076 isl_val *max;
1078 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1079 max = isl_set_max_val(set, obj);
1080 size[i] = isl_val_get_num_si(max) + 1;
1081 isl_val_free(max);
1082 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1084 isl_aff_free(obj);
1085 isl_set_free(set);
1088 /* Compute the effective block size as a list of the sizes in each dimension
1089 * and store the sizes in kernel->block_dim.
1091 * The block size specified by the user or set by default
1092 * in read_block_sizes() and applied by the thread filter,
1093 * may be too large for the given code in the sense that
1094 * it may contain threads that don't need to execute anything.
1095 * We therefore update this block size in kernel->block_dim
1096 * to the smallest block size that ensures that all threads
1097 * that actually execute code are included in the block.
1099 * The set of possible values of the thread ids is obtained from
1100 * the domain elements "domain" and kernel->thread_filter.
1101 * The current implementation eliminates all parameters, ensuring
1102 * that the size is a fixed constant in each dimension.
1103 * In principle we could also compute parametric sizes.
1104 * We would have to make sure to project out all b%d and t%d parameters,
1105 * however.
1107 static isl_stat extract_block_size(struct ppcg_kernel *kernel,
1108 __isl_take isl_union_set *domain)
1110 int i;
1111 int nparam;
1112 isl_set *block;
1114 domain = isl_union_set_intersect(domain,
1115 isl_union_set_copy(kernel->thread_filter));
1116 block = isl_union_set_params(domain);
1117 block = isl_set_from_params(block);
1118 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1119 for (i = 0; i < kernel->n_block; ++i) {
1120 int pos;
1121 isl_id *id;
1123 if (!block)
1124 return isl_stat_error;
1126 id = isl_id_list_get_id(kernel->thread_ids, i);
1127 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1128 isl_id_free(id);
1129 if (pos < 0)
1130 isl_die(isl_set_get_ctx(block), isl_error_internal,
1131 "missing constraints on thread identifier",
1132 block = isl_set_free(block));
1133 block = isl_set_equate(block, isl_dim_param, pos,
1134 isl_dim_set, i);
1136 nparam = isl_set_dim(block, isl_dim_param);
1137 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1139 if (!block)
1140 return isl_stat_error;
1142 extract_fixed_size(block, kernel->block_dim);
1144 return isl_stat_ok;
1147 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1149 int i, j;
1151 if (!kernel)
1152 return NULL;
1154 isl_id_list_free(kernel->block_ids);
1155 isl_id_list_free(kernel->thread_ids);
1156 isl_multi_pw_aff_free(kernel->grid_size);
1157 isl_ast_expr_free(kernel->grid_size_expr);
1158 isl_set_free(kernel->context);
1159 isl_union_set_free(kernel->core);
1160 isl_union_set_free(kernel->arrays);
1161 isl_union_pw_multi_aff_free(kernel->contraction);
1162 isl_union_set_free(kernel->expanded_domain);
1163 isl_space_free(kernel->space);
1164 isl_ast_node_free(kernel->tree);
1165 isl_union_set_free(kernel->block_filter);
1166 isl_union_set_free(kernel->thread_filter);
1167 isl_union_pw_multi_aff_free(kernel->copy_schedule);
1168 isl_union_set_free(kernel->sync_writes);
1170 for (i = 0; i < kernel->n_array; ++i) {
1171 struct gpu_local_array_info *array = &kernel->array[i];
1173 for (j = 0; j < array->n_group; ++j)
1174 gpu_array_ref_group_free(array->groups[j]);
1175 free(array->groups);
1177 isl_multi_pw_aff_free(array->bound);
1178 isl_ast_expr_free(array->bound_expr);
1180 free(kernel->array);
1182 for (i = 0; i < kernel->n_var; ++i) {
1183 free(kernel->var[i].name);
1184 isl_vec_free(kernel->var[i].size);
1186 free(kernel->var);
1188 free(kernel);
1190 return NULL;
1193 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1195 static void ppcg_kernel_free_wrap(void *user)
1197 struct ppcg_kernel *kernel = user;
1199 ppcg_kernel_free(kernel);
1202 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1203 struct ppcg_kernel_var *var)
1205 int j;
1206 struct gpu_array_tile *tile;
1207 isl_printer *p;
1209 var->array = group->array;
1211 var->type = gpu_array_ref_group_type(group);
1212 tile = gpu_array_ref_group_tile(group);
1214 p = isl_printer_to_str(ctx);
1215 p = gpu_array_ref_group_print_name(group, p);
1216 var->name = isl_printer_get_str(p);
1217 isl_printer_free(p);
1219 var->size = isl_vec_alloc(ctx, group->array->n_index);
1221 for (j = 0; j < group->array->n_index; ++j)
1222 var->size = isl_vec_set_element_val(var->size, j,
1223 isl_val_copy(tile->bound[j].size));
1226 static int create_kernel_vars(struct ppcg_kernel *kernel)
1228 int i, j, n;
1230 n = 0;
1231 for (i = 0; i < kernel->n_array; ++i) {
1232 struct gpu_local_array_info *array = &kernel->array[i];
1234 for (j = 0; j < array->n_group; ++j) {
1235 struct gpu_array_ref_group *group = array->groups[j];
1236 enum ppcg_group_access_type type;
1238 type = gpu_array_ref_group_type(group);
1239 if (type != ppcg_access_global)
1240 ++n;
1244 kernel->n_var = n;
1245 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1246 if (!kernel->var)
1247 return -1;
1249 n = 0;
1250 for (i = 0; i < kernel->n_array; ++i) {
1251 struct gpu_local_array_info *array = &kernel->array[i];
1253 for (j = 0; j < array->n_group; ++j) {
1254 struct gpu_array_ref_group *group = array->groups[j];
1255 enum ppcg_group_access_type type;
1257 type = gpu_array_ref_group_type(group);
1258 if (type == ppcg_access_global)
1259 continue;
1260 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1261 ++n;
1265 return 0;
1268 /* Replace "pa" by the zero function defined over the universe domain
1269 * in the space of "pa".
1271 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1273 isl_space *space;
1274 isl_aff *zero;
1276 space = isl_space_domain(isl_pw_aff_get_space(pa));
1277 isl_pw_aff_free(pa);
1278 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1280 return isl_pw_aff_from_aff(zero);
1283 /* The sizes of the arrays on the host that have been computed by
1284 * extract_array_info may depend on the parameters. Use the extra
1285 * constraints on the parameters that are valid at "host_domain"
1286 * to simplify these expressions and store the results in kernel->array.
1288 * We only need these localized bounds for arrays that are accessed
1289 * by the current kernel. If we have found at least one reference group
1290 * then the array is accessed by the kernel.
1292 * The resulting sizes may be functions that are nowhere defined
1293 * in case the access function cannot possibly access anything inside
1294 * the kernel for some reason. If so, they are replaced by the zero
1295 * function. Since the access function cannot actually access anything,
1296 * there is no harm in printing the array sizes as zero.
1298 static void localize_bounds(struct ppcg_kernel *kernel,
1299 __isl_keep isl_set *host_domain)
1301 int i, j;
1302 isl_set *context;
1304 context = isl_set_copy(host_domain);
1305 context = isl_set_params(context);
1307 for (i = 0; i < kernel->n_array; ++i) {
1308 struct gpu_local_array_info *local = &kernel->array[i];
1309 isl_multi_pw_aff *bound;
1310 int n_index;
1312 if (local->n_group == 0)
1313 continue;
1315 n_index = local->array->n_index;
1316 bound = isl_multi_pw_aff_copy(local->array->bound);
1318 for (j = 0; j < n_index; ++j) {
1319 isl_pw_aff *pwaff;
1320 int empty;
1322 pwaff = isl_multi_pw_aff_get_pw_aff(bound, j);
1323 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1324 empty = isl_pw_aff_is_empty(pwaff);
1325 if (empty < 0)
1326 pwaff = isl_pw_aff_free(pwaff);
1327 else if (empty)
1328 pwaff = set_universally_zero(pwaff);
1329 bound = isl_multi_pw_aff_set_pw_aff(bound, j, pwaff);
1332 local->n_index = n_index;
1333 local->bound = bound;
1335 isl_set_free(context);
1338 /* Create the array of gpu_local_array_info structures "array"
1339 * inside "kernel". The number of elements in this array is
1340 * the same as the number of arrays in "prog".
1341 * Initialize the "array" field of each local array to point
1342 * to the corresponding array in "prog".
1344 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1345 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1347 int i;
1348 isl_ctx *ctx;
1350 ctx = isl_set_get_ctx(prog->context);
1351 kernel->array = isl_calloc_array(ctx,
1352 struct gpu_local_array_info, prog->n_array);
1353 if (!kernel->array)
1354 return ppcg_kernel_free(kernel);
1355 kernel->n_array = prog->n_array;
1357 for (i = 0; i < prog->n_array; ++i)
1358 kernel->array[i].array = &prog->array[i];
1360 return kernel;
1363 /* Does "kernel" need to be passed an argument corresponding to array "i"?
1365 * The argument is only needed if the kernel accesses this device memory.
1367 int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1369 return kernel->array[i].global;
1372 /* Find the element in gen->stmt that has the given "id".
1373 * Return NULL if no such gpu_stmt can be found.
1375 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1377 int i;
1379 for (i = 0; i < prog->n_stmts; ++i) {
1380 if (id == prog->stmts[i].id)
1381 break;
1384 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1387 void ppcg_kernel_stmt_free(void *user)
1389 struct ppcg_kernel_stmt *stmt = user;
1391 if (!stmt)
1392 return;
1394 switch (stmt->type) {
1395 case ppcg_kernel_copy:
1396 isl_ast_expr_free(stmt->u.c.index);
1397 isl_ast_expr_free(stmt->u.c.local_index);
1398 break;
1399 case ppcg_kernel_domain:
1400 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1401 break;
1402 case ppcg_kernel_sync:
1403 break;
1406 free(stmt);
1409 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1410 * to "ref_id".
1412 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1413 __isl_keep isl_id *ref_id)
1415 struct gpu_stmt_access *access;
1417 for (access = accesses; access; access = access->next)
1418 if (access->ref_id == ref_id)
1419 return access;
1421 return NULL;
1424 /* Return the index of the array called "name" in the list of arrays.
1426 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1428 int i;
1430 for (i = 0; i < kernel->n_array; ++i)
1431 if (!strcmp(name, kernel->array[i].array->name))
1432 return i;
1434 return -1;
1437 /* Internal data structure for the index and AST expression transformation
1438 * callbacks for pet_stmt_build_ast_exprs.
1440 * "kernel" is the kernel for which are computing AST expressions and
1441 * may be NULL if we are not inside a kernel.
1442 * "accesses" is the list of gpu_stmt_access in the statement.
1443 * "iterator_map" expresses the statement iterators in terms of
1444 * the AST loop iterators.
1445 * "sched2copy" expresses the outer copy_schedule_dim dimensions of
1446 * the kernel schedule in terms of the AST loop iterators and
1447 * may be NULL if we are not inside a kernel.
1449 * The following fields are set in transform_index and used in transform_expr.
1450 * "array" is the array that is being accessed.
1451 * "global" is set if the global array is accessed (rather than
1452 * shared/private memory).
1453 * "local_array" refers to information on the array specialized
1454 * to the current kernel.
1456 struct ppcg_transform_data {
1457 struct ppcg_kernel *kernel;
1458 struct gpu_stmt_access *accesses;
1459 isl_pw_multi_aff *iterator_map;
1460 isl_pw_multi_aff *sched2copy;
1462 struct gpu_array_info *array;
1463 int global;
1464 struct gpu_local_array_info *local_array;
1467 /* Return a pointer to the gpu_array_ref_group in "local"
1468 * that contains the reference "access".
1469 * Return NULL if no such group can be found.
1471 static struct gpu_array_ref_group *find_ref_group(
1472 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1474 int i, j;
1476 for (i = 0; i < local->n_group; ++i) {
1477 struct gpu_array_ref_group *group = local->groups[i];
1479 for (j = 0; j < group->n_ref; ++j)
1480 if (group->refs[j] == access)
1481 return group;
1484 return NULL;
1487 /* Given an index expression "index" of the form
1489 * L -> F(A),
1491 * with F(A) either A or some subfield of A and L the AST loop iterators,
1492 * and a tiling "tiling" of the form
1494 * [L -> A] -> T
1496 * apply the tiling to the outer array in the index expression to obtain
1498 * L -> T(A)
1500 * If F(A) is some subfield of A, then separate the member access
1501 * into the base index expression and the field index expression,
1502 * apply the tiling to the base index expression and combine the result
1503 * with the field index expression.
1505 * If F(A) is A, then modify index to keep track of the iterators
1507 * L -> [L -> A]
1509 * and combine the result with the tiling to obtain a tiled index expression
1510 * in terms of the AST loop iterators
1512 * L -> T
1514 static __isl_give isl_multi_pw_aff *tile_outer(
1515 __isl_take isl_multi_pw_aff *index, __isl_take isl_multi_pw_aff *tiling)
1517 isl_bool is_wrapping;
1518 isl_space *space;
1519 isl_multi_pw_aff *mpa;
1521 is_wrapping = isl_multi_pw_aff_range_is_wrapping(index);
1522 if (is_wrapping < 0)
1523 goto error;
1524 if (is_wrapping) {
1525 isl_multi_pw_aff *field;
1527 field = isl_multi_pw_aff_copy(index);
1528 field = isl_multi_pw_aff_range_factor_range(field);
1529 index = isl_multi_pw_aff_range_factor_domain(index);
1530 index = tile_outer(index, tiling);
1531 return isl_multi_pw_aff_range_product(index, field);
1534 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1535 space = isl_space_map_from_set(space);
1536 mpa = isl_multi_pw_aff_identity(space);
1537 index = isl_multi_pw_aff_range_product(mpa, index);
1538 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1540 return index;
1541 error:
1542 isl_multi_pw_aff_free(index);
1543 isl_multi_pw_aff_free(tiling);
1544 return NULL;
1547 /* Index transformation callback for pet_stmt_build_ast_exprs.
1549 * "index" expresses the array indices in terms of statement iterators
1551 * We first reformulate "index" in terms of the AST loop iterators.
1552 * Then we check if we are accessing the global array or
1553 * a shared/private copy. In particular, if we are not inside a kernel
1554 * then we must be accessing a global array.
1555 * In the former case, we simply return
1556 * the updated index. If "index" is an affine expression rather
1557 * than an array access, then we also return the updated index here.
1559 * If no reference groups have been computed for the array,
1560 * then we can only be accessing the global array.
1562 * Otherwise, we apply the tiling to the index.
1563 * This tiling is of the form
1565 * [D -> A] -> T
1567 * where D corresponds to the outer tile->depth dimensions of
1568 * the kernel schedule.
1569 * The index is of the form
1571 * L -> A
1573 * We update the tiling to refer to the AST loop iterators
1575 * [L -> A] -> T
1577 * and combine it with the index to obtain a tiled index expression in terms
1578 * of the AST loop iterators
1580 * L -> T
1582 * Note that while the tiling applies directly to an outer array.
1583 * the index may refer to some subfield of this outer array.
1584 * In such cases, the result will refer to the same subfield of the tile.
1585 * That is, an index expression of the form L -> F(A) will be transformed
1586 * into an index expression of the form L -> F(T).
1588 static __isl_give isl_multi_pw_aff *transform_index(
1589 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1590 void *user)
1592 struct ppcg_transform_data *data = user;
1593 struct gpu_stmt_access *access;
1594 struct gpu_array_ref_group *group;
1595 struct gpu_array_tile *tile;
1596 isl_pw_multi_aff *iterator_map;
1597 int i;
1598 int dim;
1599 const char *name;
1600 isl_space *space;
1601 isl_multi_pw_aff *tiling;
1602 isl_pw_multi_aff *pma;
1603 isl_multi_pw_aff *mpa;
1604 isl_pw_multi_aff *sched2depth;
1606 data->array = NULL;
1608 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1609 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1611 if (!data->kernel)
1612 return index;
1614 access = find_access(data->accesses, ref_id);
1615 if (!access)
1616 return index;
1617 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1618 return index;
1620 name = get_outer_array_name(access->access);
1621 i = find_array_index(data->kernel, name);
1622 if (i < 0)
1623 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1624 "cannot find array",
1625 return isl_multi_pw_aff_free(index));
1626 data->local_array = &data->kernel->array[i];
1627 data->array = data->local_array->array;
1629 group = find_ref_group(data->local_array, access);
1630 if (!group) {
1631 data->global = 1;
1632 return index;
1635 tile = gpu_array_ref_group_tile(group);
1636 data->global = !tile;
1637 if (!tile)
1638 return index;
1640 space = isl_space_domain(isl_multi_aff_get_space(tile->tiling));
1641 space = isl_space_range(isl_space_unwrap(space));
1642 space = isl_space_map_from_set(space);
1643 pma = isl_pw_multi_aff_identity(space);
1644 sched2depth = isl_pw_multi_aff_copy(data->sched2copy);
1645 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1646 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1647 tile->depth, dim - tile->depth);
1648 pma = isl_pw_multi_aff_product(sched2depth, pma);
1649 tiling = isl_multi_pw_aff_from_multi_aff(
1650 isl_multi_aff_copy(tile->tiling));
1651 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1653 index = tile_outer(index, tiling);
1655 return index;
1658 /* Dereference "expr" by adding an index [0].
1659 * The original "expr" is assumed not to have any indices.
1661 * If "expr" is a member access, then the dereferencing needs
1662 * to be applied to the structure argument of this member access.
1664 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1666 isl_ctx *ctx;
1667 isl_ast_expr *arg0, *res;
1668 isl_ast_expr_list *list;
1670 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1671 if (!arg0)
1672 return isl_ast_expr_free(expr);
1673 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1674 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1675 isl_ast_expr *arg;
1677 arg = isl_ast_expr_get_op_arg(arg0, 0);
1678 arg = dereference(arg);
1679 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1680 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1682 return expr;
1684 isl_ast_expr_free(arg0);
1686 ctx = isl_ast_expr_get_ctx(expr);
1687 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1688 list = isl_ast_expr_list_from_ast_expr(res);
1689 res = isl_ast_expr_get_op_arg(expr, 0);
1690 res = isl_ast_expr_access(res, list);
1691 isl_ast_expr_free(expr);
1693 return res;
1696 /* Linearize the index expression "expr" based on the array bounds
1697 * of "array".
1699 * That is, transform expression
1701 * A[i_0][i_1]...[i_n]
1703 * to
1705 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1707 * where b_0, b_1, ..., b_n are the bounds on the array.
1709 * If the base of "expr" is a member access, then the linearization needs
1710 * to be applied to the structure argument of this member access.
1712 * In the base case, if "expr" has no arguments (other than the name of
1713 * the array), then we are passing an entire array to a function.
1714 * In this case, there is nothing to linearize.
1715 * Note that at this point an expression with no arguments can
1716 * only be an entire array because the scalar case and
1717 * the case of single struct are handled by the caller.
1719 * If the number of specified index expressions in "expr"
1720 * is smaller than the dimension of the accessed array,
1721 * then the missing i_j also do not appear in the linearized expression.
1722 * Furthermore, since such an expression does not refer to a single
1723 * element while the default linearized expression would refer to
1724 * a single element, we return the expression
1726 * A + (..((i_0 * b_1 + i_1) ... ) * b_l + i_l)
1728 * instead. Note that because of the special case handling above,
1729 * we can assume here that there is at least one index expression.
1731 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1732 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1734 int i, n;
1735 isl_ast_expr *arg0;
1736 isl_ast_expr *res;
1737 isl_ast_expr_list *list;
1739 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1740 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1741 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1742 isl_ast_expr *arg;
1744 arg = isl_ast_expr_get_op_arg(arg0, 0);
1745 arg = gpu_local_array_info_linearize_index(array, arg);
1746 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1747 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1749 return expr;
1751 isl_ast_expr_free(arg0);
1753 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1754 return expr;
1756 n = isl_ast_expr_get_op_n_arg(expr);
1757 res = isl_ast_expr_get_op_arg(expr, 1);
1758 for (i = 1; i < array->n_index; ++i) {
1759 isl_ast_expr *expr_i;
1761 expr_i = isl_ast_expr_get_op_arg(array->bound_expr, 1 + i);
1762 res = isl_ast_expr_mul(res, expr_i);
1764 if (i + 1 >= n)
1765 continue;
1766 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1767 res = isl_ast_expr_add(res, expr_i);
1770 if (1 + array->n_index > n) {
1771 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1772 } else {
1773 list = isl_ast_expr_list_from_ast_expr(res);
1774 res = isl_ast_expr_get_op_arg(expr, 0);
1775 res = isl_ast_expr_access(res, list);
1778 isl_ast_expr_free(expr);
1780 return res;
1783 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1785 * If the AST expression refers to an array that is not accessed
1786 * at all, then this means the value of the expression is not used,
1787 * so we might as well print zero (NULL pointer) instead.
1789 * If the AST expression refers to a global scalar that is not
1790 * a read-only scalar, then its address was passed to the kernel and
1791 * we need to dereference it.
1793 * If the AST expression refers to an access to a global array,
1794 * then we linearize the access exploiting the bounds in data->local_array.
1796 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1797 __isl_keep isl_id *id, void *user)
1799 struct ppcg_transform_data *data = user;
1801 if (!data->array)
1802 return expr;
1803 if (!data->array->accessed) {
1804 isl_ctx *ctx;
1806 ctx = isl_ast_expr_get_ctx(expr);
1807 isl_ast_expr_free(expr);
1808 return isl_ast_expr_from_val(isl_val_zero(ctx));
1810 if (gpu_array_is_read_only_scalar(data->array))
1811 return expr;
1812 if (!data->global)
1813 return expr;
1814 if (data->array->n_index == 0)
1815 return dereference(expr);
1816 if (!data->array->linearize)
1817 return expr;
1819 return gpu_local_array_info_linearize_index(data->local_array, expr);
1822 /* This function is called for each instance of a user statement
1823 * in the kernel "kernel", identified by "gpu_stmt".
1824 * "kernel" may be NULL if we are not inside a kernel.
1826 * We attach a struct ppcg_kernel_stmt to the "node", containing
1827 * a computed AST expression for each access, through an annotation
1828 * with name "user".
1829 * These AST expressions are computed from iterator_map,
1830 * which expresses the domain
1831 * elements in terms of the generated loops, and sched2copy,
1832 * which expresses the outer copy_schedule_dim dimensions of
1833 * the kernel schedule computed by PPCG in terms of the generated loops.
1835 static __isl_give isl_ast_node *create_domain_leaf(
1836 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1837 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1839 struct ppcg_transform_data data;
1840 struct ppcg_kernel_stmt *stmt;
1841 isl_ctx *ctx;
1842 isl_id *id;
1843 isl_pw_multi_aff *sched2copy;
1844 isl_map *map;
1845 isl_pw_multi_aff *iterator_map;
1846 isl_union_map *schedule;
1848 if (!node)
1849 return NULL;
1850 ctx = isl_ast_node_get_ctx(node);
1852 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1853 if (!stmt)
1854 return isl_ast_node_free(node);
1856 schedule = isl_ast_build_get_schedule(build);
1857 map = isl_map_reverse(isl_map_from_union_map(schedule));
1858 iterator_map = isl_pw_multi_aff_from_map(map);
1859 if (kernel)
1860 sched2copy = compute_sched_to_copy(kernel,
1861 isl_pw_multi_aff_copy(iterator_map));
1862 else
1863 sched2copy = NULL;
1865 stmt->type = ppcg_kernel_domain;
1866 stmt->u.d.stmt = gpu_stmt;
1868 data.kernel = kernel;
1869 data.accesses = stmt->u.d.stmt->accesses;
1870 data.iterator_map = iterator_map;
1871 data.sched2copy = sched2copy;
1872 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1873 build, &transform_index, &data,
1874 &transform_expr, &data);
1876 isl_pw_multi_aff_free(iterator_map);
1877 isl_pw_multi_aff_free(sched2copy);
1879 id = isl_id_alloc(ctx, "user", stmt);
1880 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1881 return isl_ast_node_set_annotation(node, id);
1884 /* This function is called for each statement node in the AST
1885 * for copying to or from shared/private memory.
1886 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1887 * statement to the node.
1888 * The statement name is "read" or "write", depending on whether we are
1889 * reading from global memory or writing to global memory.
1891 * The schedule is of the form
1893 * type[D -> A] -> L
1895 * where D corresponds to the outer tile->depth dimensions of
1896 * the kernel schedule, A to the global array and L to the outer
1897 * generated AST schedule.
1898 * We compute the inverse and strip off the type, resulting in
1900 * L -> [D -> A]
1902 * We combine this mapping with on the one hand the projection
1904 * [D -> A] -> A
1906 * and on the other hand the group tiling
1908 * [D -> A] -> T
1910 * resulting in
1912 * L -> A and L -> T
1914 * and store the corresponding expressions in stmt->index and stmt->local_index,
1915 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1916 * stmt->index is linearized if the global memory array is linearized.
1918 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1919 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1920 __isl_keep isl_ast_build *build)
1922 struct ppcg_kernel_stmt *stmt;
1923 struct gpu_array_tile *tile;
1924 isl_id *id;
1925 isl_ast_expr *expr;
1926 isl_space *space;
1927 isl_map *access;
1928 isl_pw_multi_aff *pma, *pma2;
1929 const char *type;
1931 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1932 if (!stmt)
1933 return isl_ast_node_free(node);
1935 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1936 type = isl_map_get_tuple_name(access, isl_dim_in);
1937 stmt->u.c.read = !strcmp(type, "read");
1938 access = isl_map_reverse(access);
1939 pma = isl_pw_multi_aff_from_map(access);
1940 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1942 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1943 space = isl_space_unwrap(space);
1944 pma2 = isl_pw_multi_aff_range_map(space);
1945 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1946 isl_pw_multi_aff_copy(pma));
1947 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1948 if (group->array->linearize)
1949 expr = gpu_local_array_info_linearize_index(group->local_array,
1950 expr);
1951 stmt->u.c.index = expr;
1953 tile = gpu_array_ref_group_tile(group);
1954 pma2 = isl_pw_multi_aff_from_multi_aff(
1955 isl_multi_aff_copy(tile->tiling));
1956 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1957 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1958 stmt->u.c.local_index = expr;
1960 stmt->u.c.array = group->array;
1961 stmt->u.c.local_array = group->local_array;
1962 stmt->type = ppcg_kernel_copy;
1964 id = isl_id_alloc(kernel->ctx, "copy", stmt);
1965 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1966 return isl_ast_node_set_annotation(node, id);
1969 /* Create a synchronization ppcg_kernel_stmt and
1970 * attach it to the node "node" representing the synchronization.
1972 static __isl_give isl_ast_node *create_sync_leaf(
1973 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1974 __isl_keep isl_ast_build *build)
1976 struct ppcg_kernel_stmt *stmt;
1977 isl_id *id;
1979 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1980 if (!stmt)
1981 return isl_ast_node_free(node);
1983 stmt->type = ppcg_kernel_sync;
1984 id = isl_id_alloc(kernel->ctx, "sync", stmt);
1985 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1986 return isl_ast_node_set_annotation(node, id);
1989 /* Build AST expressions for the device array sizes of all arrays in "prog"
1990 * that require allocation on the device using "build", as well as
1991 * for the original array sizes of all arrays that need to be declared
1992 * on the host.
1993 * "node" is freed in case of error.
1995 static __isl_give isl_ast_node *build_array_bounds(
1996 __isl_take isl_ast_node *node, struct gpu_prog *prog,
1997 __isl_keep isl_ast_build *build)
1999 int i;
2001 for (i = 0; i < prog->n_array; ++i) {
2002 struct gpu_array_info *array = &prog->array[i];
2003 isl_multi_pw_aff *size;
2004 isl_ast_expr *expr;
2006 if (!gpu_array_requires_device_allocation(array))
2007 continue;
2009 size = isl_multi_pw_aff_copy(array->bound);
2010 expr = ppcg_build_size_expr(size, build);
2011 array->bound_expr = expr;
2012 if (!expr)
2013 return isl_ast_node_free(node);
2016 for (i = 0; i < prog->n_array; ++i) {
2017 struct gpu_array_info *array = &prog->array[i];
2018 isl_set *extent;
2019 isl_multi_pw_aff *size;
2020 isl_ast_expr *expr;
2022 if (!array->declare_local)
2023 continue;
2024 extent = isl_set_copy(array->declared_extent);
2025 size = ppcg_size_from_extent(extent);
2026 expr = ppcg_build_size_expr(size, build);
2027 array->declared_size = expr;
2028 if (!expr)
2029 return isl_ast_node_free(node);
2032 return node;
2035 /* Internal data structure for at_domain.
2037 * "prog" represents the entire scop.
2038 * "kernel" points to the kernel to which the current schedule node
2039 * belongs. It is set by before_mark and reset by after_mark.
2040 * It may be NULL if we are outside any kernel.
2042 struct ppcg_at_domain_data {
2043 struct gpu_prog *prog;
2044 struct ppcg_kernel *kernel;
2047 /* This function is called for each instance of a user statement
2048 * in the kernel. This may be one of the original user statements
2049 * or a statement introduced by PPCG.
2051 * We first check if the statement id corresponds to a gpu statement,
2052 * which indicates the statement is an original user statement. Any statement
2053 * that is not an original user statement has been introduced by PPCG and
2054 * requires special handling.
2056 * If the user statement is one of the original user statements, then we call
2057 * create_domain_leaf. If it is "init_device", then we call
2058 * build_array_bounds. Otherwise, we check if it is a copy or synchronization
2059 * statement and call the appropriate functions. Statements that copy an array
2060 * to/from the device do not need any further treatment.
2061 * Neither does "clear_device".
2063 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
2064 __isl_keep isl_ast_build *build, void *user)
2066 struct ppcg_at_domain_data *data = user;
2067 struct gpu_stmt *gpu_stmt;
2068 isl_ast_expr *expr, *arg;
2069 isl_id *id;
2070 int is_sync;
2071 const char *name;
2072 void *p;
2074 expr = isl_ast_node_user_get_expr(node);
2075 arg = isl_ast_expr_get_op_arg(expr, 0);
2076 id = isl_ast_expr_get_id(arg);
2077 name = isl_id_get_name(id);
2078 p = isl_id_get_user(id);
2079 isl_ast_expr_free(expr);
2080 isl_ast_expr_free(arg);
2082 gpu_stmt = find_stmt(data->prog, id);
2083 is_sync = gpu_tree_id_is_sync(id, data->kernel);
2084 isl_id_free(id);
2086 if (gpu_stmt)
2087 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
2089 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
2090 return node;
2091 if (!strcmp(name, "init_device"))
2092 return build_array_bounds(node, data->prog, build);
2093 if (!strcmp(name, "clear_device"))
2094 return node;
2095 if (is_sync < 0)
2096 return isl_ast_node_free(node);
2097 if (!strcmp(name, "read") || !strcmp(name, "write")) {
2098 struct gpu_array_ref_group *group = p;
2099 return create_access_leaf(data->kernel, group, node, build);
2101 if (!is_sync)
2102 isl_die(data->prog->ctx, isl_error_internal,
2103 "unknown statement type",
2104 return isl_ast_node_free(node));
2105 return create_sync_leaf(data->kernel, node, build);
2108 /* Given a set of wrapped references "ref", return the corresponding
2109 * access relations based on the tagged access relations "tagged".
2111 * The elements of "ref" are of the form
2113 * [D -> R]
2115 * with D an iteration domains and R a reference.
2116 * The elements of "tagged" are of the form
2118 * [D -> R] -> A
2120 * with A an array.
2122 * Extend "tagged" to include the iteration domain in the range, i.e.,
2124 * [D -> R] -> [D -> A]
2126 * apply the result to "ref" and then unwrap the resulting set
2127 * to obtain relations of the form
2129 * D -> A
2131 static __isl_give isl_union_map *wrapped_reference_to_access(
2132 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2134 isl_union_map *tag2access;
2136 tag2access = isl_union_map_copy(tagged);
2137 tag2access = isl_union_map_universe(tag2access);
2138 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2139 tag2access = isl_union_map_domain_map(tag2access);
2140 tag2access = isl_union_map_range_product(tag2access, tagged);
2142 ref = isl_union_set_coalesce(ref);
2143 ref = isl_union_set_apply(ref, tag2access);
2145 return isl_union_set_unwrap(ref);
2148 /* Given an access relation "access" from one or more array reference groups,
2149 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2150 * that are only needed to communicate data within
2151 * the same iteration of "sched".
2152 * The domain of "sched" corresponds to the original statement instances,
2153 * i.e., those that appear in the domains of the access relations.
2154 * "tagged" contains all tagged access relations to all
2155 * the array reference groups accessed by "access" from statement
2156 * instances scheduled by "sched".
2158 * If the access is a read then it is either an element of
2160 * live_in union (range flow)
2162 * where live_in and flow may be overapproximations, or
2163 * it reads an uninitialized value (that is not live-in because
2164 * there is an intermediate kill) or it reads a value that was
2165 * written within the same (compound) statement instance.
2166 * If the access is a write then it is either an element of
2168 * live_out union (domain flow)
2170 * or it writes a value that is never read (and is not live-out
2171 * because of an intermediate kill) or only
2172 * within the same (compound) statement instance.
2173 * In both cases, the access relation is also a subset of
2174 * the group access relation.
2176 * The cases where an uninitialized value is read or a value is written
2177 * that is never read or where the dataflow occurs within a statement
2178 * instance are also considered local and may also be removed.
2180 * Essentially, we compute the intersection of "access" with either
2182 * live_in union (range non-local-flow)
2184 * or
2186 * live_out union (domain non-local-flow)
2188 * We first construct a relation "local"
2190 * [[D -> R] -> [D' -> R']]
2192 * of pairs of domain iterations accessing the reference group
2193 * and references in the group that are coscheduled by "sched".
2195 * If this relation does not intersect the dataflow dependences,
2196 * then there is nothing we can possibly remove, unless the dataflow
2197 * dependences themselves only relate a subset of the accesses.
2198 * In particular, the accesses may not be involved in any dataflow
2199 * dependences, either because they are uninitialized reads/dead writes
2200 * or because the dataflow occurs inside a statement instance.
2202 * Since the computation below may break up the access relation
2203 * into smaller pieces, we only perform the intersection with
2204 * the non-local dependent accesses if the local pairs
2205 * intersect the dataflow dependences. Otherwise, we intersect
2206 * with the universe of the non-local dependent accesses.
2207 * This should at least remove accesses from statements that
2208 * do not participate in any dependences.
2210 * In particular, we remove the "local" dataflow dependences from
2211 * the set of all dataflow dependences, or at least those
2212 * that may contribute to a domain/range that intersects
2213 * the domain of "access".
2214 * Note that if the potential dataflow dependences are an overapproximation
2215 * of the actual dataflow dependences, then the result remains an
2216 * overapproximation of the non-local dataflow dependences.
2217 * Copying to/from global memory is only needed for the references
2218 * in the domain/range of the result or for accesses that are live out/in
2219 * for the entire scop.
2221 * We therefore map the domain/range of the "external" relation
2222 * to the corresponding access relation and take the union with
2223 * the live out/in relation.
2225 static __isl_give isl_union_map *remove_local_accesses(
2226 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2227 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2228 int read)
2230 int empty;
2231 isl_union_pw_multi_aff *tagger;
2232 isl_union_set *domain, *access_domain;
2233 isl_union_map *local, *external, *universe;
2234 isl_union_set *tag_set;
2236 if (isl_union_map_is_empty(access)) {
2237 isl_union_map_free(sched);
2238 isl_union_map_free(tagged);
2239 return access;
2242 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2243 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2244 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2245 isl_union_set_copy(domain));
2246 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2248 local = isl_union_map_apply_range(sched,
2249 isl_union_map_reverse(isl_union_map_copy(sched)));
2250 local = isl_union_map_intersect(local,
2251 isl_union_map_copy(prog->scop->tagged_dep_flow));
2253 empty = isl_union_map_is_empty(local);
2255 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2256 universe = isl_union_map_universe(isl_union_map_copy(access));
2257 access_domain = isl_union_map_domain(universe);
2258 domain = isl_union_set_universe(domain);
2259 universe = isl_union_set_unwrap(domain);
2260 universe = isl_union_map_intersect_domain(universe, access_domain);
2261 domain = isl_union_map_wrap(universe);
2262 if (read)
2263 external = isl_union_map_intersect_range(external, domain);
2264 else
2265 external = isl_union_map_intersect_domain(external, domain);
2266 external = isl_union_map_intersect_params(external,
2267 isl_set_copy(prog->scop->context));
2268 external = isl_union_map_subtract(external, local);
2270 if (read) {
2271 tag_set = isl_union_map_range(external);
2272 external = wrapped_reference_to_access(tag_set, tagged);
2273 external = isl_union_map_union(external,
2274 isl_union_map_copy(prog->scop->live_in));
2275 } else {
2276 tag_set = isl_union_map_domain(external);
2277 external = wrapped_reference_to_access(tag_set, tagged);
2278 external = isl_union_map_union(external,
2279 isl_union_map_copy(prog->scop->live_out));
2282 if (empty < 0)
2283 external = isl_union_map_free(external);
2284 else if (empty)
2285 external = isl_union_map_universe(external);
2287 access = isl_union_map_intersect(access, external);
2289 return access;
2292 /* Given an access relation "access" from "group", remove those reads
2293 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2294 * communicate data within the same iteration of the schedule "prefix"
2295 * at the position where the copying of the group is inserted.
2296 * That is, the output dimension of "prefix"
2297 * is equal to tile->depth.
2298 * The domain of "prefix" corresponds to the original statement instances,
2299 * i.e., those that appear in the domains of the access relations.
2301 * Extract the tagged access relation of "group" and
2302 * then call remove_local_accesses.
2304 static __isl_give isl_union_map *remove_local_accesses_group(
2305 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2306 __isl_take isl_union_map *access, __isl_keep isl_union_map *prefix,
2307 int read)
2309 isl_union_map *sched, *tagged;
2311 if (isl_union_map_is_empty(access))
2312 return access;
2314 tagged = group_tagged_access_relation(group);
2315 sched = isl_union_map_copy(prefix);
2317 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2320 /* Build an access AST expression for the effective grid size using "build".
2321 * Store the result in kernel->grid_size_expr.
2323 static isl_stat build_grid_size(struct ppcg_kernel *kernel,
2324 __isl_keep isl_ast_build *build)
2326 isl_multi_pw_aff *size;
2328 size = isl_multi_pw_aff_copy(kernel->grid_size);
2329 size = isl_multi_pw_aff_set_tuple_name(size, isl_dim_out, "grid");
2330 kernel->grid_size_expr = ppcg_build_size_expr(size, build);
2332 if (!kernel->grid_size_expr)
2333 return isl_stat_error;
2334 return isl_stat_ok;
2337 /* Build access AST expressions for the localized array sizes using "build".
2338 * Store the result in local->bound_expr.
2339 * Only do this for arrays for which localized bounds have been computed.
2341 static isl_stat build_local_array_sizes(struct ppcg_kernel *kernel,
2342 __isl_keep isl_ast_build *build)
2344 int i;
2346 for (i = 0; i < kernel->n_array; ++i) {
2347 struct gpu_local_array_info *local = &kernel->array[i];
2348 isl_multi_pw_aff *size;
2350 if (local->n_group == 0)
2351 continue;
2352 size = isl_multi_pw_aff_copy(local->bound);
2353 local->bound_expr = ppcg_build_size_expr(size, build);
2354 if (!local->bound_expr)
2355 return isl_stat_error;
2358 return isl_stat_ok;
2361 /* Build access AST expressions for the effective grid size and
2362 * the localized array sizes using "build".
2364 static isl_stat build_grid_and_local_array_sizes(struct ppcg_kernel *kernel,
2365 __isl_keep isl_ast_build *build)
2367 if (build_grid_size(kernel, build) < 0)
2368 return isl_stat_error;
2369 if (build_local_array_sizes(kernel, build) < 0)
2370 return isl_stat_error;
2371 return isl_stat_ok;
2374 /* This function is called before the AST generator starts traversing
2375 * the schedule subtree of a node with mark "mark".
2377 * If the mark is called "kernel", store the kernel pointer in data->kernel
2378 * for use in at_domain and build AST expressions for the grid size and
2379 * the localized array sizes.
2381 static isl_stat before_mark(__isl_keep isl_id *mark,
2382 __isl_keep isl_ast_build *build, void *user)
2384 struct ppcg_at_domain_data *data = user;
2386 if (!mark)
2387 return isl_stat_error;
2388 if (!strcmp(isl_id_get_name(mark), "kernel")) {
2389 data->kernel = isl_id_get_user(mark);
2390 if (build_grid_and_local_array_sizes(data->kernel, build) < 0)
2391 return isl_stat_error;
2393 return isl_stat_ok;
2396 /* This function is called after the AST generator has finished traversing
2397 * the schedule subtree of a mark node. "node" points to the corresponding
2398 * mark AST node.
2400 * If the mark is called "kernel", then replace "node" by a user node
2401 * that "calls" the kernel, representing the launch of the kernel.
2402 * The original "node" is stored inside the kernel object so that
2403 * it can be used to print the device code.
2404 * Note that this assumes that a kernel is only launched once.
2405 * Also clear data->kernel.
2407 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2408 __isl_keep isl_ast_build *build, void *user)
2410 isl_ctx *ctx;
2411 isl_id *id;
2412 isl_ast_expr *expr;
2413 isl_ast_expr_list *list;
2414 struct ppcg_kernel *kernel;
2415 struct ppcg_at_domain_data *data = user;
2417 ctx = isl_ast_node_get_ctx(node);
2418 id = isl_ast_node_mark_get_id(node);
2419 if (!id)
2420 return isl_ast_node_free(node);
2421 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2422 isl_id_free(id);
2423 return node;
2425 kernel = data->kernel;
2426 data->kernel = NULL;
2427 kernel->space = isl_ast_build_get_schedule_space(build);
2428 kernel->tree = isl_ast_node_mark_get_node(node);
2429 isl_ast_node_free(node);
2431 expr = isl_ast_expr_from_id(isl_id_copy(id));
2432 list = isl_ast_expr_list_alloc(ctx, 0);
2433 expr = isl_ast_expr_call(expr, list);
2434 node = isl_ast_node_alloc_user(expr);
2435 node = isl_ast_node_set_annotation(node, id);
2437 return node;
2440 static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2442 int *depth = user;
2443 int node_depth;
2445 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2446 return isl_bool_true;
2447 node_depth = isl_schedule_node_get_schedule_depth(node);
2448 if (node_depth > *depth)
2449 *depth = node_depth;
2451 return isl_bool_false;
2454 /* Use isl to generate code for both the host and the device
2455 * from "schedule".
2456 * The device code is marked by "kernel" mark nodes in the schedule tree,
2457 * containing a pointer to a ppcg_kernel object.
2458 * The returned AST only contains the AST for the host code.
2459 * The ASTs for the device code are embedded in ppcg_kernel objects
2460 * attached to the leaf nodes that call "kernel".
2462 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2463 __isl_take isl_schedule *schedule)
2465 struct ppcg_at_domain_data data;
2466 isl_ast_build *build;
2467 isl_ast_node *tree;
2468 isl_id_list *iterators;
2469 int depth;
2471 data.prog = gen->prog;
2472 data.kernel = NULL;
2474 depth = 0;
2475 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2476 &depth) < 0)
2477 return NULL;
2478 build = isl_ast_build_alloc(gen->prog->ctx);
2479 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2480 build = isl_ast_build_set_iterators(build, iterators);
2481 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2482 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2483 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2484 if (gen->prog->scop->options->debug->dump_final_schedule)
2485 isl_schedule_dump(schedule);
2486 tree = isl_ast_build_node_from_schedule(build, schedule);
2487 isl_ast_build_free(build);
2489 return tree;
2492 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2494 if (!str)
2495 return NULL;
2496 return isl_union_map_read_from_str(ctx, str);
2499 /* Can "node" be tiled and then mapped to block and thread identifiers?
2500 * That is, is it permutable with at least one coincident dimension?
2502 static int is_permutable(__isl_keep isl_schedule_node *node)
2504 if (!node)
2505 return -1;
2507 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2508 return 0;
2509 if (!isl_schedule_node_band_get_permutable(node))
2510 return 0;
2511 if (isl_schedule_node_band_n_member(node) < 1)
2512 return 0;
2513 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2514 return 0;
2516 return 1;
2519 /* A isl_schedule_foreach_schedule_node_top_down callback
2520 * for setting *any_permutable and aborting the search
2521 * if "node" is a permutable band with coincident dimensions.
2522 * Otherwise, continue searching.
2524 static isl_bool set_permutable(__isl_keep isl_schedule_node *node, void *user)
2526 int *any_permutable = user;
2527 int permutable;
2529 permutable = is_permutable(node);
2530 if (permutable < 0)
2531 return isl_bool_error;
2532 if (!permutable)
2533 return isl_bool_true;
2535 *any_permutable = 1;
2537 return isl_bool_error;
2540 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
2541 * That is, does it have any nodes that are permutable and that
2542 * have a least one coincident dimension?
2544 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
2546 int any_parallelism = 0;
2548 if (isl_schedule_node_foreach_descendant_top_down(node, &set_permutable,
2549 &any_parallelism) < 0 &&
2550 !any_parallelism)
2551 return -1;
2553 return any_parallelism;
2556 /* Does "schedule" contain any permutable band with at least one coincident
2557 * member?
2559 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2561 isl_schedule_node *root;
2562 int any_permutable;
2564 root = isl_schedule_get_root(schedule);
2565 any_permutable = subtree_has_permutable_bands(root);
2566 isl_schedule_node_free(root);
2568 return any_permutable;
2571 /* Is "node" a candidate for mapping to block and thread identifiers?
2572 * In particular, is it permutable with at least one coincident dimension?
2573 * Alternatively, does the subtree rooted at "node" not contain
2574 * any such permutable node? Filter nodes are skipped in this case,
2575 * because a band node will be inserted in front of the returned
2576 * node and this is not possible for filter nodes that are children
2577 * of set or sequence nodes.
2579 static int is_candidate(__isl_keep isl_schedule_node *node)
2581 int permutable;
2583 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2584 return 1;
2585 permutable = is_permutable(node);
2586 if (permutable < 0 || permutable)
2587 return permutable;
2588 if (isl_schedule_node_get_type(node) == isl_schedule_node_filter)
2589 return 0;
2590 permutable = subtree_has_permutable_bands(node);
2591 if (permutable < 0)
2592 return -1;
2593 return !permutable;
2596 /* Is "node" the outermost node in its branch that can be tiled
2597 * and then mapped to block and thread identifiers?
2598 * If there are no such nodes in the subtree at "node" and
2599 * if "node" is not a filter node, then it is accepted too.
2601 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2603 int tilable;
2604 isl_schedule_node *ancestor;
2606 tilable = is_candidate(node);
2607 if (tilable < 0)
2608 return -1;
2609 if (!tilable)
2610 return 0;
2612 tilable = 0;
2613 ancestor = isl_schedule_node_copy(node);
2614 while (isl_schedule_node_has_parent(ancestor)) {
2615 ancestor = isl_schedule_node_parent(ancestor);
2617 tilable = is_candidate(ancestor);
2618 if (tilable < 0 || tilable)
2619 break;
2622 isl_schedule_node_free(ancestor);
2623 return tilable < 0 ? -1 : !tilable;
2626 /* Collect the references to all writes in "group".
2627 * Each reference is represented by a universe set in a space
2629 * [S[i,j] -> R[]]
2631 * with S[i,j] the statement instance space and R[] the array reference.
2633 static __isl_give isl_union_set *group_tagged_writes(
2634 struct gpu_array_ref_group *group)
2636 int i;
2637 isl_space *space;
2638 isl_union_set *writes;
2640 space = isl_map_get_space(group->access);
2641 writes = isl_union_set_empty(space);
2642 for (i = 0; i < group->n_ref; ++i) {
2643 isl_space *space;
2644 isl_set *writes_i;
2646 if (!group->refs[i]->write)
2647 continue;
2649 space = isl_map_get_space(group->refs[i]->tagged_access);
2650 space = isl_space_domain(space);
2651 writes_i = isl_set_universe(space);
2652 writes = isl_union_set_add_set(writes, writes_i);
2655 return writes;
2658 /* Is there any write access in "group" that requires synchronization
2659 * on a write to global memory?
2660 * We currently take into account all writes that would require
2661 * synchronization at the thread level depth, but if the copying
2662 * for this group is performed at an outer level, then we do not
2663 * actually need to take into account dependences at intermediate levels.
2665 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2666 struct gpu_array_ref_group *group)
2668 isl_union_set *writes;
2669 int empty, disjoint;
2671 empty = isl_union_set_is_empty(kernel->sync_writes);
2672 if (empty < 0)
2673 return -1;
2674 if (empty)
2675 return 0;
2677 writes = group_tagged_writes(group);
2678 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2679 isl_union_set_free(writes);
2681 return disjoint < 0 ? -1 : !disjoint;
2684 /* Collect the references to all writes in "kernel" that write directly
2685 * to global or shared memory, i.e., that are not mapped to private memory.
2686 * Each reference is represented by a universe set in a space
2688 * [S[i,j] -> R[]]
2690 * with S[i,j] the statement instance space and R[] the array reference.
2692 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2693 struct ppcg_kernel *kernel)
2695 isl_union_set *writes;
2696 int i, j;
2698 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2700 for (i = 0; i < kernel->n_array; ++i) {
2701 struct gpu_local_array_info *array = &kernel->array[i];
2703 for (j = 0; j < array->n_group; ++j) {
2704 struct gpu_array_ref_group *group = array->groups[j];
2705 enum ppcg_group_access_type type;
2706 isl_union_set *writes_ij;
2708 if (!group->write)
2709 continue;
2710 type = gpu_array_ref_group_type(group);
2711 if (type == ppcg_access_private)
2712 continue;
2713 writes_ij = group_tagged_writes(group);
2714 writes = isl_union_set_union(writes, writes_ij);
2718 return writes;
2721 /* Are there any direct writes to global memory that require
2722 * synchronization?
2724 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2726 isl_union_set *writes;
2727 int empty, disjoint;
2729 empty = isl_union_set_is_empty(kernel->sync_writes);
2730 if (empty < 0)
2731 return -1;
2732 if (empty)
2733 return 0;
2735 writes = collect_non_private_tagged_writes(kernel);
2736 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2737 isl_union_set_free(writes);
2739 return disjoint < 0 ? -1 : !disjoint;
2742 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2743 * from the elements in "tile_size".
2745 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2746 __isl_keep isl_schedule_node *node, int *tile_size)
2748 int i, n;
2749 isl_ctx *ctx;
2750 isl_space *space;
2751 isl_multi_val *mv;
2753 if (!node)
2754 return NULL;
2756 ctx = isl_schedule_node_get_ctx(node);
2757 space = isl_schedule_node_band_get_space(node);
2758 n = isl_schedule_node_band_n_member(node);
2759 mv = isl_multi_val_zero(space);
2760 for (i = 0; i < n; ++i) {
2761 isl_val *v;
2763 v = isl_val_int_from_si(ctx, tile_size[i]);
2764 mv = isl_multi_val_set_val(mv, i, v);
2767 return mv;
2770 /* Replace the partial schedule S of the band node "node" by
2772 * floor(S/f)
2774 * or
2776 * f * floor(S/f)
2778 * if scale_tile_loops is set, with f the integers in "factor".
2779 * The list that "factor" points to is assumed to contain at least
2780 * as many elements as the number of members in the band.
2782 static __isl_give isl_schedule_node *snap_band_to_sizes(
2783 __isl_take isl_schedule_node *node, int *factor,
2784 struct ppcg_options *options)
2786 isl_multi_val *mv;
2788 mv = construct_band_tiles_sizes(node, factor);
2789 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2790 if (options->scale_tile_loops)
2791 node = isl_schedule_node_band_scale(node,
2792 isl_multi_val_copy(mv));
2793 isl_multi_val_free(mv);
2795 return node;
2798 /* Tile "band" with tile size specified by "sizes".
2800 * Since the tile loops will be mapped to block ids, we forcibly
2801 * turn off tile loop scaling. We may want to enable tile loop scaling
2802 * at some later point, but then we would have to support the detection
2803 * of strides during the mapping to block ids.
2804 * Similarly, since the point loops will be mapped to thread ids,
2805 * we forcibly shift the point loops so that they start at zero.
2807 static __isl_give isl_schedule_node *tile_band(
2808 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2810 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2811 int scale_tile;
2812 int shift_point;
2814 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2815 isl_options_set_tile_scale_tile_loops(ctx, 0);
2816 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2817 isl_options_set_tile_shift_point_loops(ctx, 1);
2819 node = isl_schedule_node_band_tile(node, sizes);
2821 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2822 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2824 return node;
2827 /* Extract the set of parameter values and outer schedule dimensions
2828 * for which any statement instance
2829 * in the kernel inserted at "node" needs to be executed.
2830 * Intersect the set of parameter values derived from the host schedule
2831 * relation with the context of "prog".
2833 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2834 struct gpu_prog *prog)
2836 isl_union_map *schedule;
2837 isl_union_set *schedule_domain;
2838 isl_set *context;
2839 int empty;
2841 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2842 schedule_domain = isl_union_map_range(schedule);
2843 empty = isl_union_set_is_empty(schedule_domain);
2844 if (empty < 0) {
2845 isl_union_set_free(schedule_domain);
2846 return NULL;
2848 if (empty) {
2849 int depth;
2850 isl_space *space;
2852 space = isl_union_set_get_space(schedule_domain);
2853 isl_union_set_free(schedule_domain);
2854 space = isl_space_set_from_params(space);
2855 depth = isl_schedule_node_get_schedule_depth(node);
2856 space = isl_space_add_dims(space, isl_dim_set, depth);
2857 context = isl_set_empty(space);
2858 } else {
2859 context = isl_set_from_union_set(schedule_domain);
2861 context = isl_set_intersect_params(context,
2862 isl_set_copy(prog->context));
2864 return context;
2867 /* Return the set of outer array elements accessed by
2868 * by the statement instances in "domain" in "prog".
2869 * The instances in "domain" are those that appear
2870 * in the domains of the access relations in "prog".
2872 static __isl_give isl_union_set *accessed_by_domain(
2873 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2875 isl_union_map *access;
2876 isl_union_set *arrays;
2878 access = isl_union_map_union(isl_union_map_copy(prog->read),
2879 isl_union_map_copy(prog->may_write));
2880 access = isl_union_map_intersect_domain(access, domain);
2881 arrays = isl_union_map_range(access);
2882 arrays = isl_union_set_apply(arrays,
2883 isl_union_map_copy(prog->to_outer));
2885 return arrays;
2888 /* Return the number of outer band members of the band node "node"
2889 * that are marked coincident.
2891 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2893 int i, n;
2895 n = isl_schedule_node_band_n_member(node);
2897 for (i = 0; i < n; ++i)
2898 if (!isl_schedule_node_band_member_get_coincident(node, i))
2899 break;
2901 return i;
2904 /* If the band node "node" has more than "n" members, then split off
2905 * the first "n" of them.
2907 static __isl_give isl_schedule_node *split_band(
2908 __isl_take isl_schedule_node *node, int n)
2910 int dim;
2912 dim = isl_schedule_node_band_n_member(node);
2913 if (n < dim)
2914 node = isl_schedule_node_band_split(node, n);
2916 return node;
2919 /* Scale a band node that may have been split by split_band.
2920 * "sizes" are the scaling factors for the original node.
2921 * "node" either points to the original band node, or the outer
2922 * of the two pieces after splitting.
2924 * If the number of elements in "node" is smaller than the number of
2925 * elements in "sizes", then some splitting has occurred and we split
2926 * "sizes" in the same way.
2928 static __isl_give isl_schedule_node *scale_band(
2929 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2931 int n, dim;
2933 n = isl_multi_val_dim(sizes, isl_dim_set);
2934 dim = isl_schedule_node_band_n_member(node);
2935 if (n > dim) {
2936 isl_multi_val *sizes2;
2938 sizes2 = isl_multi_val_copy(sizes);
2939 sizes = isl_multi_val_drop_dims(sizes,
2940 isl_dim_set, dim, n - dim);
2941 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2942 node = isl_schedule_node_child(node, 0);
2943 node = isl_schedule_node_band_scale(node, sizes2);
2944 node = isl_schedule_node_parent(node);
2947 return isl_schedule_node_band_scale(node, sizes);
2950 /* Return an isl_multi_aff, with as elements the parameters in "space"
2951 * that have the names specified by the elements in "names".
2952 * If (some of) these parameters do not already appear in "space",
2953 * then they are added first.
2955 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2956 __isl_keep isl_id_list *names)
2958 int i, n;
2959 isl_local_space *ls;
2960 isl_multi_aff *ma;
2962 if (!names)
2963 space = isl_space_free(space);
2965 n = isl_id_list_n_id(names);
2966 for (i = 0; i < n; ++i) {
2967 int pos;
2968 isl_id *id;
2970 id = isl_id_list_get_id(names, i);
2971 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2972 if (pos >= 0) {
2973 isl_id_free(id);
2974 continue;
2976 pos = isl_space_dim(space, isl_dim_param);
2977 space = isl_space_add_dims(space, isl_dim_param, 1);
2978 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2980 ma = isl_multi_aff_zero(isl_space_copy(space));
2981 ls = isl_local_space_from_space(isl_space_domain(space));
2982 for (i = 0; i < n; ++i) {
2983 int pos;
2984 isl_id *id;
2985 isl_aff *aff;
2987 id = isl_id_list_get_id(names, i);
2988 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2989 isl_id_free(id);
2990 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2991 isl_dim_param, pos);
2992 ma = isl_multi_aff_set_aff(ma, i, aff);
2994 isl_local_space_free(ls);
2996 return ma;
2999 /* Return constraints on the domain elements that equate a sequence of
3000 * parameters called "names", to the partial schedule
3001 * of "node" modulo the integers in "size".
3002 * The number of elements in the array "size" should be equal
3003 * to the number of elements in "names".
3004 * The number of members of the band node "node" should be smaller
3005 * than or equal to this number. If it is smaller, then the first
3006 * elements of "names" are equated to zero.
3008 static __isl_give isl_union_set *set_schedule_modulo(
3009 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
3010 int *size)
3012 int n, n_zero;
3013 isl_space *space;
3014 isl_multi_aff *ma;
3015 isl_multi_union_pw_aff *mupa, *mupa2;
3016 isl_multi_val *mv;
3017 isl_union_set *domain;
3019 if (!node)
3020 return NULL;
3021 n = isl_id_list_n_id(names);
3022 if (n == 0)
3023 return isl_schedule_node_get_universe_domain(node);
3024 n_zero = n - isl_schedule_node_band_n_member(node);
3026 mupa = isl_schedule_node_band_get_partial_schedule(node);
3027 mv = construct_band_tiles_sizes(node, size + n_zero);
3028 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
3030 space = isl_multi_union_pw_aff_get_space(mupa);
3031 space = isl_space_params(space);
3032 space = isl_space_set_from_params(space);
3033 space = isl_space_add_dims(space, isl_dim_set, n_zero);
3034 ma = isl_multi_aff_zero(space);
3036 domain = isl_schedule_node_get_universe_domain(node);
3037 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
3038 isl_union_set_copy(domain), ma);
3039 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
3041 space = isl_multi_union_pw_aff_get_space(mupa);
3042 ma = parameter_vector(space, names);
3044 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
3045 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
3047 return isl_multi_union_pw_aff_zero_union_set(mupa);
3050 /* Insert a context node at "node" introducing the block and thread
3051 * identifiers along with their bounds, which are stored in kernel->grid_size
3052 * and kernel->block_dim.
3053 * Note that the bounds on the block identifiers may implicitly impose
3054 * constraints on the parameters. A guard needs to be inserted
3055 * in the schedule tree to ensure that those bounds hold at "node".
3056 * This guard is inserted in insert_guard.
3058 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
3059 __isl_take isl_schedule_node *node)
3061 isl_set *context;
3063 context = isl_set_universe(isl_set_get_space(kernel->context));
3065 context = add_bounded_parameters_dynamic(context,
3066 kernel->grid_size, kernel->block_ids);
3067 context = add_bounded_parameters(context,
3068 kernel->block_dim, kernel->thread_ids);
3070 node = isl_schedule_node_insert_context(node, context);
3072 return node;
3075 /* Insert a guard that eliminates kernel launches where the kernel
3076 * obviously does not have any work to do.
3078 * In particular, eliminate kernel launches where there are obviously
3079 * zero blocks.
3080 * Use the same block size constraints that are used to create the context
3081 * to ensure that all constraints implicit in the constructed context
3082 * are imposed by the guard.
3084 * Additionally, add other constraints that are valid
3085 * for each executed instance ("context"), as long as this does not result
3086 * in a disjunction.
3088 static __isl_give isl_schedule_node *insert_guard(
3089 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
3090 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
3092 unsigned nparam, n;
3093 isl_set *guard;
3094 isl_id_list *ids;
3096 guard = isl_set_copy(context);
3097 guard = isl_set_compute_divs(guard);
3098 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
3100 nparam = isl_set_dim(guard, isl_dim_param);
3101 n = isl_multi_pw_aff_dim(size, isl_dim_out);
3102 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
3103 guard = add_bounded_parameters_dynamic(guard, size, ids);
3104 isl_id_list_free(ids);
3105 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
3107 node = isl_schedule_node_insert_guard(node, guard);
3109 return node;
3112 /* Does any array reference group mapping require the band that is mapped
3113 * to threads to be unrolled?
3115 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
3117 int i, j;
3119 for (i = 0; i < kernel->n_array; ++i) {
3120 struct gpu_local_array_info *array = &kernel->array[i];
3122 for (j = 0; j < array->n_group; ++j) {
3123 struct gpu_array_ref_group *group = array->groups[j];
3124 if (gpu_array_ref_group_requires_unroll(group))
3125 return 1;
3129 return 0;
3132 /* Mark the given band node "node" for unrolling by the AST generator and
3133 * then sink it to the leaves of the schedule tree.
3134 * All dimensions of "node" are assumed to be coincident, such that this
3135 * sinking is a valid operation.
3137 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
3139 node = ppcg_set_schedule_node_type(node, isl_ast_loop_unroll);
3141 node = isl_schedule_node_band_sink(node);
3143 return node;
3146 /* Insert a synchronization node in the schedule tree of "node"
3147 * after the core computation of "kernel" at the level of the band
3148 * that is mapped to threads, except if that level is equal to
3149 * that of the band that is mapped to blocks or if there are no writes
3150 * to global or shared memory in the core computation that require
3151 * synchronization.
3152 * If there are any writes to shared memory and the shared memory
3153 * copying is performed at the same level, then synchronization
3154 * is needed between the core and the copying anyway, so we might
3155 * as well add it here. If the copying is performed at a higher
3156 * level, then different iterations of intermediate schedule dimensions
3157 * may have a different mapping from between shared memory elements and
3158 * threads, such that synchronization is required after the core.
3159 * "node" is assumed to point to the kernel node.
3161 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
3162 __isl_take isl_schedule_node *node)
3164 int kernel_depth;
3165 int need_sync;
3167 need_sync = any_global_or_shared_sync_writes(kernel);
3168 if (need_sync < 0)
3169 return isl_schedule_node_free(node);
3170 if (!need_sync)
3171 return node;
3173 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3175 node = gpu_tree_move_down_to_thread(node, kernel->core);
3176 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
3177 return gpu_tree_move_up_to_kernel(node);
3179 node = gpu_tree_ensure_following_sync(node, kernel);
3181 node = gpu_tree_move_up_to_kernel(node);
3183 return node;
3186 /* Return a read ("read" is 1) or write access relation for "group"
3187 * with those accesses removed that are only needed to communicate data
3188 * within the subtree of the schedule rooted at "node".
3189 * Furthermore, include the prefix schedule at "node".
3190 * That is, return a relation of the form
3192 * S -> [D -> A]
3194 * with D the outer schedule dimensions at "node".
3196 static __isl_give isl_union_map *anchored_non_local_accesses(
3197 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3198 __isl_take isl_schedule_node *node, int read)
3200 isl_union_map *access;
3201 isl_union_map *prefix;
3203 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3204 prefix = isl_union_map_preimage_domain_union_pw_multi_aff(prefix,
3205 isl_union_pw_multi_aff_copy(kernel->contraction));
3206 access = gpu_array_ref_group_access_relation(group, read, !read);
3207 access = remove_local_accesses_group(kernel, group, access, prefix,
3208 read);
3209 access = isl_union_map_range_product(prefix, access);
3211 return access;
3214 /* Given an array reference group "group", create a mapping
3216 * read[D -> A] -> [D -> A]
3218 * if "read" is set or
3220 * write[D -> A] -> [D -> A]
3222 * if "read" is not set.
3223 * D corresponds to the outer tile->depth dimensions of
3224 * the kernel schedule.
3226 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3227 struct gpu_array_ref_group *group, int read)
3229 struct gpu_array_tile *tile;
3230 isl_space *space;
3231 isl_id *id;
3233 tile = gpu_array_ref_group_tile(group);
3234 space = isl_space_copy(group->array->space);
3235 space = isl_space_from_range(space);
3236 space = isl_space_add_dims(space, isl_dim_in, tile->depth);
3237 space = isl_space_wrap(space);
3238 space = isl_space_map_from_set(space);
3240 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3241 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3243 return isl_multi_aff_identity(space);
3246 /* If any writes in "group" require synchronization, then make sure
3247 * that there is a synchronization node for "kernel" after the node
3248 * following "node" in a sequence.
3250 * If "shared" is set and no synchronization is needed for
3251 * the writes to global memory, then add synchronization before
3252 * the kernel to protect shared memory from being overwritten
3253 * by the next iteration of the core computation.
3254 * No additional synchronization is needed to protect against
3255 * the next copy into shared memory because each element of
3256 * the shared memory tile is always copied by the same thread.
3258 static __isl_give isl_schedule_node *add_group_write_sync(
3259 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3260 struct gpu_array_ref_group *group, int shared)
3262 int need_sync;
3264 need_sync = any_sync_writes_in_group(kernel, group);
3265 if (need_sync < 0)
3266 return isl_schedule_node_free(node);
3267 if (need_sync) {
3268 node = isl_schedule_node_parent(node);
3269 node = isl_schedule_node_next_sibling(node);
3270 node = isl_schedule_node_child(node, 0);
3271 node = gpu_tree_ensure_following_sync(node, kernel);
3272 } else if (shared) {
3273 struct gpu_array_tile *tile;
3275 tile = gpu_array_ref_group_tile(group);
3276 node = isl_schedule_node_parent(node);
3277 node = isl_schedule_node_parent(node);
3278 node = gpu_tree_move_down_to_depth(node, tile->depth,
3279 kernel->core);
3280 node = gpu_tree_move_left_to_sync(node, kernel);
3283 return node;
3286 /* Add copy statements to the schedule tree of "node"
3287 * for reading from global memory to private memory (if "read" is set) or
3288 * for writing back from private memory to global memory
3289 * (if "read" is not set) for the array reference group "group" that
3290 * is mapped to private memory.
3291 * On input, "node" points to the kernel node, and it is moved
3292 * back there on output.
3294 * The copies are performed in the order of the array elements.
3295 * The copy statement instances include a reference to the outer
3296 * tile->depth dimensions of the kernel schedule for ease of
3297 * combining them with the group tiling.
3299 * That is, the extra schedule is of the form
3301 * type[D -> A] -> A
3303 * where D corresponds to the outer tile->depth dimensions of
3304 * the kernel schedule and A to the global array.
3305 * This schedule is unrolled because registers are not addressable.
3307 * The copying is inserted in the schedule tree through an extension
3308 * of the form
3310 * D -> type[D -> A]
3312 * where the extra domain elements type[D -> A] are those accessed
3313 * by the group.
3314 * A filter is inserted on type[D -> A] to ensure that the element
3315 * is read/written by the same thread that needs the element.
3316 * This filter is obtained by applying
3318 * S -> type[D -> A]
3320 * to the thread filter for the core statements.
3322 * The extension is inserted before the core computation in case of a read
3323 * and after the core computation in case of a write.
3324 * In the latter case, we also make sure that there is a synchronization
3325 * node after the write to global memory, unless this write is performed
3326 * at the outer level of the kernel.
3327 * In principle, this synchronization could be inserted higher
3328 * in the schedule tree depending on where the corresponding reads
3329 * from global memory are performed.
3331 static __isl_give isl_schedule_node *add_copies_group_private(
3332 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3333 __isl_take isl_schedule_node *node, int read)
3335 struct gpu_array_tile *tile;
3336 isl_union_map *access;
3337 isl_union_set *domain;
3338 isl_space *space;
3339 isl_multi_aff *from_access;
3340 isl_multi_pw_aff *mpa;
3341 isl_multi_union_pw_aff *mupa;
3342 isl_union_pw_multi_aff *contraction;
3343 isl_schedule_node *graft;
3344 isl_union_set *filter;
3345 int kernel_depth;
3346 int empty;
3348 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3349 tile = gpu_array_ref_group_tile(group);
3350 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3352 access = anchored_non_local_accesses(kernel, group, node, read);
3353 empty = isl_union_map_is_empty(access);
3354 if (empty < 0 || empty) {
3355 isl_union_map_free(access);
3356 if (empty < 0)
3357 return isl_schedule_node_free(node);
3358 return gpu_tree_move_up_to_kernel(node);
3361 group->array->global = 1;
3362 group->local_array->global = 1;
3364 from_access = create_from_access(kernel->ctx, group, read);
3365 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3366 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3368 filter = isl_union_set_copy(kernel->thread_filter);
3369 contraction = isl_union_pw_multi_aff_copy(kernel->contraction);
3370 filter = isl_union_set_preimage_union_pw_multi_aff(filter, contraction);
3371 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3372 filter = isl_union_set_detect_equalities(filter);
3373 filter = isl_union_set_coalesce(filter);
3375 domain = isl_union_map_range(access);
3376 access = isl_union_set_wrapped_domain_map(domain);
3377 access = isl_union_map_reverse(access);
3378 access = isl_union_map_coalesce(access);
3379 graft = isl_schedule_node_from_extension(access);
3381 space = isl_space_map_from_set(space);
3382 mpa = isl_multi_pw_aff_identity(space);
3383 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3384 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3386 graft = isl_schedule_node_child(graft, 0);
3387 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3388 graft = unroll(graft);
3390 graft = isl_schedule_node_insert_filter(graft, filter);
3392 graft = isl_schedule_node_parent(graft);
3394 if (read)
3395 node = isl_schedule_node_graft_before(node, graft);
3396 else {
3397 node = isl_schedule_node_graft_after(node, graft);
3398 if (kernel_depth < tile->depth)
3399 node = add_group_write_sync(node, kernel, group, 0);
3402 node = gpu_tree_move_up_to_kernel(node);
3404 return node;
3407 /* Add copy statements to the schedule tree of "node"
3408 * for reading from global memory to shared memory (if "read" is set) or
3409 * for writing back from shared memory to global memory
3410 * (if "read" is not set) for the array reference group "group" that
3411 * is mapped to shared memory.
3412 * On input, "node" points to the kernel node, and it is moved
3413 * back there on output.
3415 * The copies are performed in the order of the corresponding shared
3416 * memory tile.
3417 * The copy statement instances include a reference to the outer
3418 * tile->depth dimensions of the kernel schedule for ease of
3419 * combining them with the group tiling.
3421 * If we are performing a read from global memory to shared memory and
3422 * if the array involved is not a scalar, then we copy
3423 * the entire tile to shared memory. This may result in some extra
3424 * elements getting copied, but it should lead to simpler code
3425 * (which means that fewer registers may be needed) and less divergence.
3427 * Otherwise, we only copy the elements that will be read or have been written
3428 * in the kernel.
3430 * That is, the extra schedule is of the form
3432 * type[D -> A] -> T
3434 * where D corresponds to the outer tile->depth dimensions of
3435 * the kernel schedule, A to the global array and T is the corresponding
3436 * shared memory tile.
3438 * The copying is inserted in the schedule tree through an extension
3439 * of the form
3441 * D -> type[D -> A]
3443 * where the extra domain elements type[D -> A] are those accessed
3444 * by the group. In the case of read from a non-scalar, this set
3445 * is replaced by the entire shared memory tile.
3447 * A filter is inserted on type[D -> A] to map the copy instances
3448 * to the threads. In particular, the thread identifiers are
3449 * equated to the position inside the shared memory tile (T)
3450 * modulo the block size.
3451 * We try to align the innermost tile dimension with the innermost
3452 * thread identifier (x) as a heuristic to improve coalescing.
3453 * In particular, if the dimension of the tile is greater than
3454 * the dimension of the block, then the schedule mapping to the tile
3455 * is broken up into two pieces and the filter is applied to the inner part.
3456 * If, on the other hand, the dimension of the tile is smaller than
3457 * the dimension of the block, then the initial thread identifiers
3458 * are equated to zero and the remaining thread identifiers are
3459 * matched to the memory tile.
3461 * The extension is inserted before the core computation in case of a read
3462 * and after the core computation in case of a write.
3463 * In the case of a read, we first need to make sure there is some
3464 * synchronization before the core computation such that we can put the read
3465 * from global memory to shared memory before that synchronization.
3466 * This ensures that all threads have finished copying into shared memory
3467 * before the shared memory is used.
3468 * We also need to make sure that there is a synchronization node after
3469 * the core computation to ensure that the next load into shared memory
3470 * only happens after all data has been used. There is no need for
3471 * this synchronization if we are at the outer level since then there
3472 * won't be a next load.
3473 * In the case of a write, we need to make sure there is some synchronization
3474 * after the core computation such taht we can put the write from shared
3475 * memory to global memory after that synchronization.
3476 * Unless we are at the outer level, we also need a synchronization node
3477 * after the write to ensure the data is saved to global memory
3478 * before the next iteration write to the same shared memory.
3479 * It also makes sure the data has arrived in global memory before
3480 * it is read in a subsequent iteration.
3482 static __isl_give isl_schedule_node *add_copies_group_shared(
3483 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3484 __isl_take isl_schedule_node *node, int read)
3486 struct gpu_array_tile *tile;
3487 isl_union_map *access;
3488 isl_union_set *domain;
3489 isl_multi_aff *ma;
3490 isl_multi_aff *from_access;
3491 isl_multi_pw_aff *mpa;
3492 isl_multi_union_pw_aff *mupa;
3493 isl_schedule_node *graft;
3494 isl_union_set *filter;
3495 int skip;
3496 int kernel_depth;
3497 int empty;
3499 tile = gpu_array_ref_group_tile(group);
3500 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3501 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3503 access = anchored_non_local_accesses(kernel, group, node, read);
3504 empty = isl_union_map_is_empty(access);
3505 if (empty < 0 || empty) {
3506 isl_union_map_free(access);
3507 if (empty < 0)
3508 return isl_schedule_node_free(node);
3509 return gpu_tree_move_up_to_kernel(node);
3512 group->array->global = 1;
3513 group->local_array->global = 1;
3515 from_access = create_from_access(kernel->ctx, group, read);
3517 ma = isl_multi_aff_copy(tile->tiling);
3518 ma = isl_multi_aff_pullback_multi_aff(ma,
3519 isl_multi_aff_copy(from_access));
3520 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3521 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3523 domain = isl_union_map_range(access);
3525 if (read && !gpu_array_is_scalar(group->array)) {
3526 isl_map *map;
3527 isl_union_set_free(domain);
3528 map = group_tile(group);
3529 domain = isl_union_set_from_set(isl_map_wrap(map));
3532 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3533 access = isl_union_set_wrapped_domain_map(domain);
3534 access = isl_union_map_reverse(access);
3535 access = isl_union_map_coalesce(access);
3536 graft = isl_schedule_node_from_extension(access);
3538 graft = isl_schedule_node_child(graft, 0);
3540 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3542 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3543 graft = isl_schedule_node_band_split(graft,
3544 tile->n - kernel->n_block);
3545 graft = isl_schedule_node_child(graft, 0);
3547 if (tile->n < kernel->n_block)
3548 skip = kernel->n_block - tile->n;
3549 else
3550 skip = 0;
3551 filter = set_schedule_modulo(graft, kernel->thread_ids,
3552 kernel->block_dim);
3553 if (!kernel->options->wrap)
3554 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3555 kernel->options);
3556 if (tile->n > kernel->n_block && kernel->n_block > 0)
3557 graft = isl_schedule_node_parent(graft);
3558 graft = isl_schedule_node_insert_filter(graft, filter);
3560 while (graft && isl_schedule_node_has_parent(graft))
3561 graft = isl_schedule_node_parent(graft);
3563 if (read) {
3564 if (kernel_depth < tile->depth)
3565 node = gpu_tree_ensure_sync_after_core(node, kernel);
3566 node = gpu_tree_move_left_to_sync(node, kernel);
3567 node = isl_schedule_node_graft_before(node, graft);
3568 } else {
3569 node = gpu_tree_move_right_to_sync(node, kernel);
3570 node = isl_schedule_node_graft_after(node, graft);
3571 if (kernel_depth < tile->depth)
3572 node = add_group_write_sync(node, kernel, group, 1);
3575 node = gpu_tree_move_up_to_kernel(node);
3577 return node;
3580 /* Check whether the array reference group "group" is mapped to
3581 * private or shared memory and, if so,
3582 * add copy statements to the schedule tree of "node"
3583 * for reading from global memory to private or shared memory
3584 * (if "read" is set) or for writing back from private or shared memory
3585 * to global memory (if "read" is not set) for this group.
3586 * On input, "node" points to the kernel node, and it is moved
3587 * back there on output.
3589 static __isl_give isl_schedule_node *add_copies_group(
3590 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3591 __isl_take isl_schedule_node *node, int read)
3593 enum ppcg_group_access_type type;
3595 type = gpu_array_ref_group_type(group);
3596 if (type == ppcg_access_private)
3597 return add_copies_group_private(kernel, group, node, read);
3598 if (type == ppcg_access_shared)
3599 return add_copies_group_shared(kernel, group, node, read);
3600 return node;
3603 /* For each array reference group that is mapped to private or shared memory,
3604 * add copy statements to the schedule tree of "node"
3605 * for reading from global memory to private or shared memory
3606 * and for writing back.
3607 * On input, "node" points to the kernel node, and it is moved
3608 * back there on output.
3610 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3611 __isl_take isl_schedule_node *node)
3613 int i, j;
3615 for (i = 0; i < kernel->n_array; ++i) {
3616 struct gpu_local_array_info *array = &kernel->array[i];
3618 for (j = 0; j < array->n_group; ++j) {
3619 struct gpu_array_ref_group *group = array->groups[j];
3621 node = add_copies_group(kernel, group, node, 1);
3622 if (!node)
3623 return NULL;
3624 node = add_copies_group(kernel, group, node, 0);
3625 if (!node)
3626 return NULL;
3630 return node;
3633 /* Mark all dimensions in the current band node atomic.
3635 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3637 return ppcg_set_schedule_node_type(node, isl_ast_loop_atomic);
3640 /* Mark "node" atomic, if it is a band node.
3641 * Do the same for all ancestors.
3642 * Return a pointer to "node" (in the updated schedule tree).
3644 static __isl_give isl_schedule_node *atomic_ancestors(
3645 __isl_take isl_schedule_node *node)
3647 int pos;
3649 if (!node)
3650 return NULL;
3651 if (!isl_schedule_node_has_parent(node))
3652 return node;
3654 pos = isl_schedule_node_get_child_position(node);
3655 node = isl_schedule_node_parent(node);
3656 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3657 node = atomic(node);
3658 node = atomic_ancestors(node);
3659 node = isl_schedule_node_child(node, pos);
3661 return node;
3664 /* Collect all write references that require synchronization.
3665 * "node" is assumed to point to the kernel node.
3666 * Each reference is represented by a universe set in a space
3668 * [S[i,j] -> R[]]
3670 * with S[i,j] the statement instance space and R[] the array reference.
3672 * This function should be called before block and thread filters are added.
3674 * Synchronization is needed after a write if there is a subsequent read
3675 * within the same block that may not be performed by the same thread.
3676 * There should not be any dependences between different blocks,
3677 * so we start with the flow dependences within the same kernel invocation
3678 * and we subtract from these those dependences that are mapped
3679 * to the same iteration of the bands where synchronization is inserted.
3680 * We do not remove pairs of instances that are known to map to
3681 * the same thread across different iterations of the intermediate
3682 * bands because the read may be performed by a different thread
3683 * than the one that needs the value if shared memory is involved.
3685 * We also consider all pairs of possible writes that access the same
3686 * memory location and that may be mapped to the same block but not
3687 * to the same iteration of the intermediate bands.
3688 * In theory, it would be possible for one thread to still be in
3689 * a previous iteration of a loop in these bands.
3690 * A write to global memory in this delayed thread could then overwrite
3691 * a write from another thread that has already moved on to
3692 * the next iteration.
3694 * After computing the above writes paired off with reads or writes
3695 * that depend on them, we project onto the domain writes.
3696 * Sychronization is needed after writes to global memory
3697 * through these references.
3699 static __isl_give isl_union_set *compute_sync_writes(
3700 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3702 isl_union_map *local;
3703 isl_union_map *may_writes, *shared_access;
3704 isl_union_map *kernel_prefix, *thread_prefix;
3705 isl_union_map *equal;
3706 isl_union_set *wrap;
3707 isl_union_set *domain;
3708 isl_union_pw_multi_aff *contraction;
3710 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3711 node = isl_schedule_node_copy(node);
3712 node = gpu_tree_move_down_to_thread(node, kernel->core);
3713 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3714 isl_schedule_node_free(node);
3716 contraction = kernel->contraction;
3717 kernel_prefix = isl_union_map_preimage_domain_union_pw_multi_aff(
3718 kernel_prefix, isl_union_pw_multi_aff_copy(contraction));
3719 thread_prefix = isl_union_map_preimage_domain_union_pw_multi_aff(
3720 thread_prefix, isl_union_pw_multi_aff_copy(contraction));
3721 domain = isl_union_set_copy(kernel->expanded_domain);
3722 domain = isl_union_set_universe(domain);
3724 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3725 may_writes = isl_union_map_curry(may_writes);
3726 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3727 may_writes = isl_union_map_uncurry(may_writes);
3728 shared_access = isl_union_map_copy(may_writes);
3729 shared_access = isl_union_map_apply_range(shared_access,
3730 isl_union_map_reverse(may_writes));
3732 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3733 local = isl_union_map_union(local, shared_access);
3734 local = isl_union_map_zip(local);
3736 equal = isl_union_map_apply_range(kernel_prefix,
3737 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3738 wrap = isl_union_map_wrap(equal);
3739 local = isl_union_map_intersect_domain(local, wrap);
3740 equal = isl_union_map_apply_range(thread_prefix,
3741 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3742 wrap = isl_union_map_wrap(equal);
3743 local = isl_union_map_subtract_domain(local, wrap);
3745 local = isl_union_map_zip(local);
3746 local = isl_union_map_universe(local);
3748 return isl_union_map_domain(local);
3751 /* Group the domain elements into a single space, named kernelX,
3752 * with X the kernel sequence number "kernel_id".
3754 static __isl_give isl_schedule_node *group_statements(
3755 __isl_take isl_schedule_node *node, int kernel_id)
3757 char buffer[20];
3758 isl_id *id;
3760 if (!node)
3761 return NULL;
3763 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3764 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3765 return isl_schedule_node_group(node, id);
3768 /* Create a ppcg_kernel representing the domain instances that reach "node"
3769 * and insert a mark node pointing to the ppcg_kernel before "node".
3770 * The band that "node" points to is the band that needs to be mapped
3771 * to block identifiers. The band that needs to be mapped to thread
3772 * identifiers should be marked by a "thread" mark by the caller.
3773 * This mark is removed by this function.
3774 * If "scale" is set, then the band that "node" points to is scaled
3775 * by "sizes".
3777 * Mark all outer band nodes as atomic to ensure each kernel is only
3778 * scheduled once.
3779 * If the domain elements that reach "node" live in more than one space,
3780 * then group the domain elements into a single space, named kernelX,
3781 * with X the kernel sequence number.
3783 * Insert a guard node governing the kernel node to ensure that
3784 * no kernels with zero blocks are launched.
3786 * Insert a context node describing the block and thread
3787 * identifiers inside the kernel mark.
3788 * The context node needs to be inserted after the effective block size
3789 * has been determined such that the bounds on the thread identifiers
3790 * would reflect the effective block size.
3791 * Insert a filter node inside the context node mapping the statement
3792 * instances to block identifiers. In particular, the block identifiers
3793 * are equated to the partial schedule of band that was marked for mapping
3794 * to blocks modulo the grid size.
3795 * Insert a filter node inside the "thread" mark mapping the statement
3796 * instances to thread identifiers. In particular, the thread identifiers
3797 * are equated to the partial schedule of band that was marked for mapping
3798 * to threads modulo the block size.
3800 * Compute array reference groups for all arrays, set the local
3801 * array bounds based on the set of domain instances that reach
3802 * the kernel node, check the total amount of shared memory used
3803 * and compute all group tilings.
3804 * The array reference groups are computed after the block filter
3805 * has been inserted because it affects the mapping to shared or
3806 * private memory. This computation also requires the thread filter
3807 * (in the ppcg_kernel object), but this thread filter should not
3808 * have been added to the schedule tree yet since the computation
3809 * requires the schedule of the band that needs to be mapped to
3810 * threads before the privatization is applied.
3812 * If any array reference group requires the band mapped to threads
3813 * to be unrolled, then we perform the required unrolling.
3815 * We save a copy of the schedule that may influence the mappings
3816 * to shared or private memory in kernel->copy_schedule.
3818 * Finally, we add synchronization and copy statements to the schedule tree,
3819 * remove the "thread" mark and create representations for the local
3820 * variables in the kernel.
3822 * We keep a copy of the isl_id that points to the kernel to ensure
3823 * that the kernel does not get destroyed if the schedule node
3824 * is freed due to some error condition.
3826 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3827 __isl_take isl_schedule_node *node, int scale,
3828 __isl_keep isl_multi_val *sizes)
3830 struct ppcg_kernel *kernel;
3831 isl_id *id;
3832 isl_schedule_node *node_thread;
3833 isl_union_map *host_schedule;
3834 isl_union_pw_multi_aff *contraction;
3835 isl_set *host_domain;
3836 isl_union_set *domain, *expanded;
3837 int single_statement;
3839 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3840 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3841 if (!kernel)
3842 return isl_schedule_node_free(node);
3844 domain = isl_schedule_node_get_domain(node);
3845 single_statement = isl_union_set_n_set(domain) == 1;
3847 kernel->ctx = gen->ctx;
3848 kernel->prog = gen->prog;
3849 kernel->options = gen->options;
3850 kernel->context = extract_context(node, gen->prog);
3851 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3852 contraction = isl_schedule_node_get_subtree_contraction(node);
3853 kernel->contraction = isl_union_pw_multi_aff_copy(contraction);
3854 expanded = isl_union_set_copy(domain);
3855 expanded = isl_union_set_preimage_union_pw_multi_aff(expanded,
3856 contraction);
3857 kernel->expanded_domain = isl_union_set_copy(expanded);
3858 kernel->arrays = accessed_by_domain(expanded, gen->prog);
3859 kernel->n_grid = n_outer_coincidence(node);
3860 node_thread = isl_schedule_node_copy(node);
3861 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3862 node_thread = isl_schedule_node_child(node_thread, 0);
3863 kernel->n_block = n_outer_coincidence(node_thread);
3864 isl_schedule_node_free(node_thread);
3865 kernel->id = gen->kernel_id++;
3866 read_grid_and_block_sizes(kernel, gen);
3868 kernel->sync_writes = compute_sync_writes(kernel, node);
3870 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3871 host_domain = isl_set_from_union_set(isl_union_map_range(
3872 host_schedule));
3874 node = atomic_ancestors(node);
3876 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3877 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3878 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3880 if (!single_statement)
3881 node = group_statements(node, kernel->id);
3883 node = isl_schedule_node_child(node, 0);
3884 node = split_band(node, kernel->n_grid);
3885 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3886 kernel->n_grid, "b");
3887 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3888 kernel->grid_dim);
3889 kernel->grid_size = extract_grid_size(kernel,
3890 isl_union_set_copy(domain));
3891 if (!kernel->options->wrap)
3892 node = snap_band_to_sizes(node, kernel->grid_dim,
3893 kernel->options);
3894 if (scale)
3895 node = scale_band(node, isl_multi_val_copy(sizes));
3896 node = isl_schedule_node_parent(node);
3897 if (!single_statement)
3898 node = isl_schedule_node_parent(node);
3899 node = insert_guard(node, kernel->context, kernel->grid_size,
3900 gen->prog->scop);
3901 node = gpu_tree_move_down_to_thread(node, kernel->core);
3902 node = isl_schedule_node_child(node, 0);
3903 node = split_band(node, kernel->n_block);
3904 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3905 kernel->n_block, "t");
3906 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3907 kernel->block_dim);
3908 if (extract_block_size(kernel, domain) < 0)
3909 node = isl_schedule_node_free(node);
3911 node = gpu_tree_move_up_to_kernel(node);
3912 node = isl_schedule_node_child(node, 0);
3913 node = insert_context(kernel, node);
3914 node = isl_schedule_node_child(node, 0);
3915 node = isl_schedule_node_insert_filter(node,
3916 isl_union_set_copy(kernel->block_filter));
3918 node = gpu_tree_move_up_to_kernel(node);
3920 if (gpu_group_references(kernel, node) < 0)
3921 node = isl_schedule_node_free(node);
3922 localize_bounds(kernel, host_domain);
3923 isl_set_free(host_domain);
3925 check_shared_memory_bound(kernel);
3926 mark_global_arrays(kernel);
3927 compute_group_tilings(kernel);
3929 node = gpu_tree_move_down_to_thread(node, kernel->core);
3930 node = isl_schedule_node_child(node, 0);
3931 if (!kernel->options->wrap)
3932 node = snap_band_to_sizes(node, kernel->block_dim,
3933 kernel->options);
3934 node = isl_schedule_node_insert_filter(node,
3935 isl_union_set_copy(kernel->thread_filter));
3936 if (kernel_requires_unroll(kernel)) {
3937 node = isl_schedule_node_child(node, 0);
3938 node = unroll(node);
3941 node = gpu_tree_move_up_to_thread(node);
3942 kernel->copy_schedule_dim = isl_schedule_node_get_schedule_depth(node);
3943 kernel->copy_schedule =
3944 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3945 contraction = isl_union_pw_multi_aff_copy(kernel->contraction);
3946 kernel->copy_schedule =
3947 isl_union_pw_multi_aff_pullback_union_pw_multi_aff(
3948 kernel->copy_schedule, contraction);
3950 node = gpu_tree_move_up_to_kernel(node);
3952 node = add_sync(kernel, node);
3953 node = add_copies(kernel, node);
3955 node = gpu_tree_move_down_to_thread(node, kernel->core);
3956 node = isl_schedule_node_delete(node);
3958 node = gpu_tree_move_up_to_kernel(node);
3960 if (create_kernel_vars(kernel) < 0)
3961 node = isl_schedule_node_free(node);
3963 if (!single_statement)
3964 node = isl_schedule_node_parent(node);
3965 node = isl_schedule_node_parent(node);
3967 isl_id_free(id);
3968 return node;
3971 /* Insert a zero-dimensional permutable band at "node".
3973 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3974 __isl_take isl_schedule_node *node)
3976 isl_space *space;
3977 isl_schedule *schedule;
3978 isl_union_set *domain;
3979 isl_multi_union_pw_aff *mupa;
3981 schedule = isl_schedule_node_get_schedule(node);
3982 domain = isl_schedule_get_domain(schedule);
3983 space = isl_union_set_get_space(domain);
3984 isl_union_set_free(domain);
3985 isl_schedule_free(schedule);
3987 space = isl_space_set_from_params(space);
3988 mupa = isl_multi_union_pw_aff_zero(space);
3989 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3990 node = isl_schedule_node_band_set_permutable(node, 1);
3992 return node;
3995 /* If "node" is the outermost permutable band that can be mapped to block and
3996 * thread identifiers in its branch (or the root of a subtree with
3997 * no such outer bands),
3998 * then mark the band as such, attaching a ppcg_kernel to the mark.
4000 * If "node" is the root of a subtree without permutable bands,
4001 * then insert a zero-dimensional permutable band such that
4002 * we can assume that "node" always points to a band node.
4003 * This includes the case where "node" already points to a band node,
4004 * but one without any coincident dimension. In this case,
4005 * the extra node ensures that this original node does not get tiled.
4007 * Tile "node" using user specified tile sizes, after splitting the band
4008 * if the number of specified tile sizes is smaller than the dimension
4009 * of the band. Mark the point band of this tiling as the band that
4010 * needs to be mapped to threads.
4011 * Create a kernel representing the domain instances that reach "node" and
4012 * insert a mark node pointing to the ppcg_kernel before the band node.
4014 static __isl_give isl_schedule_node *mark_outer_permutable(
4015 __isl_take isl_schedule_node *node, void *user)
4017 struct gpu_gen *gen = user;
4018 int outer;
4019 int scale;
4020 int tile_len;
4021 int *tile_size;
4022 isl_id *id;
4023 isl_multi_val *sizes;
4025 outer = is_outer_tilable(node);
4026 if (outer < 0)
4027 return isl_schedule_node_free(node);
4028 if (!outer)
4029 return node;
4031 if (isl_schedule_node_get_type(node) != isl_schedule_node_band ||
4032 !isl_schedule_node_band_member_get_coincident(node, 0))
4033 node = insert_empty_permutable_band(node);
4035 tile_len = isl_schedule_node_band_n_member(node);
4036 tile_size = read_tile_sizes(gen, &tile_len);
4037 if (!tile_size)
4038 return isl_schedule_node_free(node);
4039 if (tile_len < isl_schedule_node_band_n_member(node))
4040 node = isl_schedule_node_band_split(node, tile_len);
4041 sizes = construct_band_tiles_sizes(node, tile_size);
4042 node = tile_band(node, isl_multi_val_copy(sizes));
4043 node = isl_schedule_node_child(node, 0);
4044 id = isl_id_alloc(gen->ctx, "thread", NULL);
4045 node = isl_schedule_node_insert_mark(node, id);
4046 node = isl_schedule_node_parent(node);
4048 scale = gen->options->scale_tile_loops;
4049 node = create_kernel(gen, node, scale, sizes);
4050 isl_multi_val_free(sizes);
4051 free(tile_size);
4053 return node;
4056 /* Given a set or sequence node, return the union the filters of either all
4057 * (if "only_initial" is not set) or the initial (if "only_initial" is set)
4058 * direct subtrees that do not contain any suitably permutable bands
4059 * (according to subtree_has_permutable_bands).
4061 static __isl_give isl_union_set *get_non_parallel_subtree_filters(
4062 __isl_keep isl_schedule_node *node, int only_initial)
4064 isl_space *space;
4065 isl_union_set *filter;
4066 int i, n;
4068 n = isl_schedule_node_n_children(node);
4069 if (n < 0)
4070 return NULL;
4072 node = isl_schedule_node_copy(node);
4073 node = isl_schedule_node_child(node, 0);
4074 filter = isl_schedule_node_filter_get_filter(node);
4075 node = isl_schedule_node_parent(node);
4076 space = isl_union_set_get_space(filter);
4077 isl_union_set_free(filter);
4078 filter = isl_union_set_empty(space);
4080 for (i = 0; i < n; ++i) {
4081 int parallelism;
4083 node = isl_schedule_node_child(node, i);
4084 parallelism = subtree_has_permutable_bands(node);
4085 if (parallelism < 0) {
4086 filter = isl_union_set_free(filter);
4087 } else if (!parallelism) {
4088 isl_union_set *filter_i;
4089 filter_i = isl_schedule_node_filter_get_filter(node);
4090 filter = isl_union_set_union(filter, filter_i);
4091 } else if (only_initial)
4092 break;
4093 node = isl_schedule_node_parent(node);
4096 isl_schedule_node_free(node);
4098 return filter;
4101 /* Given a set or sequence node, return the union of the filters of
4102 * the direct subtrees that do not contain any suitably permutable bands
4103 * (according to subtree_has_permutable_bands).
4105 static __isl_give isl_union_set *get_all_non_parallel_subtree_filters(
4106 __isl_keep isl_schedule_node *node)
4108 return get_non_parallel_subtree_filters(node, 0);
4111 /* Given a set or sequence node, return the union of the filters of
4112 * the initial direct subtrees that do not contain any suitably permutable
4113 * bands (according to subtree_has_permutable_bands).
4115 static __isl_give isl_union_set *get_initial_non_parallel_subtree_filters(
4116 __isl_keep isl_schedule_node *node)
4118 return get_non_parallel_subtree_filters(node, 1);
4121 /* Mark all variables that are accessed by the statement instances in "domain"
4122 * and that are local to "prog" as requiring a declaration in the host code.
4123 * The statement instances in "domain" correspond to (a subset of)
4124 * the active instances at "node".
4125 * "node" is not modified by this function, except that NULL is returned
4126 * in case of error.
4128 static __isl_give isl_schedule_node *declare_accessed_local_variables(
4129 __isl_take isl_schedule_node *node, struct gpu_prog *prog,
4130 __isl_keep isl_union_set *domain)
4132 isl_union_pw_multi_aff *contraction;
4133 isl_union_set *arrays;
4134 int i;
4136 if (!ppcg_scop_any_hidden_declarations(prog->scop))
4137 return node;
4138 contraction = isl_schedule_node_get_subtree_contraction(node);
4139 domain = isl_union_set_copy(domain);
4140 domain = isl_union_set_preimage_union_pw_multi_aff(domain, contraction);
4141 arrays = accessed_by_domain(domain, prog);
4143 for (i = 0; i < prog->n_array; ++i) {
4144 isl_space *space;
4145 isl_set *set;
4146 int empty;
4148 if (!prog->array[i].local)
4149 continue;
4150 space = isl_set_get_space(prog->array[i].extent);
4151 set = isl_union_set_extract_set(arrays, space);
4152 empty = isl_set_plain_is_empty(set);
4153 isl_set_free(set);
4154 if (empty < 0)
4155 goto error;
4156 if (!empty)
4157 prog->array[i].declare_local = 1;
4160 isl_union_set_free(arrays);
4161 return node;
4162 error:
4163 isl_union_set_free(arrays);
4164 return isl_schedule_node_free(node);
4167 /* If "node" points to a set node, then separate its children
4168 * into subtrees that have suitably permutable bands and
4169 * those that do not.
4170 * Adjust the schedule tree in order to execute the second group
4171 * after the first group and return a pointer to the first group,
4172 * assuming there are any such subtrees.
4173 * If "node" points to a sequence node, then separate the initial
4174 * children that do not have suitably permutable bands and
4175 * return a pointer to the subsequence of children that do have such bands,
4176 * assuming there are any such subtrees.
4178 * In both cases, mark all local variables in "prog" that are accessed by
4179 * the group without permutable bands as requiring a declaration on the host.
4181 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
4182 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
4184 isl_union_set *filter;
4185 enum isl_schedule_node_type type;
4187 if (!node)
4188 return NULL;
4189 type = isl_schedule_node_get_type(node);
4190 if (type == isl_schedule_node_set) {
4191 filter = get_all_non_parallel_subtree_filters(node);
4192 node = declare_accessed_local_variables(node, prog, filter);
4193 node = isl_schedule_node_order_after(node, filter);
4194 } else if (type == isl_schedule_node_sequence) {
4195 filter = get_initial_non_parallel_subtree_filters(node);
4196 node = declare_accessed_local_variables(node, prog, filter);
4197 node = isl_schedule_node_order_before(node, filter);
4200 return node;
4203 /* Replace any reference to an array element in the range of "copy"
4204 * by a reference to all array elements (defined by the extent of the array).
4206 static __isl_give isl_union_map *approximate_copy_out(
4207 __isl_take isl_union_map *copy, struct gpu_prog *prog)
4209 int i;
4210 isl_union_map *res;
4212 res = isl_union_map_empty(isl_union_map_get_space(copy));
4214 for (i = 0; i < prog->n_array; ++i) {
4215 isl_space *space;
4216 isl_set *set;
4217 isl_union_map *copy_i;
4218 isl_union_set *extent, *domain;
4220 space = isl_space_copy(prog->array[i].space);
4221 extent = isl_union_set_from_set(isl_set_universe(space));
4222 copy_i = isl_union_map_copy(copy);
4223 copy_i = isl_union_map_intersect_range(copy_i, extent);
4224 set = isl_set_copy(prog->array[i].extent);
4225 extent = isl_union_set_from_set(set);
4226 domain = isl_union_map_domain(copy_i);
4227 copy_i = isl_union_map_from_domain_and_range(domain, extent);
4228 res = isl_union_map_union(res, copy_i);
4231 isl_union_map_free(copy);
4233 return res;
4236 /* Insert "kernel" marks that point to a ppcg_kernel structure
4237 * in front of all outermost tilable band that (by construction)
4238 * have at least one parallel loop.
4240 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
4241 __isl_take isl_schedule_node *node)
4243 return isl_schedule_node_map_descendant_bottom_up(node,
4244 &mark_outer_permutable, gen);
4247 /* Construct schedule constraints from the dependences in prog->scop and
4248 * the array order dependences in prog->array_order.
4250 * If live range reordering is allowed, then we need to make sure
4251 * that live ranges on arrays are not run in parallel since doing
4252 * so would require array expansion. We therefore add the array
4253 * order dependences to the coincidence dependences. Non-zero array
4254 * order dependences will then prevent a schedule dimension from being
4255 * considered parallel.
4256 * Live ranges derived from scalars are allowed to be run in parallel
4257 * since we force the scalars to be mapped to private memory in
4258 * check_scalar_live_ranges.
4259 * If live range reordering is allowed, then the false dependences
4260 * are not added to the validity constraints as that would prevent
4261 * reordering. Instead, the external false dependences that enforce that reads
4262 * from potentially live-in data precede any later write and
4263 * that writes of potentially live-out data follow any other earlier write
4264 * are added to the validity and the coincidence constraints.
4265 * The false dependences are still added to the proximity constraints
4266 * for consistency with the case where live range reordering is not allowed.
4267 * The coincidence constraints then consist of flow dependences,
4268 * external false dependences and array order dependences.
4269 * The independences can be filtered out from the first two sets.
4270 * They have already been filtered out from the array order dependences
4271 * on a per array basis in collect_order_dependences.
4272 * There is no need for a per array handling of the other two sets
4273 * as there should be no flow or external false dependence on local
4274 * variables that can be filtered out.
4276 static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4277 struct gpu_prog *prog)
4279 isl_union_set *domain;
4280 isl_union_map *dep_raw, *dep;
4281 isl_union_map *validity, *proximity, *coincidence;
4282 isl_schedule_constraints *sc;
4284 domain = isl_union_set_copy(prog->scop->domain);
4285 sc = isl_schedule_constraints_on_domain(domain);
4286 sc = isl_schedule_constraints_set_context(sc,
4287 isl_set_copy(prog->scop->context));
4288 if (prog->scop->options->live_range_reordering) {
4289 sc = isl_schedule_constraints_set_conditional_validity(sc,
4290 isl_union_map_copy(prog->scop->tagged_dep_flow),
4291 isl_union_map_copy(prog->scop->tagged_dep_order));
4292 proximity = isl_union_map_copy(prog->scop->dep_flow);
4293 validity = isl_union_map_copy(proximity);
4294 validity = isl_union_map_union(validity,
4295 isl_union_map_copy(prog->scop->dep_forced));
4296 proximity = isl_union_map_union(proximity,
4297 isl_union_map_copy(prog->scop->dep_false));
4298 coincidence = isl_union_map_copy(validity);
4299 coincidence = isl_union_map_subtract(coincidence,
4300 isl_union_map_copy(prog->scop->independence));
4301 coincidence = isl_union_map_union(coincidence,
4302 isl_union_map_copy(prog->array_order));
4303 } else {
4304 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4305 dep = isl_union_map_copy(prog->scop->dep_false);
4306 dep = isl_union_map_union(dep, dep_raw);
4307 dep = isl_union_map_coalesce(dep);
4308 proximity = isl_union_map_copy(dep);
4309 coincidence = isl_union_map_copy(dep);
4310 validity = dep;
4312 sc = isl_schedule_constraints_set_validity(sc, validity);
4313 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4314 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4316 if (prog->scop->options->debug->dump_schedule_constraints)
4317 isl_schedule_constraints_dump(sc);
4318 return sc;
4321 /* Compute an appropriate schedule based on the accesses in
4322 * gen->read and gen->write.
4324 * We derive schedule constraints from the dependences in gen->prog->scop
4325 * and then use isl to compute a schedule that has a parallel loop
4326 * in each tilable band.
4327 * During the schedule construction, some statement instances
4328 * may be grouped first based on the input schedule.
4330 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4332 isl_schedule_constraints *sc;
4333 isl_schedule *schedule;
4335 sc = construct_schedule_constraints(gen->prog);
4336 schedule = gen->prog->scop->schedule;
4337 schedule = ppcg_compute_schedule(sc, schedule, gen->options);
4339 return schedule;
4342 /* If the band node "node" has exactly one member then mark it permutable.
4344 static __isl_give isl_schedule_node *band_set_permutable(
4345 __isl_take isl_schedule_node *node,
4346 __isl_keep isl_schedule_constraints *sc)
4348 if (isl_schedule_node_band_n_member(node) == 1)
4349 node = isl_schedule_node_band_set_permutable(node, 1);
4351 return node;
4354 /* Return the coincidence constraints between pairs of instances
4355 * that are scheduled together by the ancestors of "node".
4356 * That is, select those coincidence constraints that relate
4357 * pairs of instances that have the same value for the prefix schedule.
4358 * If the schedule depth is zero, then the prefix schedule does not
4359 * contain any information, so we intersect domain and range
4360 * of the schedule constraints with the reaching domain elements instead.
4362 static __isl_give isl_union_map *get_local_coincidence(
4363 __isl_keep isl_schedule_node *node,
4364 __isl_keep isl_schedule_constraints *sc)
4366 isl_union_map *coincidence;
4367 isl_multi_union_pw_aff *prefix;
4368 isl_union_pw_multi_aff *contraction;
4370 coincidence = isl_schedule_constraints_get_coincidence(sc);
4371 contraction = isl_schedule_node_get_subtree_contraction(node);
4372 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4373 isl_union_set *domain;
4375 domain = isl_schedule_node_get_domain(node);
4376 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4377 contraction);
4378 coincidence = isl_union_map_intersect_domain(coincidence,
4379 isl_union_set_copy(domain));
4380 coincidence = isl_union_map_intersect_range(coincidence,
4381 domain);
4382 return coincidence;
4385 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4386 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4387 contraction);
4388 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4391 /* For each member in the band node "node", determine whether
4392 * it is coincident with respect to the outer nodes and mark
4393 * it accordingly.
4395 * That is, for each coincidence constraint between pairs
4396 * of instances that are scheduled together by the outer nodes,
4397 * check that domain and range are assigned the same value
4398 * by the band member. This test is performed by checking
4399 * that imposing the same value for the band member does not
4400 * remove any elements from the set of coincidence constraints.
4402 static __isl_give isl_schedule_node *band_set_coincident(
4403 __isl_take isl_schedule_node *node,
4404 __isl_keep isl_schedule_constraints *sc)
4406 isl_union_map *coincidence;
4407 isl_union_pw_multi_aff *contraction;
4408 isl_multi_union_pw_aff *partial;
4409 int i, n;
4411 coincidence = get_local_coincidence(node, sc);
4413 partial = isl_schedule_node_band_get_partial_schedule(node);
4414 contraction = isl_schedule_node_get_subtree_contraction(node);
4415 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4416 contraction);
4417 n = isl_schedule_node_band_n_member(node);
4418 for (i = 0; i < n; ++i) {
4419 isl_union_map *coincidence_i;
4420 isl_union_pw_aff *upa;
4421 isl_multi_union_pw_aff *partial_i;
4422 int subset;
4424 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4425 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4426 coincidence_i = isl_union_map_copy(coincidence);
4427 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4428 coincidence_i, partial_i);
4429 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4430 isl_union_map_free(coincidence_i);
4432 if (subset < 0)
4433 break;
4434 node = isl_schedule_node_band_member_set_coincident(node, i,
4435 subset);
4437 if (i < n)
4438 node = isl_schedule_node_free(node);
4439 isl_multi_union_pw_aff_free(partial);
4440 isl_union_map_free(coincidence);
4442 return node;
4445 /* If "node" is a band, then set its properties.
4447 * In particular, if the band has exactly one member, then mark it permutable.
4448 * Mark the band member coincident based on the coincidence constraints
4449 * of "sc".
4451 static __isl_give isl_schedule_node *set_band_properties(
4452 __isl_take isl_schedule_node *node, void *user)
4454 isl_schedule_constraints *sc = user;
4456 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4457 return node;
4458 if (isl_schedule_node_band_n_member(node) == 0)
4459 return node;
4461 node = band_set_permutable(node, sc);
4462 node = band_set_coincident(node, sc);
4464 return node;
4467 /* Return the original schedule with all bands marked permutable and
4468 * all band members marked coincident based on the coincidence constraints.
4469 * The bands are explicitly marked permutable so that they will be considered
4470 * by mark_outer_permutable.
4472 static __isl_give isl_schedule *determine_properties_original_schedule(
4473 struct gpu_gen *gen)
4475 isl_schedule *schedule;
4476 isl_schedule_constraints *sc;
4478 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4479 sc = construct_schedule_constraints(gen->prog);
4480 schedule = isl_schedule_map_schedule_node_bottom_up(schedule,
4481 &set_band_properties, sc);
4482 isl_schedule_constraints_free(sc);
4484 return schedule;
4487 /* Compute a schedule or determine the properties of the original schedule
4488 * depending on the value of the "reschedule" option.
4490 static __isl_give isl_schedule *compute_or_set_properties(void *user)
4492 struct gpu_gen *gen = user;
4494 if (gen->options->reschedule)
4495 return compute_schedule(gen);
4496 else
4497 return determine_properties_original_schedule(gen);
4500 /* Obtain a schedule for the scop, by reading it from
4501 * a file, by computing one or by determining the properties
4502 * of the original schedule.
4504 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4506 return ppcg_get_schedule(gen->ctx, gen->options,
4507 &compute_or_set_properties, gen);
4510 /* Construct the string "<a>_<b>".
4512 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4514 isl_printer *p;
4515 char *s;
4517 p = isl_printer_to_str(ctx);
4518 p = isl_printer_print_str(p, a);
4519 p = isl_printer_print_str(p, "_");
4520 p = isl_printer_print_str(p, b);
4521 s = isl_printer_get_str(p);
4522 isl_printer_free(p);
4524 return s;
4527 /* For each array in "prog" of which an element appears in "accessed" and
4528 * that is not a read only scalar, create a zero-dimensional universe set
4529 * of which the tuple id has name "<prefix>_<name of array>" and a user
4530 * pointer pointing to the array (gpu_array_info).
4532 * If the array is local to "prog", then make sure it will be declared
4533 * in the host code.
4535 * Return the list of these universe sets.
4537 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4538 const char *prefix, __isl_take isl_union_set *accessed)
4540 int i;
4541 isl_ctx *ctx;
4542 isl_union_set_list *filters;
4544 ctx = prog->ctx;
4545 filters = isl_union_set_list_alloc(ctx, 0);
4546 for (i = 0; i < prog->n_array; ++i) {
4547 struct gpu_array_info *array = &prog->array[i];
4548 isl_space *space;
4549 isl_set *accessed_i;
4550 int empty;
4551 char *name;
4552 isl_id *id;
4553 isl_union_set *uset;
4555 if (gpu_array_is_read_only_scalar(array))
4556 continue;
4558 space = isl_space_copy(array->space);
4559 accessed_i = isl_union_set_extract_set(accessed, space);
4560 empty = isl_set_plain_is_empty(accessed_i);
4561 isl_set_free(accessed_i);
4562 if (empty < 0) {
4563 filters = isl_union_set_list_free(filters);
4564 break;
4566 if (empty)
4567 continue;
4569 array->global = 1;
4570 if (array->local)
4571 array->declare_local = 1;
4573 name = concat(ctx, prefix, array->name);
4574 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4575 free(name);
4576 space = isl_space_set_alloc(ctx, 0, 0);
4577 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4578 uset = isl_union_set_from_set(isl_set_universe(space));
4580 filters = isl_union_set_list_add(filters, uset);
4582 isl_union_set_free(accessed);
4584 return filters;
4587 /* Make sure that code for the statements in "filters" that
4588 * copy arrays to or from the device is only generated when
4589 * the size of the corresponding array is positive.
4590 * That is, add a set node underneath "graft" with "filters" as children
4591 * and for each child add a guard that the selects the parameter
4592 * values for which the corresponding array has a positive size.
4593 * The array is available in the user pointer of the statement identifier.
4594 * "depth" is the schedule depth of the position where "graft"
4595 * will be added.
4597 static __isl_give isl_schedule_node *insert_positive_size_guards(
4598 __isl_take isl_schedule_node *graft,
4599 __isl_take isl_union_set_list *filters, int depth)
4601 int i, n;
4603 graft = isl_schedule_node_child(graft, 0);
4604 graft = isl_schedule_node_insert_set(graft, filters);
4605 n = isl_schedule_node_n_children(graft);
4606 for (i = 0; i < n; ++i) {
4607 isl_union_set *filter;
4608 isl_set *domain, *guard;
4609 isl_id *id;
4610 struct gpu_array_info *array;
4612 graft = isl_schedule_node_child(graft, i);
4613 filter = isl_schedule_node_filter_get_filter(graft);
4614 domain = isl_set_from_union_set(filter);
4615 id = isl_set_get_tuple_id(domain);
4616 array = isl_id_get_user(id);
4617 isl_id_free(id);
4618 isl_set_free(domain);
4619 guard = gpu_array_positive_size_guard(array);
4620 guard = isl_set_from_params(guard);
4621 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4622 graft = isl_schedule_node_child(graft, 0);
4623 graft = isl_schedule_node_insert_guard(graft, guard);
4624 graft = isl_schedule_node_parent(graft);
4625 graft = isl_schedule_node_parent(graft);
4627 graft = isl_schedule_node_parent(graft);
4629 return graft;
4632 /* Create a graft for copying arrays to or from the device,
4633 * whenever the size of the array is strictly positive.
4634 * Each statement is called "<prefix>_<name of array>" and
4635 * the identifier has a user pointer pointing to the array.
4636 * The graft will be added at the position specified by "node".
4637 * "copy" contains the array elements that need to be copied.
4638 * Only arrays of which some elements need to be copied
4639 * will have a corresponding statement in the graph.
4640 * Note though that each such statement will copy the entire array.
4642 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4643 __isl_keep isl_schedule_node *node, const char *prefix,
4644 __isl_take isl_union_set *copy)
4646 int depth;
4647 isl_ctx *ctx;
4648 isl_space *space;
4649 isl_union_set *all, *domain;
4650 isl_union_set_list *filters;
4651 isl_union_map *extension;
4652 isl_schedule_node *graft;
4654 ctx = prog->ctx;
4655 depth = isl_schedule_node_get_schedule_depth(node);
4656 filters = create_copy_filters(prog, prefix, copy);
4657 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4659 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4660 domain = isl_union_set_from_set(isl_set_universe(space));
4661 extension = isl_union_map_from_domain_and_range(domain, all);
4662 graft = isl_schedule_node_from_extension(extension);
4664 if (!filters)
4665 return isl_schedule_node_free(graft);
4666 if (isl_union_set_list_n_union_set(filters) == 0) {
4667 isl_union_set_list_free(filters);
4668 return graft;
4671 return insert_positive_size_guards(graft, filters, depth);
4674 /* Return (the universe spaces of) the arrays that are declared
4675 * inside the scop corresponding to "prog" and for which all
4676 * potential writes inside the scop form a subset of "domain".
4678 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4679 __isl_keep isl_union_set *domain)
4681 int i;
4682 isl_union_set *local;
4684 local = isl_union_set_empty(isl_union_set_get_space(domain));
4686 for (i = 0; i < prog->n_array; ++i) {
4687 isl_set *set;
4688 isl_union_map *to_outer;
4689 isl_union_map *may_write;
4690 isl_union_set *write_domain;
4691 isl_union_set *fields;
4692 int subset;
4694 if (!prog->array[i].local)
4695 continue;
4697 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4698 to_outer = isl_union_map_copy(prog->to_outer);
4699 to_outer = isl_union_map_intersect_range(to_outer,
4700 isl_union_set_from_set(isl_set_copy(set)));
4701 fields = isl_union_map_domain(to_outer);
4702 may_write = isl_union_map_copy(prog->may_write);
4703 may_write = isl_union_map_intersect_range(may_write, fields);
4704 write_domain = isl_union_map_domain(may_write);
4705 subset = isl_union_set_is_subset(write_domain, domain);
4706 isl_union_set_free(write_domain);
4708 if (subset < 0) {
4709 isl_set_free(set);
4710 return isl_union_set_free(local);
4711 } else if (subset) {
4712 local = isl_union_set_add_set(local, set);
4713 } else {
4714 isl_set_free(set);
4718 return local;
4721 /* Internal data structure for node_may_persist.
4723 * "tagger" maps tagged iteration domains to the corresponding untagged
4724 * iteration domain.
4726 * "may_persist_flow" is the set of all tagged dataflow dependences
4727 * with those dependences removed that either precede or follow
4728 * the kernel launch in a sequence.
4729 * "inner_band_flow" is the set of all tagged dataflow dependences
4730 * that are local to a given iteration of the outer band nodes
4731 * with respect to the current node.
4732 * "local_flow" is equal to "inner_band_flow", except that the domain
4733 * and the range have been intersected with intermediate filters
4734 * on children of sets or sequences.
4736 struct ppcg_may_persist_data {
4737 isl_union_pw_multi_aff *tagger;
4739 isl_union_map *local_flow;
4740 isl_union_map *inner_band_flow;
4741 isl_union_map *may_persist_flow;
4744 /* Update the information in "data" based on the band ancestor "node".
4746 * In particular, we restrict the dependences in data->local_flow
4747 * to those dependence where the source and the sink occur in
4748 * the same iteration of the given band node.
4749 * We also update data->inner_band_flow to the new value of
4750 * data->local_flow.
4752 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4753 struct ppcg_may_persist_data *data)
4755 isl_multi_union_pw_aff *partial;
4756 isl_union_pw_multi_aff *contraction;
4757 isl_union_map *flow;
4759 if (isl_schedule_node_band_n_member(node) == 0)
4760 return 0;
4762 partial = isl_schedule_node_band_get_partial_schedule(node);
4763 contraction = isl_schedule_node_get_subtree_contraction(node);
4764 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4765 contraction);
4766 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4767 isl_union_pw_multi_aff_copy(data->tagger));
4769 flow = data->local_flow;
4770 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4771 data->local_flow = flow;
4773 isl_union_map_free(data->inner_band_flow);
4774 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4776 return 0;
4779 /* Given a set of local reaching domain elements "domain",
4780 * expand them to the corresponding leaf domain elements using "contraction"
4781 * and insert the array references tags using data->tagger.
4783 static __isl_give isl_union_set *expand_and_tag(
4784 __isl_take isl_union_set *domain,
4785 __isl_take isl_union_pw_multi_aff *contraction,
4786 struct ppcg_may_persist_data *data)
4788 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4789 contraction);
4790 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4791 isl_union_pw_multi_aff_copy(data->tagger));
4792 return domain;
4795 /* Given a filter node that is the child of a set or sequence node,
4796 * restrict data->local_flow to refer only to those elements
4797 * in the filter of the node.
4798 * "contraction" maps the leaf domain elements of the schedule tree
4799 * to the corresponding domain elements at (the parent of) "node".
4801 static int filter_flow(__isl_keep isl_schedule_node *node,
4802 struct ppcg_may_persist_data *data,
4803 __isl_take isl_union_pw_multi_aff *contraction)
4805 isl_union_set *filter;
4806 isl_union_map *flow;
4808 flow = data->local_flow;
4809 filter = isl_schedule_node_filter_get_filter(node);
4810 filter = expand_and_tag(filter, contraction, data);
4811 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4812 flow = isl_union_map_intersect_range(flow, filter);
4813 data->local_flow = flow;
4815 return 0;
4818 /* Given a filter node "node", collect the filters on all preceding siblings
4819 * (which are also filter nodes), add them to "filters" and return the result.
4821 static __isl_give isl_union_set *add_previous_filters(
4822 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4824 isl_schedule_node *sibling;
4826 sibling = isl_schedule_node_copy(node);
4827 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4828 isl_union_set *filter;
4830 sibling = isl_schedule_node_previous_sibling(sibling);
4831 filter = isl_schedule_node_filter_get_filter(sibling);
4832 filters = isl_union_set_union(filters, filter);
4834 isl_schedule_node_free(sibling);
4835 if (!sibling)
4836 return isl_union_set_free(filters);
4838 return filters;
4841 /* Given a filter node "node", collect the filters on all following siblings
4842 * (which are also filter nodes), add them to "filters" and return the result.
4844 static __isl_give isl_union_set *add_next_filters(
4845 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4847 isl_schedule_node *sibling;
4849 sibling = isl_schedule_node_copy(node);
4850 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4851 isl_union_set *filter;
4853 sibling = isl_schedule_node_next_sibling(sibling);
4854 filter = isl_schedule_node_filter_get_filter(sibling);
4855 filters = isl_union_set_union(filters, filter);
4857 isl_schedule_node_free(sibling);
4858 if (!sibling)
4859 return isl_union_set_free(filters);
4861 return filters;
4864 /* Remove those flow dependences from data->may_persist_flow
4865 * that flow between elements of "domain" within the same iteration
4866 * of all outer band nodes.
4867 * "contraction" maps the leaf domain elements of the schedule tree
4868 * to the corresponding elements "domain".
4870 static void remove_external_flow(struct ppcg_may_persist_data *data,
4871 __isl_take isl_union_set *domain,
4872 __isl_keep isl_union_pw_multi_aff *contraction)
4874 isl_union_map *flow;
4876 contraction = isl_union_pw_multi_aff_copy(contraction);
4877 domain = expand_and_tag(domain, contraction, data);
4878 flow = isl_union_map_copy(data->local_flow);
4879 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4880 flow = isl_union_map_intersect_range(flow, domain);
4882 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4883 flow);
4886 /* Update the information in "data" based on the filter ancestor "node".
4887 * We only need to modify anything if the filter is the child
4888 * of a set or sequence node.
4890 * In the case of a sequence, we remove the dependences between
4891 * statement instances that are both executed either before or
4892 * after the subtree that will be mapped to a kernel, within
4893 * the same iteration of outer bands.
4895 * In both cases, we restrict data->local_flow to the current child.
4897 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4898 struct ppcg_may_persist_data *data)
4900 enum isl_schedule_node_type type;
4901 isl_schedule_node *parent;
4902 isl_space *space;
4903 isl_union_pw_multi_aff *contraction;
4904 isl_union_set *before, *after, *filter;
4906 type = isl_schedule_node_get_parent_type(node);
4907 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4908 return 0;
4910 parent = isl_schedule_node_copy(node);
4911 parent = isl_schedule_node_parent(parent);
4912 contraction = isl_schedule_node_get_subtree_contraction(parent);
4913 isl_schedule_node_free(parent);
4915 if (type == isl_schedule_node_set)
4916 return filter_flow(node, data, contraction);
4918 filter = isl_schedule_node_filter_get_filter(node);
4919 space = isl_union_set_get_space(filter);
4920 isl_union_set_free(filter);
4921 before = isl_union_set_empty(space);
4922 after = isl_union_set_copy(before);
4923 before = add_previous_filters(before, node);
4924 after = add_next_filters(after, node);
4926 remove_external_flow(data, before, contraction);
4927 remove_external_flow(data, after, contraction);
4929 return filter_flow(node, data, contraction);
4932 /* Update the information in "data" based on the ancestor "node".
4934 static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
4935 void *user)
4937 struct ppcg_may_persist_data *data = user;
4939 switch (isl_schedule_node_get_type(node)) {
4940 case isl_schedule_node_error:
4941 return isl_stat_error;
4942 case isl_schedule_node_context:
4943 case isl_schedule_node_domain:
4944 case isl_schedule_node_expansion:
4945 case isl_schedule_node_extension:
4946 case isl_schedule_node_guard:
4947 case isl_schedule_node_leaf:
4948 case isl_schedule_node_mark:
4949 case isl_schedule_node_sequence:
4950 case isl_schedule_node_set:
4951 break;
4952 case isl_schedule_node_band:
4953 if (update_may_persist_at_band(node, data) < 0)
4954 return isl_stat_error;
4955 break;
4956 case isl_schedule_node_filter:
4957 if (update_may_persist_at_filter(node, data) < 0)
4958 return isl_stat_error;
4959 break;
4962 return isl_stat_ok;
4965 /* Determine the set of array elements that may need to be perserved
4966 * by a kernel constructed from the subtree at "node".
4967 * This includes the set of array elements that may need to be preserved
4968 * by the entire scop (prog->may_persist) and the elements for which
4969 * there is a potential flow dependence that may cross a kernel launch.
4971 * To determine the second set, we start from all flow dependences.
4972 * From this set of dependences, we remove those that cannot possibly
4973 * require data to be preserved by a kernel launch.
4974 * In particular, we consider the following sets of dependences.
4975 * - dependences of which the write occurs inside the kernel.
4976 * If the data is needed outside the kernel, then it will
4977 * be copied out immediately after the kernel launch, so there
4978 * is no need for any special care.
4979 * - dependences of which the read occurs inside the kernel and the
4980 * corresponding write occurs inside the same iteration of the
4981 * outer band nodes. This means that the data is needed in
4982 * the first kernel launch after the write, which is already
4983 * taken care of by the standard copy-in. That is, the data
4984 * do not need to be preserved by any intermediate call to
4985 * the same kernel.
4986 * - dependences of which the write and the read either both occur
4987 * before the kernel launch or both occur after the kernel launch,
4988 * within the same iteration of the outer band nodes with respect
4989 * to the sequence that determines the ordering of the dependence
4990 * and the kernel launch. Such flow dependences cannot cross
4991 * any kernel launch.
4993 * For the remaining (tagged) dependences, we take the domain
4994 * (i.e., the tagged writes) and apply the tagged access relation
4995 * to obtain the accessed data elements.
4996 * These are then combined with the elements that may need to be
4997 * preserved by the entire scop.
4999 static __isl_give isl_union_set *node_may_persist(
5000 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
5002 struct ppcg_may_persist_data data;
5003 isl_union_pw_multi_aff *contraction;
5004 isl_union_set *domain;
5005 isl_union_set *persist;
5006 isl_union_map *flow, *local_flow;
5008 data.tagger = prog->scop->tagger;
5010 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
5011 data.local_flow = isl_union_map_copy(flow);
5012 data.inner_band_flow = isl_union_map_copy(flow);
5013 data.may_persist_flow = flow;
5014 if (isl_schedule_node_foreach_ancestor_top_down(node,
5015 &update_may_persist_at, &data) < 0)
5016 data.may_persist_flow =
5017 isl_union_map_free(data.may_persist_flow);
5018 flow = data.may_persist_flow;
5019 isl_union_map_free(data.local_flow);
5021 domain = isl_schedule_node_get_domain(node);
5022 contraction = isl_schedule_node_get_subtree_contraction(node);
5023 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5024 contraction);
5025 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5026 isl_union_pw_multi_aff_copy(data.tagger));
5027 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
5028 local_flow = data.inner_band_flow;
5029 local_flow = isl_union_map_intersect_range(local_flow, domain);
5030 flow = isl_union_map_subtract(flow, local_flow);
5032 persist = isl_union_map_domain(flow);
5033 persist = isl_union_set_apply(persist,
5034 isl_union_map_copy(prog->scop->tagged_may_writes));
5035 persist = isl_union_set_union(persist,
5036 isl_union_set_copy(prog->may_persist));
5038 return persist;
5041 /* Add nodes for copying outer arrays in and out of the device
5042 * before and after the subtree "node", which contains one or more kernels.
5043 * "domain" contains the original statement instances, i.e.,
5044 * those that correspond to the domains of the access relations in "prog".
5045 * In particular, the domain has not been contracted in any way.
5046 * "prefix" contains the prefix schedule at that point, in terms
5047 * of the same original statement instances.
5049 * We first compute the sets of outer array elements that need
5050 * to be copied in and out and then graft in the nodes for
5051 * performing this copying.
5053 * In particular, for each array that is possibly written anywhere in
5054 * the subtree "node" and that may be used after "node"
5055 * or that may be visible outside the corresponding scop,
5056 * we copy out its entire extent.
5058 * Any array elements that is read without first being written inside
5059 * the subtree "node" needs to be copied in.
5060 * Furthermore, if there are any array elements that
5061 * are copied out, but that may not be written inside "node, then
5062 * they also need to be copied in to ensure that the value after execution
5063 * is the same as the value before execution, at least for those array
5064 * elements that may have their values preserved by the scop or that
5065 * may be written before "node" and read after "node".
5066 * In case the array elements are structures, we need to take into
5067 * account that all members of the structures need to be written
5068 * by "node" before we can avoid copying the data structure in.
5070 * Note that the may_write relation is intersected with the domain,
5071 * which has been intersected with the context.
5072 * This helps in those cases where the arrays are declared with a fixed size,
5073 * while the accesses are parametric and the context assigns a fixed value
5074 * to the parameters.
5076 * If an element from a local array is read without first being written,
5077 * then there is no point in copying it in since it cannot have been
5078 * written prior to the scop. Warn about the uninitialized read instead.
5080 static __isl_give isl_schedule_node *add_to_from_device(
5081 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
5082 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
5084 isl_union_set *local;
5085 isl_union_set *may_persist;
5086 isl_union_map *may_write, *must_write, *copy_out, *not_written;
5087 isl_union_map *read, *copy_in;
5088 isl_union_map *tagged;
5089 isl_union_map *local_uninitialized;
5090 isl_schedule_node *graft;
5092 tagged = isl_union_map_copy(prog->scop->tagged_reads);
5093 tagged = isl_union_map_union(tagged,
5094 isl_union_map_copy(prog->scop->tagged_may_writes));
5096 may_write = isl_union_map_copy(prog->may_write);
5097 may_write = isl_union_map_intersect_domain(may_write,
5098 isl_union_set_copy(domain));
5099 may_write = remove_local_accesses(prog,
5100 isl_union_map_copy(tagged), may_write,
5101 isl_union_map_copy(prefix), 0);
5102 may_write = isl_union_map_apply_range(may_write,
5103 isl_union_map_copy(prog->to_outer));
5104 may_write = isl_union_map_apply_domain(may_write,
5105 isl_union_map_copy(prefix));
5106 may_write = approximate_copy_out(may_write, prog);
5107 copy_out = isl_union_map_copy(may_write);
5108 may_write = isl_union_map_apply_range(may_write,
5109 isl_union_map_copy(prog->to_inner));
5110 must_write = isl_union_map_copy(prog->must_write);
5111 must_write = isl_union_map_apply_domain(must_write,
5112 isl_union_map_copy(prefix));
5113 may_persist = node_may_persist(node, prog);
5114 may_write = isl_union_map_intersect_range(may_write, may_persist);
5115 not_written = isl_union_map_subtract(may_write, must_write);
5117 local = extract_local_accesses(prog, domain);
5118 read = isl_union_map_copy(prog->read);
5119 read = isl_union_map_intersect_domain(read, domain);
5120 read = remove_local_accesses(prog, tagged, read,
5121 isl_union_map_copy(prefix), 1);
5122 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
5123 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
5124 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5125 local);
5126 local_uninitialized = isl_union_map_intersect(local_uninitialized,
5127 isl_union_map_copy(read));
5128 if (!isl_union_map_is_empty(local_uninitialized)) {
5129 fprintf(stderr,
5130 "possibly uninitialized reads (not copied in):\n");
5131 isl_union_map_dump(local_uninitialized);
5133 read = isl_union_map_subtract(read, local_uninitialized);
5134 read = isl_union_map_apply_domain(read, prefix);
5135 copy_in = isl_union_map_union(read, not_written);
5136 copy_in = isl_union_map_apply_range(copy_in,
5137 isl_union_map_copy(prog->to_outer));
5139 graft = create_copy_device(prog, node, "to_device",
5140 isl_union_map_range(copy_in));
5141 node = isl_schedule_node_graft_before(node, graft);
5142 graft = create_copy_device(prog, node, "from_device",
5143 isl_union_map_range(copy_out));
5144 node = isl_schedule_node_graft_after(node, graft);
5146 return node;
5149 /* Add nodes for initializing ("init_device") and clearing ("clear_device")
5150 * the device before and after "node".
5152 static __isl_give isl_schedule_node *add_init_clear_device(
5153 __isl_take isl_schedule_node *node)
5155 isl_ctx *ctx;
5156 isl_space *space;
5157 isl_union_set *domain;
5158 isl_schedule_node *graft;
5160 ctx = isl_schedule_node_get_ctx(node);
5162 space = isl_space_set_alloc(ctx, 0, 0);
5163 space = isl_space_set_tuple_name(space, isl_dim_set, "init_device");
5164 domain = isl_union_set_from_set(isl_set_universe(space));
5165 graft = isl_schedule_node_from_domain(domain);
5167 node = isl_schedule_node_graft_before(node, graft);
5169 space = isl_space_set_alloc(ctx, 0, 0);
5170 space = isl_space_set_tuple_name(space, isl_dim_set, "clear_device");
5171 domain = isl_union_set_from_set(isl_set_universe(space));
5172 graft = isl_schedule_node_from_domain(domain);
5174 node = isl_schedule_node_graft_after(node, graft);
5176 return node;
5179 /* Update "schedule" for mapping to a GPU device.
5181 * In particular, insert a context node, create kernels for
5182 * each outermost tilable band and introduce nodes for copying arrays
5183 * in and out of the device and for initializing and clearing the device.
5184 * If the child of the initial root points to a set node,
5185 * then children of this node that do not contain any tilable bands
5186 * are separated from the other children and are not mapped to
5187 * the device.
5189 * The GPU code is generated in a context where at least one
5190 * statement instance is executed. The corresponding guard is inserted
5191 * around the entire schedule.
5193 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
5194 __isl_take isl_schedule *schedule)
5196 isl_schedule_node *node;
5197 isl_set *context;
5198 isl_set *guard;
5199 isl_union_set *domain;
5200 isl_union_map *prefix;
5201 isl_union_pw_multi_aff *contraction;
5202 struct gpu_prog *prog;
5204 context = isl_set_copy(gen->prog->context);
5205 context = isl_set_from_params(context);
5206 schedule = isl_schedule_insert_context(schedule, context);
5208 prog = gen->prog;
5209 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5210 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5211 guard = isl_set_from_params(guard);
5213 node = isl_schedule_get_root(schedule);
5214 isl_schedule_free(schedule);
5215 node = isl_schedule_node_child(node, 0);
5216 node = isl_schedule_node_child(node, 0);
5217 node = isolate_permutable_subtrees(node, gen->prog);
5218 domain = isl_schedule_node_get_domain(node);
5219 contraction = isl_schedule_node_get_subtree_contraction(node);
5220 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5221 isl_union_pw_multi_aff_copy(contraction));
5222 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
5223 prefix = isl_union_map_preimage_domain_union_pw_multi_aff(prefix,
5224 contraction);
5225 node = mark_kernels(gen, node);
5226 node = add_to_from_device(node, domain, prefix, gen->prog);
5227 node = isl_schedule_node_root(node);
5228 node = isl_schedule_node_child(node, 0);
5229 node = isl_schedule_node_child(node, 0);
5230 node = isl_schedule_node_insert_guard(node, guard);
5231 node = isl_schedule_node_child(node, 0);
5232 node = add_init_clear_device(node);
5233 schedule = isl_schedule_node_get_schedule(node);
5234 isl_schedule_node_free(node);
5236 return schedule;
5239 /* Internal data structure for extract_access.
5240 * "next_access" points to the end of a linked list that is extended
5241 * by extract_access.
5242 * "single_expression" is set if the access expressions belong to
5243 * an expression statement (i.e., a statement without internal control).
5244 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5246 struct ppcg_extract_access_data {
5247 struct gpu_stmt_access **next_access;
5248 int single_expression;
5249 isl_union_map *any_to_outer;
5252 /* Given a tagged access relation to a single array "tagged", extract it
5253 * as a map, taking into account that the input may be empty.
5254 * If the access relation is empty, then it does not contain
5255 * any space information, so we try to recover it from the index
5256 * expression.
5257 * The space of the index expression is of the form I -> A,
5258 * with I the statement instances and A the array, or [I -> F] -> A,
5259 * with F the filters corresponding to arguments.
5260 * We first drop F, if present, obtaining I -> A.
5261 * Then we construct I -> R, with R the reference tag,
5262 * combine the two into I -> [R -> A] and uncurry to obtain
5263 * the final result [I -> R] -> A.
5264 * Note that the index expression may have a lower dimension
5265 * than that of the array, but this dimension is not used
5266 * if the access relation is empty.
5268 static __isl_give isl_map *extract_single_tagged_access(
5269 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5271 int empty;
5272 isl_id *id;
5273 isl_space *space, *space2;
5274 isl_multi_pw_aff *index;
5276 empty = isl_union_map_is_empty(tagged);
5277 if (empty < 0)
5278 goto error;
5279 if (!empty)
5280 return isl_map_from_union_map(tagged);
5281 isl_union_map_free(tagged);
5283 index = pet_expr_access_get_index(expr);
5284 space = isl_multi_pw_aff_get_space(index);
5285 isl_multi_pw_aff_free(index);
5286 if (isl_space_domain_is_wrapping(space))
5287 space = isl_space_domain_factor_domain(space);
5288 space2 = isl_space_copy(space);
5289 space2 = isl_space_from_domain(isl_space_domain(space));
5290 id = pet_expr_access_get_ref_id(expr);
5291 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5292 space = isl_space_range_product(space2, space);
5293 space = isl_space_uncurry(space);
5295 return isl_map_empty(space);
5296 error:
5297 isl_union_map_free(tagged);
5298 return NULL;
5301 /* Does the index expression "index" of "expr" represent an access
5302 * to a single element?
5303 * That is, is "index" completely specified?
5305 * If "expr" accesses elements from different spaces (i.e., fields
5306 * of a structure), then it does not access a single element.
5307 * Otherwise, if the single space of the access matches the space
5308 * of "index", then the index expression is completely specified
5309 * (no pointer to a lower-dimensional slice of the accessed array)
5310 * and a single element is being accessed.
5312 static isl_bool complete_index(__isl_keep pet_expr *expr,
5313 __isl_keep isl_multi_pw_aff *index)
5315 isl_union_map *read, *write, *all;
5316 isl_map *map;
5317 isl_space *space1, *space2;
5318 isl_bool complete;
5320 read = pet_expr_access_get_may_read(expr);
5321 write = pet_expr_access_get_may_write(expr);
5322 all = isl_union_map_union(read, write);
5323 if (!all)
5324 return isl_bool_error;
5325 if (isl_union_map_n_map(all) != 1) {
5326 isl_union_map_free(all);
5327 return isl_bool_false;
5329 map = isl_map_from_union_map(all);
5330 space1 = isl_map_get_space(map);
5331 isl_map_free(map);
5332 space2 = isl_multi_pw_aff_get_space(index);
5333 complete = isl_space_tuple_is_equal(space1, isl_dim_out,
5334 space2, isl_dim_out);
5335 isl_space_free(space1);
5336 isl_space_free(space2);
5338 return complete;
5341 /* Does "expr" access a single, fixed element (independently of the statement
5342 * instance)?
5343 * That is, does it have a completely specified constant index expression?
5345 * Note that it is not sufficient for the index expression to be
5346 * piecewise constant. isl_multi_pw_aff_is_cst can therefore not be used.
5348 static isl_bool accesses_fixed_element(__isl_keep pet_expr *expr)
5350 int i, n;
5351 isl_multi_pw_aff *index;
5352 isl_bool fixed = isl_bool_true;
5354 index = pet_expr_access_get_index(expr);
5355 if (index < 0)
5356 return isl_bool_error;
5357 n = isl_multi_pw_aff_dim(index, isl_dim_out);
5358 for (i = 0; i < n; ++i) {
5359 isl_pw_aff *pa;
5361 pa = isl_multi_pw_aff_get_pw_aff(index, 0);
5362 fixed = isl_pw_aff_n_piece(pa) == 1;
5363 if (fixed)
5364 fixed = isl_pw_aff_is_cst(pa);
5365 isl_pw_aff_free(pa);
5366 if (fixed < 0 || !fixed)
5367 break;
5369 if (fixed >= 0 && fixed)
5370 fixed = complete_index(expr, index);
5371 isl_multi_pw_aff_free(index);
5373 return fixed;
5376 /* Extract a gpu_stmt_access from "expr", append it to the list
5377 * that ends in *data->next_access and update the end of the list.
5378 * If the access expression performs a write, then it is considered
5379 * exact only if it appears in a single expression statement and
5380 * if its may access relation is equal to its must access relation.
5382 * The combined set of may accesses may be a union if member accesses
5383 * are involved, but the entire set is derived from a single reference and
5384 * therefore from a single index expression. These accesses therefore
5385 * all map to the same outer array.
5387 static int extract_access(__isl_keep pet_expr *expr, void *user)
5389 struct ppcg_extract_access_data *data = user;
5390 isl_union_map *tagged;
5391 struct gpu_stmt_access *access;
5392 isl_ctx *ctx = pet_expr_get_ctx(expr);
5393 isl_multi_pw_aff *index;
5395 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5396 assert(access);
5397 access->next = NULL;
5398 access->read = pet_expr_access_is_read(expr);
5399 access->write = pet_expr_access_is_write(expr);
5400 tagged = pet_expr_access_get_tagged_may_read(expr);
5401 tagged = isl_union_map_union(tagged,
5402 pet_expr_access_get_tagged_may_write(expr));
5403 tagged = isl_union_map_apply_range(tagged,
5404 isl_union_map_copy(data->any_to_outer));
5405 if (!access->write) {
5406 access->exact_write = 1;
5407 } else if (!data->single_expression) {
5408 access->exact_write = 0;
5409 } else {
5410 isl_union_map *must, *may;
5411 may = isl_union_map_copy(tagged);
5412 may = isl_union_map_domain_factor_domain(may);
5413 must = pet_expr_access_get_must_write(expr);
5414 access->exact_write = isl_union_map_is_equal(must, may);
5415 isl_union_map_free(must);
5416 isl_union_map_free(may);
5418 index = pet_expr_access_get_index(expr);
5419 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5420 isl_multi_pw_aff_free(index);
5421 access->ref_id = pet_expr_access_get_ref_id(expr);
5422 access->tagged_access = extract_single_tagged_access(tagged, expr);
5423 access->access = isl_map_copy(access->tagged_access);
5424 access->access = isl_map_domain_factor_domain(access->access);
5425 access->fixed_element = accesses_fixed_element(expr);
5427 *data->next_access = access;
5428 data->next_access = &(*data->next_access)->next;
5430 if (!access->access || access->fixed_element < 0)
5431 return -1;
5433 return 0;
5436 /* Construct a linked list of gpu_stmt_access objects,
5437 * one for each access expression in the statement body.
5438 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5440 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5441 __isl_keep isl_union_map *any_to_outer)
5443 struct ppcg_extract_access_data data;
5445 stmt->accesses = NULL;
5446 data.next_access = &stmt->accesses;
5447 data.single_expression =
5448 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5449 data.any_to_outer = any_to_outer;
5450 return pet_tree_foreach_access_expr(stmt->stmt->body,
5451 &extract_access, &data);
5454 /* Has statement "stmt" been killed from "scop"?
5455 * That is, is the instance set of "scop" free from any
5456 * instances of "stmt"?
5458 static isl_bool is_stmt_killed(struct ppcg_scop *scop, struct pet_stmt *stmt)
5460 isl_space *space;
5461 isl_set *left;
5462 isl_bool empty;
5464 if (!scop || !stmt)
5465 return isl_bool_error;
5466 space = isl_set_get_space(stmt->domain);
5467 left = isl_union_set_extract_set(scop->domain, space);
5468 empty = isl_set_plain_is_empty(left);
5469 isl_set_free(left);
5471 return empty;
5474 /* Return an array of gpu_stmt representing the statements in "scop".
5475 * Do not collect array accesses for statements that have been killed.
5477 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5478 __isl_keep isl_union_map *any_to_outer)
5480 int i;
5481 struct gpu_stmt *stmts;
5483 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5484 if (!stmts)
5485 return NULL;
5487 for (i = 0; i < scop->pet->n_stmt; ++i) {
5488 struct gpu_stmt *s = &stmts[i];
5489 isl_bool killed;
5491 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5492 s->stmt = scop->pet->stmts[i];
5493 killed = is_stmt_killed(scop, scop->pet->stmts[i]);
5494 if (killed < 0)
5495 return free_stmts(stmts, i + 1);
5496 if (killed)
5497 continue;
5498 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5499 return free_stmts(stmts, i + 1);
5502 return stmts;
5505 /* Generate CUDA code for "scop" and print it to "p".
5506 * After generating an AST for the transformed scop as explained below,
5507 * we call "gen->print" to print the AST in the desired output format
5508 * to "p".
5510 * If it turns out that it does not make sense to generate GPU code,
5511 * then we generate CPU code instead.
5513 * The declarations of the arrays that are visible outside of the scop
5514 * are printed outside of the code generated from the schedule,
5515 * because the generated code may involve a guard around the entire code.
5517 * We first compute a schedule that respects the dependences
5518 * of the original program and select the outermost bands
5519 * of tilable dimensions that have at least one parallel loop.
5520 * If the --load-schedule is specified, then the loaded schedule
5521 * is used instead of a computed schedule.
5523 * Each of these bands B is then tiled according to "tile" sizes, resulting
5524 * in two nested bands, with a kernel marker on top
5532 * We then split off at most 2 parallel dimensions from the T band and
5533 * at most 3 parallel dimension from the P band
5538 * T1
5540 * T2
5542 * P1
5544 * P2
5546 * A filter is introduced in front of T1 that maps the domain instances
5547 * to block identifiers. Similarly, a filter is introduced in front of P1
5548 * that maps the domain instances to thread identifiers.
5550 * For each iteration of the T2 band and for each array, we compute
5551 * the array elements accessed by that iteration, construct a rectangular
5552 * box around it and shift it to the origin. The result is used
5553 * as shared memory for the array.
5555 * Copying and synchronization statements are added to this schedule tree.
5556 * In principle, these are added in front of the P1 band, but some of
5557 * them may get hoisted up to higher levels.
5559 * The entire AST is then generated from the single resulting schedule tree.
5560 * During the generation the subtrees at kernel nodes (K) are saved
5561 * aside and replaced by kernel calls. The result is printed as host code
5562 * while the saved subtrees are printed as device code.
5564 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5565 struct gpu_gen *gen, struct ppcg_scop *scop,
5566 struct ppcg_options *options)
5568 struct gpu_prog *prog;
5569 isl_ctx *ctx;
5570 isl_schedule *schedule;
5571 int any_permutable;
5573 if (!scop)
5574 return isl_printer_free(p);
5576 ctx = isl_printer_get_ctx(p);
5577 prog = gpu_prog_alloc(ctx, scop);
5578 if (!prog)
5579 return isl_printer_free(p);
5581 gen->prog = prog;
5582 schedule = get_schedule(gen);
5584 any_permutable = has_any_permutable_node(schedule);
5585 if (any_permutable < 0 || !any_permutable) {
5586 if (any_permutable < 0)
5587 p = isl_printer_free(p);
5588 else
5589 p = print_cpu(p, scop, options);
5590 isl_schedule_free(schedule);
5591 } else {
5592 schedule = map_to_device(gen, schedule);
5593 gen->tree = generate_code(gen, schedule);
5594 p = ppcg_set_macro_names(p);
5595 p = ppcg_print_exposed_declarations(p, prog->scop);
5596 p = gen->print(p, gen->prog, gen->tree, &gen->types,
5597 gen->print_user);
5598 isl_ast_node_free(gen->tree);
5601 gpu_prog_free(prog);
5603 return p;
5606 /* Wrapper around generate for use as a ppcg_transform callback.
5608 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5609 struct ppcg_scop *scop, void *user)
5611 struct gpu_gen *gen = user;
5613 return generate(p, gen, scop, gen->options);
5616 /* Transform the code in the file called "input" by replacing
5617 * all scops by corresponding GPU code and write the results to "out".
5619 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5620 struct ppcg_options *options,
5621 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5622 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5623 struct gpu_types *types, void *user), void *user)
5625 struct gpu_gen gen;
5626 int r;
5627 int i;
5629 gen.ctx = ctx;
5630 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5631 gen.options = options;
5632 gen.kernel_id = 0;
5633 gen.print = print;
5634 gen.print_user = user;
5635 gen.types.n = 0;
5636 gen.types.name = NULL;
5638 if (options->debug->dump_sizes) {
5639 isl_space *space = isl_space_params_alloc(ctx, 0);
5640 gen.used_sizes = isl_union_map_empty(space);
5643 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5645 if (options->debug->dump_sizes) {
5646 isl_union_map_dump(gen.used_sizes);
5647 isl_union_map_free(gen.used_sizes);
5650 isl_union_map_free(gen.sizes);
5651 for (i = 0; i < gen.types.n; ++i)
5652 free(gen.types.name[i]);
5653 free(gen.types.name);
5655 return r;
5658 /* Compute the set of inner array elements that may have their values
5659 * preserved by "prog". In particular, collect the array elements of
5660 * arrays that are not local to "prog" and remove those elements that
5661 * are definitely killed or definitely written by "prog".
5663 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5665 int i;
5666 isl_union_set *may_persist, *killed;
5667 isl_union_map *must_kill;
5669 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5670 for (i = 0; i < prog->n_array; ++i) {
5671 isl_set *extent;
5673 if (prog->array[i].local)
5674 continue;
5676 extent = isl_set_copy(prog->array[i].extent);
5677 may_persist = isl_union_set_add_set(may_persist, extent);
5680 may_persist = isl_union_set_intersect_params(may_persist,
5681 isl_set_copy(prog->context));
5682 may_persist = isl_union_set_apply(may_persist,
5683 isl_union_map_copy(prog->to_inner));
5684 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5685 killed = isl_union_map_range(must_kill);
5686 must_kill = isl_union_map_copy(prog->must_write);
5687 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5689 may_persist = isl_union_set_subtract(may_persist, killed);
5690 return may_persist;
5693 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5695 struct gpu_prog *prog;
5696 isl_space *space;
5697 isl_map *id;
5699 if (!scop)
5700 return NULL;
5702 prog = isl_calloc_type(ctx, struct gpu_prog);
5703 assert(prog);
5705 prog->ctx = ctx;
5706 prog->scop = scop;
5707 prog->context = isl_set_copy(scop->context);
5708 prog->n_stmts = scop->pet->n_stmt;
5709 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5710 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5711 space = isl_union_map_get_space(prog->any_to_outer);
5712 space = isl_space_set_from_params(space);
5713 space = isl_space_add_dims(space, isl_dim_set, 1);
5714 space = isl_space_map_from_set(space);
5715 id = isl_map_identity(space);
5716 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5717 prog->stmts = extract_stmts(ctx, scop, prog->any_to_outer);
5718 prog->read = isl_union_map_copy(scop->reads);
5719 prog->may_write = isl_union_map_copy(scop->may_writes);
5720 prog->must_write = isl_union_map_copy(scop->must_writes);
5721 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5722 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5723 prog->to_outer = isl_union_map_copy(prog->to_inner);
5724 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5726 if (!prog->stmts)
5727 return gpu_prog_free(prog);
5729 if (collect_array_info(prog) < 0)
5730 return gpu_prog_free(prog);
5731 prog->may_persist = compute_may_persist(prog);
5733 return prog;
5736 void *gpu_prog_free(struct gpu_prog *prog)
5738 if (!prog)
5739 return NULL;
5740 free_array_info(prog);
5741 free_stmts(prog->stmts, prog->n_stmts);
5742 isl_union_map_free(prog->any_to_outer);
5743 isl_union_map_free(prog->to_outer);
5744 isl_union_map_free(prog->to_inner);
5745 isl_union_map_free(prog->read);
5746 isl_union_map_free(prog->may_write);
5747 isl_union_map_free(prog->must_write);
5748 isl_union_map_free(prog->tagged_must_kill);
5749 isl_union_map_free(prog->array_order);
5750 isl_union_set_free(prog->may_persist);
5751 isl_set_free(prog->context);
5752 free(prog);
5753 return NULL;