update pet to version 0.10
[ppcg.git] / gpu.c
blob5b0a123ad1bbb874a62aebbd7d8f4a20b5d5865b
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
4 * Copyright 2015-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_hybrid.h"
33 #include "gpu_tree.h"
34 #include "hybrid.h"
35 #include "schedule.h"
36 #include "ppcg_options.h"
37 #include "print.h"
38 #include "util.h"
40 struct gpu_array_info;
42 /* Return the name of the outer array (of structs) accessed by "access".
44 static const char *get_outer_array_name(__isl_keep isl_map *access)
46 isl_space *space;
47 const char *name;
49 space = isl_space_range(isl_map_get_space(access));
50 while (space && isl_space_is_wrapping(space))
51 space = isl_space_domain(isl_space_unwrap(space));
52 name = isl_space_get_tuple_name(space, isl_dim_set);
53 isl_space_free(space);
55 return name;
58 /* Collect all references to the given array and store pointers to them
59 * in array->refs.
61 static void collect_references(struct gpu_prog *prog,
62 struct gpu_array_info *array)
64 int i;
65 int n;
67 n = 0;
68 for (i = 0; i < prog->n_stmts; ++i) {
69 struct gpu_stmt *stmt = &prog->stmts[i];
70 struct gpu_stmt_access *access;
72 for (access = stmt->accesses; access; access = access->next) {
73 const char *name;
74 name = get_outer_array_name(access->access);
75 if (name && !strcmp(array->name, name))
76 n++;
80 array->n_ref = n;
81 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
82 assert(array->refs);
84 n = 0;
85 for (i = 0; i < prog->n_stmts; ++i) {
86 struct gpu_stmt *stmt = &prog->stmts[i];
87 struct gpu_stmt_access *access;
89 for (access = stmt->accesses; access; access = access->next) {
90 const char *name;
91 name = get_outer_array_name(access->access);
92 if (!name || strcmp(array->name, name))
93 continue;
95 array->refs[n++] = access;
100 /* Compute and return the extent of "array", taking into account the set of
101 * accessed elements.
103 * In particular, the extent in the outer dimension is taken
104 * from "accessed", while the extents in the remaining dimensions
105 * are taken from array->extent.
107 * The extent in the outer dimension cannot be taken from array->extent
108 * because that may be unbounded. Furthermore, even if it is bounded,
109 * it may be larger than the piece of the array that is being accessed.
111 static __isl_give isl_set *compute_extent(struct pet_array *array,
112 __isl_keep isl_set *accessed)
114 int n_index;
115 isl_id *id;
116 isl_set *outer;
117 isl_set *extent;
119 extent = isl_set_copy(array->extent);
121 n_index = isl_set_dim(accessed, isl_dim_set);
122 if (n_index == 0)
123 return extent;
125 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
126 outer = isl_set_copy(accessed);
127 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
128 extent = isl_set_flat_product(outer, extent);
129 id = isl_set_get_tuple_id(accessed);
130 extent = isl_set_set_tuple_id(extent, id);
132 return extent;
135 /* Is the array "array" being extracted a read-only scalar?
137 * That is, is "array" a scalar that is never possibly written to.
138 * An array containing structures is never considered to be a scalar.
140 static int is_read_only_scalar(struct gpu_array_info *array,
141 struct gpu_prog *prog)
143 isl_set *space;
144 isl_union_map *write;
145 int empty;
147 if (array->has_compound_element)
148 return 0;
149 if (array->n_index != 0)
150 return 0;
152 write = isl_union_map_copy(prog->may_write);
153 space = isl_set_universe(isl_space_copy(array->space));
154 write = isl_union_map_intersect_range(write,
155 isl_union_set_from_set(space));
156 empty = isl_union_map_is_empty(write);
157 isl_union_map_free(write);
159 return empty;
162 /* Is "array" only accessed as individual, fixed elements?
163 * That is, does each access to "array" access a single, fixed element?
165 static isl_bool only_fixed_element_accessed(struct gpu_array_info *array)
167 int i;
169 for (i = 0; i < array->n_ref; ++i)
170 if (!array->refs[i]->fixed_element)
171 return isl_bool_false;
173 return isl_bool_true;
176 /* Compute bounds on the host array "pa" based on the corresponding
177 * accessed elements in "arrays"
178 * and collect all references to the array.
179 * Store the results in "info".
181 * If the array is zero-dimensional and does not contain structures,
182 * i.e., if the array is a scalar, we check whether it is read-only.
183 * We also check whether the array is accessed at all.
185 static int extract_array_info(struct gpu_prog *prog,
186 struct gpu_array_info *info, struct pet_array *pa,
187 __isl_keep isl_union_set *arrays)
189 int empty;
190 const char *name;
191 int n_index;
192 isl_multi_pw_aff *bounds;
193 isl_set *accessed, *extent;
195 n_index = isl_set_dim(pa->extent, isl_dim_set);
196 name = isl_set_get_tuple_name(pa->extent);
198 info->space = isl_set_get_space(pa->extent);
199 info->name = strdup(name);
200 info->n_index = n_index;
201 info->linearize = prog->scop->options->linearize_device_arrays;
203 info->type = strdup(pa->element_type);
204 info->size = pa->element_size;
205 info->local = pa->declared && !pa->exposed;
206 info->has_compound_element = pa->element_is_record;
207 info->read_only_scalar = is_read_only_scalar(info, prog);
209 info->declared_extent = isl_set_copy(pa->extent);
210 accessed = isl_union_set_extract_set(arrays,
211 isl_space_copy(info->space));
212 empty = isl_set_is_empty(accessed);
213 extent = compute_extent(pa, accessed);
214 isl_set_free(accessed);
215 info->extent = extent;
216 if (empty < 0)
217 return -1;
218 info->accessed = !empty;
219 bounds = ppcg_size_from_extent(isl_set_copy(extent));
220 bounds = isl_multi_pw_aff_gist(bounds, isl_set_copy(prog->context));
221 if (!bounds)
222 return -1;
223 if (!isl_multi_pw_aff_is_cst(bounds))
224 info->linearize = 1;
225 info->bound = bounds;
227 collect_references(prog, info);
228 info->only_fixed_element = only_fixed_element_accessed(info);
230 return 0;
233 /* Remove independence from the order constraints "order" on array "array".
234 * Since the pairs of iterations in the filter relation of an independence
235 * are guaranteed to be completely independent by the user, there is
236 * no need to ensure that live ranges are ordered along thong pairs.
237 * We make an exception for local variables, though, as the independence
238 * guarantee does not apply to those.
240 * The order constraints are used in two places.
241 * Those on scalars are used in check_scalar_live_ranges to check if
242 * we need to force the scalar to be private. Any non-local scalar
243 * should not be forced scalar if it only appears in independent loops.
244 * Those on non-scalars are added to the coincidence constraints
245 * in compute_schedule because we do not support any array expansion.
246 * Accesses to non-local arrays should not prevent a loop from being
247 * considered coincident so we should indeed remove those constraints
248 * from the order constraints.
250 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
251 struct gpu_array_info *array, __isl_take isl_union_map *order)
253 int i;
255 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
256 struct pet_independence *pi = prog->scop->pet->independences[i];
257 if (isl_union_set_contains(pi->local, array->space))
258 continue;
260 order = isl_union_map_subtract(order,
261 isl_union_map_copy(pi->filter));
264 return order;
267 /* For each array in "prog", store the (untagged) order dependences
268 * derived from the array in array->dep_order.
269 * In particular, consider all references that access the given array
270 * and take the order dependences that have one of these references
271 * as source. (Since an order dependence relates two references to
272 * the same array, the target of these order dependences will also
273 * be one of these references.)
274 * Additionally, store the union of these array->dep_order relations
275 * for all arrays that cannot be mapped to private memory in prog->array_order.
277 void collect_order_dependences(struct gpu_prog *prog)
279 int i;
280 isl_space *space;
281 isl_union_map *accesses;
283 space = isl_union_map_get_space(prog->read);
284 prog->array_order = isl_union_map_empty(space);
286 accesses = isl_union_map_copy(prog->scop->tagged_reads);
287 accesses = isl_union_map_union(accesses,
288 isl_union_map_copy(prog->scop->tagged_may_writes));
289 accesses = isl_union_map_universe(accesses);
290 accesses = isl_union_map_apply_range(accesses,
291 isl_union_map_copy(prog->to_outer));
293 for (i = 0; i < prog->n_array; ++i) {
294 struct gpu_array_info *array = &prog->array[i];
295 isl_set *set;
296 isl_union_set *uset;
297 isl_union_map *order;
299 set = isl_set_universe(isl_space_copy(array->space));
300 uset = isl_union_set_from_set(set);
301 uset = isl_union_map_domain(
302 isl_union_map_intersect_range(isl_union_map_copy(accesses),
303 uset));
304 order = isl_union_map_copy(prog->scop->tagged_dep_order);
305 order = isl_union_map_intersect_domain(order, uset);
306 order = isl_union_map_zip(order);
307 order = isl_union_set_unwrap(isl_union_map_domain(order));
308 order = remove_independences(prog, array, order);
309 array->dep_order = order;
311 if (gpu_array_can_be_private(array))
312 continue;
314 prog->array_order = isl_union_map_union(prog->array_order,
315 isl_union_map_copy(array->dep_order));
318 isl_union_map_free(accesses);
321 /* Construct a gpu_array_info for each array referenced by prog->scop and
322 * collect them in prog->array.
324 * The sizes are based on the extents and the set of possibly accessed
325 * elements by "prog".
326 * If there are any member accesses involved, then they are first mapped
327 * to the outer arrays of structs.
328 * Only extract gpu_array_info entries for these outer arrays.
330 * If we are allowing live range reordering, then also set
331 * the dep_order field. Otherwise leave it NULL.
333 static int collect_array_info(struct gpu_prog *prog)
335 int i;
336 int r = 0;
337 isl_union_set *arrays;
339 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
340 arrays = isl_union_set_union(arrays,
341 isl_union_map_range(isl_union_map_copy(prog->may_write)));
343 arrays = isl_union_set_apply(arrays,
344 isl_union_map_copy(prog->to_outer));
346 arrays = isl_union_set_coalesce(arrays);
348 prog->n_array = prog->scop->pet->n_array;
349 prog->array = isl_calloc_array(prog->ctx,
350 struct gpu_array_info, prog->n_array);
351 assert(prog->array);
352 prog->n_array = 0;
353 for (i = 0; i < prog->scop->pet->n_array; ++i) {
354 isl_bool field;
356 field = isl_set_is_wrapping(prog->scop->pet->arrays[i]->extent);
357 if (field < 0)
358 break;
359 if (field)
360 continue;
361 if (extract_array_info(prog, &prog->array[prog->n_array++],
362 prog->scop->pet->arrays[i], arrays) < 0)
363 r = -1;
365 if (i < prog->scop->pet->n_array)
366 r = -1;
368 isl_union_set_free(arrays);
370 if (prog->scop->options->live_range_reordering)
371 collect_order_dependences(prog);
373 return r;
376 static void free_array_info(struct gpu_prog *prog)
378 int i;
380 for (i = 0; i < prog->n_array; ++i) {
381 free(prog->array[i].type);
382 free(prog->array[i].name);
383 isl_multi_pw_aff_free(prog->array[i].bound);
384 isl_ast_expr_free(prog->array[i].bound_expr);
385 isl_space_free(prog->array[i].space);
386 isl_set_free(prog->array[i].declared_extent);
387 isl_set_free(prog->array[i].extent);
388 isl_ast_expr_free(prog->array[i].declared_size);
389 free(prog->array[i].refs);
390 isl_union_map_free(prog->array[i].dep_order);
392 free(prog->array);
395 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
396 * as an array or through a pointer reference, but as a single data element.
397 * At the moment, scalars are represented as zero-dimensional arrays.
398 * Note that the single data element may be an entire structure.
400 int gpu_array_is_scalar(struct gpu_array_info *array)
402 return array->n_index == 0;
405 /* Can "array" be mapped to private memory?
406 * That is, is it only accessed as individual elements with
407 * constant index expressions?
409 isl_bool gpu_array_can_be_private(struct gpu_array_info *array)
411 if (!array)
412 return isl_bool_error;
413 return array->only_fixed_element;
416 /* Is "array" a read-only scalar?
418 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
420 return array->read_only_scalar;
423 /* Does "array" need to be allocated on the device?
424 * If it is a read-only scalar, then it will be passed as an argument
425 * to the kernel and therefore does not require any allocation.
426 * If this device memory is not accessed at all, then it does not
427 * need to be allocated either.
429 int gpu_array_requires_device_allocation(struct gpu_array_info *array)
431 if (gpu_array_is_read_only_scalar(array))
432 return 0;
433 if (!array->global)
434 return 0;
435 return 1;
438 /* Return the set of parameter values for which the array has a positive
439 * size in all dimensions.
440 * If the sizes are only valid for some parameter values, then those
441 * constraints are also taken into account.
443 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
445 int i;
446 isl_space *space;
447 isl_set *guard;
449 if (!array)
450 return NULL;
452 space = isl_space_params(isl_space_copy(array->space));
453 guard = isl_set_universe(space);
455 for (i = 0; i < array->n_index; ++i) {
456 isl_pw_aff *bound;
457 isl_set *guard_i, *zero;
459 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
460 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
461 zero = isl_pw_aff_zero_set(bound);
462 guard_i = isl_set_subtract(guard_i, zero);
463 guard = isl_set_intersect(guard, guard_i);
466 return guard;
469 /* Internal data structure for extract_size_of_type.
470 * "type" specifies the name of the space that we want to extract.
471 * "res" is used to store the subset of that space.
473 struct ppcg_extract_size_data {
474 const char *type;
475 isl_set *res;
478 /* This function is called for each set in a union_set.
479 * If the name of the set matches data->type, we store the
480 * set in data->res.
482 static isl_stat extract_size_of_type(__isl_take isl_set *size, void *user)
484 struct ppcg_extract_size_data *data = user;
485 const char *name;
487 name = isl_set_get_tuple_name(size);
488 if (name && !strcmp(name, data->type)) {
489 data->res = size;
490 return isl_stat_error;
493 isl_set_free(size);
494 return isl_stat_ok;
497 /* Given a union map { kernel[i] -> *[...] },
498 * return the range in the space called "type" for the kernel with
499 * sequence number "id".
501 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
502 const char *type, int id)
504 isl_space *space;
505 isl_set *dom;
506 isl_union_set *local_sizes;
507 struct ppcg_extract_size_data data = { type, NULL };
509 if (!sizes)
510 return NULL;
512 space = isl_union_map_get_space(sizes);
513 space = isl_space_set_from_params(space);
514 space = isl_space_add_dims(space, isl_dim_set, 1);
515 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
516 dom = isl_set_universe(space);
517 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
519 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
520 isl_union_map_copy(sizes));
521 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
522 isl_union_set_free(local_sizes);
523 return data.res;
526 /* Given a singleton set, extract the first (at most *len) elements
527 * of the single integer tuple into *sizes and update *len if needed.
529 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
531 int i;
532 int dim;
534 if (!set)
535 return;
537 dim = isl_set_dim(set, isl_dim_set);
538 if (dim < *len)
539 *len = dim;
541 for (i = 0; i < *len; ++i) {
542 isl_val *v;
544 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
545 assert(v);
547 sizes[i] = isl_val_get_num_si(v);
548 isl_val_free(v);
551 isl_set_free(set);
554 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
555 * if the option debug->dump_sizes is set.
557 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
558 int *sizes, int len)
560 int i;
561 isl_space *space;
562 isl_map *map;
564 if (!gen->options->debug->dump_sizes)
565 return;
567 space = isl_union_map_get_space(gen->used_sizes);
568 space = isl_space_set_from_params(space);
569 space = isl_space_add_dims(space, isl_dim_set, 1);
570 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
571 space = isl_space_from_domain(space);
572 space = isl_space_add_dims(space, isl_dim_out, len);
573 space = isl_space_set_tuple_name(space, isl_dim_out, type);
575 map = isl_map_universe(space);
576 map = isl_map_fix_si(map, isl_dim_in, 0, id);
577 for (i = 0; i < len; ++i)
578 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
580 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
583 /* Extract user specified "tile" sizes from the "sizes" command line option,
584 * defaulting to option->tile_size in each dimension.
585 * *tile_len contains the maximum number of tile sizes needed.
586 * Update *tile_len to the number of specified tile sizes, if any, and
587 * return a pointer to the tile sizes (or NULL on error).
588 * Add the effectively used sizes to gen->used_sizes.
590 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
592 int n;
593 int *tile_size;
594 isl_set *size;
596 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
597 if (!tile_size)
598 return NULL;
599 for (n = 0; n < *tile_len; ++n)
600 tile_size[n] = gen->options->tile_size;
602 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
603 read_sizes_from_set(size, tile_size, tile_len);
604 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
606 return tile_size;
609 /* Extract user specified "block" sizes from the "sizes" command line option,
610 * after filling in some potentially useful defaults.
612 static void read_block_sizes(struct ppcg_kernel *kernel,
613 __isl_keep isl_union_map *sizes)
615 isl_set *size;
617 if (kernel->n_block > 3)
618 kernel->n_block = 3;
619 switch (kernel->n_block) {
620 case 1:
621 kernel->block_dim[0] = 512;
622 break;
623 case 2:
624 kernel->block_dim[0] = 32;
625 kernel->block_dim[1] = 16;
626 break;
627 default:
628 kernel->block_dim[0] = 32;
629 kernel->block_dim[1] = 4;
630 kernel->block_dim[2] = 4;
631 break;
634 size = extract_sizes(sizes, "block", kernel->id);
635 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
638 /* Extract user specified "grid" sizes from the "sizes" command line option,
639 * after filling in some potentially useful defaults.
641 static void read_grid_sizes(struct ppcg_kernel *kernel,
642 __isl_keep isl_union_map *sizes)
644 isl_set *size;
646 if (kernel->n_grid > 2)
647 kernel->n_grid = 2;
648 switch (kernel->n_grid) {
649 case 1:
650 kernel->grid_dim[0] = 32768;
651 break;
652 default:
653 kernel->grid_dim[0] = 256;
654 kernel->grid_dim[1] = 256;
655 break;
658 size = extract_sizes(sizes, "grid", kernel->id);
659 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
662 /* Extract user specified grid and block sizes from the gen->sizes
663 * command line option after filling in some potentially useful defaults.
664 * Store the extracted sizes in "kernel".
665 * Add the effectively used sizes to gen->used_sizes.
667 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
668 struct gpu_gen *gen)
670 read_block_sizes(kernel, gen->sizes);
671 read_grid_sizes(kernel, gen->sizes);
672 set_used_sizes(gen, "block", kernel->id,
673 kernel->block_dim, kernel->n_block);
674 set_used_sizes(gen, "grid", kernel->id,
675 kernel->grid_dim, kernel->n_grid);
678 static void *free_stmts(struct gpu_stmt *stmts, int n)
680 int i;
682 if (!stmts)
683 return NULL;
685 for (i = 0; i < n; ++i) {
686 struct gpu_stmt_access *access, *next;
688 for (access = stmts[i].accesses; access; access = next) {
689 next = access->next;
690 isl_id_free(access->ref_id);
691 isl_map_free(access->access);
692 isl_map_free(access->tagged_access);
693 free(access);
696 isl_id_free(stmts[i].id);
698 free(stmts);
700 return NULL;
703 /* Add parameters p[i] with identifiers "ids" to "set",
704 * with bounds to 0 <= p[i] < size[i].
706 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
707 int *size, __isl_keep isl_id_list *ids)
709 int i, len;
710 unsigned nparam;
712 len = isl_id_list_n_id(ids);
713 nparam = isl_set_dim(set, isl_dim_param);
714 set = isl_set_add_dims(set, isl_dim_param, len);
716 for (i = 0; i < len; ++i) {
717 isl_id *id;
719 id = isl_id_list_get_id(ids, i);
720 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
721 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
722 set = isl_set_upper_bound_si(set, isl_dim_param,
723 nparam + i, size[i] - 1);
726 return set;
729 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
730 * with
732 * { : 0 <= p[i] < size[i] }
734 * or an overapproximation.
736 static __isl_give isl_set *add_bounded_parameters_dynamic(
737 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
738 __isl_keep isl_id_list *ids)
740 int i, len;
741 unsigned nparam;
742 isl_space *space;
743 isl_local_space *ls;
745 len = isl_multi_pw_aff_dim(size, isl_dim_out);
746 nparam = isl_set_dim(set, isl_dim_param);
747 set = isl_set_add_dims(set, isl_dim_param, len);
749 for (i = 0; i < len; ++i) {
750 isl_id *id;
752 id = isl_id_list_get_id(ids, i);
753 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
756 space = isl_space_params(isl_set_get_space(set));
757 ls = isl_local_space_from_space(space);
758 for (i = 0; i < len; ++i) {
759 isl_pw_aff *param, *size_i, *zero;
760 isl_set *bound;
762 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
763 isl_dim_param, nparam + i);
765 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
766 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
767 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
768 set = isl_set_intersect_params(set, bound);
770 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
771 bound = isl_pw_aff_ge_set(param, zero);
772 set = isl_set_intersect_params(set, bound);
774 isl_local_space_free(ls);
776 return set;
779 /* Return the union of all tagged access relations in the group.
781 static __isl_give isl_union_map *group_tagged_access_relation(
782 struct gpu_array_ref_group *group)
784 int i;
785 isl_union_map *access;
787 access = isl_union_map_empty(isl_map_get_space(group->access));
788 for (i = 0; i < group->n_ref; ++i) {
789 isl_map *map_i;
791 map_i = isl_map_copy(group->refs[i]->tagged_access);
792 access = isl_union_map_union(access,
793 isl_union_map_from_map(map_i));
796 return access;
799 /* Return the extent of "array", recomputed from the bounds.
800 * The recomputed extent may be simpler than the original extent.
802 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
804 int i;
805 isl_id *id;
806 isl_space *space;
807 isl_local_space *ls;
808 isl_set *extent;
810 id = isl_set_get_tuple_id(array->extent);
811 space = isl_set_get_space(array->extent);
812 extent = isl_set_universe(isl_space_copy(space));
813 ls = isl_local_space_from_space(space);
814 for (i = 0; i < array->n_index; ++i) {
815 isl_pw_aff *bound;
816 isl_aff *aff;
817 isl_pw_aff *index;
818 isl_set *lt;
820 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
822 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
823 isl_dim_set, i);
824 index = isl_pw_aff_from_aff(aff);
825 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
826 bound = isl_pw_aff_from_range(bound);
827 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
828 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
829 isl_id_copy(id));
830 lt = isl_pw_aff_lt_set(index, bound);
831 extent = isl_set_intersect(extent, lt);
833 isl_local_space_free(ls);
834 isl_id_free(id);
836 return extent;
839 /* Return a map from the first group->shared_tile->depth dimensions
840 * of the computed schedule to the array tile in
841 * global memory that corresponds to the shared memory copy.
843 * In particular, return a map
845 * { D[i] -> A[a] }
847 * with constraints
849 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
851 * and
853 * 0 <= a <= array_size - 1 (2)
855 * Note that if some stride has been detected (i.e., when
856 * group->shared_tile->bound[i].shift is set), then a in (1) refers
857 * to the shifted and scaled down version.
859 * Constraints (1) are obtained by mapping the size constraints on the
860 * shared/private memory tile back to the access relation.
861 * Constraints (2) are obtained from the (recomputed) extent.
863 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
865 int i;
866 int n_index = group->array->n_index;
867 isl_map *tile;
868 isl_space *space;
869 isl_set *local;
870 isl_set *extent;
872 space = isl_multi_aff_get_space(group->shared_tile->tiling);
873 space = isl_space_range(space);
874 local = isl_set_universe(space);
875 for (i = 0; i < n_index; ++i) {
876 isl_val *bound;
878 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
879 bound = isl_val_copy(group->shared_tile->bound[i].size);
880 bound = isl_val_sub_ui(bound, 1);
881 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
883 local = isl_set_preimage_multi_aff(local,
884 isl_multi_aff_copy(group->shared_tile->tiling));
885 tile = isl_set_unwrap(local);
886 extent = array_extent(group->array);
887 tile = isl_map_intersect_range(tile, extent);
889 return tile;
892 /* Given a mapping "iterator_map" from the AST schedule to a domain,
893 * return the corresponding mapping from the AST schedule to
894 * to the outer kernel->copy_schedule_dim dimensions of
895 * the schedule computed by PPCG for this kernel.
897 * Note that kernel->copy_schedule_dim is at least as large as
898 * the largest depth of any array reference group associated to the kernel.
899 * This is needed as the returned schedule is used to extract a mapping
900 * to the outer tile->depth dimensions in transform_index.
902 static __isl_give isl_pw_multi_aff *compute_sched_to_copy(
903 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
905 isl_union_pw_multi_aff *upma;
906 isl_pw_multi_aff *pma;
907 isl_space *space;
909 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
910 space = isl_space_from_domain(space);
911 space = isl_space_add_dims(space, isl_dim_out,
912 kernel->copy_schedule_dim);
914 upma = isl_union_pw_multi_aff_copy(kernel->copy_schedule);
915 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
916 isl_union_pw_multi_aff_free(upma);
918 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
921 /* If max_shared_memory is not set to infinity (-1), then make
922 * sure that the total amount of shared memory required by the
923 * array reference groups mapped to shared memory by "kernel"
924 * is no larger than this maximum.
926 * We apply a greedy approach and discard (keep in global memory)
927 * those groups that would result in a total memory size that
928 * is larger than the maximum.
930 * This function should be called after any function that may
931 * affect the decision on whether to place a reference group
932 * in private, shared or global memory.
934 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
936 int i, j;
937 isl_val *left, *size;
939 if (kernel->options->max_shared_memory < 0)
940 return;
942 left = isl_val_int_from_si(kernel->ctx,
943 kernel->options->max_shared_memory);
945 for (i = 0; i < kernel->n_array; ++i) {
946 struct gpu_local_array_info *local = &kernel->array[i];
948 for (j = 0; j < local->n_group; ++j) {
949 struct gpu_array_ref_group *group;
950 enum ppcg_group_access_type type;
952 group = local->groups[j];
953 type = gpu_array_ref_group_type(group);
954 if (type != ppcg_access_shared)
955 continue;
957 size = gpu_array_tile_size(group->shared_tile);
958 size = isl_val_mul_ui(size, local->array->size);
960 if (isl_val_le(size, left)) {
961 left = isl_val_sub(left, size);
962 continue;
964 isl_val_free(size);
966 group->shared_tile =
967 gpu_array_tile_free(group->shared_tile);
971 isl_val_free(left);
974 /* Mark all arrays of "kernel" that have an array reference group
975 * that is not mapped to private or shared memory as
976 * accessing the corresponding global device memory.
978 static void mark_global_arrays(struct ppcg_kernel *kernel)
980 int i, j;
982 for (i = 0; i < kernel->n_array; ++i) {
983 struct gpu_local_array_info *local = &kernel->array[i];
985 if (local->global)
986 continue;
987 for (j = 0; j < local->n_group; ++j) {
988 if (gpu_array_ref_group_tile(local->groups[j]))
989 continue;
991 local->global = 1;
992 local->array->global = 1;
993 break;
998 /* Compute a tiling for all the array reference groups in "kernel".
1000 static void compute_group_tilings(struct ppcg_kernel *kernel)
1002 int i, j;
1004 for (i = 0; i < kernel->n_array; ++i) {
1005 struct gpu_local_array_info *array = &kernel->array[i];
1007 for (j = 0; j < array->n_group; ++j)
1008 gpu_array_ref_group_compute_tiling(array->groups[j]);
1012 /* Compute the effective grid size as a list of the sizes in each dimension.
1014 * The grid size specified by the user or set by default
1015 * in read_grid_sizes() and applied by the block filter,
1016 * may be too large for the given code in the sense that
1017 * it may contain blocks that don't need to execute anything.
1018 * We therefore don't return this grid size, but instead the
1019 * smallest grid size that ensures that all blocks that actually
1020 * execute code are included in the grid.
1022 * We first extract a description of the grid, i.e., the possible values
1023 * of the block ids, from the domain elements in "domain" and
1024 * kernel->block_filter.
1025 * The block ids are parameters in kernel->block_filter.
1026 * We simply need to change them into set dimensions.
1028 * Then, for each block dimension, we compute the maximal value of the block id
1029 * and add one.
1031 static __isl_give isl_multi_pw_aff *extract_grid_size(
1032 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1034 int i;
1035 isl_set *grid;
1036 isl_set *context;
1037 isl_multi_pw_aff *size;
1039 domain = isl_union_set_intersect(domain,
1040 isl_union_set_copy(kernel->block_filter));
1041 grid = isl_union_set_params(domain);
1042 grid = isl_set_from_params(grid);
1043 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1044 for (i = 0; i < kernel->n_grid; ++i) {
1045 int pos;
1046 isl_id *id;
1048 id = isl_id_list_get_id(kernel->block_ids, i);
1049 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1050 isl_id_free(id);
1051 assert(pos >= 0);
1052 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1053 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1056 grid = isl_set_coalesce(grid);
1057 size = ppcg_size_from_extent(grid);
1058 context = isl_set_params(isl_set_copy(kernel->context));
1059 return isl_multi_pw_aff_gist(size, context);
1062 /* Compute the size of a fixed bounding box around the origin and "set",
1063 * where "set" is assumed to contain only non-negative elements,
1064 * and store the results in "size".
1065 * In particular, compute the maximal value of "set" in each direction
1066 * and add one.
1068 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1070 int i, n;
1071 isl_local_space *ls;
1072 isl_aff *obj;
1074 n = isl_set_dim(set, isl_dim_set);
1075 ls = isl_local_space_from_space(isl_set_get_space(set));
1076 obj = isl_aff_zero_on_domain(ls);
1077 for (i = 0; i < n; ++i) {
1078 isl_val *max;
1080 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1081 max = isl_set_max_val(set, obj);
1082 size[i] = isl_val_get_num_si(max) + 1;
1083 isl_val_free(max);
1084 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1086 isl_aff_free(obj);
1087 isl_set_free(set);
1090 /* Compute the effective block size as a list of the sizes in each dimension
1091 * and store the sizes in kernel->block_dim.
1093 * The block size specified by the user or set by default
1094 * in read_block_sizes() and applied by the thread filter,
1095 * may be too large for the given code in the sense that
1096 * it may contain threads that don't need to execute anything.
1097 * We therefore update this block size in kernel->block_dim
1098 * to the smallest block size that ensures that all threads
1099 * that actually execute code are included in the block.
1101 * The set of possible values of the thread ids is obtained from
1102 * the domain elements "domain" and kernel->thread_filter.
1103 * The current implementation eliminates all parameters, ensuring
1104 * that the size is a fixed constant in each dimension.
1105 * In principle we could also compute parametric sizes.
1106 * We would have to make sure to project out all b%d and t%d parameters,
1107 * however.
1109 static isl_stat extract_block_size(struct ppcg_kernel *kernel,
1110 __isl_take isl_union_set *domain)
1112 int i;
1113 int nparam;
1114 isl_set *block;
1116 domain = isl_union_set_intersect(domain,
1117 isl_union_set_copy(kernel->thread_filter));
1118 block = isl_union_set_params(domain);
1119 block = isl_set_from_params(block);
1120 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1121 for (i = 0; i < kernel->n_block; ++i) {
1122 int pos;
1123 isl_id *id;
1125 if (!block)
1126 return isl_stat_error;
1128 id = isl_id_list_get_id(kernel->thread_ids, i);
1129 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1130 isl_id_free(id);
1131 if (pos < 0)
1132 isl_die(isl_set_get_ctx(block), isl_error_internal,
1133 "missing constraints on thread identifier",
1134 block = isl_set_free(block));
1135 block = isl_set_equate(block, isl_dim_param, pos,
1136 isl_dim_set, i);
1138 nparam = isl_set_dim(block, isl_dim_param);
1139 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1141 if (!block)
1142 return isl_stat_error;
1144 extract_fixed_size(block, kernel->block_dim);
1146 return isl_stat_ok;
1149 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1151 int i, j;
1153 if (!kernel)
1154 return NULL;
1156 isl_id_list_free(kernel->block_ids);
1157 isl_id_list_free(kernel->thread_ids);
1158 isl_multi_pw_aff_free(kernel->grid_size);
1159 isl_ast_expr_free(kernel->grid_size_expr);
1160 isl_set_free(kernel->context);
1161 isl_union_set_free(kernel->core);
1162 isl_union_set_free(kernel->arrays);
1163 isl_union_pw_multi_aff_free(kernel->contraction);
1164 isl_union_set_free(kernel->expanded_domain);
1165 isl_space_free(kernel->space);
1166 isl_ast_node_free(kernel->tree);
1167 isl_union_set_free(kernel->block_filter);
1168 isl_union_set_free(kernel->thread_filter);
1169 isl_union_pw_multi_aff_free(kernel->copy_schedule);
1170 isl_union_set_free(kernel->sync_writes);
1172 for (i = 0; i < kernel->n_array; ++i) {
1173 struct gpu_local_array_info *array = &kernel->array[i];
1175 for (j = 0; j < array->n_group; ++j)
1176 gpu_array_ref_group_free(array->groups[j]);
1177 free(array->groups);
1179 isl_multi_pw_aff_free(array->bound);
1180 isl_ast_expr_free(array->bound_expr);
1182 free(kernel->array);
1184 for (i = 0; i < kernel->n_var; ++i) {
1185 free(kernel->var[i].name);
1186 isl_vec_free(kernel->var[i].size);
1188 free(kernel->var);
1190 free(kernel);
1192 return NULL;
1195 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1197 static void ppcg_kernel_free_wrap(void *user)
1199 struct ppcg_kernel *kernel = user;
1201 ppcg_kernel_free(kernel);
1204 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1205 struct ppcg_kernel_var *var)
1207 int j;
1208 struct gpu_array_tile *tile;
1209 isl_printer *p;
1211 var->array = group->array;
1213 var->type = gpu_array_ref_group_type(group);
1214 tile = gpu_array_ref_group_tile(group);
1216 p = isl_printer_to_str(ctx);
1217 p = gpu_array_ref_group_print_name(group, p);
1218 var->name = isl_printer_get_str(p);
1219 isl_printer_free(p);
1221 var->size = isl_vec_alloc(ctx, group->array->n_index);
1223 for (j = 0; j < group->array->n_index; ++j)
1224 var->size = isl_vec_set_element_val(var->size, j,
1225 isl_val_copy(tile->bound[j].size));
1228 static int create_kernel_vars(struct ppcg_kernel *kernel)
1230 int i, j, n;
1232 n = 0;
1233 for (i = 0; i < kernel->n_array; ++i) {
1234 struct gpu_local_array_info *array = &kernel->array[i];
1236 for (j = 0; j < array->n_group; ++j) {
1237 struct gpu_array_ref_group *group = array->groups[j];
1238 enum ppcg_group_access_type type;
1240 type = gpu_array_ref_group_type(group);
1241 if (type != ppcg_access_global)
1242 ++n;
1246 kernel->n_var = n;
1247 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1248 if (!kernel->var)
1249 return -1;
1251 n = 0;
1252 for (i = 0; i < kernel->n_array; ++i) {
1253 struct gpu_local_array_info *array = &kernel->array[i];
1255 for (j = 0; j < array->n_group; ++j) {
1256 struct gpu_array_ref_group *group = array->groups[j];
1257 enum ppcg_group_access_type type;
1259 type = gpu_array_ref_group_type(group);
1260 if (type == ppcg_access_global)
1261 continue;
1262 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1263 ++n;
1267 return 0;
1270 /* Replace "pa" by the zero function defined over the universe domain
1271 * in the space of "pa".
1273 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1275 isl_space *space;
1276 isl_aff *zero;
1278 space = isl_space_domain(isl_pw_aff_get_space(pa));
1279 isl_pw_aff_free(pa);
1280 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1282 return isl_pw_aff_from_aff(zero);
1285 /* The sizes of the arrays on the host that have been computed by
1286 * extract_array_info may depend on the parameters. Use the extra
1287 * constraints on the parameters that are valid at "host_domain"
1288 * to simplify these expressions and store the results in kernel->array.
1290 * We only need these localized bounds for arrays that are accessed
1291 * by the current kernel. If we have found at least one reference group
1292 * then the array is accessed by the kernel.
1294 * The resulting sizes may be functions that are nowhere defined
1295 * in case the access function cannot possibly access anything inside
1296 * the kernel for some reason. If so, they are replaced by the zero
1297 * function. Since the access function cannot actually access anything,
1298 * there is no harm in printing the array sizes as zero.
1300 static void localize_bounds(struct ppcg_kernel *kernel,
1301 __isl_keep isl_set *host_domain)
1303 int i, j;
1304 isl_set *context;
1306 context = isl_set_copy(host_domain);
1307 context = isl_set_params(context);
1309 for (i = 0; i < kernel->n_array; ++i) {
1310 struct gpu_local_array_info *local = &kernel->array[i];
1311 isl_multi_pw_aff *bound;
1312 int n_index;
1314 if (local->n_group == 0)
1315 continue;
1317 n_index = local->array->n_index;
1318 bound = isl_multi_pw_aff_copy(local->array->bound);
1320 for (j = 0; j < n_index; ++j) {
1321 isl_pw_aff *pwaff;
1322 int empty;
1324 pwaff = isl_multi_pw_aff_get_pw_aff(bound, j);
1325 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1326 empty = isl_pw_aff_is_empty(pwaff);
1327 if (empty < 0)
1328 pwaff = isl_pw_aff_free(pwaff);
1329 else if (empty)
1330 pwaff = set_universally_zero(pwaff);
1331 bound = isl_multi_pw_aff_set_pw_aff(bound, j, pwaff);
1334 local->n_index = n_index;
1335 local->bound = bound;
1337 isl_set_free(context);
1340 /* Create the array of gpu_local_array_info structures "array"
1341 * inside "kernel". The number of elements in this array is
1342 * the same as the number of arrays in "prog".
1343 * Initialize the "array" field of each local array to point
1344 * to the corresponding array in "prog".
1346 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1347 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1349 int i;
1350 isl_ctx *ctx;
1352 ctx = isl_set_get_ctx(prog->context);
1353 kernel->array = isl_calloc_array(ctx,
1354 struct gpu_local_array_info, prog->n_array);
1355 if (!kernel->array)
1356 return ppcg_kernel_free(kernel);
1357 kernel->n_array = prog->n_array;
1359 for (i = 0; i < prog->n_array; ++i)
1360 kernel->array[i].array = &prog->array[i];
1362 return kernel;
1365 /* Does "kernel" need to be passed an argument corresponding to array "i"?
1367 * The argument is only needed if the kernel accesses this device memory.
1369 int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1371 return kernel->array[i].global;
1374 /* Find the element in gen->stmt that has the given "id".
1375 * Return NULL if no such gpu_stmt can be found.
1377 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1379 int i;
1381 for (i = 0; i < prog->n_stmts; ++i) {
1382 if (id == prog->stmts[i].id)
1383 break;
1386 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1389 void ppcg_kernel_stmt_free(void *user)
1391 struct ppcg_kernel_stmt *stmt = user;
1393 if (!stmt)
1394 return;
1396 switch (stmt->type) {
1397 case ppcg_kernel_copy:
1398 isl_ast_expr_free(stmt->u.c.index);
1399 isl_ast_expr_free(stmt->u.c.local_index);
1400 break;
1401 case ppcg_kernel_domain:
1402 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1403 break;
1404 case ppcg_kernel_sync:
1405 break;
1408 free(stmt);
1411 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1412 * to "ref_id".
1414 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1415 __isl_keep isl_id *ref_id)
1417 struct gpu_stmt_access *access;
1419 for (access = accesses; access; access = access->next)
1420 if (access->ref_id == ref_id)
1421 return access;
1423 return NULL;
1426 /* Return the index of the array called "name" in the list of arrays.
1428 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1430 int i;
1432 for (i = 0; i < kernel->n_array; ++i)
1433 if (!strcmp(name, kernel->array[i].array->name))
1434 return i;
1436 return -1;
1439 /* Internal data structure for the index and AST expression transformation
1440 * callbacks for pet_stmt_build_ast_exprs.
1442 * "kernel" is the kernel for which are computing AST expressions and
1443 * may be NULL if we are not inside a kernel.
1444 * "accesses" is the list of gpu_stmt_access in the statement.
1445 * "iterator_map" expresses the statement iterators in terms of
1446 * the AST loop iterators.
1447 * "sched2copy" expresses the outer copy_schedule_dim dimensions of
1448 * the kernel schedule in terms of the AST loop iterators and
1449 * may be NULL if we are not inside a kernel.
1451 * The following fields are set in transform_index and used in transform_expr.
1452 * "array" is the array that is being accessed.
1453 * "global" is set if the global array is accessed (rather than
1454 * shared/private memory).
1455 * "local_array" refers to information on the array specialized
1456 * to the current kernel.
1458 struct ppcg_transform_data {
1459 struct ppcg_kernel *kernel;
1460 struct gpu_stmt_access *accesses;
1461 isl_pw_multi_aff *iterator_map;
1462 isl_pw_multi_aff *sched2copy;
1464 struct gpu_array_info *array;
1465 int global;
1466 struct gpu_local_array_info *local_array;
1469 /* Return a pointer to the gpu_array_ref_group in "local"
1470 * that contains the reference "access".
1471 * Return NULL if no such group can be found.
1473 static struct gpu_array_ref_group *find_ref_group(
1474 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1476 int i, j;
1478 for (i = 0; i < local->n_group; ++i) {
1479 struct gpu_array_ref_group *group = local->groups[i];
1481 for (j = 0; j < group->n_ref; ++j)
1482 if (group->refs[j] == access)
1483 return group;
1486 return NULL;
1489 /* Given an index expression "index" of the form
1491 * L -> F(A),
1493 * with F(A) either A or some subfield of A and L the AST loop iterators,
1494 * and a tiling "tiling" of the form
1496 * [L -> A] -> T
1498 * apply the tiling to the outer array in the index expression to obtain
1500 * L -> T(A)
1502 * If F(A) is some subfield of A, then separate the member access
1503 * into the base index expression and the field index expression,
1504 * apply the tiling to the base index expression and combine the result
1505 * with the field index expression.
1507 * If F(A) is A, then modify index to keep track of the iterators
1509 * L -> [L -> A]
1511 * and combine the result with the tiling to obtain a tiled index expression
1512 * in terms of the AST loop iterators
1514 * L -> T
1516 static __isl_give isl_multi_pw_aff *tile_outer(
1517 __isl_take isl_multi_pw_aff *index, __isl_take isl_multi_pw_aff *tiling)
1519 isl_bool is_wrapping;
1520 isl_space *space;
1521 isl_multi_pw_aff *mpa;
1523 is_wrapping = isl_multi_pw_aff_range_is_wrapping(index);
1524 if (is_wrapping < 0)
1525 goto error;
1526 if (is_wrapping) {
1527 isl_multi_pw_aff *field;
1529 field = isl_multi_pw_aff_copy(index);
1530 field = isl_multi_pw_aff_range_factor_range(field);
1531 index = isl_multi_pw_aff_range_factor_domain(index);
1532 index = tile_outer(index, tiling);
1533 return isl_multi_pw_aff_range_product(index, field);
1536 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1537 space = isl_space_map_from_set(space);
1538 mpa = isl_multi_pw_aff_identity(space);
1539 index = isl_multi_pw_aff_range_product(mpa, index);
1540 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1542 return index;
1543 error:
1544 isl_multi_pw_aff_free(index);
1545 isl_multi_pw_aff_free(tiling);
1546 return NULL;
1549 /* Index transformation callback for pet_stmt_build_ast_exprs.
1551 * "index" expresses the array indices in terms of statement iterators
1553 * We first reformulate "index" in terms of the AST loop iterators.
1554 * Then we check if we are accessing the global array or
1555 * a shared/private copy. In particular, if we are not inside a kernel
1556 * then we must be accessing a global array.
1557 * In the former case, we simply return
1558 * the updated index. If "index" is an affine expression rather
1559 * than an array access, then we also return the updated index here.
1561 * If no reference groups have been computed for the array,
1562 * then we can only be accessing the global array.
1564 * Otherwise, we apply the tiling to the index.
1565 * This tiling is of the form
1567 * [D -> A] -> T
1569 * where D corresponds to the outer tile->depth dimensions of
1570 * the kernel schedule.
1571 * The index is of the form
1573 * L -> A
1575 * We update the tiling to refer to the AST loop iterators
1577 * [L -> A] -> T
1579 * and combine it with the index to obtain a tiled index expression in terms
1580 * of the AST loop iterators
1582 * L -> T
1584 * Note that while the tiling applies directly to an outer array.
1585 * the index may refer to some subfield of this outer array.
1586 * In such cases, the result will refer to the same subfield of the tile.
1587 * That is, an index expression of the form L -> F(A) will be transformed
1588 * into an index expression of the form L -> F(T).
1590 static __isl_give isl_multi_pw_aff *transform_index(
1591 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1592 void *user)
1594 struct ppcg_transform_data *data = user;
1595 struct gpu_stmt_access *access;
1596 struct gpu_array_ref_group *group;
1597 struct gpu_array_tile *tile;
1598 isl_pw_multi_aff *iterator_map;
1599 int i;
1600 int dim;
1601 const char *name;
1602 isl_space *space;
1603 isl_multi_pw_aff *tiling;
1604 isl_pw_multi_aff *pma;
1605 isl_multi_pw_aff *mpa;
1606 isl_pw_multi_aff *sched2depth;
1608 data->array = NULL;
1610 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1611 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1613 if (!data->kernel)
1614 return index;
1616 access = find_access(data->accesses, ref_id);
1617 if (!access)
1618 return index;
1619 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1620 return index;
1622 name = get_outer_array_name(access->access);
1623 i = find_array_index(data->kernel, name);
1624 if (i < 0)
1625 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1626 "cannot find array",
1627 return isl_multi_pw_aff_free(index));
1628 data->local_array = &data->kernel->array[i];
1629 data->array = data->local_array->array;
1631 group = find_ref_group(data->local_array, access);
1632 if (!group) {
1633 data->global = 1;
1634 return index;
1637 tile = gpu_array_ref_group_tile(group);
1638 data->global = !tile;
1639 if (!tile)
1640 return index;
1642 space = isl_space_domain(isl_multi_aff_get_space(tile->tiling));
1643 space = isl_space_range(isl_space_unwrap(space));
1644 space = isl_space_map_from_set(space);
1645 pma = isl_pw_multi_aff_identity(space);
1646 sched2depth = isl_pw_multi_aff_copy(data->sched2copy);
1647 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1648 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1649 tile->depth, dim - tile->depth);
1650 pma = isl_pw_multi_aff_product(sched2depth, pma);
1651 tiling = isl_multi_pw_aff_from_multi_aff(
1652 isl_multi_aff_copy(tile->tiling));
1653 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1655 index = tile_outer(index, tiling);
1657 return index;
1660 /* Dereference "expr" by adding an index [0].
1661 * The original "expr" is assumed not to have any indices.
1663 * If "expr" is a member access, then the dereferencing needs
1664 * to be applied to the structure argument of this member access.
1666 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1668 isl_ctx *ctx;
1669 isl_ast_expr *arg0, *res;
1670 isl_ast_expr_list *list;
1672 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1673 if (!arg0)
1674 return isl_ast_expr_free(expr);
1675 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1676 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1677 isl_ast_expr *arg;
1679 arg = isl_ast_expr_get_op_arg(arg0, 0);
1680 arg = dereference(arg);
1681 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1682 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1684 return expr;
1686 isl_ast_expr_free(arg0);
1688 ctx = isl_ast_expr_get_ctx(expr);
1689 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1690 list = isl_ast_expr_list_from_ast_expr(res);
1691 res = isl_ast_expr_get_op_arg(expr, 0);
1692 res = isl_ast_expr_access(res, list);
1693 isl_ast_expr_free(expr);
1695 return res;
1698 /* Linearize the index expression "expr" based on the array bounds
1699 * of "array".
1701 * That is, transform expression
1703 * A[i_0][i_1]...[i_n]
1705 * to
1707 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1709 * where b_0, b_1, ..., b_n are the bounds on the array.
1711 * If the base of "expr" is a member access, then the linearization needs
1712 * to be applied to the structure argument of this member access.
1714 * In the base case, if "expr" has no arguments (other than the name of
1715 * the array), then we are passing an entire array to a function.
1716 * In this case, there is nothing to linearize.
1717 * Note that at this point an expression with no arguments can
1718 * only be an entire array because the scalar case and
1719 * the case of single struct are handled by the caller.
1721 * If the number of specified index expressions in "expr"
1722 * is smaller than the dimension of the accessed array,
1723 * then the missing i_j also do not appear in the linearized expression.
1724 * Furthermore, since such an expression does not refer to a single
1725 * element while the default linearized expression would refer to
1726 * a single element, we return the expression
1728 * A + (..((i_0 * b_1 + i_1) ... ) * b_l + i_l)
1730 * instead. Note that because of the special case handling above,
1731 * we can assume here that there is at least one index expression.
1733 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1734 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1736 int i, n;
1737 isl_ast_expr *arg0;
1738 isl_ast_expr *res;
1739 isl_ast_expr_list *list;
1741 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1742 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1743 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1744 isl_ast_expr *arg;
1746 arg = isl_ast_expr_get_op_arg(arg0, 0);
1747 arg = gpu_local_array_info_linearize_index(array, arg);
1748 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1749 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1751 return expr;
1753 isl_ast_expr_free(arg0);
1755 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1756 return expr;
1758 n = isl_ast_expr_get_op_n_arg(expr);
1759 res = isl_ast_expr_get_op_arg(expr, 1);
1760 for (i = 1; i < array->n_index; ++i) {
1761 isl_ast_expr *expr_i;
1763 expr_i = isl_ast_expr_get_op_arg(array->bound_expr, 1 + i);
1764 res = isl_ast_expr_mul(res, expr_i);
1766 if (i + 1 >= n)
1767 continue;
1768 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1769 res = isl_ast_expr_add(res, expr_i);
1772 if (1 + array->n_index > n) {
1773 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1774 } else {
1775 list = isl_ast_expr_list_from_ast_expr(res);
1776 res = isl_ast_expr_get_op_arg(expr, 0);
1777 res = isl_ast_expr_access(res, list);
1780 isl_ast_expr_free(expr);
1782 return res;
1785 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1787 * If the AST expression refers to an array that is not accessed
1788 * at all, then this means the value of the expression is not used,
1789 * so we might as well print zero (NULL pointer) instead.
1791 * If the AST expression refers to a global scalar that is not
1792 * a read-only scalar, then its address was passed to the kernel and
1793 * we need to dereference it.
1795 * If the AST expression refers to an access to a global array,
1796 * then we linearize the access exploiting the bounds in data->local_array.
1798 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1799 __isl_keep isl_id *id, void *user)
1801 struct ppcg_transform_data *data = user;
1803 if (!data->array)
1804 return expr;
1805 if (!data->array->accessed) {
1806 isl_ctx *ctx;
1808 ctx = isl_ast_expr_get_ctx(expr);
1809 isl_ast_expr_free(expr);
1810 return isl_ast_expr_from_val(isl_val_zero(ctx));
1812 if (gpu_array_is_read_only_scalar(data->array))
1813 return expr;
1814 if (!data->global)
1815 return expr;
1816 if (data->array->n_index == 0)
1817 return dereference(expr);
1818 if (!data->array->linearize)
1819 return expr;
1821 return gpu_local_array_info_linearize_index(data->local_array, expr);
1824 /* This function is called for each instance of a user statement
1825 * in the kernel "kernel", identified by "gpu_stmt".
1826 * "kernel" may be NULL if we are not inside a kernel.
1828 * We attach a struct ppcg_kernel_stmt to the "node", containing
1829 * a computed AST expression for each access, through an annotation
1830 * with name "user".
1831 * These AST expressions are computed from iterator_map,
1832 * which expresses the domain
1833 * elements in terms of the generated loops, and sched2copy,
1834 * which expresses the outer copy_schedule_dim dimensions of
1835 * the kernel schedule computed by PPCG in terms of the generated loops.
1837 static __isl_give isl_ast_node *create_domain_leaf(
1838 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1839 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1841 struct ppcg_transform_data data;
1842 struct ppcg_kernel_stmt *stmt;
1843 isl_ctx *ctx;
1844 isl_id *id;
1845 isl_pw_multi_aff *sched2copy;
1846 isl_map *map;
1847 isl_pw_multi_aff *iterator_map;
1848 isl_union_map *schedule;
1850 if (!node)
1851 return NULL;
1852 ctx = isl_ast_node_get_ctx(node);
1854 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1855 if (!stmt)
1856 return isl_ast_node_free(node);
1858 schedule = isl_ast_build_get_schedule(build);
1859 map = isl_map_reverse(isl_map_from_union_map(schedule));
1860 iterator_map = isl_pw_multi_aff_from_map(map);
1861 if (kernel)
1862 sched2copy = compute_sched_to_copy(kernel,
1863 isl_pw_multi_aff_copy(iterator_map));
1864 else
1865 sched2copy = NULL;
1867 stmt->type = ppcg_kernel_domain;
1868 stmt->u.d.stmt = gpu_stmt;
1870 data.kernel = kernel;
1871 data.accesses = stmt->u.d.stmt->accesses;
1872 data.iterator_map = iterator_map;
1873 data.sched2copy = sched2copy;
1874 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1875 build, &transform_index, &data,
1876 &transform_expr, &data);
1878 isl_pw_multi_aff_free(iterator_map);
1879 isl_pw_multi_aff_free(sched2copy);
1881 id = isl_id_alloc(ctx, "user", stmt);
1882 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1883 return isl_ast_node_set_annotation(node, id);
1886 /* This function is called for each statement node in the AST
1887 * for copying to or from shared/private memory.
1888 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1889 * statement to the node.
1890 * The statement name is "read" or "write", depending on whether we are
1891 * reading from global memory or writing to global memory.
1893 * The schedule is of the form
1895 * type[D -> A] -> L
1897 * where D corresponds to the outer tile->depth dimensions of
1898 * the kernel schedule, A to the global array and L to the outer
1899 * generated AST schedule.
1900 * We compute the inverse and strip off the type, resulting in
1902 * L -> [D -> A]
1904 * We combine this mapping with on the one hand the projection
1906 * [D -> A] -> A
1908 * and on the other hand the group tiling
1910 * [D -> A] -> T
1912 * resulting in
1914 * L -> A and L -> T
1916 * and store the corresponding expressions in stmt->index and stmt->local_index,
1917 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1918 * stmt->index is linearized if the global memory array is linearized.
1920 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1921 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1922 __isl_keep isl_ast_build *build)
1924 struct ppcg_kernel_stmt *stmt;
1925 struct gpu_array_tile *tile;
1926 isl_id *id;
1927 isl_ast_expr *expr;
1928 isl_space *space;
1929 isl_map *access;
1930 isl_pw_multi_aff *pma, *pma2;
1931 const char *type;
1933 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1934 if (!stmt)
1935 return isl_ast_node_free(node);
1937 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1938 type = isl_map_get_tuple_name(access, isl_dim_in);
1939 stmt->u.c.read = !strcmp(type, "read");
1940 access = isl_map_reverse(access);
1941 pma = isl_pw_multi_aff_from_map(access);
1942 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1944 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1945 space = isl_space_unwrap(space);
1946 pma2 = isl_pw_multi_aff_range_map(space);
1947 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1948 isl_pw_multi_aff_copy(pma));
1949 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1950 if (group->array->linearize)
1951 expr = gpu_local_array_info_linearize_index(group->local_array,
1952 expr);
1953 stmt->u.c.index = expr;
1955 tile = gpu_array_ref_group_tile(group);
1956 pma2 = isl_pw_multi_aff_from_multi_aff(
1957 isl_multi_aff_copy(tile->tiling));
1958 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1959 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1960 stmt->u.c.local_index = expr;
1962 stmt->u.c.array = group->array;
1963 stmt->u.c.local_array = group->local_array;
1964 stmt->type = ppcg_kernel_copy;
1966 id = isl_id_alloc(kernel->ctx, "copy", stmt);
1967 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1968 return isl_ast_node_set_annotation(node, id);
1971 /* Create a synchronization ppcg_kernel_stmt and
1972 * attach it to the node "node" representing the synchronization.
1974 static __isl_give isl_ast_node *create_sync_leaf(
1975 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1976 __isl_keep isl_ast_build *build)
1978 struct ppcg_kernel_stmt *stmt;
1979 isl_id *id;
1981 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1982 if (!stmt)
1983 return isl_ast_node_free(node);
1985 stmt->type = ppcg_kernel_sync;
1986 id = isl_id_alloc(kernel->ctx, "sync", stmt);
1987 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1988 return isl_ast_node_set_annotation(node, id);
1991 /* Build AST expressions for the device array sizes of all arrays in "prog"
1992 * that require allocation on the device using "build", as well as
1993 * for the original array sizes of all arrays that need to be declared
1994 * on the host.
1995 * "node" is freed in case of error.
1997 static __isl_give isl_ast_node *build_array_bounds(
1998 __isl_take isl_ast_node *node, struct gpu_prog *prog,
1999 __isl_keep isl_ast_build *build)
2001 int i;
2003 for (i = 0; i < prog->n_array; ++i) {
2004 struct gpu_array_info *array = &prog->array[i];
2005 isl_multi_pw_aff *size;
2006 isl_ast_expr *expr;
2008 if (!gpu_array_requires_device_allocation(array))
2009 continue;
2011 size = isl_multi_pw_aff_copy(array->bound);
2012 expr = ppcg_build_size_expr(size, build);
2013 array->bound_expr = expr;
2014 if (!expr)
2015 return isl_ast_node_free(node);
2018 for (i = 0; i < prog->n_array; ++i) {
2019 struct gpu_array_info *array = &prog->array[i];
2020 isl_set *extent;
2021 isl_multi_pw_aff *size;
2022 isl_ast_expr *expr;
2024 if (!array->declare_local)
2025 continue;
2026 extent = isl_set_copy(array->declared_extent);
2027 size = ppcg_size_from_extent(extent);
2028 expr = ppcg_build_size_expr(size, build);
2029 array->declared_size = expr;
2030 if (!expr)
2031 return isl_ast_node_free(node);
2034 return node;
2037 /* Internal data structure for at_domain.
2039 * "prog" represents the entire scop.
2040 * "kernel" points to the kernel to which the current schedule node
2041 * belongs. It is set by before_mark and reset by after_mark.
2042 * It may be NULL if we are outside any kernel.
2044 struct ppcg_at_domain_data {
2045 struct gpu_prog *prog;
2046 struct ppcg_kernel *kernel;
2049 /* This function is called for each instance of a user statement
2050 * in the kernel. This may be one of the original user statements
2051 * or a statement introduced by PPCG.
2053 * We first check if the statement id corresponds to a gpu statement,
2054 * which indicates the statement is an original user statement. Any statement
2055 * that is not an original user statement has been introduced by PPCG and
2056 * requires special handling.
2058 * If the user statement is one of the original user statements, then we call
2059 * create_domain_leaf. If it is "init_device", then we call
2060 * build_array_bounds. Otherwise, we check if it is a copy or synchronization
2061 * statement and call the appropriate functions. Statements that copy an array
2062 * to/from the device do not need any further treatment.
2063 * Neither does "clear_device".
2065 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
2066 __isl_keep isl_ast_build *build, void *user)
2068 struct ppcg_at_domain_data *data = user;
2069 struct gpu_stmt *gpu_stmt;
2070 isl_ast_expr *expr, *arg;
2071 isl_id *id;
2072 int is_sync;
2073 const char *name;
2074 void *p;
2076 expr = isl_ast_node_user_get_expr(node);
2077 arg = isl_ast_expr_get_op_arg(expr, 0);
2078 id = isl_ast_expr_get_id(arg);
2079 name = isl_id_get_name(id);
2080 p = isl_id_get_user(id);
2081 isl_ast_expr_free(expr);
2082 isl_ast_expr_free(arg);
2084 gpu_stmt = find_stmt(data->prog, id);
2085 is_sync = gpu_tree_id_is_sync(id, data->kernel);
2086 isl_id_free(id);
2088 if (gpu_stmt)
2089 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
2091 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
2092 return node;
2093 if (!strcmp(name, "init_device"))
2094 return build_array_bounds(node, data->prog, build);
2095 if (!strcmp(name, "clear_device"))
2096 return node;
2097 if (is_sync < 0)
2098 return isl_ast_node_free(node);
2099 if (!strcmp(name, "read") || !strcmp(name, "write")) {
2100 struct gpu_array_ref_group *group = p;
2101 return create_access_leaf(data->kernel, group, node, build);
2103 if (!is_sync)
2104 isl_die(data->prog->ctx, isl_error_internal,
2105 "unknown statement type",
2106 return isl_ast_node_free(node));
2107 return create_sync_leaf(data->kernel, node, build);
2110 /* Given a set of wrapped references "ref", return the corresponding
2111 * access relations based on the tagged access relations "tagged".
2113 * The elements of "ref" are of the form
2115 * [D -> R]
2117 * with D an iteration domains and R a reference.
2118 * The elements of "tagged" are of the form
2120 * [D -> R] -> A
2122 * with A an array.
2124 * Extend "tagged" to include the iteration domain in the range, i.e.,
2126 * [D -> R] -> [D -> A]
2128 * apply the result to "ref" and then unwrap the resulting set
2129 * to obtain relations of the form
2131 * D -> A
2133 static __isl_give isl_union_map *wrapped_reference_to_access(
2134 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2136 isl_union_map *tag2access;
2138 tag2access = isl_union_map_copy(tagged);
2139 tag2access = isl_union_map_universe(tag2access);
2140 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2141 tag2access = isl_union_map_domain_map(tag2access);
2142 tag2access = isl_union_map_range_product(tag2access, tagged);
2144 ref = isl_union_set_coalesce(ref);
2145 ref = isl_union_set_apply(ref, tag2access);
2147 return isl_union_set_unwrap(ref);
2150 /* Given an access relation "access" from one or more array reference groups,
2151 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2152 * that are only needed to communicate data within
2153 * the same iteration of "sched".
2154 * The domain of "sched" corresponds to the original statement instances,
2155 * i.e., those that appear in the domains of the access relations.
2156 * "tagged" contains all tagged access relations to all
2157 * the array reference groups accessed by "access" from statement
2158 * instances scheduled by "sched".
2160 * If the access is a read then it is either an element of
2162 * live_in union (range flow)
2164 * where live_in and flow may be overapproximations, or
2165 * it reads an uninitialized value (that is not live-in because
2166 * there is an intermediate kill) or it reads a value that was
2167 * written within the same (compound) statement instance.
2168 * If the access is a write then it is either an element of
2170 * live_out union (domain flow)
2172 * or it writes a value that is never read (and is not live-out
2173 * because of an intermediate kill) or only
2174 * within the same (compound) statement instance.
2175 * In both cases, the access relation is also a subset of
2176 * the group access relation.
2178 * The cases where an uninitialized value is read or a value is written
2179 * that is never read or where the dataflow occurs within a statement
2180 * instance are also considered local and may also be removed.
2182 * Essentially, we compute the intersection of "access" with either
2184 * live_in union (range non-local-flow)
2186 * or
2188 * live_out union (domain non-local-flow)
2190 * We first construct a relation "local"
2192 * [[D -> R] -> [D' -> R']]
2194 * of pairs of domain iterations accessing the reference group
2195 * and references in the group that are coscheduled by "sched".
2197 * If this relation does not intersect the dataflow dependences,
2198 * then there is nothing we can possibly remove, unless the dataflow
2199 * dependences themselves only relate a subset of the accesses.
2200 * In particular, the accesses may not be involved in any dataflow
2201 * dependences, either because they are uninitialized reads/dead writes
2202 * or because the dataflow occurs inside a statement instance.
2204 * Since the computation below may break up the access relation
2205 * into smaller pieces, we only perform the intersection with
2206 * the non-local dependent accesses if the local pairs
2207 * intersect the dataflow dependences. Otherwise, we intersect
2208 * with the universe of the non-local dependent accesses.
2209 * This should at least remove accesses from statements that
2210 * do not participate in any dependences.
2212 * In particular, we remove the "local" dataflow dependences from
2213 * the set of all dataflow dependences, or at least those
2214 * that may contribute to a domain/range that intersects
2215 * the domain of "access".
2216 * Note that if the potential dataflow dependences are an overapproximation
2217 * of the actual dataflow dependences, then the result remains an
2218 * overapproximation of the non-local dataflow dependences.
2219 * Copying to/from global memory is only needed for the references
2220 * in the domain/range of the result or for accesses that are live out/in
2221 * for the entire scop.
2223 * We therefore map the domain/range of the "external" relation
2224 * to the corresponding access relation and take the union with
2225 * the live out/in relation.
2227 static __isl_give isl_union_map *remove_local_accesses(
2228 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2229 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2230 int read)
2232 int empty;
2233 isl_union_pw_multi_aff *tagger;
2234 isl_union_set *domain, *access_domain;
2235 isl_union_map *local, *external, *universe;
2236 isl_union_set *tag_set;
2238 if (isl_union_map_is_empty(access)) {
2239 isl_union_map_free(sched);
2240 isl_union_map_free(tagged);
2241 return access;
2244 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2245 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2246 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2247 isl_union_set_copy(domain));
2248 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2250 local = isl_union_map_apply_range(sched,
2251 isl_union_map_reverse(isl_union_map_copy(sched)));
2252 local = isl_union_map_intersect(local,
2253 isl_union_map_copy(prog->scop->tagged_dep_flow));
2255 empty = isl_union_map_is_empty(local);
2257 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2258 universe = isl_union_map_universe(isl_union_map_copy(access));
2259 access_domain = isl_union_map_domain(universe);
2260 domain = isl_union_set_universe(domain);
2261 universe = isl_union_set_unwrap(domain);
2262 universe = isl_union_map_intersect_domain(universe, access_domain);
2263 domain = isl_union_map_wrap(universe);
2264 if (read)
2265 external = isl_union_map_intersect_range(external, domain);
2266 else
2267 external = isl_union_map_intersect_domain(external, domain);
2268 external = isl_union_map_intersect_params(external,
2269 isl_set_copy(prog->scop->context));
2270 external = isl_union_map_subtract(external, local);
2272 if (read) {
2273 tag_set = isl_union_map_range(external);
2274 external = wrapped_reference_to_access(tag_set, tagged);
2275 external = isl_union_map_union(external,
2276 isl_union_map_copy(prog->scop->live_in));
2277 } else {
2278 tag_set = isl_union_map_domain(external);
2279 external = wrapped_reference_to_access(tag_set, tagged);
2280 external = isl_union_map_union(external,
2281 isl_union_map_copy(prog->scop->live_out));
2284 if (empty < 0)
2285 external = isl_union_map_free(external);
2286 else if (empty)
2287 external = isl_union_map_universe(external);
2289 access = isl_union_map_intersect(access, external);
2291 return access;
2294 /* Given an access relation "access" from "group", remove those reads
2295 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2296 * communicate data within the same iteration of the schedule "prefix"
2297 * at the position where the copying of the group is inserted.
2298 * That is, the output dimension of "prefix"
2299 * is equal to tile->depth.
2300 * The domain of "prefix" corresponds to the original statement instances,
2301 * i.e., those that appear in the domains of the access relations.
2303 * Extract the tagged access relation of "group" and
2304 * then call remove_local_accesses.
2306 static __isl_give isl_union_map *remove_local_accesses_group(
2307 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2308 __isl_take isl_union_map *access, __isl_keep isl_union_map *prefix,
2309 int read)
2311 isl_union_map *sched, *tagged;
2313 if (isl_union_map_is_empty(access))
2314 return access;
2316 tagged = group_tagged_access_relation(group);
2317 sched = isl_union_map_copy(prefix);
2319 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2322 /* Build an access AST expression for the effective grid size using "build".
2323 * Store the result in kernel->grid_size_expr.
2325 static isl_stat build_grid_size(struct ppcg_kernel *kernel,
2326 __isl_keep isl_ast_build *build)
2328 isl_multi_pw_aff *size;
2330 size = isl_multi_pw_aff_copy(kernel->grid_size);
2331 size = isl_multi_pw_aff_set_tuple_name(size, isl_dim_out, "grid");
2332 kernel->grid_size_expr = ppcg_build_size_expr(size, build);
2334 if (!kernel->grid_size_expr)
2335 return isl_stat_error;
2336 return isl_stat_ok;
2339 /* Build access AST expressions for the localized array sizes using "build".
2340 * Store the result in local->bound_expr.
2341 * Only do this for arrays for which localized bounds have been computed.
2343 static isl_stat build_local_array_sizes(struct ppcg_kernel *kernel,
2344 __isl_keep isl_ast_build *build)
2346 int i;
2348 for (i = 0; i < kernel->n_array; ++i) {
2349 struct gpu_local_array_info *local = &kernel->array[i];
2350 isl_multi_pw_aff *size;
2352 if (local->n_group == 0)
2353 continue;
2354 size = isl_multi_pw_aff_copy(local->bound);
2355 local->bound_expr = ppcg_build_size_expr(size, build);
2356 if (!local->bound_expr)
2357 return isl_stat_error;
2360 return isl_stat_ok;
2363 /* Build access AST expressions for the effective grid size and
2364 * the localized array sizes using "build".
2366 static isl_stat build_grid_and_local_array_sizes(struct ppcg_kernel *kernel,
2367 __isl_keep isl_ast_build *build)
2369 if (build_grid_size(kernel, build) < 0)
2370 return isl_stat_error;
2371 if (build_local_array_sizes(kernel, build) < 0)
2372 return isl_stat_error;
2373 return isl_stat_ok;
2376 /* This function is called before the AST generator starts traversing
2377 * the schedule subtree of a node with mark "mark".
2379 * If the mark is called "kernel", store the kernel pointer in data->kernel
2380 * for use in at_domain and build AST expressions for the grid size and
2381 * the localized array sizes.
2383 static isl_stat before_mark(__isl_keep isl_id *mark,
2384 __isl_keep isl_ast_build *build, void *user)
2386 struct ppcg_at_domain_data *data = user;
2388 if (!mark)
2389 return isl_stat_error;
2390 if (!strcmp(isl_id_get_name(mark), "kernel")) {
2391 data->kernel = isl_id_get_user(mark);
2392 if (build_grid_and_local_array_sizes(data->kernel, build) < 0)
2393 return isl_stat_error;
2395 return isl_stat_ok;
2398 /* This function is called after the AST generator has finished traversing
2399 * the schedule subtree of a mark node. "node" points to the corresponding
2400 * mark AST node.
2402 * If the mark is called "kernel", then replace "node" by a user node
2403 * that "calls" the kernel, representing the launch of the kernel.
2404 * The original "node" is stored inside the kernel object so that
2405 * it can be used to print the device code.
2406 * Note that this assumes that a kernel is only launched once.
2407 * Also clear data->kernel.
2409 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2410 __isl_keep isl_ast_build *build, void *user)
2412 isl_ctx *ctx;
2413 isl_id *id;
2414 isl_ast_expr *expr;
2415 isl_ast_expr_list *list;
2416 struct ppcg_kernel *kernel;
2417 struct ppcg_at_domain_data *data = user;
2419 ctx = isl_ast_node_get_ctx(node);
2420 id = isl_ast_node_mark_get_id(node);
2421 if (!id)
2422 return isl_ast_node_free(node);
2423 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2424 isl_id_free(id);
2425 return node;
2427 kernel = data->kernel;
2428 data->kernel = NULL;
2429 kernel->space = isl_ast_build_get_schedule_space(build);
2430 kernel->tree = isl_ast_node_mark_get_node(node);
2431 isl_ast_node_free(node);
2433 expr = isl_ast_expr_from_id(isl_id_copy(id));
2434 list = isl_ast_expr_list_alloc(ctx, 0);
2435 expr = isl_ast_expr_call(expr, list);
2436 node = isl_ast_node_alloc_user(expr);
2437 node = isl_ast_node_set_annotation(node, id);
2439 return node;
2442 static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2444 int *depth = user;
2445 int node_depth;
2447 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2448 return isl_bool_true;
2449 node_depth = isl_schedule_node_get_schedule_depth(node);
2450 if (node_depth > *depth)
2451 *depth = node_depth;
2453 return isl_bool_false;
2456 /* Use isl to generate code for both the host and the device
2457 * from "schedule".
2458 * The device code is marked by "kernel" mark nodes in the schedule tree,
2459 * containing a pointer to a ppcg_kernel object.
2460 * The returned AST only contains the AST for the host code.
2461 * The ASTs for the device code are embedded in ppcg_kernel objects
2462 * attached to the leaf nodes that call "kernel".
2464 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2465 __isl_take isl_schedule *schedule)
2467 struct ppcg_at_domain_data data;
2468 isl_ast_build *build;
2469 isl_ast_node *tree;
2470 isl_id_list *iterators;
2471 int depth;
2473 data.prog = gen->prog;
2474 data.kernel = NULL;
2476 depth = 0;
2477 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2478 &depth) < 0)
2479 return NULL;
2480 build = isl_ast_build_alloc(gen->prog->ctx);
2481 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2482 build = isl_ast_build_set_iterators(build, iterators);
2483 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2484 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2485 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2486 if (gen->prog->scop->options->debug->dump_final_schedule)
2487 isl_schedule_dump(schedule);
2488 tree = isl_ast_build_node_from_schedule(build, schedule);
2489 isl_ast_build_free(build);
2491 return tree;
2494 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2496 if (!str)
2497 return NULL;
2498 return isl_union_map_read_from_str(ctx, str);
2501 /* Can "node" be tiled and then mapped to block and thread identifiers?
2502 * That is, is it permutable with at least one coincident dimension?
2504 static int is_permutable(__isl_keep isl_schedule_node *node)
2506 if (!node)
2507 return -1;
2509 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2510 return 0;
2511 if (!isl_schedule_node_band_get_permutable(node))
2512 return 0;
2513 if (isl_schedule_node_band_n_member(node) < 1)
2514 return 0;
2515 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2516 return 0;
2518 return 1;
2521 /* A isl_schedule_foreach_schedule_node_top_down callback
2522 * for setting *any_permutable and aborting the search
2523 * if "node" is a permutable band with coincident dimensions.
2524 * Otherwise, continue searching.
2526 static isl_bool set_permutable(__isl_keep isl_schedule_node *node, void *user)
2528 int *any_permutable = user;
2529 int permutable;
2531 permutable = is_permutable(node);
2532 if (permutable < 0)
2533 return isl_bool_error;
2534 if (!permutable)
2535 return isl_bool_true;
2537 *any_permutable = 1;
2539 return isl_bool_error;
2542 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
2543 * That is, does it have any nodes that are permutable and that
2544 * have a least one coincident dimension?
2546 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
2548 int any_parallelism = 0;
2550 if (isl_schedule_node_foreach_descendant_top_down(node, &set_permutable,
2551 &any_parallelism) < 0 &&
2552 !any_parallelism)
2553 return -1;
2555 return any_parallelism;
2558 /* Does "schedule" contain any permutable band with at least one coincident
2559 * member?
2561 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2563 isl_schedule_node *root;
2564 int any_permutable;
2566 root = isl_schedule_get_root(schedule);
2567 any_permutable = subtree_has_permutable_bands(root);
2568 isl_schedule_node_free(root);
2570 return any_permutable;
2573 /* Is "node" a candidate for mapping to block and thread identifiers?
2574 * In particular, is it permutable with at least one coincident dimension?
2575 * Alternatively, does the subtree rooted at "node" not contain
2576 * any such permutable node? Filter nodes are skipped in this case,
2577 * because a band node will be inserted in front of the returned
2578 * node and this is not possible for filter nodes that are children
2579 * of set or sequence nodes.
2581 static int is_candidate(__isl_keep isl_schedule_node *node)
2583 int permutable;
2585 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2586 return 1;
2587 permutable = is_permutable(node);
2588 if (permutable < 0 || permutable)
2589 return permutable;
2590 if (isl_schedule_node_get_type(node) == isl_schedule_node_filter)
2591 return 0;
2592 permutable = subtree_has_permutable_bands(node);
2593 if (permutable < 0)
2594 return -1;
2595 return !permutable;
2598 /* Is "node" the outermost node in its branch that can be tiled
2599 * and then mapped to block and thread identifiers?
2600 * If there are no such nodes in the subtree at "node" and
2601 * if "node" is not a filter node, then it is accepted too.
2603 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2605 int tilable;
2606 isl_schedule_node *ancestor;
2608 tilable = is_candidate(node);
2609 if (tilable < 0)
2610 return -1;
2611 if (!tilable)
2612 return 0;
2614 tilable = 0;
2615 ancestor = isl_schedule_node_copy(node);
2616 while (isl_schedule_node_has_parent(ancestor)) {
2617 ancestor = isl_schedule_node_parent(ancestor);
2619 tilable = is_candidate(ancestor);
2620 if (tilable < 0 || tilable)
2621 break;
2624 isl_schedule_node_free(ancestor);
2625 return tilable < 0 ? -1 : !tilable;
2628 /* Collect the references to all writes in "group".
2629 * Each reference is represented by a universe set in a space
2631 * [S[i,j] -> R[]]
2633 * with S[i,j] the statement instance space and R[] the array reference.
2635 static __isl_give isl_union_set *group_tagged_writes(
2636 struct gpu_array_ref_group *group)
2638 int i;
2639 isl_space *space;
2640 isl_union_set *writes;
2642 space = isl_map_get_space(group->access);
2643 writes = isl_union_set_empty(space);
2644 for (i = 0; i < group->n_ref; ++i) {
2645 isl_space *space;
2646 isl_set *writes_i;
2648 if (!group->refs[i]->write)
2649 continue;
2651 space = isl_map_get_space(group->refs[i]->tagged_access);
2652 space = isl_space_domain(space);
2653 writes_i = isl_set_universe(space);
2654 writes = isl_union_set_add_set(writes, writes_i);
2657 return writes;
2660 /* Is there any write access in "group" that requires synchronization
2661 * on a write to global memory?
2662 * We currently take into account all writes that would require
2663 * synchronization at the thread level depth, but if the copying
2664 * for this group is performed at an outer level, then we do not
2665 * actually need to take into account dependences at intermediate levels.
2667 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2668 struct gpu_array_ref_group *group)
2670 isl_union_set *writes;
2671 int empty, disjoint;
2673 empty = isl_union_set_is_empty(kernel->sync_writes);
2674 if (empty < 0)
2675 return -1;
2676 if (empty)
2677 return 0;
2679 writes = group_tagged_writes(group);
2680 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2681 isl_union_set_free(writes);
2683 return disjoint < 0 ? -1 : !disjoint;
2686 /* Collect the references to all writes in "kernel" that write directly
2687 * to global or shared memory, i.e., that are not mapped to private memory.
2688 * Each reference is represented by a universe set in a space
2690 * [S[i,j] -> R[]]
2692 * with S[i,j] the statement instance space and R[] the array reference.
2694 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2695 struct ppcg_kernel *kernel)
2697 isl_union_set *writes;
2698 int i, j;
2700 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2702 for (i = 0; i < kernel->n_array; ++i) {
2703 struct gpu_local_array_info *array = &kernel->array[i];
2705 for (j = 0; j < array->n_group; ++j) {
2706 struct gpu_array_ref_group *group = array->groups[j];
2707 enum ppcg_group_access_type type;
2708 isl_union_set *writes_ij;
2710 if (!group->write)
2711 continue;
2712 type = gpu_array_ref_group_type(group);
2713 if (type == ppcg_access_private)
2714 continue;
2715 writes_ij = group_tagged_writes(group);
2716 writes = isl_union_set_union(writes, writes_ij);
2720 return writes;
2723 /* Are there any direct writes to global memory that require
2724 * synchronization?
2726 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2728 isl_union_set *writes;
2729 int empty, disjoint;
2731 empty = isl_union_set_is_empty(kernel->sync_writes);
2732 if (empty < 0)
2733 return -1;
2734 if (empty)
2735 return 0;
2737 writes = collect_non_private_tagged_writes(kernel);
2738 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2739 isl_union_set_free(writes);
2741 return disjoint < 0 ? -1 : !disjoint;
2744 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2745 * from the elements in "tile_size".
2747 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2748 __isl_keep isl_schedule_node *node, int *tile_size)
2750 isl_space *space;
2752 if (!node)
2753 return NULL;
2755 space = isl_schedule_node_band_get_space(node);
2756 return ppcg_multi_val_from_int_list(space, tile_size);
2759 /* Replace the partial schedule S of the band node "node" by
2761 * floor(S/f)
2763 * or
2765 * f * floor(S/f)
2767 * if scale_tile_loops is set, with f the integers in "factor".
2768 * The list that "factor" points to is assumed to contain at least
2769 * as many elements as the number of members in the band.
2771 static __isl_give isl_schedule_node *snap_band_to_sizes(
2772 __isl_take isl_schedule_node *node, int *factor,
2773 struct ppcg_options *options)
2775 isl_multi_val *mv;
2777 mv = construct_band_tiles_sizes(node, factor);
2778 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2779 if (options->scale_tile_loops)
2780 node = isl_schedule_node_band_scale(node,
2781 isl_multi_val_copy(mv));
2782 isl_multi_val_free(mv);
2784 return node;
2787 /* Tile "band" with tile size specified by "sizes".
2789 * Since the tile loops will be mapped to block ids, we forcibly
2790 * turn off tile loop scaling. We may want to enable tile loop scaling
2791 * at some later point, but then we would have to support the detection
2792 * of strides during the mapping to block ids.
2793 * Similarly, since the point loops will be mapped to thread ids,
2794 * we forcibly shift the point loops so that they start at zero.
2796 static __isl_give isl_schedule_node *tile_band(
2797 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2799 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2800 int scale_tile;
2801 int shift_point;
2803 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2804 isl_options_set_tile_scale_tile_loops(ctx, 0);
2805 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2806 isl_options_set_tile_shift_point_loops(ctx, 1);
2808 node = isl_schedule_node_band_tile(node, sizes);
2810 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2811 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2813 return node;
2816 /* Extract the set of parameter values and outer schedule dimensions
2817 * for which any statement instance
2818 * in the kernel inserted at "node" needs to be executed.
2819 * Intersect the set of parameter values derived from the host schedule
2820 * relation with the context of "prog".
2822 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2823 struct gpu_prog *prog)
2825 isl_union_map *schedule;
2826 isl_union_set *schedule_domain;
2827 isl_set *context;
2828 int empty;
2830 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2831 schedule_domain = isl_union_map_range(schedule);
2832 empty = isl_union_set_is_empty(schedule_domain);
2833 if (empty < 0) {
2834 isl_union_set_free(schedule_domain);
2835 return NULL;
2837 if (empty) {
2838 int depth;
2839 isl_space *space;
2841 space = isl_union_set_get_space(schedule_domain);
2842 isl_union_set_free(schedule_domain);
2843 space = isl_space_set_from_params(space);
2844 depth = isl_schedule_node_get_schedule_depth(node);
2845 space = isl_space_add_dims(space, isl_dim_set, depth);
2846 context = isl_set_empty(space);
2847 } else {
2848 context = isl_set_from_union_set(schedule_domain);
2850 context = isl_set_intersect_params(context,
2851 isl_set_copy(prog->context));
2853 return context;
2856 /* Return the set of outer array elements accessed by
2857 * by the statement instances in "domain" in "prog".
2858 * The instances in "domain" are those that appear
2859 * in the domains of the access relations in "prog".
2861 static __isl_give isl_union_set *accessed_by_domain(
2862 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2864 isl_union_map *access;
2865 isl_union_set *arrays;
2867 access = isl_union_map_union(isl_union_map_copy(prog->read),
2868 isl_union_map_copy(prog->may_write));
2869 access = isl_union_map_intersect_domain(access, domain);
2870 arrays = isl_union_map_range(access);
2871 arrays = isl_union_set_apply(arrays,
2872 isl_union_map_copy(prog->to_outer));
2874 return arrays;
2877 /* Return the number of outer band members of the band node "node"
2878 * that are marked coincident.
2880 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2882 int i, n;
2884 n = isl_schedule_node_band_n_member(node);
2886 for (i = 0; i < n; ++i)
2887 if (!isl_schedule_node_band_member_get_coincident(node, i))
2888 break;
2890 return i;
2893 /* If the band node "node" has more than "n" members, then split off
2894 * the first "n" of them.
2896 static __isl_give isl_schedule_node *split_band(
2897 __isl_take isl_schedule_node *node, int n)
2899 int dim;
2901 dim = isl_schedule_node_band_n_member(node);
2902 if (n < dim)
2903 node = isl_schedule_node_band_split(node, n);
2905 return node;
2908 /* Scale a band node that may have been split by split_band.
2909 * "sizes" are the scaling factors for the original node.
2910 * "node" either points to the original band node, or the outer
2911 * of the two pieces after splitting.
2913 * If the number of elements in "node" is smaller than the number of
2914 * elements in "sizes", then some splitting has occurred and we split
2915 * "sizes" in the same way.
2917 static __isl_give isl_schedule_node *scale_band(
2918 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2920 int n, dim;
2922 n = isl_multi_val_dim(sizes, isl_dim_set);
2923 dim = isl_schedule_node_band_n_member(node);
2924 if (n > dim) {
2925 isl_multi_val *sizes2;
2927 sizes2 = isl_multi_val_copy(sizes);
2928 sizes = isl_multi_val_drop_dims(sizes,
2929 isl_dim_set, dim, n - dim);
2930 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2931 node = isl_schedule_node_child(node, 0);
2932 node = isl_schedule_node_band_scale(node, sizes2);
2933 node = isl_schedule_node_parent(node);
2936 return isl_schedule_node_band_scale(node, sizes);
2939 /* Return an isl_multi_aff, with as elements the parameters in "space"
2940 * that have the names specified by the elements in "names".
2941 * If (some of) these parameters do not already appear in "space",
2942 * then they are added first.
2944 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2945 __isl_keep isl_id_list *names)
2947 int i, n;
2948 isl_local_space *ls;
2949 isl_multi_aff *ma;
2951 if (!names)
2952 space = isl_space_free(space);
2954 n = isl_id_list_n_id(names);
2955 for (i = 0; i < n; ++i) {
2956 int pos;
2957 isl_id *id;
2959 id = isl_id_list_get_id(names, i);
2960 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2961 if (pos >= 0) {
2962 isl_id_free(id);
2963 continue;
2965 pos = isl_space_dim(space, isl_dim_param);
2966 space = isl_space_add_dims(space, isl_dim_param, 1);
2967 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2969 ma = isl_multi_aff_zero(isl_space_copy(space));
2970 ls = isl_local_space_from_space(isl_space_domain(space));
2971 for (i = 0; i < n; ++i) {
2972 int pos;
2973 isl_id *id;
2974 isl_aff *aff;
2976 id = isl_id_list_get_id(names, i);
2977 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2978 isl_id_free(id);
2979 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2980 isl_dim_param, pos);
2981 ma = isl_multi_aff_set_aff(ma, i, aff);
2983 isl_local_space_free(ls);
2985 return ma;
2988 /* Return constraints on the domain elements that equate a sequence of
2989 * parameters called "names", to the partial schedule
2990 * of "node" modulo the integers in "size".
2991 * The number of elements in the array "size" should be equal
2992 * to the number of elements in "names".
2993 * The number of members of the band node "node" should be smaller
2994 * than or equal to this number. If it is smaller, then the first
2995 * elements of "names" are equated to zero.
2997 static __isl_give isl_union_set *set_schedule_modulo(
2998 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2999 int *size)
3001 int n, n_zero;
3002 isl_space *space;
3003 isl_multi_aff *ma;
3004 isl_multi_union_pw_aff *mupa, *mupa2;
3005 isl_multi_val *mv;
3006 isl_union_set *domain;
3008 if (!node)
3009 return NULL;
3010 n = isl_id_list_n_id(names);
3011 if (n == 0)
3012 return isl_schedule_node_get_universe_domain(node);
3013 n_zero = n - isl_schedule_node_band_n_member(node);
3015 mupa = isl_schedule_node_band_get_partial_schedule(node);
3016 mv = construct_band_tiles_sizes(node, size + n_zero);
3017 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
3019 space = isl_multi_union_pw_aff_get_space(mupa);
3020 space = isl_space_params(space);
3021 space = isl_space_set_from_params(space);
3022 space = isl_space_add_dims(space, isl_dim_set, n_zero);
3023 ma = isl_multi_aff_zero(space);
3025 domain = isl_schedule_node_get_universe_domain(node);
3026 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
3027 isl_union_set_copy(domain), ma);
3028 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
3030 space = isl_multi_union_pw_aff_get_space(mupa);
3031 ma = parameter_vector(space, names);
3033 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
3034 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
3036 return isl_multi_union_pw_aff_zero_union_set(mupa);
3039 /* Insert a context node at "node" introducing the block and thread
3040 * identifiers along with their bounds, which are stored in kernel->grid_size
3041 * and kernel->block_dim.
3042 * Note that the bounds on the block identifiers may implicitly impose
3043 * constraints on the parameters. A guard needs to be inserted
3044 * in the schedule tree to ensure that those bounds hold at "node".
3045 * This guard is inserted in insert_guard.
3047 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
3048 __isl_take isl_schedule_node *node)
3050 isl_set *context;
3052 context = isl_set_universe(isl_set_get_space(kernel->context));
3054 context = add_bounded_parameters_dynamic(context,
3055 kernel->grid_size, kernel->block_ids);
3056 context = add_bounded_parameters(context,
3057 kernel->block_dim, kernel->thread_ids);
3059 node = isl_schedule_node_insert_context(node, context);
3061 return node;
3064 /* Insert a guard that eliminates kernel launches where the kernel
3065 * obviously does not have any work to do.
3067 * In particular, eliminate kernel launches where there are obviously
3068 * zero blocks.
3069 * Use the same block size constraints that are used to create the context
3070 * to ensure that all constraints implicit in the constructed context
3071 * are imposed by the guard.
3073 * Additionally, add other constraints that are valid
3074 * for each executed instance ("context"), as long as this does not result
3075 * in a disjunction.
3077 static __isl_give isl_schedule_node *insert_guard(
3078 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
3079 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
3081 unsigned nparam, n;
3082 isl_set *guard;
3083 isl_id_list *ids;
3085 guard = isl_set_copy(context);
3086 guard = isl_set_compute_divs(guard);
3087 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
3089 nparam = isl_set_dim(guard, isl_dim_param);
3090 n = isl_multi_pw_aff_dim(size, isl_dim_out);
3091 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
3092 guard = add_bounded_parameters_dynamic(guard, size, ids);
3093 isl_id_list_free(ids);
3094 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
3096 node = isl_schedule_node_insert_guard(node, guard);
3098 return node;
3101 /* Does any array reference group mapping require the band that is mapped
3102 * to threads to be unrolled?
3104 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
3106 int i, j;
3108 for (i = 0; i < kernel->n_array; ++i) {
3109 struct gpu_local_array_info *array = &kernel->array[i];
3111 for (j = 0; j < array->n_group; ++j) {
3112 struct gpu_array_ref_group *group = array->groups[j];
3113 if (gpu_array_ref_group_requires_unroll(group))
3114 return 1;
3118 return 0;
3121 /* Mark the given band node "node" for unrolling by the AST generator and
3122 * then sink it to the leaves of the schedule tree.
3123 * All dimensions of "node" are assumed to be coincident, such that this
3124 * sinking is a valid operation.
3126 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
3128 node = ppcg_set_schedule_node_type(node, isl_ast_loop_unroll);
3130 node = isl_schedule_node_band_sink(node);
3132 return node;
3135 /* Insert a synchronization node in the schedule tree of "node"
3136 * after the core computation of "kernel" at the level of the band
3137 * that is mapped to threads, except if that level is equal to
3138 * that of the band that is mapped to blocks or if there are no writes
3139 * to global or shared memory in the core computation that require
3140 * synchronization.
3141 * If there are any writes to shared memory and the shared memory
3142 * copying is performed at the same level, then synchronization
3143 * is needed between the core and the copying anyway, so we might
3144 * as well add it here. If the copying is performed at a higher
3145 * level, then different iterations of intermediate schedule dimensions
3146 * may have a different mapping from between shared memory elements and
3147 * threads, such that synchronization is required after the core.
3148 * "node" is assumed to point to the kernel node.
3150 * If the shared and the thread mark point to the same node, then make
3151 * sure the synchronization is inserted outside of the shared mark.
3153 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
3154 __isl_take isl_schedule_node *node)
3156 int depth;
3157 int need_sync;
3159 need_sync = any_global_or_shared_sync_writes(kernel);
3160 if (need_sync < 0)
3161 return isl_schedule_node_free(node);
3162 if (!need_sync)
3163 return node;
3165 node = gpu_tree_move_down_to_thread(node, kernel->core);
3166 depth = isl_schedule_node_get_schedule_depth(node);
3167 node = gpu_tree_move_up_to_kernel(node);
3168 if (depth == isl_schedule_node_get_schedule_depth(node))
3169 return node;
3171 node = gpu_tree_move_down_to_depth(node, depth, kernel->core);
3172 node = gpu_tree_ensure_following_sync(node, kernel);
3174 node = gpu_tree_move_up_to_kernel(node);
3176 return node;
3179 /* Return a read ("read" is 1) or write access relation for "group"
3180 * with those accesses removed that are only needed to communicate data
3181 * within the subtree of the schedule rooted at "node".
3182 * Furthermore, include the prefix schedule at "node".
3183 * That is, return a relation of the form
3185 * S -> [D -> A]
3187 * with D the outer schedule dimensions at "node".
3189 static __isl_give isl_union_map *anchored_non_local_accesses(
3190 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3191 __isl_take isl_schedule_node *node, int read)
3193 isl_union_map *access;
3194 isl_union_map *prefix;
3196 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3197 prefix = isl_union_map_preimage_domain_union_pw_multi_aff(prefix,
3198 isl_union_pw_multi_aff_copy(kernel->contraction));
3199 access = gpu_array_ref_group_access_relation(group, read, !read);
3200 access = remove_local_accesses_group(kernel, group, access, prefix,
3201 read);
3202 access = isl_union_map_range_product(prefix, access);
3204 return access;
3207 /* Given an array reference group "group", create a mapping
3209 * read[D -> A] -> [D -> A]
3211 * if "read" is set or
3213 * write[D -> A] -> [D -> A]
3215 * if "read" is not set.
3216 * D corresponds to the outer tile->depth dimensions of
3217 * the kernel schedule.
3219 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3220 struct gpu_array_ref_group *group, int read)
3222 struct gpu_array_tile *tile;
3223 isl_space *space;
3224 isl_id *id;
3226 tile = gpu_array_ref_group_tile(group);
3227 space = isl_space_copy(group->array->space);
3228 space = isl_space_from_range(space);
3229 space = isl_space_add_dims(space, isl_dim_in, tile->depth);
3230 space = isl_space_wrap(space);
3231 space = isl_space_map_from_set(space);
3233 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3234 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3236 return isl_multi_aff_identity(space);
3239 /* If any writes in "group" require synchronization, then make sure
3240 * that there is a synchronization node for "kernel" after the node
3241 * following "node" in a sequence.
3243 * If "shared" is set and no synchronization is needed for
3244 * the writes to global memory, then add synchronization before
3245 * the kernel to protect shared memory from being overwritten
3246 * by the next iteration of the core computation.
3247 * No additional synchronization is needed to protect against
3248 * the next copy into shared memory because each element of
3249 * the shared memory tile is always copied by the same thread.
3251 static __isl_give isl_schedule_node *add_group_write_sync(
3252 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3253 struct gpu_array_ref_group *group, int shared)
3255 int need_sync;
3257 need_sync = any_sync_writes_in_group(kernel, group);
3258 if (need_sync < 0)
3259 return isl_schedule_node_free(node);
3260 if (need_sync) {
3261 node = isl_schedule_node_parent(node);
3262 node = isl_schedule_node_next_sibling(node);
3263 node = isl_schedule_node_child(node, 0);
3264 node = gpu_tree_ensure_following_sync(node, kernel);
3265 } else if (shared) {
3266 struct gpu_array_tile *tile;
3268 tile = gpu_array_ref_group_tile(group);
3269 node = isl_schedule_node_parent(node);
3270 node = isl_schedule_node_parent(node);
3271 node = gpu_tree_move_down_to_depth(node, tile->depth,
3272 kernel->core);
3273 node = gpu_tree_move_left_to_sync(node, kernel);
3276 return node;
3279 /* Add copy statements to the schedule tree of "node"
3280 * for reading from global memory to private memory (if "read" is set) or
3281 * for writing back from private memory to global memory
3282 * (if "read" is not set) for the array reference group "group" that
3283 * is mapped to private memory.
3284 * On input, "node" points to the kernel node, and it is moved
3285 * back there on output.
3287 * The copies are performed in the order of the array elements.
3288 * The copy statement instances include a reference to the outer
3289 * tile->depth dimensions of the kernel schedule for ease of
3290 * combining them with the group tiling.
3292 * That is, the extra schedule is of the form
3294 * type[D -> A] -> A
3296 * where D corresponds to the outer tile->depth dimensions of
3297 * the kernel schedule and A to the global array.
3298 * This schedule is unrolled because registers are not addressable.
3300 * The copying is inserted in the schedule tree through an extension
3301 * of the form
3303 * D -> type[D -> A]
3305 * where the extra domain elements type[D -> A] are those accessed
3306 * by the group.
3307 * A filter is inserted on type[D -> A] to ensure that the element
3308 * is read/written by the same thread that needs the element.
3309 * This filter is obtained by applying
3311 * S -> type[D -> A]
3313 * to the thread filter for the core statements.
3315 * The extension is inserted before the core computation in case of a read
3316 * and after the core computation in case of a write.
3317 * In the latter case, we also make sure that there is a synchronization
3318 * node after the write to global memory, unless this write is performed
3319 * at the outer level of the kernel.
3320 * In principle, this synchronization could be inserted higher
3321 * in the schedule tree depending on where the corresponding reads
3322 * from global memory are performed.
3324 static __isl_give isl_schedule_node *add_copies_group_private(
3325 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3326 __isl_take isl_schedule_node *node, int read)
3328 struct gpu_array_tile *tile;
3329 isl_union_map *access;
3330 isl_union_set *domain;
3331 isl_space *space;
3332 isl_multi_aff *from_access;
3333 isl_multi_pw_aff *mpa;
3334 isl_multi_union_pw_aff *mupa;
3335 isl_union_pw_multi_aff *contraction;
3336 isl_schedule_node *graft;
3337 isl_union_set *filter;
3338 int kernel_depth;
3339 int empty;
3341 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3342 tile = gpu_array_ref_group_tile(group);
3343 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3345 access = anchored_non_local_accesses(kernel, group, node, read);
3346 empty = isl_union_map_is_empty(access);
3347 if (empty < 0 || empty) {
3348 isl_union_map_free(access);
3349 if (empty < 0)
3350 return isl_schedule_node_free(node);
3351 return gpu_tree_move_up_to_kernel(node);
3354 group->array->global = 1;
3355 group->local_array->global = 1;
3357 from_access = create_from_access(kernel->ctx, group, read);
3358 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3359 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3361 filter = isl_union_set_copy(kernel->thread_filter);
3362 contraction = isl_union_pw_multi_aff_copy(kernel->contraction);
3363 filter = isl_union_set_preimage_union_pw_multi_aff(filter, contraction);
3364 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3365 filter = isl_union_set_detect_equalities(filter);
3366 filter = isl_union_set_coalesce(filter);
3368 domain = isl_union_map_range(access);
3369 access = isl_union_set_wrapped_domain_map(domain);
3370 access = isl_union_map_reverse(access);
3371 access = isl_union_map_coalesce(access);
3372 graft = isl_schedule_node_from_extension(access);
3374 space = isl_space_map_from_set(space);
3375 mpa = isl_multi_pw_aff_identity(space);
3376 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3377 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3379 graft = isl_schedule_node_child(graft, 0);
3380 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3381 graft = unroll(graft);
3383 graft = isl_schedule_node_insert_filter(graft, filter);
3385 graft = isl_schedule_node_parent(graft);
3387 if (read)
3388 node = isl_schedule_node_graft_before(node, graft);
3389 else {
3390 node = isl_schedule_node_graft_after(node, graft);
3391 if (kernel_depth < tile->depth)
3392 node = add_group_write_sync(node, kernel, group, 0);
3395 node = gpu_tree_move_up_to_kernel(node);
3397 return node;
3400 /* Add copy statements to the schedule tree of "node"
3401 * for reading from global memory to shared memory (if "read" is set) or
3402 * for writing back from shared memory to global memory
3403 * (if "read" is not set) for the array reference group "group" that
3404 * is mapped to shared memory.
3405 * On input, "node" points to the kernel node, and it is moved
3406 * back there on output.
3408 * The copies are performed in the order of the corresponding shared
3409 * memory tile.
3410 * The copy statement instances include a reference to the outer
3411 * tile->depth dimensions of the kernel schedule for ease of
3412 * combining them with the group tiling.
3414 * If we are performing a read from global memory to shared memory and
3415 * if the array involved is not a scalar, then we copy
3416 * the entire tile to shared memory. This may result in some extra
3417 * elements getting copied, but it should lead to simpler code
3418 * (which means that fewer registers may be needed) and less divergence.
3420 * Otherwise, we only copy the elements that will be read or have been written
3421 * in the kernel.
3423 * That is, the extra schedule is of the form
3425 * type[D -> A] -> T
3427 * where D corresponds to the outer tile->depth dimensions of
3428 * the kernel schedule, A to the global array and T is the corresponding
3429 * shared memory tile.
3431 * The copying is inserted in the schedule tree through an extension
3432 * of the form
3434 * D -> type[D -> A]
3436 * where the extra domain elements type[D -> A] are those accessed
3437 * by the group. In the case of read from a non-scalar, this set
3438 * is replaced by the entire shared memory tile.
3440 * If the "unroll_copy_shared" option is set, then the AST generator
3441 * is instructed to unroll the copying code.
3443 * A filter is inserted on type[D -> A] to map the copy instances
3444 * to the threads. In particular, the thread identifiers are
3445 * equated to the position inside the shared memory tile (T)
3446 * modulo the block size.
3447 * We try to align the innermost tile dimension with the innermost
3448 * thread identifier (x) as a heuristic to improve coalescing.
3449 * In particular, if the dimension of the tile is greater than
3450 * the dimension of the block, then the schedule mapping to the tile
3451 * is broken up into two pieces and the filter is applied to the inner part.
3452 * If, on the other hand, the dimension of the tile is smaller than
3453 * the dimension of the block, then the initial thread identifiers
3454 * are equated to zero and the remaining thread identifiers are
3455 * matched to the memory tile.
3457 * The extension is inserted before the core computation in case of a read
3458 * and after the core computation in case of a write.
3459 * In the case of a read, we first need to make sure there is some
3460 * synchronization before the core computation such that we can put the read
3461 * from global memory to shared memory before that synchronization.
3462 * This ensures that all threads have finished copying into shared memory
3463 * before the shared memory is used.
3464 * We also need to make sure that there is a synchronization node after
3465 * the core computation to ensure that the next load into shared memory
3466 * only happens after all data has been used. There is no need for
3467 * this synchronization if we are at the outer level since then there
3468 * won't be a next load.
3469 * In the case of a write, we need to make sure there is some synchronization
3470 * after the core computation such taht we can put the write from shared
3471 * memory to global memory after that synchronization.
3472 * Unless we are at the outer level, we also need a synchronization node
3473 * after the write to ensure the data is saved to global memory
3474 * before the next iteration write to the same shared memory.
3475 * It also makes sure the data has arrived in global memory before
3476 * it is read in a subsequent iteration.
3478 static __isl_give isl_schedule_node *add_copies_group_shared(
3479 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3480 __isl_take isl_schedule_node *node, int read)
3482 struct gpu_array_tile *tile;
3483 isl_union_map *access;
3484 isl_union_set *domain;
3485 isl_multi_aff *ma;
3486 isl_multi_aff *from_access;
3487 isl_multi_pw_aff *mpa;
3488 isl_multi_union_pw_aff *mupa;
3489 isl_schedule_node *graft;
3490 isl_union_set *filter;
3491 int skip;
3492 int kernel_depth;
3493 int empty;
3495 tile = gpu_array_ref_group_tile(group);
3496 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3497 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3499 access = anchored_non_local_accesses(kernel, group, node, read);
3500 empty = isl_union_map_is_empty(access);
3501 if (empty < 0 || empty) {
3502 isl_union_map_free(access);
3503 if (empty < 0)
3504 return isl_schedule_node_free(node);
3505 return gpu_tree_move_up_to_kernel(node);
3508 group->array->global = 1;
3509 group->local_array->global = 1;
3511 from_access = create_from_access(kernel->ctx, group, read);
3513 ma = isl_multi_aff_copy(tile->tiling);
3514 ma = isl_multi_aff_pullback_multi_aff(ma,
3515 isl_multi_aff_copy(from_access));
3516 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3517 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3519 domain = isl_union_map_range(access);
3521 if (read && !gpu_array_is_scalar(group->array)) {
3522 isl_map *map;
3523 isl_union_set_free(domain);
3524 map = group_tile(group);
3525 domain = isl_union_set_from_set(isl_map_wrap(map));
3528 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3529 access = isl_union_set_wrapped_domain_map(domain);
3530 access = isl_union_map_reverse(access);
3531 access = isl_union_map_coalesce(access);
3532 graft = isl_schedule_node_from_extension(access);
3534 graft = isl_schedule_node_child(graft, 0);
3536 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3537 if (kernel->options->unroll_copy_shared)
3538 graft = ppcg_set_schedule_node_type(graft, isl_ast_loop_unroll);
3540 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3541 graft = isl_schedule_node_band_split(graft,
3542 tile->n - kernel->n_block);
3543 graft = isl_schedule_node_child(graft, 0);
3545 if (tile->n < kernel->n_block)
3546 skip = kernel->n_block - tile->n;
3547 else
3548 skip = 0;
3549 filter = set_schedule_modulo(graft, kernel->thread_ids,
3550 kernel->block_dim);
3551 if (!kernel->options->wrap)
3552 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3553 kernel->options);
3554 if (tile->n > kernel->n_block && kernel->n_block > 0)
3555 graft = isl_schedule_node_parent(graft);
3556 graft = isl_schedule_node_insert_filter(graft, filter);
3558 while (graft && isl_schedule_node_has_parent(graft))
3559 graft = isl_schedule_node_parent(graft);
3561 if (read) {
3562 if (kernel_depth < tile->depth)
3563 node = gpu_tree_ensure_sync_after_core(node, kernel);
3564 node = gpu_tree_move_left_to_sync(node, kernel);
3565 node = isl_schedule_node_graft_before(node, graft);
3566 } else {
3567 node = gpu_tree_move_right_to_sync(node, kernel);
3568 node = isl_schedule_node_graft_after(node, graft);
3569 if (kernel_depth < tile->depth)
3570 node = add_group_write_sync(node, kernel, group, 1);
3573 node = gpu_tree_move_up_to_kernel(node);
3575 return node;
3578 /* Check whether the array reference group "group" is mapped to
3579 * private or shared memory and, if so,
3580 * add copy statements to the schedule tree of "node"
3581 * for reading from global memory to private or shared memory
3582 * (if "read" is set) or for writing back from private or shared memory
3583 * to global memory (if "read" is not set) for this group.
3584 * On input, "node" points to the kernel node, and it is moved
3585 * back there on output.
3587 static __isl_give isl_schedule_node *add_copies_group(
3588 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3589 __isl_take isl_schedule_node *node, int read)
3591 enum ppcg_group_access_type type;
3593 type = gpu_array_ref_group_type(group);
3594 if (type == ppcg_access_private)
3595 return add_copies_group_private(kernel, group, node, read);
3596 if (type == ppcg_access_shared)
3597 return add_copies_group_shared(kernel, group, node, read);
3598 return node;
3601 /* For each array reference group that is mapped to private or shared memory,
3602 * add copy statements to the schedule tree of "node"
3603 * for reading from global memory to private or shared memory
3604 * and for writing back.
3605 * On input, "node" points to the kernel node, and it is moved
3606 * back there on output.
3608 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3609 __isl_take isl_schedule_node *node)
3611 int i, j;
3613 for (i = 0; i < kernel->n_array; ++i) {
3614 struct gpu_local_array_info *array = &kernel->array[i];
3616 for (j = 0; j < array->n_group; ++j) {
3617 struct gpu_array_ref_group *group = array->groups[j];
3619 node = add_copies_group(kernel, group, node, 1);
3620 if (!node)
3621 return NULL;
3622 node = add_copies_group(kernel, group, node, 0);
3623 if (!node)
3624 return NULL;
3628 return node;
3631 /* Mark all dimensions in the current band node atomic.
3633 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3635 return ppcg_set_schedule_node_type(node, isl_ast_loop_atomic);
3638 /* Mark "node" atomic, if it is a band node.
3639 * Do the same for all ancestors.
3640 * Return a pointer to "node" (in the updated schedule tree).
3642 static __isl_give isl_schedule_node *atomic_ancestors(
3643 __isl_take isl_schedule_node *node)
3645 int pos;
3647 if (!node)
3648 return NULL;
3649 if (!isl_schedule_node_has_parent(node))
3650 return node;
3652 pos = isl_schedule_node_get_child_position(node);
3653 node = isl_schedule_node_parent(node);
3654 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3655 node = atomic(node);
3656 node = atomic_ancestors(node);
3657 node = isl_schedule_node_child(node, pos);
3659 return node;
3662 /* Collect all write references that require synchronization.
3663 * "node" is assumed to point to the kernel node.
3664 * Each reference is represented by a universe set in a space
3666 * [S[i,j] -> R[]]
3668 * with S[i,j] the statement instance space and R[] the array reference.
3670 * This function should be called before block and thread filters are added.
3672 * Synchronization is needed after a write if there is a subsequent read
3673 * within the same block that may not be performed by the same thread.
3674 * There should not be any dependences between different blocks,
3675 * so we start with the flow dependences within the same kernel invocation
3676 * and we subtract from these those dependences that are mapped
3677 * to the same iteration of the bands where synchronization is inserted.
3678 * We do not remove pairs of instances that are known to map to
3679 * the same thread across different iterations of the intermediate
3680 * bands because the read may be performed by a different thread
3681 * than the one that needs the value if shared memory is involved.
3683 * We also consider all pairs of possible writes that access the same
3684 * memory location and that may be mapped to the same block but not
3685 * to the same iteration of the intermediate bands.
3686 * In theory, it would be possible for one thread to still be in
3687 * a previous iteration of a loop in these bands.
3688 * A write to global memory in this delayed thread could then overwrite
3689 * a write from another thread that has already moved on to
3690 * the next iteration.
3692 * After computing the above writes paired off with reads or writes
3693 * that depend on them, we project onto the domain writes.
3694 * Sychronization is needed after writes to global memory
3695 * through these references.
3697 static __isl_give isl_union_set *compute_sync_writes(
3698 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3700 isl_union_map *local;
3701 isl_union_map *may_writes, *shared_access;
3702 isl_union_map *kernel_prefix, *thread_prefix;
3703 isl_union_map *equal;
3704 isl_union_set *wrap;
3705 isl_union_set *domain;
3706 isl_union_pw_multi_aff *contraction;
3708 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3709 node = isl_schedule_node_copy(node);
3710 node = gpu_tree_move_down_to_thread(node, kernel->core);
3711 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3712 isl_schedule_node_free(node);
3714 contraction = kernel->contraction;
3715 kernel_prefix = isl_union_map_preimage_domain_union_pw_multi_aff(
3716 kernel_prefix, isl_union_pw_multi_aff_copy(contraction));
3717 thread_prefix = isl_union_map_preimage_domain_union_pw_multi_aff(
3718 thread_prefix, isl_union_pw_multi_aff_copy(contraction));
3719 domain = isl_union_set_copy(kernel->expanded_domain);
3720 domain = isl_union_set_universe(domain);
3722 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3723 may_writes = isl_union_map_curry(may_writes);
3724 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3725 may_writes = isl_union_map_uncurry(may_writes);
3726 shared_access = isl_union_map_copy(may_writes);
3727 shared_access = isl_union_map_apply_range(shared_access,
3728 isl_union_map_reverse(may_writes));
3730 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3731 local = isl_union_map_union(local, shared_access);
3732 local = isl_union_map_zip(local);
3734 equal = isl_union_map_apply_range(kernel_prefix,
3735 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3736 wrap = isl_union_map_wrap(equal);
3737 local = isl_union_map_intersect_domain(local, wrap);
3738 equal = isl_union_map_apply_range(thread_prefix,
3739 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3740 wrap = isl_union_map_wrap(equal);
3741 local = isl_union_map_subtract_domain(local, wrap);
3743 local = isl_union_map_zip(local);
3744 local = isl_union_map_universe(local);
3746 return isl_union_map_domain(local);
3749 /* Group the domain elements into a single space, named kernelX,
3750 * with X the kernel sequence number "kernel_id".
3752 static __isl_give isl_schedule_node *group_statements(
3753 __isl_take isl_schedule_node *node, int kernel_id)
3755 char buffer[20];
3756 isl_id *id;
3758 if (!node)
3759 return NULL;
3761 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3762 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3763 return isl_schedule_node_group(node, id);
3766 /* Create a ppcg_kernel representing the domain instances that reach "node"
3767 * and insert a mark node pointing to the ppcg_kernel before "node".
3768 * The band that "node" points to is the band that needs to be mapped
3769 * to block identifiers. The band that needs to be mapped to thread
3770 * identifiers should be marked by a "thread" mark by the caller.
3771 * The linear branch between the current node and the "thread" mark
3772 * may also have a "shared" mark. If present, the mapping to shared
3773 * memory is computed at that point.
3774 * Both marks are removed by this function.
3775 * If "scale" is set, then the band that "node" points to is scaled
3776 * by "sizes".
3778 * Mark all outer band nodes as atomic to ensure each kernel is only
3779 * scheduled once.
3780 * If the domain elements that reach "node" live in more than one space,
3781 * then group the domain elements into a single space, named kernelX,
3782 * with X the kernel sequence number.
3784 * Insert a guard node governing the kernel node to ensure that
3785 * no kernels with zero blocks are launched.
3787 * Insert a context node describing the block and thread
3788 * identifiers inside the kernel mark.
3789 * The context node needs to be inserted after the effective block size
3790 * has been determined such that the bounds on the thread identifiers
3791 * would reflect the effective block size.
3792 * Insert a filter node inside the context node mapping the statement
3793 * instances to block identifiers. In particular, the block identifiers
3794 * are equated to the partial schedule of band that was marked for mapping
3795 * to blocks modulo the grid size.
3796 * Insert a filter node inside the "thread" mark mapping the statement
3797 * instances to thread identifiers. In particular, the thread identifiers
3798 * are equated to the partial schedule of band that was marked for mapping
3799 * to threads modulo the block size.
3801 * Compute array reference groups for all arrays, set the local
3802 * array bounds based on the set of domain instances that reach
3803 * the kernel node, check the total amount of shared memory used
3804 * and compute all group tilings.
3805 * The array reference groups are computed after the block filter
3806 * has been inserted because it affects the mapping to shared or
3807 * private memory. This computation also requires the thread filter
3808 * (in the ppcg_kernel object), but this thread filter should not
3809 * have been added to the schedule tree yet since the computation
3810 * requires the schedule of the band that needs to be mapped to
3811 * threads before the privatization is applied.
3813 * If any array reference group requires the band mapped to threads
3814 * to be unrolled, then we perform the required unrolling.
3816 * We save a copy of the schedule that may influence the mappings
3817 * to shared or private memory in kernel->copy_schedule.
3819 * Finally, we add synchronization and copy statements to the schedule tree,
3820 * remove the "thread" mark and create representations for the local
3821 * variables in the kernel.
3823 * We keep a copy of the isl_id that points to the kernel to ensure
3824 * that the kernel does not get destroyed if the schedule node
3825 * is freed due to some error condition.
3827 __isl_give isl_schedule_node *gpu_create_kernel(struct gpu_gen *gen,
3828 __isl_take isl_schedule_node *node, int scale,
3829 __isl_keep isl_multi_val *sizes)
3831 struct ppcg_kernel *kernel;
3832 isl_id *id;
3833 isl_schedule_node *node_thread;
3834 isl_union_map *host_schedule;
3835 isl_union_pw_multi_aff *contraction;
3836 isl_set *host_domain;
3837 isl_union_set *domain, *expanded;
3838 int single_statement;
3840 node = gpu_tree_insert_shared_before_thread(node);
3841 if (!node)
3842 return NULL;
3844 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3845 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3846 if (!kernel)
3847 return isl_schedule_node_free(node);
3849 domain = isl_schedule_node_get_domain(node);
3850 single_statement = isl_union_set_n_set(domain) == 1;
3852 kernel->ctx = gen->ctx;
3853 kernel->prog = gen->prog;
3854 kernel->options = gen->options;
3855 kernel->context = extract_context(node, gen->prog);
3856 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3857 contraction = isl_schedule_node_get_subtree_contraction(node);
3858 kernel->contraction = isl_union_pw_multi_aff_copy(contraction);
3859 expanded = isl_union_set_copy(domain);
3860 expanded = isl_union_set_preimage_union_pw_multi_aff(expanded,
3861 contraction);
3862 kernel->expanded_domain = isl_union_set_copy(expanded);
3863 kernel->arrays = accessed_by_domain(expanded, gen->prog);
3864 kernel->n_grid = n_outer_coincidence(node);
3865 node_thread = isl_schedule_node_copy(node);
3866 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3867 node_thread = isl_schedule_node_child(node_thread, 0);
3868 kernel->n_block = n_outer_coincidence(node_thread);
3869 isl_schedule_node_free(node_thread);
3870 kernel->id = gen->kernel_id++;
3871 read_grid_and_block_sizes(kernel, gen);
3873 kernel->sync_writes = compute_sync_writes(kernel, node);
3875 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3876 host_domain = isl_set_from_union_set(isl_union_map_range(
3877 host_schedule));
3879 node = atomic_ancestors(node);
3881 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3882 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3883 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3885 if (!single_statement)
3886 node = group_statements(node, kernel->id);
3888 node = isl_schedule_node_child(node, 0);
3889 node = split_band(node, kernel->n_grid);
3890 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3891 kernel->n_grid, "b");
3892 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3893 kernel->grid_dim);
3894 kernel->grid_size = extract_grid_size(kernel,
3895 isl_union_set_copy(domain));
3896 if (!kernel->options->wrap)
3897 node = snap_band_to_sizes(node, kernel->grid_dim,
3898 kernel->options);
3899 if (scale)
3900 node = scale_band(node, isl_multi_val_copy(sizes));
3901 node = isl_schedule_node_parent(node);
3902 if (!single_statement)
3903 node = isl_schedule_node_parent(node);
3904 node = insert_guard(node, kernel->context, kernel->grid_size,
3905 gen->prog->scop);
3906 node = gpu_tree_move_down_to_thread(node, kernel->core);
3907 node = isl_schedule_node_child(node, 0);
3908 node = split_band(node, kernel->n_block);
3909 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3910 kernel->n_block, "t");
3911 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3912 kernel->block_dim);
3913 if (extract_block_size(kernel, domain) < 0)
3914 node = isl_schedule_node_free(node);
3916 node = gpu_tree_move_up_to_kernel(node);
3917 node = isl_schedule_node_child(node, 0);
3918 node = insert_context(kernel, node);
3919 node = isl_schedule_node_child(node, 0);
3920 node = isl_schedule_node_insert_filter(node,
3921 isl_union_set_copy(kernel->block_filter));
3923 node = gpu_tree_move_up_to_kernel(node);
3925 if (gpu_group_references(kernel, node) < 0)
3926 node = isl_schedule_node_free(node);
3927 localize_bounds(kernel, host_domain);
3928 isl_set_free(host_domain);
3930 check_shared_memory_bound(kernel);
3931 mark_global_arrays(kernel);
3932 compute_group_tilings(kernel);
3934 node = gpu_tree_move_down_to_thread(node, kernel->core);
3935 node = isl_schedule_node_child(node, 0);
3936 if (!kernel->options->wrap)
3937 node = snap_band_to_sizes(node, kernel->block_dim,
3938 kernel->options);
3939 node = isl_schedule_node_insert_filter(node,
3940 isl_union_set_copy(kernel->thread_filter));
3941 if (kernel_requires_unroll(kernel)) {
3942 node = isl_schedule_node_child(node, 0);
3943 node = unroll(node);
3946 node = gpu_tree_move_up_to_thread(node);
3947 kernel->copy_schedule_dim = isl_schedule_node_get_schedule_depth(node);
3948 kernel->copy_schedule =
3949 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3950 contraction = isl_union_pw_multi_aff_copy(kernel->contraction);
3951 kernel->copy_schedule =
3952 isl_union_pw_multi_aff_pullback_union_pw_multi_aff(
3953 kernel->copy_schedule, contraction);
3955 node = gpu_tree_move_up_to_kernel(node);
3957 node = add_sync(kernel, node);
3958 node = add_copies(kernel, node);
3960 node = gpu_tree_move_down_to_shared(node, kernel->core);
3961 node = isl_schedule_node_delete(node);
3963 node = gpu_tree_move_down_to_thread(node, kernel->core);
3964 node = isl_schedule_node_delete(node);
3966 node = gpu_tree_move_up_to_kernel(node);
3968 if (create_kernel_vars(kernel) < 0)
3969 node = isl_schedule_node_free(node);
3971 if (!single_statement)
3972 node = isl_schedule_node_parent(node);
3973 node = isl_schedule_node_parent(node);
3975 isl_id_free(id);
3976 return node;
3979 /* Insert a zero-dimensional permutable band at "node".
3981 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3982 __isl_take isl_schedule_node *node)
3984 isl_space *space;
3985 isl_schedule *schedule;
3986 isl_union_set *domain;
3987 isl_multi_union_pw_aff *mupa;
3989 schedule = isl_schedule_node_get_schedule(node);
3990 domain = isl_schedule_get_domain(schedule);
3991 space = isl_union_set_get_space(domain);
3992 isl_union_set_free(domain);
3993 isl_schedule_free(schedule);
3995 space = isl_space_set_from_params(space);
3996 mupa = isl_multi_union_pw_aff_zero(space);
3997 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3998 node = isl_schedule_node_band_set_permutable(node, 1);
4000 return node;
4003 /* See if hybrid tiling can be performed on "node" and its parent.
4004 * If so, apply hybrid tiling and return the updated schedule tree.
4005 * If not, return the original schedule tree.
4006 * Return NULL on error.
4008 * First check if "node", together with its parent, meets
4009 * the basic requirements for hybrid tiling.
4010 * If so, compute the relative dependence distances of "node"
4011 * with respect to its parent and check if they are sufficiently bounded.
4012 * If so, apply hybrid tiling using user specified tile sizes.
4014 * The tile sizes are read before the dependence distance bounds are
4015 * computed, because the user may have specified fewer dimensions
4016 * than are available. In this case, the remaining schedule dimensions
4017 * are split off and the dependence distances should be computed
4018 * after these dimensions have been split off.
4020 static __isl_give isl_schedule_node *try_hybrid_tile(struct gpu_gen *gen,
4021 __isl_take isl_schedule_node *node)
4023 int tile_len;
4024 int *tile_size;
4025 isl_bool ok;
4026 isl_schedule_node *orig = node;
4027 ppcg_ht_bounds *bounds;
4029 ok = ppcg_ht_parent_has_input_pattern(node);
4030 if (ok < 0)
4031 return isl_schedule_node_free(node);
4032 if (!ok)
4033 return orig;
4035 tile_len = 1 + 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);
4040 node = isl_schedule_node_copy(node);
4041 node = split_band(node, tile_len - 1);
4042 node = isl_schedule_node_parent(node);
4043 bounds = ppcg_ht_compute_bounds(gen->prog->scop, node);
4044 node = isl_schedule_node_child(node, 0);
4046 ok = ppcg_ht_bounds_is_valid(bounds);
4047 if (ok >= 0 && ok)
4048 node = gpu_hybrid_tile(gen, node, bounds, tile_size);
4049 else
4050 ppcg_ht_bounds_free(bounds);
4051 free(tile_size);
4053 if (ok >= 0 && !ok) {
4054 isl_schedule_node_free(node);
4055 return orig;
4057 isl_schedule_node_free(orig);
4058 if (ok < 0)
4059 return isl_schedule_node_free(node);
4060 return node;
4063 /* If "node" is the outermost permutable band that can be mapped to block and
4064 * thread identifiers in its branch (or the root of a subtree with
4065 * no such outer bands),
4066 * then mark the band as such, attaching a ppcg_kernel to the mark.
4068 * If hybrid tiling is allowed, then first try and apply it
4069 * to "node" and its parent.
4071 * If "node" is the root of a subtree without permutable bands,
4072 * then insert a zero-dimensional permutable band such that
4073 * we can assume that "node" always points to a band node.
4074 * This includes the case where "node" already points to a band node,
4075 * but one without any coincident dimension. In this case,
4076 * the extra node ensures that this original node does not get tiled.
4078 * Tile "node" using user specified tile sizes, after splitting the band
4079 * if the number of specified tile sizes is smaller than the dimension
4080 * of the band. Mark the point band of this tiling as the band that
4081 * needs to be mapped to threads and instruct the AST generator to unroll
4082 * the band if the "unroll_gpu_tile" option is set.
4083 * Create a kernel representing the domain instances that reach "node" and
4084 * insert a mark node pointing to the ppcg_kernel before the band node.
4086 static __isl_give isl_schedule_node *mark_outer_permutable(
4087 __isl_take isl_schedule_node *node, void *user)
4089 struct gpu_gen *gen = user;
4090 int outer;
4091 int scale;
4092 int tile_len;
4093 int *tile_size;
4094 isl_id *id;
4095 isl_multi_val *sizes;
4097 outer = is_outer_tilable(node);
4098 if (outer < 0)
4099 return isl_schedule_node_free(node);
4100 if (!outer)
4101 return node;
4103 if (gen->options->hybrid) {
4104 isl_schedule_node *saved = isl_schedule_node_copy(node);
4105 node = try_hybrid_tile(gen, node);
4106 isl_schedule_node_free(saved);
4107 if (node != saved)
4108 return node;
4111 if (isl_schedule_node_get_type(node) != isl_schedule_node_band ||
4112 !isl_schedule_node_band_member_get_coincident(node, 0))
4113 node = insert_empty_permutable_band(node);
4115 tile_len = isl_schedule_node_band_n_member(node);
4116 tile_size = read_tile_sizes(gen, &tile_len);
4117 if (!tile_size)
4118 return isl_schedule_node_free(node);
4119 if (tile_len < isl_schedule_node_band_n_member(node))
4120 node = isl_schedule_node_band_split(node, tile_len);
4121 sizes = construct_band_tiles_sizes(node, tile_size);
4122 node = tile_band(node, isl_multi_val_copy(sizes));
4123 node = isl_schedule_node_child(node, 0);
4124 if (gen->options->unroll_gpu_tile)
4125 node = ppcg_set_schedule_node_type(node, isl_ast_loop_unroll);
4126 id = isl_id_alloc(gen->ctx, "thread", NULL);
4127 node = isl_schedule_node_insert_mark(node, id);
4128 node = isl_schedule_node_parent(node);
4130 scale = gen->options->scale_tile_loops;
4131 node = gpu_create_kernel(gen, node, scale, sizes);
4132 isl_multi_val_free(sizes);
4133 free(tile_size);
4135 return node;
4138 /* Given a set or sequence node, return the union the filters of either all
4139 * (if "only_initial" is not set) or the initial (if "only_initial" is set)
4140 * direct subtrees that do not contain any suitably permutable bands
4141 * (according to subtree_has_permutable_bands).
4143 static __isl_give isl_union_set *get_non_parallel_subtree_filters(
4144 __isl_keep isl_schedule_node *node, int only_initial)
4146 isl_space *space;
4147 isl_union_set *filter;
4148 int i, n;
4150 n = isl_schedule_node_n_children(node);
4151 if (n < 0)
4152 return NULL;
4154 node = isl_schedule_node_copy(node);
4155 node = isl_schedule_node_child(node, 0);
4156 filter = isl_schedule_node_filter_get_filter(node);
4157 node = isl_schedule_node_parent(node);
4158 space = isl_union_set_get_space(filter);
4159 isl_union_set_free(filter);
4160 filter = isl_union_set_empty(space);
4162 for (i = 0; i < n; ++i) {
4163 int parallelism;
4165 node = isl_schedule_node_child(node, i);
4166 parallelism = subtree_has_permutable_bands(node);
4167 if (parallelism < 0) {
4168 filter = isl_union_set_free(filter);
4169 } else if (!parallelism) {
4170 isl_union_set *filter_i;
4171 filter_i = isl_schedule_node_filter_get_filter(node);
4172 filter = isl_union_set_union(filter, filter_i);
4173 } else if (only_initial)
4174 break;
4175 node = isl_schedule_node_parent(node);
4178 isl_schedule_node_free(node);
4180 return filter;
4183 /* Given a set or sequence node, return the union of the filters of
4184 * the direct subtrees that do not contain any suitably permutable bands
4185 * (according to subtree_has_permutable_bands).
4187 static __isl_give isl_union_set *get_all_non_parallel_subtree_filters(
4188 __isl_keep isl_schedule_node *node)
4190 return get_non_parallel_subtree_filters(node, 0);
4193 /* Given a set or sequence node, return the union of the filters of
4194 * the initial direct subtrees that do not contain any suitably permutable
4195 * bands (according to subtree_has_permutable_bands).
4197 static __isl_give isl_union_set *get_initial_non_parallel_subtree_filters(
4198 __isl_keep isl_schedule_node *node)
4200 return get_non_parallel_subtree_filters(node, 1);
4203 /* Mark all variables that are accessed by the statement instances in "domain"
4204 * and that are local to "prog" as requiring a declaration in the host code.
4205 * The statement instances in "domain" correspond to (a subset of)
4206 * the active instances at "node".
4207 * "node" is not modified by this function, except that NULL is returned
4208 * in case of error.
4210 static __isl_give isl_schedule_node *declare_accessed_local_variables(
4211 __isl_take isl_schedule_node *node, struct gpu_prog *prog,
4212 __isl_keep isl_union_set *domain)
4214 isl_union_pw_multi_aff *contraction;
4215 isl_union_set *arrays;
4216 int i;
4218 if (!ppcg_scop_any_hidden_declarations(prog->scop))
4219 return node;
4220 contraction = isl_schedule_node_get_subtree_contraction(node);
4221 domain = isl_union_set_copy(domain);
4222 domain = isl_union_set_preimage_union_pw_multi_aff(domain, contraction);
4223 arrays = accessed_by_domain(domain, prog);
4225 for (i = 0; i < prog->n_array; ++i) {
4226 isl_space *space;
4227 isl_set *set;
4228 int empty;
4230 if (!prog->array[i].local)
4231 continue;
4232 space = isl_set_get_space(prog->array[i].extent);
4233 set = isl_union_set_extract_set(arrays, space);
4234 empty = isl_set_plain_is_empty(set);
4235 isl_set_free(set);
4236 if (empty < 0)
4237 goto error;
4238 if (!empty)
4239 prog->array[i].declare_local = 1;
4242 isl_union_set_free(arrays);
4243 return node;
4244 error:
4245 isl_union_set_free(arrays);
4246 return isl_schedule_node_free(node);
4249 /* If "node" points to a set node, then separate its children
4250 * into subtrees that have suitably permutable bands and
4251 * those that do not.
4252 * Adjust the schedule tree in order to execute the second group
4253 * after the first group and return a pointer to the first group,
4254 * assuming there are any such subtrees.
4255 * If "node" points to a sequence node, then separate the initial
4256 * children that do not have suitably permutable bands and
4257 * return a pointer to the subsequence of children that do have such bands,
4258 * assuming there are any such subtrees.
4260 * In both cases, mark all local variables in "prog" that are accessed by
4261 * the group without permutable bands as requiring a declaration on the host.
4263 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
4264 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
4266 isl_union_set *filter;
4267 enum isl_schedule_node_type type;
4269 if (!node)
4270 return NULL;
4271 type = isl_schedule_node_get_type(node);
4272 if (type == isl_schedule_node_set) {
4273 filter = get_all_non_parallel_subtree_filters(node);
4274 node = declare_accessed_local_variables(node, prog, filter);
4275 node = isl_schedule_node_order_after(node, filter);
4276 } else if (type == isl_schedule_node_sequence) {
4277 filter = get_initial_non_parallel_subtree_filters(node);
4278 node = declare_accessed_local_variables(node, prog, filter);
4279 node = isl_schedule_node_order_before(node, filter);
4282 return node;
4285 /* Replace any reference to an array element in the range of "copy"
4286 * by a reference to all array elements (defined by the extent of the array).
4288 static __isl_give isl_union_map *approximate_copy_out(
4289 __isl_take isl_union_map *copy, struct gpu_prog *prog)
4291 int i;
4292 isl_union_map *res;
4294 res = isl_union_map_empty(isl_union_map_get_space(copy));
4296 for (i = 0; i < prog->n_array; ++i) {
4297 isl_space *space;
4298 isl_set *set;
4299 isl_union_map *copy_i;
4300 isl_union_set *extent, *domain;
4302 space = isl_space_copy(prog->array[i].space);
4303 extent = isl_union_set_from_set(isl_set_universe(space));
4304 copy_i = isl_union_map_copy(copy);
4305 copy_i = isl_union_map_intersect_range(copy_i, extent);
4306 set = isl_set_copy(prog->array[i].extent);
4307 extent = isl_union_set_from_set(set);
4308 domain = isl_union_map_domain(copy_i);
4309 copy_i = isl_union_map_from_domain_and_range(domain, extent);
4310 res = isl_union_map_union(res, copy_i);
4313 isl_union_map_free(copy);
4315 return res;
4318 /* Insert "kernel" marks that point to a ppcg_kernel structure
4319 * in front of all outermost tilable band that (by construction)
4320 * have at least one parallel loop.
4322 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
4323 __isl_take isl_schedule_node *node)
4325 return isl_schedule_node_map_descendant_bottom_up(node,
4326 &mark_outer_permutable, gen);
4329 /* Construct schedule constraints from the dependences in prog->scop and
4330 * the array order dependences in prog->array_order.
4332 * If live range reordering is allowed, then we need to make sure
4333 * that live ranges on arrays are not run in parallel since doing
4334 * so would require array expansion. We therefore add the array
4335 * order dependences to the coincidence dependences. Non-zero array
4336 * order dependences will then prevent a schedule dimension from being
4337 * considered parallel.
4338 * Live ranges derived from scalars are allowed to be run in parallel
4339 * since we force the scalars to be mapped to private memory in
4340 * check_scalar_live_ranges.
4341 * If live range reordering is allowed, then the false dependences
4342 * are not added to the validity constraints as that would prevent
4343 * reordering. Instead, the external false dependences that enforce that reads
4344 * from potentially live-in data precede any later write and
4345 * that writes of potentially live-out data follow any other earlier write
4346 * are added to the validity and the coincidence constraints.
4347 * The false dependences are still added to the proximity constraints
4348 * for consistency with the case where live range reordering is not allowed.
4349 * The coincidence constraints then consist of flow dependences,
4350 * external false dependences and array order dependences.
4351 * The independences can be filtered out from the first two sets.
4352 * They have already been filtered out from the array order dependences
4353 * on a per array basis in collect_order_dependences.
4354 * There is no need for a per array handling of the other two sets
4355 * as there should be no flow or external false dependence on local
4356 * variables that can be filtered out.
4358 static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4359 struct gpu_prog *prog)
4361 isl_union_set *domain;
4362 isl_union_map *dep_raw, *dep;
4363 isl_union_map *validity, *proximity, *coincidence;
4364 isl_schedule_constraints *sc;
4366 domain = isl_union_set_copy(prog->scop->domain);
4367 sc = isl_schedule_constraints_on_domain(domain);
4368 sc = isl_schedule_constraints_set_context(sc,
4369 isl_set_copy(prog->scop->context));
4370 if (prog->scop->options->live_range_reordering) {
4371 sc = isl_schedule_constraints_set_conditional_validity(sc,
4372 isl_union_map_copy(prog->scop->tagged_dep_flow),
4373 isl_union_map_copy(prog->scop->tagged_dep_order));
4374 proximity = isl_union_map_copy(prog->scop->dep_flow);
4375 validity = isl_union_map_copy(proximity);
4376 validity = isl_union_map_union(validity,
4377 isl_union_map_copy(prog->scop->dep_forced));
4378 proximity = isl_union_map_union(proximity,
4379 isl_union_map_copy(prog->scop->dep_false));
4380 coincidence = isl_union_map_copy(validity);
4381 coincidence = isl_union_map_subtract(coincidence,
4382 isl_union_map_copy(prog->scop->independence));
4383 coincidence = isl_union_map_union(coincidence,
4384 isl_union_map_copy(prog->array_order));
4385 } else {
4386 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4387 dep = isl_union_map_copy(prog->scop->dep_false);
4388 dep = isl_union_map_union(dep, dep_raw);
4389 dep = isl_union_map_coalesce(dep);
4390 proximity = isl_union_map_copy(dep);
4391 coincidence = isl_union_map_copy(dep);
4392 validity = dep;
4394 sc = isl_schedule_constraints_set_validity(sc, validity);
4395 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4396 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4398 if (prog->scop->options->debug->dump_schedule_constraints)
4399 isl_schedule_constraints_dump(sc);
4400 return sc;
4403 /* Compute an appropriate schedule based on the accesses in
4404 * gen->read and gen->write.
4406 * We derive schedule constraints from the dependences in gen->prog->scop
4407 * and then use isl to compute a schedule that has a parallel loop
4408 * in each tilable band.
4409 * During the schedule construction, some statement instances
4410 * may be grouped first based on the input schedule.
4412 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4414 isl_schedule_constraints *sc;
4415 isl_schedule *schedule;
4417 sc = construct_schedule_constraints(gen->prog);
4418 schedule = gen->prog->scop->schedule;
4419 schedule = ppcg_compute_schedule(sc, schedule, gen->options);
4421 return schedule;
4424 /* If the band node "node" has exactly one member then mark it permutable.
4426 static __isl_give isl_schedule_node *band_set_permutable(
4427 __isl_take isl_schedule_node *node,
4428 __isl_keep isl_schedule_constraints *sc)
4430 if (isl_schedule_node_band_n_member(node) == 1)
4431 node = isl_schedule_node_band_set_permutable(node, 1);
4433 return node;
4436 /* Return the coincidence constraints between pairs of instances
4437 * that are scheduled together by the ancestors of "node".
4438 * That is, select those coincidence constraints that relate
4439 * pairs of instances that have the same value for the prefix schedule.
4440 * If the schedule depth is zero, then the prefix schedule does not
4441 * contain any information, so we intersect domain and range
4442 * of the schedule constraints with the reaching domain elements instead.
4444 static __isl_give isl_union_map *get_local_coincidence(
4445 __isl_keep isl_schedule_node *node,
4446 __isl_keep isl_schedule_constraints *sc)
4448 isl_union_map *coincidence;
4449 isl_multi_union_pw_aff *prefix;
4450 isl_union_pw_multi_aff *contraction;
4452 coincidence = isl_schedule_constraints_get_coincidence(sc);
4453 contraction = isl_schedule_node_get_subtree_contraction(node);
4454 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4455 isl_union_set *domain;
4457 domain = isl_schedule_node_get_domain(node);
4458 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4459 contraction);
4460 coincidence = isl_union_map_intersect_domain(coincidence,
4461 isl_union_set_copy(domain));
4462 coincidence = isl_union_map_intersect_range(coincidence,
4463 domain);
4464 return coincidence;
4467 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4468 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4469 contraction);
4470 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4473 /* For each member in the band node "node", determine whether
4474 * it is coincident with respect to the outer nodes and mark
4475 * it accordingly.
4477 * That is, for each coincidence constraint between pairs
4478 * of instances that are scheduled together by the outer nodes,
4479 * check that domain and range are assigned the same value
4480 * by the band member. This test is performed by checking
4481 * that imposing the same value for the band member does not
4482 * remove any elements from the set of coincidence constraints.
4484 static __isl_give isl_schedule_node *band_set_coincident(
4485 __isl_take isl_schedule_node *node,
4486 __isl_keep isl_schedule_constraints *sc)
4488 isl_union_map *coincidence;
4489 isl_union_pw_multi_aff *contraction;
4490 isl_multi_union_pw_aff *partial;
4491 int i, n;
4493 coincidence = get_local_coincidence(node, sc);
4495 partial = isl_schedule_node_band_get_partial_schedule(node);
4496 contraction = isl_schedule_node_get_subtree_contraction(node);
4497 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4498 contraction);
4499 n = isl_schedule_node_band_n_member(node);
4500 for (i = 0; i < n; ++i) {
4501 isl_union_map *coincidence_i;
4502 isl_union_pw_aff *upa;
4503 isl_multi_union_pw_aff *partial_i;
4504 int subset;
4506 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4507 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4508 coincidence_i = isl_union_map_copy(coincidence);
4509 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4510 coincidence_i, partial_i);
4511 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4512 isl_union_map_free(coincidence_i);
4514 if (subset < 0)
4515 break;
4516 node = isl_schedule_node_band_member_set_coincident(node, i,
4517 subset);
4519 if (i < n)
4520 node = isl_schedule_node_free(node);
4521 isl_multi_union_pw_aff_free(partial);
4522 isl_union_map_free(coincidence);
4524 return node;
4527 /* If "node" is a band, then set its properties.
4529 * In particular, if the band has exactly one member, then mark it permutable.
4530 * Mark the band member coincident based on the coincidence constraints
4531 * of "sc".
4533 static __isl_give isl_schedule_node *set_band_properties(
4534 __isl_take isl_schedule_node *node, void *user)
4536 isl_schedule_constraints *sc = user;
4538 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4539 return node;
4540 if (isl_schedule_node_band_n_member(node) == 0)
4541 return node;
4543 node = band_set_permutable(node, sc);
4544 node = band_set_coincident(node, sc);
4546 return node;
4549 /* Return the original schedule with all bands marked permutable and
4550 * all band members marked coincident based on the coincidence constraints.
4551 * The bands are explicitly marked permutable so that they will be considered
4552 * by mark_outer_permutable.
4554 static __isl_give isl_schedule *determine_properties_original_schedule(
4555 struct gpu_gen *gen)
4557 isl_schedule *schedule;
4558 isl_schedule_constraints *sc;
4560 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4561 sc = construct_schedule_constraints(gen->prog);
4562 schedule = isl_schedule_map_schedule_node_bottom_up(schedule,
4563 &set_band_properties, sc);
4564 isl_schedule_constraints_free(sc);
4566 return schedule;
4569 /* Compute a schedule or determine the properties of the original schedule
4570 * depending on the value of the "reschedule" option.
4572 static __isl_give isl_schedule *compute_or_set_properties(void *user)
4574 struct gpu_gen *gen = user;
4576 if (gen->options->reschedule)
4577 return compute_schedule(gen);
4578 else
4579 return determine_properties_original_schedule(gen);
4582 /* Obtain a schedule for the scop, by reading it from
4583 * a file, by computing one or by determining the properties
4584 * of the original schedule.
4586 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4588 return ppcg_get_schedule(gen->ctx, gen->options,
4589 &compute_or_set_properties, gen);
4592 /* Construct the string "<a>_<b>".
4594 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4596 isl_printer *p;
4597 char *s;
4599 p = isl_printer_to_str(ctx);
4600 p = isl_printer_print_str(p, a);
4601 p = isl_printer_print_str(p, "_");
4602 p = isl_printer_print_str(p, b);
4603 s = isl_printer_get_str(p);
4604 isl_printer_free(p);
4606 return s;
4609 /* For each array in "prog" of which an element appears in "accessed" and
4610 * that is not a read only scalar, create a zero-dimensional universe set
4611 * of which the tuple id has name "<prefix>_<name of array>" and a user
4612 * pointer pointing to the array (gpu_array_info).
4614 * If the array is local to "prog", then make sure it will be declared
4615 * in the host code.
4617 * Return the list of these universe sets.
4619 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4620 const char *prefix, __isl_take isl_union_set *accessed)
4622 int i;
4623 isl_ctx *ctx;
4624 isl_union_set_list *filters;
4626 ctx = prog->ctx;
4627 filters = isl_union_set_list_alloc(ctx, 0);
4628 for (i = 0; i < prog->n_array; ++i) {
4629 struct gpu_array_info *array = &prog->array[i];
4630 isl_space *space;
4631 isl_set *accessed_i;
4632 int empty;
4633 char *name;
4634 isl_id *id;
4635 isl_union_set *uset;
4637 if (gpu_array_is_read_only_scalar(array))
4638 continue;
4640 space = isl_space_copy(array->space);
4641 accessed_i = isl_union_set_extract_set(accessed, space);
4642 empty = isl_set_plain_is_empty(accessed_i);
4643 isl_set_free(accessed_i);
4644 if (empty < 0) {
4645 filters = isl_union_set_list_free(filters);
4646 break;
4648 if (empty)
4649 continue;
4651 array->global = 1;
4652 if (array->local)
4653 array->declare_local = 1;
4655 name = concat(ctx, prefix, array->name);
4656 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4657 free(name);
4658 space = isl_space_set_alloc(ctx, 0, 0);
4659 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4660 uset = isl_union_set_from_set(isl_set_universe(space));
4662 filters = isl_union_set_list_add(filters, uset);
4664 isl_union_set_free(accessed);
4666 return filters;
4669 /* Make sure that code for the statements in "filters" that
4670 * copy arrays to or from the device is only generated when
4671 * the size of the corresponding array is positive.
4672 * That is, add a set node underneath "graft" with "filters" as children
4673 * and for each child add a guard that the selects the parameter
4674 * values for which the corresponding array has a positive size.
4675 * The array is available in the user pointer of the statement identifier.
4676 * "depth" is the schedule depth of the position where "graft"
4677 * will be added.
4679 static __isl_give isl_schedule_node *insert_positive_size_guards(
4680 __isl_take isl_schedule_node *graft,
4681 __isl_take isl_union_set_list *filters, int depth)
4683 int i, n;
4685 graft = isl_schedule_node_child(graft, 0);
4686 graft = isl_schedule_node_insert_set(graft, filters);
4687 n = isl_schedule_node_n_children(graft);
4688 for (i = 0; i < n; ++i) {
4689 isl_union_set *filter;
4690 isl_set *domain, *guard;
4691 isl_id *id;
4692 struct gpu_array_info *array;
4694 graft = isl_schedule_node_child(graft, i);
4695 filter = isl_schedule_node_filter_get_filter(graft);
4696 domain = isl_set_from_union_set(filter);
4697 id = isl_set_get_tuple_id(domain);
4698 array = isl_id_get_user(id);
4699 isl_id_free(id);
4700 isl_set_free(domain);
4701 guard = gpu_array_positive_size_guard(array);
4702 guard = isl_set_from_params(guard);
4703 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4704 graft = isl_schedule_node_child(graft, 0);
4705 graft = isl_schedule_node_insert_guard(graft, guard);
4706 graft = isl_schedule_node_parent(graft);
4707 graft = isl_schedule_node_parent(graft);
4709 graft = isl_schedule_node_parent(graft);
4711 return graft;
4714 /* Create a graft for copying arrays to or from the device,
4715 * whenever the size of the array is strictly positive.
4716 * Each statement is called "<prefix>_<name of array>" and
4717 * the identifier has a user pointer pointing to the array.
4718 * The graft will be added at the position specified by "node".
4719 * "copy" contains the array elements that need to be copied.
4720 * Only arrays of which some elements need to be copied
4721 * will have a corresponding statement in the graph.
4722 * Note though that each such statement will copy the entire array.
4724 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4725 __isl_keep isl_schedule_node *node, const char *prefix,
4726 __isl_take isl_union_set *copy)
4728 int depth;
4729 isl_ctx *ctx;
4730 isl_space *space;
4731 isl_union_set *all, *domain;
4732 isl_union_set_list *filters;
4733 isl_union_map *extension;
4734 isl_schedule_node *graft;
4736 ctx = prog->ctx;
4737 depth = isl_schedule_node_get_schedule_depth(node);
4738 filters = create_copy_filters(prog, prefix, copy);
4739 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4741 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4742 domain = isl_union_set_from_set(isl_set_universe(space));
4743 extension = isl_union_map_from_domain_and_range(domain, all);
4744 graft = isl_schedule_node_from_extension(extension);
4746 if (!filters)
4747 return isl_schedule_node_free(graft);
4748 if (isl_union_set_list_n_union_set(filters) == 0) {
4749 isl_union_set_list_free(filters);
4750 return graft;
4753 return insert_positive_size_guards(graft, filters, depth);
4756 /* Return (the universe spaces of) the arrays that are declared
4757 * inside the scop corresponding to "prog" and for which all
4758 * potential writes inside the scop form a subset of "domain".
4760 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4761 __isl_keep isl_union_set *domain)
4763 int i;
4764 isl_union_set *local;
4766 local = isl_union_set_empty(isl_union_set_get_space(domain));
4768 for (i = 0; i < prog->n_array; ++i) {
4769 isl_set *set;
4770 isl_union_map *to_outer;
4771 isl_union_map *may_write;
4772 isl_union_set *write_domain;
4773 isl_union_set *fields;
4774 int subset;
4776 if (!prog->array[i].local)
4777 continue;
4779 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4780 to_outer = isl_union_map_copy(prog->to_outer);
4781 to_outer = isl_union_map_intersect_range(to_outer,
4782 isl_union_set_from_set(isl_set_copy(set)));
4783 fields = isl_union_map_domain(to_outer);
4784 may_write = isl_union_map_copy(prog->may_write);
4785 may_write = isl_union_map_intersect_range(may_write, fields);
4786 write_domain = isl_union_map_domain(may_write);
4787 subset = isl_union_set_is_subset(write_domain, domain);
4788 isl_union_set_free(write_domain);
4790 if (subset < 0) {
4791 isl_set_free(set);
4792 return isl_union_set_free(local);
4793 } else if (subset) {
4794 local = isl_union_set_add_set(local, set);
4795 } else {
4796 isl_set_free(set);
4800 return local;
4803 /* Internal data structure for node_may_persist.
4805 * "tagger" maps tagged iteration domains to the corresponding untagged
4806 * iteration domain.
4808 * "may_persist_flow" is the set of all tagged dataflow dependences
4809 * with those dependences removed that either precede or follow
4810 * the kernel launch in a sequence.
4811 * "inner_band_flow" is the set of all tagged dataflow dependences
4812 * that are local to a given iteration of the outer band nodes
4813 * with respect to the current node.
4814 * "local_flow" is equal to "inner_band_flow", except that the domain
4815 * and the range have been intersected with intermediate filters
4816 * on children of sets or sequences.
4818 struct ppcg_may_persist_data {
4819 isl_union_pw_multi_aff *tagger;
4821 isl_union_map *local_flow;
4822 isl_union_map *inner_band_flow;
4823 isl_union_map *may_persist_flow;
4826 /* Update the information in "data" based on the band ancestor "node".
4828 * In particular, we restrict the dependences in data->local_flow
4829 * to those dependence where the source and the sink occur in
4830 * the same iteration of the given band node.
4831 * We also update data->inner_band_flow to the new value of
4832 * data->local_flow.
4834 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4835 struct ppcg_may_persist_data *data)
4837 isl_multi_union_pw_aff *partial;
4838 isl_union_pw_multi_aff *contraction;
4839 isl_union_map *flow;
4841 if (isl_schedule_node_band_n_member(node) == 0)
4842 return 0;
4844 partial = isl_schedule_node_band_get_partial_schedule(node);
4845 contraction = isl_schedule_node_get_subtree_contraction(node);
4846 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4847 contraction);
4848 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4849 isl_union_pw_multi_aff_copy(data->tagger));
4851 flow = data->local_flow;
4852 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4853 data->local_flow = flow;
4855 isl_union_map_free(data->inner_band_flow);
4856 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4858 return 0;
4861 /* Given a set of local reaching domain elements "domain",
4862 * expand them to the corresponding leaf domain elements using "contraction"
4863 * and insert the array references tags using data->tagger.
4865 static __isl_give isl_union_set *expand_and_tag(
4866 __isl_take isl_union_set *domain,
4867 __isl_take isl_union_pw_multi_aff *contraction,
4868 struct ppcg_may_persist_data *data)
4870 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4871 contraction);
4872 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4873 isl_union_pw_multi_aff_copy(data->tagger));
4874 return domain;
4877 /* Given a filter node that is the child of a set or sequence node,
4878 * restrict data->local_flow to refer only to those elements
4879 * in the filter of the node.
4880 * "contraction" maps the leaf domain elements of the schedule tree
4881 * to the corresponding domain elements at (the parent of) "node".
4883 static int filter_flow(__isl_keep isl_schedule_node *node,
4884 struct ppcg_may_persist_data *data,
4885 __isl_take isl_union_pw_multi_aff *contraction)
4887 isl_union_set *filter;
4888 isl_union_map *flow;
4890 flow = data->local_flow;
4891 filter = isl_schedule_node_filter_get_filter(node);
4892 filter = expand_and_tag(filter, contraction, data);
4893 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4894 flow = isl_union_map_intersect_range(flow, filter);
4895 data->local_flow = flow;
4897 return 0;
4900 /* Given a filter node "node", collect the filters on all preceding siblings
4901 * (which are also filter nodes), add them to "filters" and return the result.
4903 static __isl_give isl_union_set *add_previous_filters(
4904 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4906 isl_schedule_node *sibling;
4908 sibling = isl_schedule_node_copy(node);
4909 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4910 isl_union_set *filter;
4912 sibling = isl_schedule_node_previous_sibling(sibling);
4913 filter = isl_schedule_node_filter_get_filter(sibling);
4914 filters = isl_union_set_union(filters, filter);
4916 isl_schedule_node_free(sibling);
4917 if (!sibling)
4918 return isl_union_set_free(filters);
4920 return filters;
4923 /* Given a filter node "node", collect the filters on all following siblings
4924 * (which are also filter nodes), add them to "filters" and return the result.
4926 static __isl_give isl_union_set *add_next_filters(
4927 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4929 isl_schedule_node *sibling;
4931 sibling = isl_schedule_node_copy(node);
4932 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4933 isl_union_set *filter;
4935 sibling = isl_schedule_node_next_sibling(sibling);
4936 filter = isl_schedule_node_filter_get_filter(sibling);
4937 filters = isl_union_set_union(filters, filter);
4939 isl_schedule_node_free(sibling);
4940 if (!sibling)
4941 return isl_union_set_free(filters);
4943 return filters;
4946 /* Remove those flow dependences from data->may_persist_flow
4947 * that flow between elements of "domain" within the same iteration
4948 * of all outer band nodes.
4949 * "contraction" maps the leaf domain elements of the schedule tree
4950 * to the corresponding elements "domain".
4952 static void remove_external_flow(struct ppcg_may_persist_data *data,
4953 __isl_take isl_union_set *domain,
4954 __isl_keep isl_union_pw_multi_aff *contraction)
4956 isl_union_map *flow;
4958 contraction = isl_union_pw_multi_aff_copy(contraction);
4959 domain = expand_and_tag(domain, contraction, data);
4960 flow = isl_union_map_copy(data->local_flow);
4961 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4962 flow = isl_union_map_intersect_range(flow, domain);
4964 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4965 flow);
4968 /* Update the information in "data" based on the filter ancestor "node".
4969 * We only need to modify anything if the filter is the child
4970 * of a set or sequence node.
4972 * In the case of a sequence, we remove the dependences between
4973 * statement instances that are both executed either before or
4974 * after the subtree that will be mapped to a kernel, within
4975 * the same iteration of outer bands.
4977 * In both cases, we restrict data->local_flow to the current child.
4979 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4980 struct ppcg_may_persist_data *data)
4982 enum isl_schedule_node_type type;
4983 isl_schedule_node *parent;
4984 isl_space *space;
4985 isl_union_pw_multi_aff *contraction;
4986 isl_union_set *before, *after, *filter;
4988 type = isl_schedule_node_get_parent_type(node);
4989 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4990 return 0;
4992 parent = isl_schedule_node_copy(node);
4993 parent = isl_schedule_node_parent(parent);
4994 contraction = isl_schedule_node_get_subtree_contraction(parent);
4995 isl_schedule_node_free(parent);
4997 if (type == isl_schedule_node_set)
4998 return filter_flow(node, data, contraction);
5000 filter = isl_schedule_node_filter_get_filter(node);
5001 space = isl_union_set_get_space(filter);
5002 isl_union_set_free(filter);
5003 before = isl_union_set_empty(space);
5004 after = isl_union_set_copy(before);
5005 before = add_previous_filters(before, node);
5006 after = add_next_filters(after, node);
5008 remove_external_flow(data, before, contraction);
5009 remove_external_flow(data, after, contraction);
5011 return filter_flow(node, data, contraction);
5014 /* Update the information in "data" based on the ancestor "node".
5016 static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
5017 void *user)
5019 struct ppcg_may_persist_data *data = user;
5021 switch (isl_schedule_node_get_type(node)) {
5022 case isl_schedule_node_error:
5023 return isl_stat_error;
5024 case isl_schedule_node_context:
5025 case isl_schedule_node_domain:
5026 case isl_schedule_node_expansion:
5027 case isl_schedule_node_extension:
5028 case isl_schedule_node_guard:
5029 case isl_schedule_node_leaf:
5030 case isl_schedule_node_mark:
5031 case isl_schedule_node_sequence:
5032 case isl_schedule_node_set:
5033 break;
5034 case isl_schedule_node_band:
5035 if (update_may_persist_at_band(node, data) < 0)
5036 return isl_stat_error;
5037 break;
5038 case isl_schedule_node_filter:
5039 if (update_may_persist_at_filter(node, data) < 0)
5040 return isl_stat_error;
5041 break;
5044 return isl_stat_ok;
5047 /* Determine the set of array elements that may need to be perserved
5048 * by a kernel constructed from the subtree at "node".
5049 * This includes the set of array elements that may need to be preserved
5050 * by the entire scop (prog->may_persist) and the elements for which
5051 * there is a potential flow dependence that may cross a kernel launch.
5053 * To determine the second set, we start from all flow dependences.
5054 * From this set of dependences, we remove those that cannot possibly
5055 * require data to be preserved by a kernel launch.
5056 * In particular, we consider the following sets of dependences.
5057 * - dependences of which the write occurs inside the kernel.
5058 * If the data is needed outside the kernel, then it will
5059 * be copied out immediately after the kernel launch, so there
5060 * is no need for any special care.
5061 * - dependences of which the read occurs inside the kernel and the
5062 * corresponding write occurs inside the same iteration of the
5063 * outer band nodes. This means that the data is needed in
5064 * the first kernel launch after the write, which is already
5065 * taken care of by the standard copy-in. That is, the data
5066 * do not need to be preserved by any intermediate call to
5067 * the same kernel.
5068 * - dependences of which the write and the read either both occur
5069 * before the kernel launch or both occur after the kernel launch,
5070 * within the same iteration of the outer band nodes with respect
5071 * to the sequence that determines the ordering of the dependence
5072 * and the kernel launch. Such flow dependences cannot cross
5073 * any kernel launch.
5075 * For the remaining (tagged) dependences, we take the domain
5076 * (i.e., the tagged writes) and apply the tagged access relation
5077 * to obtain the accessed data elements.
5078 * These are then combined with the elements that may need to be
5079 * preserved by the entire scop.
5081 static __isl_give isl_union_set *node_may_persist(
5082 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
5084 struct ppcg_may_persist_data data;
5085 isl_union_pw_multi_aff *contraction;
5086 isl_union_set *domain;
5087 isl_union_set *persist;
5088 isl_union_map *flow, *local_flow;
5090 data.tagger = prog->scop->tagger;
5092 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
5093 data.local_flow = isl_union_map_copy(flow);
5094 data.inner_band_flow = isl_union_map_copy(flow);
5095 data.may_persist_flow = flow;
5096 if (isl_schedule_node_foreach_ancestor_top_down(node,
5097 &update_may_persist_at, &data) < 0)
5098 data.may_persist_flow =
5099 isl_union_map_free(data.may_persist_flow);
5100 flow = data.may_persist_flow;
5101 isl_union_map_free(data.local_flow);
5103 domain = isl_schedule_node_get_domain(node);
5104 contraction = isl_schedule_node_get_subtree_contraction(node);
5105 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5106 contraction);
5107 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5108 isl_union_pw_multi_aff_copy(data.tagger));
5109 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
5110 local_flow = data.inner_band_flow;
5111 local_flow = isl_union_map_intersect_range(local_flow, domain);
5112 flow = isl_union_map_subtract(flow, local_flow);
5114 persist = isl_union_map_domain(flow);
5115 persist = isl_union_set_apply(persist,
5116 isl_union_map_copy(prog->scop->tagged_may_writes));
5117 persist = isl_union_set_union(persist,
5118 isl_union_set_copy(prog->may_persist));
5120 return persist;
5123 /* Add nodes for copying outer arrays in and out of the device
5124 * before and after the subtree "node", which contains one or more kernels.
5125 * "domain" contains the original statement instances, i.e.,
5126 * those that correspond to the domains of the access relations in "prog".
5127 * In particular, the domain has not been contracted in any way.
5128 * "prefix" contains the prefix schedule at that point, in terms
5129 * of the same original statement instances.
5131 * We first compute the sets of outer array elements that need
5132 * to be copied in and out and then graft in the nodes for
5133 * performing this copying.
5135 * In particular, for each array that is possibly written anywhere in
5136 * the subtree "node" and that may be used after "node"
5137 * or that may be visible outside the corresponding scop,
5138 * we copy out its entire extent.
5140 * Any array elements that is read without first being written inside
5141 * the subtree "node" needs to be copied in.
5142 * Furthermore, if there are any array elements that
5143 * are copied out, but that may not be written inside "node, then
5144 * they also need to be copied in to ensure that the value after execution
5145 * is the same as the value before execution, at least for those array
5146 * elements that may have their values preserved by the scop or that
5147 * may be written before "node" and read after "node".
5148 * In case the array elements are structures, we need to take into
5149 * account that all members of the structures need to be written
5150 * by "node" before we can avoid copying the data structure in.
5152 * Note that the may_write relation is intersected with the domain,
5153 * which has been intersected with the context.
5154 * This helps in those cases where the arrays are declared with a fixed size,
5155 * while the accesses are parametric and the context assigns a fixed value
5156 * to the parameters.
5158 * If an element from a local array is read without first being written,
5159 * then there is no point in copying it in since it cannot have been
5160 * written prior to the scop. Warn about the uninitialized read instead.
5162 static __isl_give isl_schedule_node *add_to_from_device(
5163 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
5164 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
5166 isl_union_set *local;
5167 isl_union_set *may_persist;
5168 isl_union_map *may_write, *must_write, *copy_out, *not_written;
5169 isl_union_map *read, *copy_in;
5170 isl_union_map *tagged;
5171 isl_union_map *local_uninitialized;
5172 isl_schedule_node *graft;
5174 tagged = isl_union_map_copy(prog->scop->tagged_reads);
5175 tagged = isl_union_map_union(tagged,
5176 isl_union_map_copy(prog->scop->tagged_may_writes));
5178 may_write = isl_union_map_copy(prog->may_write);
5179 may_write = isl_union_map_intersect_domain(may_write,
5180 isl_union_set_copy(domain));
5181 may_write = remove_local_accesses(prog,
5182 isl_union_map_copy(tagged), may_write,
5183 isl_union_map_copy(prefix), 0);
5184 may_write = isl_union_map_apply_range(may_write,
5185 isl_union_map_copy(prog->to_outer));
5186 may_write = isl_union_map_apply_domain(may_write,
5187 isl_union_map_copy(prefix));
5188 may_write = approximate_copy_out(may_write, prog);
5189 copy_out = isl_union_map_copy(may_write);
5190 may_write = isl_union_map_apply_range(may_write,
5191 isl_union_map_copy(prog->to_inner));
5192 must_write = isl_union_map_copy(prog->must_write);
5193 must_write = isl_union_map_apply_domain(must_write,
5194 isl_union_map_copy(prefix));
5195 may_persist = node_may_persist(node, prog);
5196 may_write = isl_union_map_intersect_range(may_write, may_persist);
5197 not_written = isl_union_map_subtract(may_write, must_write);
5199 local = extract_local_accesses(prog, domain);
5200 read = isl_union_map_copy(prog->read);
5201 read = isl_union_map_intersect_domain(read, domain);
5202 read = remove_local_accesses(prog, tagged, read,
5203 isl_union_map_copy(prefix), 1);
5204 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
5205 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
5206 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5207 local);
5208 local_uninitialized = isl_union_map_intersect(local_uninitialized,
5209 isl_union_map_copy(read));
5210 if (!isl_union_map_is_empty(local_uninitialized)) {
5211 fprintf(stderr,
5212 "possibly uninitialized reads (not copied in):\n");
5213 isl_union_map_dump(local_uninitialized);
5215 read = isl_union_map_subtract(read, local_uninitialized);
5216 read = isl_union_map_apply_domain(read, prefix);
5217 copy_in = isl_union_map_union(read, not_written);
5218 copy_in = isl_union_map_apply_range(copy_in,
5219 isl_union_map_copy(prog->to_outer));
5221 graft = create_copy_device(prog, node, "to_device",
5222 isl_union_map_range(copy_in));
5223 node = isl_schedule_node_graft_before(node, graft);
5224 graft = create_copy_device(prog, node, "from_device",
5225 isl_union_map_range(copy_out));
5226 node = isl_schedule_node_graft_after(node, graft);
5228 return node;
5231 /* Add nodes for initializing ("init_device") and clearing ("clear_device")
5232 * the device before and after "node".
5234 static __isl_give isl_schedule_node *add_init_clear_device(
5235 __isl_take isl_schedule_node *node)
5237 isl_ctx *ctx;
5238 isl_space *space;
5239 isl_union_set *domain;
5240 isl_schedule_node *graft;
5242 ctx = isl_schedule_node_get_ctx(node);
5244 space = isl_space_set_alloc(ctx, 0, 0);
5245 space = isl_space_set_tuple_name(space, isl_dim_set, "init_device");
5246 domain = isl_union_set_from_set(isl_set_universe(space));
5247 graft = isl_schedule_node_from_domain(domain);
5249 node = isl_schedule_node_graft_before(node, graft);
5251 space = isl_space_set_alloc(ctx, 0, 0);
5252 space = isl_space_set_tuple_name(space, isl_dim_set, "clear_device");
5253 domain = isl_union_set_from_set(isl_set_universe(space));
5254 graft = isl_schedule_node_from_domain(domain);
5256 node = isl_schedule_node_graft_after(node, graft);
5258 return node;
5261 /* Update "schedule" for mapping to a GPU device.
5263 * In particular, insert a context node, create kernels for
5264 * each outermost tilable band and introduce nodes for copying arrays
5265 * in and out of the device and for initializing and clearing the device.
5266 * If the child of the initial root points to a set node,
5267 * then children of this node that do not contain any tilable bands
5268 * are separated from the other children and are not mapped to
5269 * the device.
5271 * The GPU code is generated in a context where at least one
5272 * statement instance is executed. The corresponding guard is inserted
5273 * around the entire schedule.
5275 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
5276 __isl_take isl_schedule *schedule)
5278 isl_schedule_node *node;
5279 isl_set *context;
5280 isl_set *guard;
5281 isl_union_set *domain;
5282 isl_union_map *prefix;
5283 isl_union_pw_multi_aff *contraction;
5284 struct gpu_prog *prog;
5286 context = isl_set_copy(gen->prog->context);
5287 context = isl_set_from_params(context);
5288 schedule = isl_schedule_insert_context(schedule, context);
5290 prog = gen->prog;
5291 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5292 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5293 guard = isl_set_from_params(guard);
5295 node = isl_schedule_get_root(schedule);
5296 isl_schedule_free(schedule);
5297 node = isl_schedule_node_child(node, 0);
5298 node = isl_schedule_node_child(node, 0);
5299 node = isolate_permutable_subtrees(node, gen->prog);
5300 domain = isl_schedule_node_get_domain(node);
5301 contraction = isl_schedule_node_get_subtree_contraction(node);
5302 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5303 isl_union_pw_multi_aff_copy(contraction));
5304 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
5305 prefix = isl_union_map_preimage_domain_union_pw_multi_aff(prefix,
5306 contraction);
5307 node = mark_kernels(gen, node);
5308 node = add_to_from_device(node, domain, prefix, gen->prog);
5309 node = isl_schedule_node_root(node);
5310 node = isl_schedule_node_child(node, 0);
5311 node = isl_schedule_node_child(node, 0);
5312 node = isl_schedule_node_insert_guard(node, guard);
5313 node = isl_schedule_node_child(node, 0);
5314 node = add_init_clear_device(node);
5315 schedule = isl_schedule_node_get_schedule(node);
5316 isl_schedule_node_free(node);
5318 return schedule;
5321 /* Internal data structure for extract_access.
5322 * "next_access" points to the end of a linked list that is extended
5323 * by extract_access.
5324 * "single_expression" is set if the access expressions belong to
5325 * an expression statement (i.e., a statement without internal control).
5326 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5328 struct ppcg_extract_access_data {
5329 struct gpu_stmt_access **next_access;
5330 int single_expression;
5331 isl_union_map *any_to_outer;
5334 /* Given a tagged access relation to a single array "tagged", extract it
5335 * as a map, taking into account that the input may be empty.
5336 * If the access relation is empty, then it does not contain
5337 * any space information, so we try to recover it from the index
5338 * expression.
5339 * The space of the index expression is of the form I -> A,
5340 * with I the statement instances and A the array, or [I -> F] -> A,
5341 * with F the filters corresponding to arguments.
5342 * We first drop F, if present, obtaining I -> A.
5343 * Then we construct I -> R, with R the reference tag,
5344 * combine the two into I -> [R -> A] and uncurry to obtain
5345 * the final result [I -> R] -> A.
5346 * Note that the index expression may have a lower dimension
5347 * than that of the array, but this dimension is not used
5348 * if the access relation is empty.
5350 static __isl_give isl_map *extract_single_tagged_access(
5351 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5353 int empty;
5354 isl_id *id;
5355 isl_space *space, *space2;
5356 isl_multi_pw_aff *index;
5358 empty = isl_union_map_is_empty(tagged);
5359 if (empty < 0)
5360 goto error;
5361 if (!empty)
5362 return isl_map_from_union_map(tagged);
5363 isl_union_map_free(tagged);
5365 index = pet_expr_access_get_index(expr);
5366 space = isl_multi_pw_aff_get_space(index);
5367 isl_multi_pw_aff_free(index);
5368 if (isl_space_domain_is_wrapping(space))
5369 space = isl_space_domain_factor_domain(space);
5370 space2 = isl_space_copy(space);
5371 space2 = isl_space_from_domain(isl_space_domain(space));
5372 id = pet_expr_access_get_ref_id(expr);
5373 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5374 space = isl_space_range_product(space2, space);
5375 space = isl_space_uncurry(space);
5377 return isl_map_empty(space);
5378 error:
5379 isl_union_map_free(tagged);
5380 return NULL;
5383 /* Does the index expression "index" of "expr" represent an access
5384 * to a single element?
5385 * That is, is "index" completely specified?
5387 * If "expr" accesses elements from different spaces (i.e., fields
5388 * of a structure), then it does not access a single element.
5389 * Otherwise, if the single space of the access matches the space
5390 * of "index", then the index expression is completely specified
5391 * (no pointer to a lower-dimensional slice of the accessed array)
5392 * and a single element is being accessed.
5394 static isl_bool complete_index(__isl_keep pet_expr *expr,
5395 __isl_keep isl_multi_pw_aff *index)
5397 isl_union_map *read, *write, *all;
5398 isl_map *map;
5399 isl_space *space1, *space2;
5400 isl_bool complete;
5402 read = pet_expr_access_get_may_read(expr);
5403 write = pet_expr_access_get_may_write(expr);
5404 all = isl_union_map_union(read, write);
5405 if (!all)
5406 return isl_bool_error;
5407 if (isl_union_map_n_map(all) != 1) {
5408 isl_union_map_free(all);
5409 return isl_bool_false;
5411 map = isl_map_from_union_map(all);
5412 space1 = isl_map_get_space(map);
5413 isl_map_free(map);
5414 space2 = isl_multi_pw_aff_get_space(index);
5415 complete = isl_space_tuple_is_equal(space1, isl_dim_out,
5416 space2, isl_dim_out);
5417 isl_space_free(space1);
5418 isl_space_free(space2);
5420 return complete;
5423 /* Does "expr" access a single, fixed element (independently of the statement
5424 * instance)?
5425 * That is, does it have a completely specified constant index expression?
5427 * Note that it is not sufficient for the index expression to be
5428 * piecewise constant. isl_multi_pw_aff_is_cst can therefore not be used.
5430 static isl_bool accesses_fixed_element(__isl_keep pet_expr *expr)
5432 int i, n;
5433 isl_multi_pw_aff *index;
5434 isl_bool fixed = isl_bool_true;
5436 index = pet_expr_access_get_index(expr);
5437 if (index < 0)
5438 return isl_bool_error;
5439 n = isl_multi_pw_aff_dim(index, isl_dim_out);
5440 for (i = 0; i < n; ++i) {
5441 isl_pw_aff *pa;
5443 pa = isl_multi_pw_aff_get_pw_aff(index, 0);
5444 fixed = isl_pw_aff_n_piece(pa) == 1;
5445 if (fixed)
5446 fixed = isl_pw_aff_is_cst(pa);
5447 isl_pw_aff_free(pa);
5448 if (fixed < 0 || !fixed)
5449 break;
5451 if (fixed >= 0 && fixed)
5452 fixed = complete_index(expr, index);
5453 isl_multi_pw_aff_free(index);
5455 return fixed;
5458 /* Extract a gpu_stmt_access from "expr", append it to the list
5459 * that ends in *data->next_access and update the end of the list.
5460 * If the access expression performs a write, then it is considered
5461 * exact only if it appears in a single expression statement and
5462 * if its may access relation is equal to its must access relation.
5464 * The combined set of may accesses may be a union if member accesses
5465 * are involved, but the entire set is derived from a single reference and
5466 * therefore from a single index expression. These accesses therefore
5467 * all map to the same outer array.
5469 static int extract_access(__isl_keep pet_expr *expr, void *user)
5471 struct ppcg_extract_access_data *data = user;
5472 isl_union_map *tagged;
5473 struct gpu_stmt_access *access;
5474 isl_ctx *ctx = pet_expr_get_ctx(expr);
5475 isl_multi_pw_aff *index;
5477 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5478 assert(access);
5479 access->next = NULL;
5480 access->read = pet_expr_access_is_read(expr);
5481 access->write = pet_expr_access_is_write(expr);
5482 tagged = pet_expr_access_get_tagged_may_read(expr);
5483 tagged = isl_union_map_union(tagged,
5484 pet_expr_access_get_tagged_may_write(expr));
5485 tagged = isl_union_map_apply_range(tagged,
5486 isl_union_map_copy(data->any_to_outer));
5487 if (!access->write) {
5488 access->exact_write = 1;
5489 } else if (!data->single_expression) {
5490 access->exact_write = 0;
5491 } else {
5492 isl_union_map *must, *may;
5493 may = isl_union_map_copy(tagged);
5494 may = isl_union_map_domain_factor_domain(may);
5495 must = pet_expr_access_get_must_write(expr);
5496 access->exact_write = isl_union_map_is_equal(must, may);
5497 isl_union_map_free(must);
5498 isl_union_map_free(may);
5500 index = pet_expr_access_get_index(expr);
5501 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5502 isl_multi_pw_aff_free(index);
5503 access->ref_id = pet_expr_access_get_ref_id(expr);
5504 access->tagged_access = extract_single_tagged_access(tagged, expr);
5505 access->access = isl_map_copy(access->tagged_access);
5506 access->access = isl_map_domain_factor_domain(access->access);
5507 access->fixed_element = accesses_fixed_element(expr);
5509 *data->next_access = access;
5510 data->next_access = &(*data->next_access)->next;
5512 if (!access->access || access->fixed_element < 0)
5513 return -1;
5515 return 0;
5518 /* Construct a linked list of gpu_stmt_access objects,
5519 * one for each access expression in the statement body.
5520 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5522 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5523 __isl_keep isl_union_map *any_to_outer)
5525 struct ppcg_extract_access_data data;
5527 stmt->accesses = NULL;
5528 data.next_access = &stmt->accesses;
5529 data.single_expression =
5530 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5531 data.any_to_outer = any_to_outer;
5532 return pet_tree_foreach_access_expr(stmt->stmt->body,
5533 &extract_access, &data);
5536 /* Has statement "stmt" been killed from "scop"?
5537 * That is, is the instance set of "scop" free from any
5538 * instances of "stmt"?
5540 static isl_bool is_stmt_killed(struct ppcg_scop *scop, struct pet_stmt *stmt)
5542 isl_space *space;
5543 isl_set *left;
5544 isl_bool empty;
5546 if (!scop || !stmt)
5547 return isl_bool_error;
5548 space = isl_set_get_space(stmt->domain);
5549 left = isl_union_set_extract_set(scop->domain, space);
5550 empty = isl_set_plain_is_empty(left);
5551 isl_set_free(left);
5553 return empty;
5556 /* Return an array of gpu_stmt representing the statements in "scop".
5557 * Do not collect array accesses for statements that have been killed.
5559 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5560 __isl_keep isl_union_map *any_to_outer)
5562 int i;
5563 struct gpu_stmt *stmts;
5565 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5566 if (!stmts)
5567 return NULL;
5569 for (i = 0; i < scop->pet->n_stmt; ++i) {
5570 struct gpu_stmt *s = &stmts[i];
5571 isl_bool killed;
5573 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5574 s->stmt = scop->pet->stmts[i];
5575 killed = is_stmt_killed(scop, scop->pet->stmts[i]);
5576 if (killed < 0)
5577 return free_stmts(stmts, i + 1);
5578 if (killed)
5579 continue;
5580 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5581 return free_stmts(stmts, i + 1);
5584 return stmts;
5587 /* Generate CUDA code for "scop" and print it to "p".
5588 * After generating an AST for the transformed scop as explained below,
5589 * we call "gen->print" to print the AST in the desired output format
5590 * to "p".
5592 * If it turns out that it does not make sense to generate GPU code,
5593 * then we generate CPU code instead.
5595 * The declarations of the arrays that are visible outside of the scop
5596 * are printed outside of the code generated from the schedule,
5597 * because the generated code may involve a guard around the entire code.
5599 * We first compute a schedule that respects the dependences
5600 * of the original program and select the outermost bands
5601 * of tilable dimensions that have at least one parallel loop.
5602 * If the --load-schedule is specified, then the loaded schedule
5603 * is used instead of a computed schedule.
5605 * Each of these bands B is then tiled according to "tile" sizes, resulting
5606 * in two nested bands, with a kernel marker on top
5614 * We then split off at most 2 parallel dimensions from the T band and
5615 * at most 3 parallel dimension from the P band
5620 * T1
5622 * T2
5624 * P1
5626 * P2
5628 * A filter is introduced in front of T1 that maps the domain instances
5629 * to block identifiers. Similarly, a filter is introduced in front of P1
5630 * that maps the domain instances to thread identifiers.
5632 * For each iteration of the T2 band and for each array, we compute
5633 * the array elements accessed by that iteration, construct a rectangular
5634 * box around it and shift it to the origin. The result is used
5635 * as shared memory for the array.
5637 * Copying and synchronization statements are added to this schedule tree.
5638 * In principle, these are added in front of the P1 band, but some of
5639 * them may get hoisted up to higher levels.
5641 * The entire AST is then generated from the single resulting schedule tree.
5642 * During the generation the subtrees at kernel nodes (K) are saved
5643 * aside and replaced by kernel calls. The result is printed as host code
5644 * while the saved subtrees are printed as device code.
5646 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5647 struct gpu_gen *gen, struct ppcg_scop *scop,
5648 struct ppcg_options *options)
5650 struct gpu_prog *prog;
5651 isl_ctx *ctx;
5652 isl_schedule *schedule;
5653 int any_permutable;
5655 if (!scop)
5656 return isl_printer_free(p);
5658 ctx = isl_printer_get_ctx(p);
5659 prog = gpu_prog_alloc(ctx, scop);
5660 if (!prog)
5661 return isl_printer_free(p);
5663 gen->prog = prog;
5664 schedule = get_schedule(gen);
5666 any_permutable = has_any_permutable_node(schedule);
5667 if (any_permutable < 0 || !any_permutable) {
5668 if (any_permutable < 0)
5669 p = isl_printer_free(p);
5670 else
5671 p = print_cpu(p, scop, options);
5672 isl_schedule_free(schedule);
5673 } else {
5674 schedule = map_to_device(gen, schedule);
5675 gen->tree = generate_code(gen, schedule);
5676 p = ppcg_set_macro_names(p);
5677 p = ppcg_print_exposed_declarations(p, prog->scop);
5678 p = gen->print(p, gen->prog, gen->tree, &gen->types,
5679 gen->print_user);
5680 isl_ast_node_free(gen->tree);
5683 gpu_prog_free(prog);
5685 return p;
5688 /* Wrapper around generate for use as a ppcg_transform callback.
5690 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5691 struct ppcg_scop *scop, void *user)
5693 struct gpu_gen *gen = user;
5695 return generate(p, gen, scop, gen->options);
5698 /* Transform the code in the file called "input" by replacing
5699 * all scops by corresponding GPU code and write the results to "out".
5701 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5702 struct ppcg_options *options,
5703 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5704 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5705 struct gpu_types *types, void *user), void *user)
5707 struct gpu_gen gen;
5708 int r;
5709 int i;
5711 gen.ctx = ctx;
5712 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5713 gen.options = options;
5714 gen.kernel_id = 0;
5715 gen.print = print;
5716 gen.print_user = user;
5717 gen.types.n = 0;
5718 gen.types.name = NULL;
5720 if (options->debug->dump_sizes) {
5721 isl_space *space = isl_space_params_alloc(ctx, 0);
5722 gen.used_sizes = isl_union_map_empty(space);
5725 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5727 if (options->debug->dump_sizes) {
5728 isl_union_map_dump(gen.used_sizes);
5729 isl_union_map_free(gen.used_sizes);
5732 isl_union_map_free(gen.sizes);
5733 for (i = 0; i < gen.types.n; ++i)
5734 free(gen.types.name[i]);
5735 free(gen.types.name);
5737 return r;
5740 /* Compute the set of inner array elements that may have their values
5741 * preserved by "prog". In particular, collect the array elements of
5742 * arrays that are not local to "prog" and remove those elements that
5743 * are definitely killed or definitely written by "prog".
5745 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5747 int i;
5748 isl_union_set *may_persist, *killed;
5749 isl_union_map *must_kill;
5751 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5752 for (i = 0; i < prog->n_array; ++i) {
5753 isl_set *extent;
5755 if (prog->array[i].local)
5756 continue;
5758 extent = isl_set_copy(prog->array[i].extent);
5759 may_persist = isl_union_set_add_set(may_persist, extent);
5762 may_persist = isl_union_set_intersect_params(may_persist,
5763 isl_set_copy(prog->context));
5764 may_persist = isl_union_set_apply(may_persist,
5765 isl_union_map_copy(prog->to_inner));
5766 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5767 killed = isl_union_map_range(must_kill);
5768 must_kill = isl_union_map_copy(prog->must_write);
5769 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5771 may_persist = isl_union_set_subtract(may_persist, killed);
5772 return may_persist;
5775 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5777 struct gpu_prog *prog;
5778 isl_space *space;
5779 isl_map *id;
5781 if (!scop)
5782 return NULL;
5784 prog = isl_calloc_type(ctx, struct gpu_prog);
5785 assert(prog);
5787 prog->ctx = ctx;
5788 prog->scop = scop;
5789 prog->context = isl_set_copy(scop->context);
5790 prog->n_stmts = scop->pet->n_stmt;
5791 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5792 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5793 space = isl_union_map_get_space(prog->any_to_outer);
5794 space = isl_space_set_from_params(space);
5795 space = isl_space_add_dims(space, isl_dim_set, 1);
5796 space = isl_space_map_from_set(space);
5797 id = isl_map_identity(space);
5798 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5799 prog->stmts = extract_stmts(ctx, scop, prog->any_to_outer);
5800 prog->read = isl_union_map_copy(scop->reads);
5801 prog->may_write = isl_union_map_copy(scop->may_writes);
5802 prog->must_write = isl_union_map_copy(scop->must_writes);
5803 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5804 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5805 prog->to_outer = isl_union_map_copy(prog->to_inner);
5806 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5808 if (!prog->stmts)
5809 return gpu_prog_free(prog);
5811 if (collect_array_info(prog) < 0)
5812 return gpu_prog_free(prog);
5813 prog->may_persist = compute_may_persist(prog);
5815 return prog;
5818 void *gpu_prog_free(struct gpu_prog *prog)
5820 if (!prog)
5821 return NULL;
5822 free_array_info(prog);
5823 free_stmts(prog->stmts, prog->n_stmts);
5824 isl_union_map_free(prog->any_to_outer);
5825 isl_union_map_free(prog->to_outer);
5826 isl_union_map_free(prog->to_inner);
5827 isl_union_map_free(prog->read);
5828 isl_union_map_free(prog->may_write);
5829 isl_union_map_free(prog->must_write);
5830 isl_union_map_free(prog->tagged_must_kill);
5831 isl_union_map_free(prog->array_order);
5832 isl_union_set_free(prog->may_persist);
5833 isl_set_free(prog->context);
5834 free(prog);
5835 return NULL;