Remove unused variable never used
[ppcg.git] / gpu.c
blob2e83964c8a8bb873b447144bed705be38520726e
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/schedule.h>
23 #include <isl/schedule_node.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "gpu_array_tile.h"
30 #include "gpu_group.h"
31 #include "gpu_tree.h"
32 #include "schedule.h"
33 #include "ppcg_options.h"
34 #include "print.h"
35 #include "util.h"
37 struct gpu_array_info;
39 /* Return the name of the outer array (of structs) accessed by "access".
41 static const char *get_outer_array_name(__isl_keep isl_map *access)
43 isl_space *space;
44 const char *name;
46 space = isl_space_range(isl_map_get_space(access));
47 while (space && isl_space_is_wrapping(space))
48 space = isl_space_domain(isl_space_unwrap(space));
49 name = isl_space_get_tuple_name(space, isl_dim_set);
50 isl_space_free(space);
52 return name;
55 /* Collect all references to the given array and store pointers to them
56 * in array->refs.
58 static void collect_references(struct gpu_prog *prog,
59 struct gpu_array_info *array)
61 int i;
62 int n;
64 n = 0;
65 for (i = 0; i < prog->n_stmts; ++i) {
66 struct gpu_stmt *stmt = &prog->stmts[i];
67 struct gpu_stmt_access *access;
69 for (access = stmt->accesses; access; access = access->next) {
70 const char *name;
71 name = get_outer_array_name(access->access);
72 if (name && !strcmp(array->name, name))
73 n++;
77 array->n_ref = n;
78 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
79 assert(array->refs);
81 n = 0;
82 for (i = 0; i < prog->n_stmts; ++i) {
83 struct gpu_stmt *stmt = &prog->stmts[i];
84 struct gpu_stmt_access *access;
86 for (access = stmt->accesses; access; access = access->next) {
87 const char *name;
88 name = get_outer_array_name(access->access);
89 if (!name || strcmp(array->name, name))
90 continue;
92 array->refs[n++] = access;
97 /* Compute and return the extent of "array", taking into account the set of
98 * accessed elements.
100 * In particular, the extent in the outer dimension is taken
101 * from "accessed", while the extents in the remaining dimensions
102 * are taken from array->extent.
104 * The extent in the outer dimension cannot be taken from array->extent
105 * because that may be unbounded. Furthermore, even if it is bounded,
106 * it may be larger than the piece of the array that is being accessed.
108 static __isl_give isl_set *compute_extent(struct pet_array *array,
109 __isl_keep isl_set *accessed)
111 int n_index;
112 isl_id *id;
113 isl_set *outer;
114 isl_set *extent;
116 extent = isl_set_copy(array->extent);
118 n_index = isl_set_dim(accessed, isl_dim_set);
119 if (n_index == 0)
120 return extent;
122 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
123 outer = isl_set_copy(accessed);
124 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
125 extent = isl_set_flat_product(outer, extent);
126 id = isl_set_get_tuple_id(accessed);
127 extent = isl_set_set_tuple_id(extent, id);
129 return extent;
132 /* Is the array "array" being extracted a read-only scalar?
134 * That is, is "array" a scalar that is never possibly written to.
135 * An array containing structures is never considered to be a scalar.
137 static int is_read_only_scalar(struct gpu_array_info *array,
138 struct gpu_prog *prog)
140 isl_set *space;
141 isl_union_map *write;
142 int empty;
144 if (array->has_compound_element)
145 return 0;
146 if (array->n_index != 0)
147 return 0;
149 write = isl_union_map_copy(prog->may_write);
150 space = isl_set_universe(isl_space_copy(array->space));
151 write = isl_union_map_intersect_range(write,
152 isl_union_set_from_set(space));
153 empty = isl_union_map_is_empty(write);
154 isl_union_map_free(write);
156 return empty;
159 /* Compute bounds on the host array "pa" based on the corresponding
160 * accessed elements in "arrays"
161 * and collect all references to the array.
162 * Store the results in "info".
164 * If the array is zero-dimensional and does not contain structures,
165 * i.e., if the array is a scalar, we check whether it is read-only.
166 * We also check whether the array is accessed at all.
168 static int extract_array_info(struct gpu_prog *prog,
169 struct gpu_array_info *info, struct pet_array *pa,
170 __isl_keep isl_union_set *arrays)
172 int empty;
173 const char *name;
174 int n_index;
175 isl_multi_pw_aff *bounds;
176 isl_set *accessed, *extent;
178 n_index = isl_set_dim(pa->extent, isl_dim_set);
179 name = isl_set_get_tuple_name(pa->extent);
181 info->space = isl_set_get_space(pa->extent);
182 info->name = strdup(name);
183 info->n_index = n_index;
184 info->linearize = prog->scop->options->linearize_device_arrays;
186 info->type = strdup(pa->element_type);
187 info->size = pa->element_size;
188 info->local = pa->declared && !pa->exposed;
189 info->has_compound_element = pa->element_is_record;
190 info->read_only_scalar = is_read_only_scalar(info, prog);
192 accessed = isl_union_set_extract_set(arrays,
193 isl_space_copy(info->space));
194 empty = isl_set_is_empty(accessed);
195 extent = compute_extent(pa, accessed);
196 isl_set_free(accessed);
197 info->extent = extent;
198 if (empty < 0)
199 return -1;
200 info->accessed = !empty;
201 bounds = ppcg_size_from_extent(isl_set_copy(extent));
202 bounds = isl_multi_pw_aff_gist(bounds, isl_set_copy(prog->context));
203 if (!bounds)
204 return -1;
205 if (!isl_multi_pw_aff_is_cst(bounds))
206 info->linearize = 1;
207 info->bound = bounds;
209 collect_references(prog, info);
211 return 0;
214 /* Remove independence from the order constraints "order" on array "array".
215 * Since the pairs of iterations in the filter relation of an independence
216 * are guaranteed to be completely independent by the user, there is
217 * no need to ensure that live ranges are ordered along thong pairs.
218 * We make an exception for local variables, though, as the independence
219 * guarantee does not apply to those.
221 * The order constraints are used in two places.
222 * Those on scalars are used in check_scalar_live_ranges to check if
223 * we need to force the scalar to be private. Any non-local scalar
224 * should not be forced scalar if it only appears in independent loops.
225 * Those on non-scalars are added to the coincidence constraints
226 * in compute_schedule because we do not support any array expansion.
227 * Accesses to non-local arrays should not prevent a loop from being
228 * considered coincident so we should indeed remove those constraints
229 * from the order constraints.
231 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
232 struct gpu_array_info *array, __isl_take isl_union_map *order)
234 int i;
236 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
237 struct pet_independence *pi = prog->scop->pet->independences[i];
238 if (isl_union_set_contains(pi->local, array->space))
239 continue;
241 order = isl_union_map_subtract(order,
242 isl_union_map_copy(pi->filter));
245 return order;
248 /* For each array in "prog", store the (untagged) order dependences
249 * derived from the array in array->dep_order.
250 * In particular, consider all references that access the given array
251 * and take the order dependences that have one of these references
252 * as source. (Since an order dependence relates two references to
253 * the same array, the target of these order dependences will also
254 * be one of these references.)
255 * Additionally, store the union of these array->dep_order relations
256 * for all non-scalar arrays in prog->array_order.
258 void collect_order_dependences(struct gpu_prog *prog)
260 int i;
261 isl_space *space;
262 isl_union_map *accesses;
264 space = isl_union_map_get_space(prog->read);
265 prog->array_order = isl_union_map_empty(space);
267 accesses = isl_union_map_copy(prog->scop->tagged_reads);
268 accesses = isl_union_map_union(accesses,
269 isl_union_map_copy(prog->scop->tagged_may_writes));
270 accesses = isl_union_map_universe(accesses);
271 accesses = isl_union_map_apply_range(accesses,
272 isl_union_map_copy(prog->to_outer));
274 for (i = 0; i < prog->n_array; ++i) {
275 struct gpu_array_info *array = &prog->array[i];
276 isl_set *set;
277 isl_union_set *uset;
278 isl_union_map *order;
280 set = isl_set_universe(isl_space_copy(array->space));
281 uset = isl_union_set_from_set(set);
282 uset = isl_union_map_domain(
283 isl_union_map_intersect_range(isl_union_map_copy(accesses),
284 uset));
285 order = isl_union_map_copy(prog->scop->tagged_dep_order);
286 order = isl_union_map_intersect_domain(order, uset);
287 order = isl_union_map_zip(order);
288 order = isl_union_set_unwrap(isl_union_map_domain(order));
289 order = remove_independences(prog, array, order);
290 array->dep_order = order;
292 if (gpu_array_is_scalar(array) && !array->has_compound_element)
293 continue;
295 prog->array_order = isl_union_map_union(prog->array_order,
296 isl_union_map_copy(array->dep_order));
299 isl_union_map_free(accesses);
302 /* Construct a gpu_array_info for each array referenced by prog->scop and
303 * collect them in prog->array.
305 * The sizes are based on the extents and the set of possibly accessed
306 * elements by "prog".
307 * If there are any member accesses involved, then they are first mapped
308 * to the outer arrays of structs.
310 * If we are allowing live range reordering, then also set
311 * the dep_order field. Otherwise leave it NULL.
313 static int collect_array_info(struct gpu_prog *prog)
315 int i;
316 int r = 0;
317 isl_union_set *arrays;
319 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
320 arrays = isl_union_set_union(arrays,
321 isl_union_map_range(isl_union_map_copy(prog->may_write)));
323 arrays = isl_union_set_apply(arrays,
324 isl_union_map_copy(prog->to_outer));
326 arrays = isl_union_set_coalesce(arrays);
328 prog->n_array = prog->scop->pet->n_array;
329 prog->array = isl_calloc_array(prog->ctx,
330 struct gpu_array_info, prog->n_array);
331 assert(prog->array);
332 for (i = 0; i < prog->scop->pet->n_array; ++i)
333 if (extract_array_info(prog, &prog->array[i],
334 prog->scop->pet->arrays[i], arrays) < 0)
335 r = -1;
337 isl_union_set_free(arrays);
339 if (prog->scop->options->live_range_reordering)
340 collect_order_dependences(prog);
342 return r;
345 static void free_array_info(struct gpu_prog *prog)
347 int i;
349 for (i = 0; i < prog->n_array; ++i) {
350 int n_index = prog->array[i].n_index;
351 free(prog->array[i].type);
352 free(prog->array[i].name);
353 isl_multi_pw_aff_free(prog->array[i].bound);
354 isl_ast_expr_free(prog->array[i].bound_expr);
355 isl_space_free(prog->array[i].space);
356 isl_set_free(prog->array[i].extent);
357 isl_ast_expr_free(prog->array[i].declared_size);
358 free(prog->array[i].refs);
359 isl_union_map_free(prog->array[i].dep_order);
361 free(prog->array);
364 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
365 * as an array or through a pointer reference, but as a single data element.
366 * At the moment, scalars are represented as zero-dimensional arrays.
367 * Note that the single data element may be an entire structure.
369 int gpu_array_is_scalar(struct gpu_array_info *array)
371 return array->n_index == 0;
374 /* Is "array" a read-only scalar?
376 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
378 return array->read_only_scalar;
381 /* Does "array" need to be allocated on the device?
382 * If it is a read-only scalar, then it will be passed as an argument
383 * to the kernel and therefore does not require any allocation.
384 * If this device memory is not accessed at all, then it does not
385 * need to be allocated either.
387 int gpu_array_requires_device_allocation(struct gpu_array_info *array)
389 if (gpu_array_is_read_only_scalar(array))
390 return 0;
391 if (!array->global)
392 return 0;
393 return 1;
396 /* Return the set of parameter values for which the array has a positive
397 * size in all dimensions.
398 * If the sizes are only valid for some parameter values, then those
399 * constraints are also taken into account.
401 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
403 int i;
404 isl_space *space;
405 isl_set *guard;
407 if (!array)
408 return NULL;
410 space = isl_space_params(isl_space_copy(array->space));
411 guard = isl_set_universe(space);
413 for (i = 0; i < array->n_index; ++i) {
414 isl_pw_aff *bound;
415 isl_set *guard_i, *zero;
417 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
418 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
419 zero = isl_pw_aff_zero_set(bound);
420 guard_i = isl_set_subtract(guard_i, zero);
421 guard = isl_set_intersect(guard, guard_i);
424 return guard;
427 /* Internal data structure for extract_size_of_type.
428 * "type" specifies the name of the space that we want to extract.
429 * "res" is used to store the subset of that space.
431 struct ppcg_extract_size_data {
432 const char *type;
433 isl_set *res;
436 /* This function is called for each set in a union_set.
437 * If the name of the set matches data->type, we store the
438 * set in data->res.
440 static isl_stat extract_size_of_type(__isl_take isl_set *size, void *user)
442 struct ppcg_extract_size_data *data = user;
443 const char *name;
445 name = isl_set_get_tuple_name(size);
446 if (name && !strcmp(name, data->type)) {
447 data->res = size;
448 return isl_stat_error;
451 isl_set_free(size);
452 return isl_stat_ok;
455 /* Given a union map { kernel[i] -> *[...] },
456 * return the range in the space called "type" for the kernel with
457 * sequence number "id".
459 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
460 const char *type, int id)
462 isl_space *space;
463 isl_set *dom;
464 isl_union_set *local_sizes;
465 struct ppcg_extract_size_data data = { type, NULL };
467 if (!sizes)
468 return NULL;
470 space = isl_union_map_get_space(sizes);
471 space = isl_space_set_from_params(space);
472 space = isl_space_add_dims(space, isl_dim_set, 1);
473 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
474 dom = isl_set_universe(space);
475 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
477 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
478 isl_union_map_copy(sizes));
479 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
480 isl_union_set_free(local_sizes);
481 return data.res;
484 /* Given a singleton set, extract the first (at most *len) elements
485 * of the single integer tuple into *sizes and update *len if needed.
487 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
489 int i;
490 int dim;
492 if (!set)
493 return;
495 dim = isl_set_dim(set, isl_dim_set);
496 if (dim < *len)
497 *len = dim;
499 for (i = 0; i < *len; ++i) {
500 isl_val *v;
502 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
503 assert(v);
505 sizes[i] = isl_val_get_num_si(v);
506 isl_val_free(v);
509 isl_set_free(set);
512 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
513 * if the option debug->dump_sizes is set.
515 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
516 int *sizes, int len)
518 int i;
519 isl_space *space;
520 isl_map *map;
522 if (!gen->options->debug->dump_sizes)
523 return;
525 space = isl_union_map_get_space(gen->used_sizes);
526 space = isl_space_set_from_params(space);
527 space = isl_space_add_dims(space, isl_dim_set, 1);
528 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
529 space = isl_space_from_domain(space);
530 space = isl_space_add_dims(space, isl_dim_out, len);
531 space = isl_space_set_tuple_name(space, isl_dim_out, type);
533 map = isl_map_universe(space);
534 map = isl_map_fix_si(map, isl_dim_in, 0, id);
535 for (i = 0; i < len; ++i)
536 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
538 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
541 /* Extract user specified "tile" sizes from the "sizes" command line option,
542 * defaulting to option->tile_size in each dimension.
543 * *tile_len contains the maximum number of tile sizes needed.
544 * Update *tile_len to the number of specified tile sizes, if any, and
545 * return a pointer to the tile sizes (or NULL on error).
546 * Add the effectively used sizes to gen->used_sizes.
548 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
550 int n;
551 int *tile_size;
552 isl_set *size;
554 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
555 if (!tile_size)
556 return NULL;
557 for (n = 0; n < *tile_len; ++n)
558 tile_size[n] = gen->options->tile_size;
560 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
561 read_sizes_from_set(size, tile_size, tile_len);
562 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
564 return tile_size;
567 /* Extract user specified "block" sizes from the "sizes" command line option,
568 * after filling in some potentially useful defaults.
570 static void read_block_sizes(struct ppcg_kernel *kernel,
571 __isl_keep isl_union_map *sizes)
573 isl_set *size;
575 if (kernel->n_block > 3)
576 kernel->n_block = 3;
577 switch (kernel->n_block) {
578 case 1:
579 kernel->block_dim[0] = 512;
580 break;
581 case 2:
582 kernel->block_dim[0] = 32;
583 kernel->block_dim[1] = 16;
584 break;
585 default:
586 kernel->block_dim[0] = 32;
587 kernel->block_dim[1] = 4;
588 kernel->block_dim[2] = 4;
589 break;
592 size = extract_sizes(sizes, "block", kernel->id);
593 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
596 /* Extract user specified "grid" sizes from the "sizes" command line option,
597 * after filling in some potentially useful defaults.
599 static void read_grid_sizes(struct ppcg_kernel *kernel,
600 __isl_keep isl_union_map *sizes)
602 isl_set *size;
604 if (kernel->n_grid > 2)
605 kernel->n_grid = 2;
606 switch (kernel->n_grid) {
607 case 1:
608 kernel->grid_dim[0] = 32768;
609 break;
610 default:
611 kernel->grid_dim[0] = 256;
612 kernel->grid_dim[1] = 256;
613 break;
616 size = extract_sizes(sizes, "grid", kernel->id);
617 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
620 /* Extract user specified grid and block sizes from the gen->sizes
621 * command line option after filling in some potentially useful defaults.
622 * Store the extracted sizes in "kernel".
623 * Add the effectively used sizes to gen->used_sizes.
625 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
626 struct gpu_gen *gen)
628 read_block_sizes(kernel, gen->sizes);
629 read_grid_sizes(kernel, gen->sizes);
630 set_used_sizes(gen, "block", kernel->id,
631 kernel->block_dim, kernel->n_block);
632 set_used_sizes(gen, "grid", kernel->id,
633 kernel->grid_dim, kernel->n_grid);
636 static void *free_stmts(struct gpu_stmt *stmts, int n)
638 int i;
640 if (!stmts)
641 return NULL;
643 for (i = 0; i < n; ++i) {
644 struct gpu_stmt_access *access, *next;
646 for (access = stmts[i].accesses; access; access = next) {
647 next = access->next;
648 isl_id_free(access->ref_id);
649 isl_map_free(access->access);
650 isl_map_free(access->tagged_access);
651 free(access);
654 isl_id_free(stmts[i].id);
656 free(stmts);
658 return NULL;
661 /* Add parameters p[i] with identifiers "ids" to "set",
662 * with bounds to 0 <= p[i] < size[i].
664 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
665 int *size, __isl_keep isl_id_list *ids)
667 int i, len;
668 unsigned nparam;
670 len = isl_id_list_n_id(ids);
671 nparam = isl_set_dim(set, isl_dim_param);
672 set = isl_set_add_dims(set, isl_dim_param, len);
674 for (i = 0; i < len; ++i) {
675 isl_id *id;
677 id = isl_id_list_get_id(ids, i);
678 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
679 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
680 set = isl_set_upper_bound_si(set, isl_dim_param,
681 nparam + i, size[i] - 1);
684 return set;
687 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
688 * with
690 * { : 0 <= p[i] < size[i] }
692 * or an overapproximation.
694 static __isl_give isl_set *add_bounded_parameters_dynamic(
695 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
696 __isl_keep isl_id_list *ids)
698 int i, len;
699 unsigned nparam;
700 isl_space *space;
701 isl_local_space *ls;
703 len = isl_multi_pw_aff_dim(size, isl_dim_out);
704 nparam = isl_set_dim(set, isl_dim_param);
705 set = isl_set_add_dims(set, isl_dim_param, len);
707 for (i = 0; i < len; ++i) {
708 isl_id *id;
710 id = isl_id_list_get_id(ids, i);
711 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
714 space = isl_space_params(isl_set_get_space(set));
715 ls = isl_local_space_from_space(space);
716 for (i = 0; i < len; ++i) {
717 isl_pw_aff *param, *size_i, *zero;
718 isl_set *bound;
720 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
721 isl_dim_param, nparam + i);
723 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
724 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
725 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
726 set = isl_set_intersect_params(set, bound);
728 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
729 bound = isl_pw_aff_ge_set(param, zero);
730 set = isl_set_intersect_params(set, bound);
732 isl_local_space_free(ls);
734 return set;
737 /* Return the union of all tagged access relations in the group.
739 static __isl_give isl_union_map *group_tagged_access_relation(
740 struct gpu_array_ref_group *group)
742 int i;
743 isl_union_map *access;
745 access = isl_union_map_empty(isl_map_get_space(group->access));
746 for (i = 0; i < group->n_ref; ++i) {
747 isl_map *map_i;
749 map_i = isl_map_copy(group->refs[i]->tagged_access);
750 access = isl_union_map_union(access,
751 isl_union_map_from_map(map_i));
754 return access;
757 /* Return the extent of "array", recomputed from the bounds.
758 * The recomputed extent may be simpler than the original extent.
760 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
762 int i;
763 isl_id *id;
764 isl_space *space;
765 isl_local_space *ls;
766 isl_set *extent;
768 id = isl_set_get_tuple_id(array->extent);
769 space = isl_set_get_space(array->extent);
770 extent = isl_set_universe(isl_space_copy(space));
771 ls = isl_local_space_from_space(space);
772 for (i = 0; i < array->n_index; ++i) {
773 isl_pw_aff *bound;
774 isl_aff *aff;
775 isl_pw_aff *index;
776 isl_set *lt;
778 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
780 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
781 isl_dim_set, i);
782 index = isl_pw_aff_from_aff(aff);
783 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
784 bound = isl_pw_aff_from_range(bound);
785 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
786 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
787 isl_id_copy(id));
788 lt = isl_pw_aff_lt_set(index, bound);
789 extent = isl_set_intersect(extent, lt);
791 isl_local_space_free(ls);
792 isl_id_free(id);
794 return extent;
797 /* Return a map from the first group->shared_tile->depth dimensions
798 * of the computed schedule to the array tile in
799 * global memory that corresponds to the shared memory copy.
801 * In particular, return a map
803 * { D[i] -> A[a] }
805 * with constraints
807 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
809 * and
811 * 0 <= a <= array_size - 1 (2)
813 * Note that if some stride has been detected (i.e., when
814 * group->shared_tile->bound[i].shift is set), then a in (1) refers
815 * to the shifted and scaled down version.
817 * Constraints (1) are obtained by mapping the size constraints on the
818 * shared/private memory tile back to the access relation.
819 * Constraints (2) are obtained from the (recomputed) extent.
821 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
823 int i;
824 int n_index = group->array->n_index;
825 isl_map *tile;
826 isl_space *space;
827 isl_set *local;
828 isl_set *extent;
830 space = isl_multi_aff_get_space(group->shared_tile->tiling);
831 space = isl_space_range(space);
832 local = isl_set_universe(space);
833 for (i = 0; i < n_index; ++i) {
834 isl_val *bound;
836 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
837 bound = isl_val_copy(group->shared_tile->bound[i].size);
838 bound = isl_val_sub_ui(bound, 1);
839 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
841 local = isl_set_preimage_multi_aff(local,
842 isl_multi_aff_copy(group->shared_tile->tiling));
843 tile = isl_set_unwrap(local);
844 extent = array_extent(group->array);
845 tile = isl_map_intersect_range(tile, extent);
847 return tile;
850 /* Given a mapping "iterator_map" from the AST schedule to a domain,
851 * return the corresponding mapping from the AST schedule to
852 * to the outer kernel->copy_schedule_dim dimensions of
853 * the schedule computed by PPCG for this kernel.
855 * Note that kernel->copy_schedule_dim is at least as large as
856 * the largest depth of any array reference group associated to the kernel.
857 * This is needed as the returned schedule is used to extract a mapping
858 * to the outer tile->depth dimensions in transform_index.
860 static __isl_give isl_pw_multi_aff *compute_sched_to_copy(
861 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
863 isl_union_pw_multi_aff *upma;
864 isl_pw_multi_aff *pma;
865 isl_space *space;
867 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
868 space = isl_space_from_domain(space);
869 space = isl_space_add_dims(space, isl_dim_out,
870 kernel->copy_schedule_dim);
872 upma = isl_union_pw_multi_aff_copy(kernel->copy_schedule);
873 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
874 isl_union_pw_multi_aff_free(upma);
876 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
879 /* If max_shared_memory is not set to infinity (-1), then make
880 * sure that the total amount of shared memory required by the
881 * array reference groups mapped to shared memory by "kernel"
882 * is no larger than this maximum.
884 * We apply a greedy approach and discard (keep in global memory)
885 * those groups that would result in a total memory size that
886 * is larger than the maximum.
888 * This function should be called after any function that may
889 * affect the decision on whether to place a reference group
890 * in private, shared or global memory.
892 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
894 int i, j;
895 isl_val *left, *size;
897 if (kernel->options->max_shared_memory < 0)
898 return;
900 left = isl_val_int_from_si(kernel->ctx,
901 kernel->options->max_shared_memory);
903 for (i = 0; i < kernel->n_array; ++i) {
904 struct gpu_local_array_info *local = &kernel->array[i];
906 for (j = 0; j < local->n_group; ++j) {
907 struct gpu_array_ref_group *group;
908 enum ppcg_group_access_type type;
910 group = local->groups[j];
911 type = gpu_array_ref_group_type(group);
912 if (type != ppcg_access_shared)
913 continue;
915 size = gpu_array_tile_size(group->shared_tile);
916 size = isl_val_mul_ui(size, local->array->size);
918 if (isl_val_le(size, left)) {
919 left = isl_val_sub(left, size);
920 continue;
922 isl_val_free(size);
924 group->shared_tile =
925 gpu_array_tile_free(group->shared_tile);
929 isl_val_free(left);
932 /* Mark all arrays of "kernel" that have an array reference group
933 * that is not mapped to private or shared memory as
934 * accessing the corresponding global device memory.
936 static void mark_global_arrays(struct ppcg_kernel *kernel)
938 int i, j;
940 for (i = 0; i < kernel->n_array; ++i) {
941 struct gpu_local_array_info *local = &kernel->array[i];
943 if (local->global)
944 continue;
945 for (j = 0; j < local->n_group; ++j) {
946 if (gpu_array_ref_group_tile(local->groups[j]))
947 continue;
949 local->global = 1;
950 local->array->global = 1;
951 break;
956 /* Compute a tiling for all the array reference groups in "kernel".
958 static void compute_group_tilings(struct ppcg_kernel *kernel)
960 int i, j;
962 for (i = 0; i < kernel->n_array; ++i) {
963 struct gpu_local_array_info *array = &kernel->array[i];
965 for (j = 0; j < array->n_group; ++j)
966 gpu_array_ref_group_compute_tiling(array->groups[j]);
970 /* Compute the effective grid size as a list of the sizes in each dimension.
972 * The grid size specified by the user or set by default
973 * in read_grid_sizes() and applied by the block filter,
974 * may be too large for the given code in the sense that
975 * it may contain blocks that don't need to execute anything.
976 * We therefore don't return this grid size, but instead the
977 * smallest grid size that ensures that all blocks that actually
978 * execute code are included in the grid.
980 * We first extract a description of the grid, i.e., the possible values
981 * of the block ids, from the domain elements in "domain" and
982 * kernel->block_filter.
983 * The block ids are parameters in kernel->block_filter.
984 * We simply need to change them into set dimensions.
986 * Then, for each block dimension, we compute the maximal value of the block id
987 * and add one.
989 static __isl_give isl_multi_pw_aff *extract_grid_size(
990 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
992 int i;
993 isl_set *grid;
994 isl_set *context;
995 isl_multi_pw_aff *size;
997 domain = isl_union_set_intersect(domain,
998 isl_union_set_copy(kernel->block_filter));
999 grid = isl_union_set_params(domain);
1000 grid = isl_set_from_params(grid);
1001 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1002 for (i = 0; i < kernel->n_grid; ++i) {
1003 int pos;
1004 isl_id *id;
1006 id = isl_id_list_get_id(kernel->block_ids, i);
1007 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1008 isl_id_free(id);
1009 assert(pos >= 0);
1010 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1011 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1014 grid = isl_set_coalesce(grid);
1015 size = ppcg_size_from_extent(grid);
1016 context = isl_set_params(isl_set_copy(kernel->context));
1017 return isl_multi_pw_aff_gist(size, context);
1020 /* Compute the size of a fixed bounding box around the origin and "set",
1021 * where "set" is assumed to contain only non-negative elements,
1022 * and store the results in "size".
1023 * In particular, compute the maximal value of "set" in each direction
1024 * and add one.
1026 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1028 int i, n;
1029 isl_local_space *ls;
1030 isl_aff *obj;
1032 n = isl_set_dim(set, isl_dim_set);
1033 ls = isl_local_space_from_space(isl_set_get_space(set));
1034 obj = isl_aff_zero_on_domain(ls);
1035 for (i = 0; i < n; ++i) {
1036 isl_val *max;
1038 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1039 max = isl_set_max_val(set, obj);
1040 size[i] = isl_val_get_num_si(max) + 1;
1041 isl_val_free(max);
1042 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1044 isl_aff_free(obj);
1045 isl_set_free(set);
1048 /* Compute the effective block size as a list of the sizes in each dimension
1049 * and store the sizes in kernel->block_dim.
1051 * The block size specified by the user or set by default
1052 * in read_block_sizes() and applied by the thread filter,
1053 * may be too large for the given code in the sense that
1054 * it may contain threads that don't need to execute anything.
1055 * We therefore update this block size in kernel->block_dim
1056 * to the smallest block size that ensures that all threads
1057 * that actually execute code are included in the block.
1059 * The possible values of the thread ids is obtained from
1060 * the domain elements "domain" and kernel->thread_filter.
1061 * The current implementation eliminates all parameters, ensuring
1062 * that the size is a fixed constant in each dimension.
1063 * In principle we could also compute parametric sizes.
1064 * We would have to make sure to project out all b%d and t%d parameters,
1065 * however.
1067 static isl_stat extract_block_size(struct ppcg_kernel *kernel,
1068 __isl_take isl_union_set *domain)
1070 int i;
1071 int nparam;
1072 isl_set *block;
1074 domain = isl_union_set_intersect(domain,
1075 isl_union_set_copy(kernel->thread_filter));
1076 block = isl_union_set_params(domain);
1077 block = isl_set_from_params(block);
1078 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1079 for (i = 0; i < kernel->n_block; ++i) {
1080 int pos;
1081 isl_id *id;
1083 if (!block)
1084 return isl_stat_error;
1086 id = isl_id_list_get_id(kernel->thread_ids, i);
1087 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1088 isl_id_free(id);
1089 if (pos < 0)
1090 isl_die(isl_set_get_ctx(block), isl_error_internal,
1091 "missing constraints on thread identifier",
1092 block = isl_set_free(block));
1093 block = isl_set_equate(block, isl_dim_param, pos,
1094 isl_dim_set, i);
1096 nparam = isl_set_dim(block, isl_dim_param);
1097 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1099 if (!block)
1100 return isl_stat_error;
1102 extract_fixed_size(block, kernel->block_dim);
1104 return isl_stat_ok;
1107 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1109 int i, j;
1111 if (!kernel)
1112 return NULL;
1114 isl_id_list_free(kernel->block_ids);
1115 isl_id_list_free(kernel->thread_ids);
1116 isl_multi_pw_aff_free(kernel->grid_size);
1117 isl_ast_expr_free(kernel->grid_size_expr);
1118 isl_set_free(kernel->context);
1119 isl_union_set_free(kernel->core);
1120 isl_union_set_free(kernel->arrays);
1121 isl_space_free(kernel->space);
1122 isl_ast_node_free(kernel->tree);
1123 isl_union_set_free(kernel->block_filter);
1124 isl_union_set_free(kernel->thread_filter);
1125 isl_union_pw_multi_aff_free(kernel->copy_schedule);
1126 isl_union_set_free(kernel->sync_writes);
1128 for (i = 0; i < kernel->n_array; ++i) {
1129 struct gpu_local_array_info *array = &kernel->array[i];
1131 for (j = 0; j < array->n_group; ++j)
1132 gpu_array_ref_group_free(array->groups[j]);
1133 free(array->groups);
1135 isl_multi_pw_aff_free(array->bound);
1136 isl_ast_expr_free(array->bound_expr);
1138 free(kernel->array);
1140 for (i = 0; i < kernel->n_var; ++i) {
1141 free(kernel->var[i].name);
1142 isl_vec_free(kernel->var[i].size);
1144 free(kernel->var);
1146 free(kernel);
1148 return NULL;
1151 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1153 static void ppcg_kernel_free_wrap(void *user)
1155 struct ppcg_kernel *kernel = user;
1157 ppcg_kernel_free(kernel);
1160 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1161 struct ppcg_kernel_var *var)
1163 int j;
1164 struct gpu_array_tile *tile;
1165 isl_printer *p;
1166 char *name;
1168 var->array = group->array;
1170 var->type = gpu_array_ref_group_type(group);
1171 tile = gpu_array_ref_group_tile(group);
1173 p = isl_printer_to_str(ctx);
1174 p = gpu_array_ref_group_print_name(group, p);
1175 var->name = isl_printer_get_str(p);
1176 isl_printer_free(p);
1178 var->size = isl_vec_alloc(ctx, group->array->n_index);
1180 for (j = 0; j < group->array->n_index; ++j)
1181 var->size = isl_vec_set_element_val(var->size, j,
1182 isl_val_copy(tile->bound[j].size));
1185 static int create_kernel_vars(struct ppcg_kernel *kernel)
1187 int i, j, n;
1189 n = 0;
1190 for (i = 0; i < kernel->n_array; ++i) {
1191 struct gpu_local_array_info *array = &kernel->array[i];
1193 for (j = 0; j < array->n_group; ++j) {
1194 struct gpu_array_ref_group *group = array->groups[j];
1195 enum ppcg_group_access_type type;
1197 type = gpu_array_ref_group_type(group);
1198 if (type != ppcg_access_global)
1199 ++n;
1203 kernel->n_var = n;
1204 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1205 if (!kernel->var)
1206 return -1;
1208 n = 0;
1209 for (i = 0; i < kernel->n_array; ++i) {
1210 struct gpu_local_array_info *array = &kernel->array[i];
1212 for (j = 0; j < array->n_group; ++j) {
1213 struct gpu_array_ref_group *group = array->groups[j];
1214 enum ppcg_group_access_type type;
1216 type = gpu_array_ref_group_type(group);
1217 if (type == ppcg_access_global)
1218 continue;
1219 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1220 ++n;
1224 return 0;
1227 /* Replace "pa" by the zero function defined over the universe domain
1228 * in the space of "pa".
1230 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1232 isl_space *space;
1233 isl_aff *zero;
1235 space = isl_space_domain(isl_pw_aff_get_space(pa));
1236 isl_pw_aff_free(pa);
1237 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1239 return isl_pw_aff_from_aff(zero);
1242 /* The sizes of the arrays on the host that have been computed by
1243 * extract_array_info may depend on the parameters. Use the extra
1244 * constraints on the parameters that are valid at "host_domain"
1245 * to simplify these expressions and store the results in kernel->array.
1247 * We only need these localized bounds for arrays that are accessed
1248 * by the current kernel. If we have found at least one reference group
1249 * then the array is accessed by the kernel.
1251 * The resulting sizes may be functions that are nowhere defined
1252 * in case the access function cannot possibly access anything inside
1253 * the kernel for some reason. If so, they are replaced by the zero
1254 * function. Since the access function cannot actually access anything,
1255 * there is no harm in printing the array sizes as zero.
1257 static void localize_bounds(struct ppcg_kernel *kernel,
1258 __isl_keep isl_set *host_domain)
1260 int i, j;
1261 isl_set *context;
1263 context = isl_set_copy(host_domain);
1264 context = isl_set_params(context);
1266 for (i = 0; i < kernel->n_array; ++i) {
1267 struct gpu_local_array_info *local = &kernel->array[i];
1268 isl_multi_pw_aff *bound;
1269 int n_index;
1271 if (local->n_group == 0)
1272 continue;
1274 n_index = local->array->n_index;
1275 bound = isl_multi_pw_aff_copy(local->array->bound);
1277 for (j = 0; j < n_index; ++j) {
1278 isl_pw_aff *pwaff;
1279 int empty;
1281 pwaff = isl_multi_pw_aff_get_pw_aff(bound, j);
1282 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1283 empty = isl_pw_aff_is_empty(pwaff);
1284 if (empty < 0)
1285 pwaff = isl_pw_aff_free(pwaff);
1286 else if (empty)
1287 pwaff = set_universally_zero(pwaff);
1288 bound = isl_multi_pw_aff_set_pw_aff(bound, j, pwaff);
1291 local->n_index = n_index;
1292 local->bound = bound;
1294 isl_set_free(context);
1297 /* Create the array of gpu_local_array_info structures "array"
1298 * inside "kernel". The number of elements in this array is
1299 * the same as the number of arrays in "prog".
1300 * Initialize the "array" field of each local array to point
1301 * to the corresponding array in "prog".
1303 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1304 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1306 int i;
1307 isl_ctx *ctx;
1309 ctx = isl_set_get_ctx(prog->context);
1310 kernel->array = isl_calloc_array(ctx,
1311 struct gpu_local_array_info, prog->n_array);
1312 if (!kernel->array)
1313 return ppcg_kernel_free(kernel);
1314 kernel->n_array = prog->n_array;
1316 for (i = 0; i < prog->n_array; ++i)
1317 kernel->array[i].array = &prog->array[i];
1319 return kernel;
1322 /* Does "kernel" need to be passed an argument corresponding to array "i"?
1324 * The argument is only needed if the kernel accesses this device memory.
1326 int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1328 return kernel->array[i].global;
1331 /* Find the element in gen->stmt that has the given "id".
1332 * Return NULL if no such gpu_stmt can be found.
1334 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1336 int i;
1338 for (i = 0; i < prog->n_stmts; ++i) {
1339 if (id == prog->stmts[i].id)
1340 break;
1343 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1346 void ppcg_kernel_stmt_free(void *user)
1348 int i;
1349 struct ppcg_kernel_stmt *stmt = user;
1351 if (!stmt)
1352 return;
1354 switch (stmt->type) {
1355 case ppcg_kernel_copy:
1356 isl_ast_expr_free(stmt->u.c.index);
1357 isl_ast_expr_free(stmt->u.c.local_index);
1358 break;
1359 case ppcg_kernel_domain:
1360 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1361 break;
1362 case ppcg_kernel_sync:
1363 break;
1366 free(stmt);
1369 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1370 * to "ref_id".
1372 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1373 __isl_keep isl_id *ref_id)
1375 struct gpu_stmt_access *access;
1377 for (access = accesses; access; access = access->next)
1378 if (access->ref_id == ref_id)
1379 return access;
1381 return NULL;
1384 /* Return the index of the array called "name" in the list of arrays.
1386 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1388 int i;
1390 for (i = 0; i < kernel->n_array; ++i)
1391 if (!strcmp(name, kernel->array[i].array->name))
1392 return i;
1394 return -1;
1397 /* Internal data structure for the index and AST expression transformation
1398 * callbacks for pet_stmt_build_ast_exprs.
1400 * "kernel" is the kernel for which are computing AST expressions and
1401 * may be NULL if we are not inside a kernel.
1402 * "accesses" is the list of gpu_stmt_access in the statement.
1403 * "iterator_map" expresses the statement iterators in terms of
1404 * the AST loop iterators.
1405 * "sched2copy" expresses the outer copy_schedule_dim dimensions of
1406 * the kernel schedule in terms of the AST loop iterators and
1407 * may be NULL if we are not inside a kernel.
1409 * The following fields are set in transform_index and used in transform_expr.
1410 * "array" is the array that is being accessed.
1411 * "global" is set if the global array is accessed (rather than
1412 * shared/private memory).
1413 * "local_array" refers to information on the array specialized
1414 * to the current kernel.
1416 struct ppcg_transform_data {
1417 struct ppcg_kernel *kernel;
1418 struct gpu_stmt_access *accesses;
1419 isl_pw_multi_aff *iterator_map;
1420 isl_pw_multi_aff *sched2copy;
1422 struct gpu_array_info *array;
1423 int global;
1424 struct gpu_local_array_info *local_array;
1427 /* Return a pointer to the gpu_array_ref_group in "local"
1428 * that contains the reference "access".
1429 * Return NULL if no such group can be found.
1431 static struct gpu_array_ref_group *find_ref_group(
1432 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1434 int i, j;
1436 for (i = 0; i < local->n_group; ++i) {
1437 struct gpu_array_ref_group *group = local->groups[i];
1439 for (j = 0; j < group->n_ref; ++j)
1440 if (group->refs[j] == access)
1441 return group;
1444 return NULL;
1447 /* Index transformation callback for pet_stmt_build_ast_exprs.
1449 * "index" expresses the array indices in terms of statement iterators
1451 * We first reformulate "index" in terms of the AST loop iterators.
1452 * Then we check if we are accessing the global array or
1453 * a shared/private copy. In particular, if we are not inside a kernel
1454 * then we must be accessing a global array.
1455 * In the former case, we simply return
1456 * the updated index. If "index" is an affine expression rather
1457 * than an array access, then we also return the updated index here.
1459 * If no reference groups have been computed for the array,
1460 * then we can only be accessing the global array.
1462 * Otherwise, we apply the tiling to the index.
1463 * This tiling is of the form
1465 * [D -> A] -> T
1467 * where D corresponds to the outer tile->depth dimensions of
1468 * the kernel schedule.
1469 * The index is of the form
1471 * L -> A
1473 * We update the tiling to refer to the AST loop iterators
1475 * [L -> A] -> T
1477 * and modify index to keep track of those iterators
1479 * L -> [L -> A]
1481 * Combining these two yields a tiled index expression in terms
1482 * of the AST loop iterators
1484 * L -> T
1486 static __isl_give isl_multi_pw_aff *transform_index(
1487 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1488 void *user)
1490 struct ppcg_transform_data *data = user;
1491 struct gpu_stmt_access *access;
1492 struct gpu_array_ref_group *group;
1493 struct gpu_array_tile *tile;
1494 isl_pw_multi_aff *iterator_map;
1495 int i;
1496 int dim;
1497 const char *name;
1498 isl_space *space;
1499 isl_multi_pw_aff *tiling;
1500 isl_pw_multi_aff *pma;
1501 isl_multi_pw_aff *mpa;
1502 isl_pw_multi_aff *sched2depth;
1504 data->array = NULL;
1506 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1507 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1509 if (!data->kernel)
1510 return index;
1512 access = find_access(data->accesses, ref_id);
1513 if (!access)
1514 return index;
1515 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1516 return index;
1518 name = get_outer_array_name(access->access);
1519 i = find_array_index(data->kernel, name);
1520 if (i < 0)
1521 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1522 "cannot find array",
1523 return isl_multi_pw_aff_free(index));
1524 data->local_array = &data->kernel->array[i];
1525 data->array = data->local_array->array;
1527 group = find_ref_group(data->local_array, access);
1528 if (!group) {
1529 data->global = 1;
1530 return index;
1533 tile = gpu_array_ref_group_tile(group);
1534 data->global = !tile;
1535 if (!tile)
1536 return index;
1538 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1539 space = isl_space_map_from_set(space);
1540 pma = isl_pw_multi_aff_identity(space);
1541 sched2depth = isl_pw_multi_aff_copy(data->sched2copy);
1542 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1543 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1544 tile->depth, dim - tile->depth);
1545 pma = isl_pw_multi_aff_product(sched2depth, pma);
1546 tiling = isl_multi_pw_aff_from_multi_aff(
1547 isl_multi_aff_copy(tile->tiling));
1548 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1550 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1551 space = isl_space_map_from_set(space);
1552 mpa = isl_multi_pw_aff_identity(space);
1553 index = isl_multi_pw_aff_range_product(mpa, index);
1554 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1556 return index;
1559 /* Dereference "expr" by adding an index [0].
1560 * The original "expr" is assumed not to have any indices.
1562 * If "expr" is a member access, then the dereferencing needs
1563 * to be applied to the structure argument of this member access.
1565 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1567 isl_ctx *ctx;
1568 isl_ast_expr *arg0, *res;
1569 isl_ast_expr_list *list;
1571 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1572 if (!arg0)
1573 return isl_ast_expr_free(expr);
1574 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1575 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1576 isl_ast_expr *arg;
1578 arg = isl_ast_expr_get_op_arg(arg0, 0);
1579 arg = dereference(arg);
1580 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1581 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1583 return expr;
1585 isl_ast_expr_free(arg0);
1587 ctx = isl_ast_expr_get_ctx(expr);
1588 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1589 list = isl_ast_expr_list_from_ast_expr(res);
1590 res = isl_ast_expr_get_op_arg(expr, 0);
1591 res = isl_ast_expr_access(res, list);
1592 isl_ast_expr_free(expr);
1594 return res;
1597 /* Linearize the index expression "expr" based on the array bounds
1598 * of "array".
1600 * That is, transform expression
1602 * A[i_0][i_1]...[i_n]
1604 * to
1606 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1608 * where b_0, b_1, ..., b_n are the bounds on the array.
1610 * If the base of "expr" is a member access, then the linearization needs
1611 * to be applied to the structure argument of this member access.
1613 * In the base case, if "expr" has no arguments (other than the name of
1614 * the array), then we are passing an entire array to a function.
1615 * In this case, there is nothing to linearize.
1616 * Note that at this point an expression with no arguments can
1617 * only be an entire array because the scalar case and
1618 * the case of single struct are handled by the caller.
1620 * If the number of specified index expressions in "expr"
1621 * is smaller than the dimension of the accessed array,
1622 * then the missing i_j also do not appear in the linearized expression.
1623 * Furthermore, since such an expression does not refer to a single
1624 * element while the default linearized expression would refer to
1625 * a single element, we return the expression
1627 * A + (..((i_0 * b_1 + i_1) ... ) * b_l + i_l)
1629 * instead. Note that because of the special case handling above,
1630 * we can assume here that there is at least one index expression.
1632 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1633 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1635 int i, n;
1636 isl_ast_expr *arg0;
1637 isl_ast_expr *res;
1638 isl_ast_expr_list *list;
1640 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1641 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1642 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1643 isl_ast_expr *arg;
1645 arg = isl_ast_expr_get_op_arg(arg0, 0);
1646 arg = gpu_local_array_info_linearize_index(array, arg);
1647 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1648 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1650 return expr;
1652 isl_ast_expr_free(arg0);
1654 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1655 return expr;
1657 n = isl_ast_expr_get_op_n_arg(expr);
1658 res = isl_ast_expr_get_op_arg(expr, 1);
1659 for (i = 1; i < array->n_index; ++i) {
1660 isl_ast_expr *expr_i;
1662 expr_i = isl_ast_expr_get_op_arg(array->bound_expr, 1 + i);
1663 res = isl_ast_expr_mul(res, expr_i);
1665 if (i + 1 >= n)
1666 continue;
1667 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1668 res = isl_ast_expr_add(res, expr_i);
1671 if (1 + array->n_index > n) {
1672 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1673 } else {
1674 list = isl_ast_expr_list_from_ast_expr(res);
1675 res = isl_ast_expr_get_op_arg(expr, 0);
1676 res = isl_ast_expr_access(res, list);
1679 isl_ast_expr_free(expr);
1681 return res;
1684 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1686 * If the AST expression refers to an array that is not accessed
1687 * at all, then this means the value of the expression is not used,
1688 * so we might as well print zero (NULL pointer) instead.
1690 * If the AST expression refers to a global scalar that is not
1691 * a read-only scalar, then its address was passed to the kernel and
1692 * we need to dereference it.
1694 * If the AST expression refers to an access to a global array,
1695 * then we linearize the access exploiting the bounds in data->local_array.
1697 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1698 __isl_keep isl_id *id, void *user)
1700 struct ppcg_transform_data *data = user;
1702 if (!data->array)
1703 return expr;
1704 if (!data->array->accessed) {
1705 isl_ctx *ctx;
1707 ctx = isl_ast_expr_get_ctx(expr);
1708 isl_ast_expr_free(expr);
1709 return isl_ast_expr_from_val(isl_val_zero(ctx));
1711 if (gpu_array_is_read_only_scalar(data->array))
1712 return expr;
1713 if (!data->global)
1714 return expr;
1715 if (data->array->n_index == 0)
1716 return dereference(expr);
1717 if (!data->array->linearize)
1718 return expr;
1720 return gpu_local_array_info_linearize_index(data->local_array, expr);
1723 /* This function is called for each instance of a user statement
1724 * in the kernel "kernel", identified by "gpu_stmt".
1725 * "kernel" may be NULL if we are not inside a kernel.
1727 * We attach a struct ppcg_kernel_stmt to the "node", containing
1728 * a computed AST expression for each access, through an annotation
1729 * with name "user".
1730 * These AST expressions are computed from iterator_map,
1731 * which expresses the domain
1732 * elements in terms of the generated loops, and sched2copy,
1733 * which expresses the outer copy_schedule_dim dimensions of
1734 * the kernel schedule computed by PPCG in terms of the generated loops.
1736 static __isl_give isl_ast_node *create_domain_leaf(
1737 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1738 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1740 struct ppcg_transform_data data;
1741 struct ppcg_kernel_stmt *stmt;
1742 isl_ctx *ctx;
1743 isl_id *id;
1744 isl_pw_multi_aff *sched2copy;
1745 isl_map *map;
1746 isl_pw_multi_aff *iterator_map;
1747 isl_union_map *schedule;
1749 if (!node)
1750 return NULL;
1751 ctx = isl_ast_node_get_ctx(node);
1753 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1754 if (!stmt)
1755 return isl_ast_node_free(node);
1757 schedule = isl_ast_build_get_schedule(build);
1758 map = isl_map_reverse(isl_map_from_union_map(schedule));
1759 iterator_map = isl_pw_multi_aff_from_map(map);
1760 if (kernel)
1761 sched2copy = compute_sched_to_copy(kernel,
1762 isl_pw_multi_aff_copy(iterator_map));
1763 else
1764 sched2copy = NULL;
1766 stmt->type = ppcg_kernel_domain;
1767 stmt->u.d.stmt = gpu_stmt;
1769 data.kernel = kernel;
1770 data.accesses = stmt->u.d.stmt->accesses;
1771 data.iterator_map = iterator_map;
1772 data.sched2copy = sched2copy;
1773 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1774 build, &transform_index, &data,
1775 &transform_expr, &data);
1777 isl_pw_multi_aff_free(iterator_map);
1778 isl_pw_multi_aff_free(sched2copy);
1780 id = isl_id_alloc(ctx, "user", stmt);
1781 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1782 return isl_ast_node_set_annotation(node, id);
1785 /* This function is called for each statement node in the AST
1786 * for copying to or from shared/private memory.
1787 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1788 * statement to the node.
1789 * The statement name is "read" or "write", depending on whether we are
1790 * reading from global memory or writing to global memory.
1792 * The schedule is of the form
1794 * type[D -> A] -> L
1796 * where D corresponds to the outer tile->depth dimensions of
1797 * the kernel schedule, A to the global array and L to the outer
1798 * generated AST schedule.
1799 * We compute the inverse and strip off the type, resulting in
1801 * L -> [D -> A]
1803 * We combine this mapping with on the one hand the projection
1805 * [D -> A] -> A
1807 * and on the other hand the group tiling
1809 * [D -> A] -> T
1811 * resulting in
1813 * L -> A and L -> T
1815 * and store the corresponding expressions in stmt->index and stmt->local_index,
1816 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1817 * stmt->index is linearized if the global memory array is linearized.
1819 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1820 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1821 __isl_keep isl_ast_build *build)
1823 struct ppcg_kernel_stmt *stmt;
1824 struct gpu_array_tile *tile;
1825 isl_id *id;
1826 isl_ast_expr *expr;
1827 isl_space *space;
1828 isl_map *access;
1829 isl_pw_multi_aff *pma, *pma2;
1830 const char *type;
1832 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1833 if (!stmt)
1834 return isl_ast_node_free(node);
1836 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1837 type = isl_map_get_tuple_name(access, isl_dim_in);
1838 stmt->u.c.read = !strcmp(type, "read");
1839 access = isl_map_reverse(access);
1840 pma = isl_pw_multi_aff_from_map(access);
1841 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1843 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1844 space = isl_space_unwrap(space);
1845 pma2 = isl_pw_multi_aff_range_map(space);
1846 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1847 isl_pw_multi_aff_copy(pma));
1848 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1849 if (group->array->linearize)
1850 expr = gpu_local_array_info_linearize_index(group->local_array,
1851 expr);
1852 stmt->u.c.index = expr;
1854 tile = gpu_array_ref_group_tile(group);
1855 pma2 = isl_pw_multi_aff_from_multi_aff(
1856 isl_multi_aff_copy(tile->tiling));
1857 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1858 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1859 stmt->u.c.local_index = expr;
1861 stmt->u.c.array = group->array;
1862 stmt->u.c.local_array = group->local_array;
1863 stmt->type = ppcg_kernel_copy;
1865 id = isl_id_alloc(kernel->ctx, "copy", stmt);
1866 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1867 return isl_ast_node_set_annotation(node, id);
1870 /* Create a synchronization ppcg_kernel_stmt and
1871 * attach it to the node "node" representing the synchronization.
1873 static __isl_give isl_ast_node *create_sync_leaf(
1874 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1875 __isl_keep isl_ast_build *build)
1877 struct ppcg_kernel_stmt *stmt;
1878 isl_id *id;
1880 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1881 if (!stmt)
1882 return isl_ast_node_free(node);
1884 stmt->type = ppcg_kernel_sync;
1885 id = isl_id_alloc(kernel->ctx, "sync", stmt);
1886 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1887 return isl_ast_node_set_annotation(node, id);
1890 /* Build AST expressions for the device array sizes of all arrays in "prog"
1891 * that require allocation on the device using "build", as well as
1892 * for the original array sizes of all arrays that need to be declared
1893 * on the host.
1894 * "node" is freed in case of error.
1896 static __isl_give isl_ast_node *build_array_bounds(
1897 __isl_take isl_ast_node *node, struct gpu_prog *prog,
1898 __isl_keep isl_ast_build *build)
1900 int i;
1902 for (i = 0; i < prog->n_array; ++i) {
1903 struct gpu_array_info *array = &prog->array[i];
1904 isl_multi_pw_aff *size;
1905 isl_ast_expr *expr;
1907 if (!gpu_array_requires_device_allocation(array))
1908 continue;
1910 size = isl_multi_pw_aff_copy(array->bound);
1911 expr = ppcg_build_size_expr(size, build);
1912 array->bound_expr = expr;
1913 if (!expr)
1914 return isl_ast_node_free(node);
1917 for (i = 0; i < prog->n_array; ++i) {
1918 struct gpu_array_info *array = &prog->array[i];
1919 struct pet_array *pet_array = prog->scop->pet->arrays[i];
1920 isl_multi_pw_aff *size;
1921 isl_ast_expr *expr;
1923 if (!array->declare_local)
1924 continue;
1925 size = ppcg_size_from_extent(isl_set_copy(pet_array->extent));
1926 expr = ppcg_build_size_expr(size, build);
1927 array->declared_size = expr;
1928 if (!expr)
1929 return isl_ast_node_free(node);
1932 return node;
1935 /* Internal data structure for at_domain.
1937 * "prog" represents the entire scop.
1938 * "kernel" points to the kernel to which the current schedule node
1939 * belongs. It is set by before_mark and reset by after_mark.
1940 * It may be NULL if we are outside any kernel.
1942 struct ppcg_at_domain_data {
1943 struct gpu_prog *prog;
1944 struct ppcg_kernel *kernel;
1947 /* This function is called for each instance of a user statement
1948 * in the kernel. This may be one of the original user statements
1949 * or a statement introduced by PPCG.
1951 * We first check if the statement id corresponds to a gpu statement,
1952 * which indicates the statement is an original user statement. Any statement
1953 * that is not an original user statement has been introduced by PPCG and
1954 * requires special handling.
1956 * If the user statement is one of the original user statements, then we call
1957 * create_domain_leaf. If it is "init_device", then we call
1958 * build_array_bounds. Otherwise, we check if it is a copy or synchronization
1959 * statement and call the appropriate functions. Statements that copy an array
1960 * to/from the device do not need any further treatment.
1961 * Neither does "clear_device".
1963 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1964 __isl_keep isl_ast_build *build, void *user)
1966 struct ppcg_at_domain_data *data = user;
1967 struct gpu_stmt *gpu_stmt;
1968 isl_ast_expr *expr, *arg;
1969 isl_id *id;
1970 int is_sync;
1971 const char *name;
1972 void *p;
1974 expr = isl_ast_node_user_get_expr(node);
1975 arg = isl_ast_expr_get_op_arg(expr, 0);
1976 id = isl_ast_expr_get_id(arg);
1977 name = isl_id_get_name(id);
1978 p = isl_id_get_user(id);
1979 isl_ast_expr_free(expr);
1980 isl_ast_expr_free(arg);
1982 gpu_stmt = find_stmt(data->prog, id);
1983 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1984 isl_id_free(id);
1986 if (gpu_stmt)
1987 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
1989 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
1990 return node;
1991 if (!strcmp(name, "init_device"))
1992 return build_array_bounds(node, data->prog, build);
1993 if (!strcmp(name, "clear_device"))
1994 return node;
1995 if (is_sync < 0)
1996 return isl_ast_node_free(node);
1997 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1998 struct gpu_array_ref_group *group = p;
1999 return create_access_leaf(data->kernel, group, node, build);
2001 if (!is_sync)
2002 isl_die(data->prog->ctx, isl_error_internal,
2003 "unknown statement type",
2004 return isl_ast_node_free(node));
2005 return create_sync_leaf(data->kernel, node, build);
2008 /* Given a set of wrapped references "ref", return the corresponding
2009 * access relations based on the tagged access relations "tagged".
2011 * The elements of "ref" are of the form
2013 * [D -> R]
2015 * with D an iteration domains and R a reference.
2016 * The elements of "tagged" are of the form
2018 * [D -> R] -> A
2020 * with A an array.
2022 * Extend "tagged" to include the iteration domain in the range, i.e.,
2024 * [D -> R] -> [D -> A]
2026 * apply the result to "ref" and then unwrap the resulting set
2027 * to obtain relations of the form
2029 * D -> A
2031 static __isl_give isl_union_map *wrapped_reference_to_access(
2032 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2034 isl_union_map *tag2access;
2036 tag2access = isl_union_map_copy(tagged);
2037 tag2access = isl_union_map_universe(tag2access);
2038 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2039 tag2access = isl_union_map_domain_map(tag2access);
2040 tag2access = isl_union_map_range_product(tag2access, tagged);
2042 ref = isl_union_set_coalesce(ref);
2043 ref = isl_union_set_apply(ref, tag2access);
2045 return isl_union_set_unwrap(ref);
2048 /* Given an access relation "access" from one or more array reference groups,
2049 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2050 * that are only needed to communicate data within
2051 * the same iteration of "sched".
2052 * "tagged" contains all tagged access relations to all
2053 * the array reference groups accessed by "access" from statement
2054 * instances scheduled by "sched".
2056 * If the access is a read then it is either an element of
2058 * live_in union (range flow)
2060 * where live_in and flow may be overapproximations, or
2061 * it reads an uninitialized value (that is not live-in because
2062 * there is an intermediate kill) or it reads a value that was
2063 * written within the same (compound) statement instance.
2064 * If the access is a write then it is either an element of
2066 * live_out union (domain flow)
2068 * or it writes a value that is never read (and is not live-out
2069 * because of an intermediate kill) or only
2070 * within the same (compound) statement instance.
2071 * In both cases, the access relation is also a subset of
2072 * the group access relation.
2074 * The cases where an uninitialized value is read or a value is written
2075 * that is never read or where the dataflow occurs within a statement
2076 * instance are also considered local and may also be removed.
2078 * Essentially, we compute the intersection of "access" with either
2080 * live_in union (range non-local-flow)
2082 * or
2084 * live_out union (domain non-local-flow)
2086 * We first construct a relation "local"
2088 * [[D -> R] -> [D' -> R']]
2090 * of pairs of domain iterations accessing the reference group
2091 * and references in the group that are coscheduled by "sched".
2093 * If this relation does not intersect the dataflow dependences,
2094 * then there is nothing we can possibly remove, unless the dataflow
2095 * dependences themselves only relate a subset of the accesses.
2096 * In particular, the accesses may not be involved in any dataflow
2097 * dependences, either because they are uninitialized reads/dead writes
2098 * or because the dataflow occurs inside a statement instance.
2100 * Since the computation below may break up the access relation
2101 * into smaller pieces, we only perform the intersection with
2102 * the non-local dependent accesses if the local pairs
2103 * intersect the dataflow dependences. Otherwise, we intersect
2104 * with the universe of the non-local dependent accesses.
2105 * This should at least remove accesses from statements that
2106 * do not participate in any dependences.
2108 * In particular, we remove the "local" dataflow dependences from
2109 * the set of all dataflow dependences, or at least those
2110 * that may contribute to a domain/range that intersects
2111 * the domain of "access".
2112 * Note that if the potential dataflow dependences are an overapproximation
2113 * of the actual dataflow dependences, then the result remains an
2114 * overapproximation of the non-local dataflow dependences.
2115 * Copying to/from global memory is only needed for the references
2116 * in the domain/range of the result or for accesses that are live out/in
2117 * for the entire scop.
2119 * We therefore map the domain/range of the "external" relation
2120 * to the corresponding access relation and take the union with
2121 * the live out/in relation.
2123 static __isl_give isl_union_map *remove_local_accesses(
2124 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2125 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2126 int read)
2128 int empty;
2129 isl_union_pw_multi_aff *tagger;
2130 isl_union_set *domain, *access_domain;
2131 isl_union_map *local, *external, *universe;
2132 isl_union_set *tag_set;
2134 if (isl_union_map_is_empty(access)) {
2135 isl_union_map_free(sched);
2136 isl_union_map_free(tagged);
2137 return access;
2140 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2141 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2142 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2143 isl_union_set_copy(domain));
2144 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2146 local = isl_union_map_apply_range(sched,
2147 isl_union_map_reverse(isl_union_map_copy(sched)));
2148 local = isl_union_map_intersect(local,
2149 isl_union_map_copy(prog->scop->tagged_dep_flow));
2151 empty = isl_union_map_is_empty(local);
2153 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2154 universe = isl_union_map_universe(isl_union_map_copy(access));
2155 access_domain = isl_union_map_domain(universe);
2156 domain = isl_union_set_universe(domain);
2157 universe = isl_union_set_unwrap(domain);
2158 universe = isl_union_map_intersect_domain(universe, access_domain);
2159 domain = isl_union_map_wrap(universe);
2160 if (read)
2161 external = isl_union_map_intersect_range(external, domain);
2162 else
2163 external = isl_union_map_intersect_domain(external, domain);
2164 external = isl_union_map_intersect_params(external,
2165 isl_set_copy(prog->scop->context));
2166 external = isl_union_map_subtract(external, local);
2168 if (read) {
2169 tag_set = isl_union_map_range(external);
2170 external = wrapped_reference_to_access(tag_set, tagged);
2171 external = isl_union_map_union(external,
2172 isl_union_map_copy(prog->scop->live_in));
2173 } else {
2174 tag_set = isl_union_map_domain(external);
2175 external = wrapped_reference_to_access(tag_set, tagged);
2176 external = isl_union_map_union(external,
2177 isl_union_map_copy(prog->scop->live_out));
2180 if (empty < 0)
2181 external = isl_union_map_free(external);
2182 else if (empty)
2183 external = isl_union_map_universe(external);
2185 access = isl_union_map_intersect(access, external);
2187 return access;
2190 /* Given an access relation "access" from "group", remove those reads
2191 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2192 * communicate data within the same iteration of the schedule at the
2193 * position where the copying of the group is inserted.
2194 * "node" points to this position, i.e., the depth at "node"
2195 * is equal to tile->depth.
2197 * We extract a schedule that picks out the iterations of the outer
2198 * tile->depth dimensions and call remove_local_accesses.
2200 static __isl_give isl_union_map *remove_local_accesses_group(
2201 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2202 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2203 int read)
2205 isl_union_map *sched, *tagged;
2207 if (isl_union_map_is_empty(access))
2208 return access;
2210 tagged = group_tagged_access_relation(group);
2211 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2213 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2216 /* Build an access AST expression for the effective grid size using "build".
2217 * Store the result in kernel->grid_size_expr.
2219 static isl_stat build_grid_size(struct ppcg_kernel *kernel,
2220 __isl_keep isl_ast_build *build)
2222 isl_multi_pw_aff *size;
2224 size = isl_multi_pw_aff_copy(kernel->grid_size);
2225 size = isl_multi_pw_aff_set_tuple_name(size, isl_dim_out, "grid");
2226 kernel->grid_size_expr = ppcg_build_size_expr(size, build);
2228 if (!kernel->grid_size_expr)
2229 return isl_stat_error;
2230 return isl_stat_ok;
2233 /* Build access AST expressions for the localized array sizes using "build".
2234 * Store the result in local->bound_expr.
2235 * Only do this for arrays for which localized bounds have been computed.
2237 static isl_stat build_local_array_sizes(struct ppcg_kernel *kernel,
2238 __isl_keep isl_ast_build *build)
2240 int i;
2242 for (i = 0; i < kernel->n_array; ++i) {
2243 struct gpu_local_array_info *local = &kernel->array[i];
2244 isl_multi_pw_aff *size;
2246 if (local->n_group == 0)
2247 continue;
2248 size = isl_multi_pw_aff_copy(local->bound);
2249 local->bound_expr = ppcg_build_size_expr(size, build);
2250 if (!local->bound_expr)
2251 return isl_stat_error;
2254 return isl_stat_ok;
2257 /* Build access AST expressions for the effective grid size and
2258 * the localized array sizes using "build".
2260 static isl_stat build_grid_and_local_array_sizes(struct ppcg_kernel *kernel,
2261 __isl_keep isl_ast_build *build)
2263 if (build_grid_size(kernel, build) < 0)
2264 return isl_stat_error;
2265 if (build_local_array_sizes(kernel, build) < 0)
2266 return isl_stat_error;
2267 return isl_stat_ok;
2270 /* This function is called before the AST generator starts traversing
2271 * the schedule subtree of a node with mark "mark".
2273 * If the mark is called "kernel", store the kernel pointer in data->kernel
2274 * for use in at_domain and build AST expressions for the grid size and
2275 * the localized array sizes.
2277 static isl_stat before_mark(__isl_keep isl_id *mark,
2278 __isl_keep isl_ast_build *build, void *user)
2280 struct ppcg_at_domain_data *data = user;
2282 if (!mark)
2283 return isl_stat_error;
2284 if (!strcmp(isl_id_get_name(mark), "kernel")) {
2285 data->kernel = isl_id_get_user(mark);
2286 if (build_grid_and_local_array_sizes(data->kernel, build) < 0)
2287 return isl_stat_error;
2289 return isl_stat_ok;
2292 /* This function is called after the AST generator has finished traversing
2293 * the schedule subtree of a mark node. "node" points to the corresponding
2294 * mark AST node.
2296 * If the mark is called "kernel", then replace "node" by a user node
2297 * that "calls" the kernel, representing the launch of the kernel.
2298 * The original "node" is stored inside the kernel object so that
2299 * it can be used to print the device code.
2300 * Note that this assumes that a kernel is only launched once.
2301 * Also clear data->kernel.
2303 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2304 __isl_keep isl_ast_build *build, void *user)
2306 isl_ctx *ctx;
2307 isl_id *id;
2308 isl_ast_expr *expr;
2309 isl_ast_expr_list *list;
2310 struct ppcg_kernel *kernel;
2311 struct ppcg_at_domain_data *data = user;
2313 ctx = isl_ast_node_get_ctx(node);
2314 id = isl_ast_node_mark_get_id(node);
2315 if (!id)
2316 return isl_ast_node_free(node);
2317 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2318 isl_id_free(id);
2319 return node;
2321 kernel = data->kernel;
2322 data->kernel = NULL;
2323 kernel->space = isl_ast_build_get_schedule_space(build);
2324 kernel->tree = isl_ast_node_mark_get_node(node);
2325 isl_ast_node_free(node);
2327 expr = isl_ast_expr_from_id(isl_id_copy(id));
2328 list = isl_ast_expr_list_alloc(ctx, 0);
2329 expr = isl_ast_expr_call(expr, list);
2330 node = isl_ast_node_alloc_user(expr);
2331 node = isl_ast_node_set_annotation(node, id);
2333 return node;
2336 static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2338 int *depth = user;
2339 int node_depth;
2341 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2342 return isl_bool_true;
2343 node_depth = isl_schedule_node_get_schedule_depth(node);
2344 if (node_depth > *depth)
2345 *depth = node_depth;
2347 return isl_bool_false;
2350 /* Use isl to generate code for both the host and the device
2351 * from "schedule".
2352 * The device code is marked by "kernel" mark nodes in the schedule tree,
2353 * containing a pointer to a ppcg_kernel object.
2354 * The returned AST only contains the AST for the host code.
2355 * The ASTs for the device code are embedded in ppcg_kernel objects
2356 * attached to the leaf nodes that call "kernel".
2358 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2359 __isl_take isl_schedule *schedule)
2361 struct ppcg_at_domain_data data;
2362 isl_ast_build *build;
2363 isl_ast_node *tree;
2364 isl_id_list *iterators;
2365 int depth;
2367 data.prog = gen->prog;
2368 data.kernel = NULL;
2370 depth = 0;
2371 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2372 &depth) < 0)
2373 return NULL;
2374 build = isl_ast_build_alloc(gen->prog->ctx);
2375 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2376 build = isl_ast_build_set_iterators(build, iterators);
2377 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2378 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2379 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2380 if (gen->prog->scop->options->debug->dump_final_schedule)
2381 isl_schedule_dump(schedule);
2382 tree = isl_ast_build_node_from_schedule(build, schedule);
2383 isl_ast_build_free(build);
2385 return tree;
2388 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2390 if (!str)
2391 return NULL;
2392 return isl_union_map_read_from_str(ctx, str);
2395 /* Can "node" be tiled and then mapped to block and thread identifiers?
2396 * That is, is it permutable with at least one coincident dimension?
2398 static int is_permutable(__isl_keep isl_schedule_node *node)
2400 if (!node)
2401 return -1;
2403 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2404 return 0;
2405 if (!isl_schedule_node_band_get_permutable(node))
2406 return 0;
2407 if (isl_schedule_node_band_n_member(node) < 1)
2408 return 0;
2409 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2410 return 0;
2412 return 1;
2415 /* A isl_schedule_foreach_schedule_node_top_down callback
2416 * for setting *any_permutable and aborting the search
2417 * if "node" is a permutable band with coincident dimensions.
2418 * Otherwise, continue searching.
2420 static isl_bool set_permutable(__isl_keep isl_schedule_node *node, void *user)
2422 int *any_permutable = user;
2423 int permutable;
2425 permutable = is_permutable(node);
2426 if (permutable < 0)
2427 return isl_bool_error;
2428 if (!permutable)
2429 return isl_bool_true;
2431 *any_permutable = 1;
2433 return isl_bool_error;
2436 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
2437 * That is, does it have any nodes that are permutable and that
2438 * have a least one coincident dimension?
2440 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
2442 int any_parallelism = 0;
2444 if (isl_schedule_node_foreach_descendant_top_down(node, &set_permutable,
2445 &any_parallelism) < 0 &&
2446 !any_parallelism)
2447 return -1;
2449 return any_parallelism;
2452 /* Does "schedule" contain any permutable band with at least one coincident
2453 * member?
2455 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2457 isl_schedule_node *root;
2458 int any_permutable;
2460 root = isl_schedule_get_root(schedule);
2461 any_permutable = subtree_has_permutable_bands(root);
2462 isl_schedule_node_free(root);
2464 return any_permutable;
2467 /* Is "node" a candidate for mapping to block and thread identifiers?
2468 * In particular, is it permutable with at least one coincident dimension?
2469 * Alternatively, does the subtree rooted at "node" not contain
2470 * any such permutable node? Filter nodes are skipped in this case,
2471 * because a band node will be inserted in front of the returned
2472 * node and this is not possible for filter nodes that are children
2473 * of set or sequence nodes.
2475 static int is_candidate(__isl_keep isl_schedule_node *node)
2477 int permutable;
2479 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2480 return 1;
2481 permutable = is_permutable(node);
2482 if (permutable < 0 || permutable)
2483 return permutable;
2484 if (isl_schedule_node_get_type(node) == isl_schedule_node_filter)
2485 return 0;
2486 permutable = subtree_has_permutable_bands(node);
2487 if (permutable < 0)
2488 return -1;
2489 return !permutable;
2492 /* Is "node" the outermost node in its branch that can be tiled
2493 * and then mapped to block and thread identifiers?
2494 * If there are no such nodes in the subtree at "node" and
2495 * if "node" is not a filter node, then it is accepted too.
2497 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2499 int tilable;
2500 isl_schedule_node *ancestor;
2502 tilable = is_candidate(node);
2503 if (tilable < 0)
2504 return -1;
2505 if (!tilable)
2506 return 0;
2508 tilable = 0;
2509 ancestor = isl_schedule_node_copy(node);
2510 while (isl_schedule_node_has_parent(ancestor)) {
2511 ancestor = isl_schedule_node_parent(ancestor);
2513 tilable = is_candidate(ancestor);
2514 if (tilable < 0 || tilable)
2515 break;
2518 isl_schedule_node_free(ancestor);
2519 return tilable < 0 ? -1 : !tilable;
2522 /* Collect the references to all writes in "group".
2523 * Each reference is represented by a universe set in a space
2525 * [S[i,j] -> R[]]
2527 * with S[i,j] the statement instance space and R[] the array reference.
2529 static __isl_give isl_union_set *group_tagged_writes(
2530 struct gpu_array_ref_group *group)
2532 int i;
2533 isl_space *space;
2534 isl_union_set *writes;
2536 space = isl_map_get_space(group->access);
2537 writes = isl_union_set_empty(space);
2538 for (i = 0; i < group->n_ref; ++i) {
2539 isl_space *space;
2540 isl_set *writes_i;
2542 if (!group->refs[i]->write)
2543 continue;
2545 space = isl_map_get_space(group->refs[i]->tagged_access);
2546 space = isl_space_domain(space);
2547 writes_i = isl_set_universe(space);
2548 writes = isl_union_set_add_set(writes, writes_i);
2551 return writes;
2554 /* Is there any write access in "group" that requires synchronization
2555 * on a write to global memory?
2556 * We currently take into account all writes that would require
2557 * synchronization at the thread level depth, but if the copying
2558 * for this group is performed at an outer level, then we do not
2559 * actually need to take into account dependences at intermediate levels.
2561 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2562 struct gpu_array_ref_group *group)
2564 isl_union_set *writes;
2565 int empty, disjoint;
2567 empty = isl_union_set_is_empty(kernel->sync_writes);
2568 if (empty < 0)
2569 return -1;
2570 if (empty)
2571 return 0;
2573 writes = group_tagged_writes(group);
2574 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2575 isl_union_set_free(writes);
2577 return disjoint < 0 ? -1 : !disjoint;
2580 /* Collect the references to all writes in "kernel" that write directly
2581 * to global or shared memory, i.e., that are not mapped to private memory.
2582 * Each reference is represented by a universe set in a space
2584 * [S[i,j] -> R[]]
2586 * with S[i,j] the statement instance space and R[] the array reference.
2588 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2589 struct ppcg_kernel *kernel)
2591 isl_union_set *writes;
2592 int i, j;
2594 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2596 for (i = 0; i < kernel->n_array; ++i) {
2597 struct gpu_local_array_info *array = &kernel->array[i];
2599 for (j = 0; j < array->n_group; ++j) {
2600 struct gpu_array_ref_group *group = array->groups[j];
2601 enum ppcg_group_access_type type;
2602 isl_union_set *writes_ij;
2604 if (!group->write)
2605 continue;
2606 type = gpu_array_ref_group_type(group);
2607 if (type == ppcg_access_private)
2608 continue;
2609 writes_ij = group_tagged_writes(group);
2610 writes = isl_union_set_union(writes, writes_ij);
2614 return writes;
2617 /* Are there any direct writes to global memory that require
2618 * synchronization?
2620 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2622 isl_union_set *writes;
2623 int empty, disjoint;
2625 empty = isl_union_set_is_empty(kernel->sync_writes);
2626 if (empty < 0)
2627 return -1;
2628 if (empty)
2629 return 0;
2631 writes = collect_non_private_tagged_writes(kernel);
2632 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2633 isl_union_set_free(writes);
2635 return disjoint < 0 ? -1 : !disjoint;
2638 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2639 * from the elements in "tile_size".
2641 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2642 __isl_keep isl_schedule_node *node, int *tile_size)
2644 int i, n;
2645 isl_ctx *ctx;
2646 isl_space *space;
2647 isl_multi_val *mv;
2649 if (!node)
2650 return NULL;
2652 ctx = isl_schedule_node_get_ctx(node);
2653 space = isl_schedule_node_band_get_space(node);
2654 n = isl_schedule_node_band_n_member(node);
2655 mv = isl_multi_val_zero(space);
2656 for (i = 0; i < n; ++i) {
2657 isl_val *v;
2659 v = isl_val_int_from_si(ctx, tile_size[i]);
2660 mv = isl_multi_val_set_val(mv, i, v);
2663 return mv;
2666 /* Replace the partial schedule S of the band node "node" by
2668 * floor(S/f)
2670 * or
2672 * f * floor(S/f)
2674 * if scale_tile_loops is set, with f the integers in "factor".
2675 * The list that "factor" points to is assumed to contain at least
2676 * as many elements as the number of members in the band.
2678 static __isl_give isl_schedule_node *snap_band_to_sizes(
2679 __isl_take isl_schedule_node *node, int *factor,
2680 struct ppcg_options *options)
2682 isl_multi_val *mv;
2684 mv = construct_band_tiles_sizes(node, factor);
2685 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2686 if (options->scale_tile_loops)
2687 node = isl_schedule_node_band_scale(node,
2688 isl_multi_val_copy(mv));
2689 isl_multi_val_free(mv);
2691 return node;
2694 /* Tile "band" with tile size specified by "sizes".
2696 * Since the tile loops will be mapped to block ids, we forcibly
2697 * turn off tile loop scaling. We may want to enable tile loop scaling
2698 * at some later point, but then we would have to support the detection
2699 * of strides during the mapping to block ids.
2700 * Similarly, since the point loops will be mapped to thread ids,
2701 * we forcibly shift the point loops so that they start at zero.
2703 static __isl_give isl_schedule_node *tile_band(
2704 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2706 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2707 int scale_tile;
2708 int shift_point;
2710 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2711 isl_options_set_tile_scale_tile_loops(ctx, 0);
2712 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2713 isl_options_set_tile_shift_point_loops(ctx, 1);
2715 node = isl_schedule_node_band_tile(node, sizes);
2717 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2718 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2720 return node;
2723 /* Extract the set of parameter values and outer schedule dimensions
2724 * for which any statement instance
2725 * in the kernel inserted at "node" needs to be executed.
2726 * Intersect the set of parameter values derived from the host schedule
2727 * relation with the context of "prog".
2729 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2730 struct gpu_prog *prog)
2732 isl_union_map *schedule;
2733 isl_union_set *schedule_domain;
2734 isl_set *context;
2735 int empty;
2737 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2738 schedule_domain = isl_union_map_range(schedule);
2739 empty = isl_union_set_is_empty(schedule_domain);
2740 if (empty < 0) {
2741 isl_union_set_free(schedule_domain);
2742 return NULL;
2744 if (empty) {
2745 int depth;
2746 isl_space *space;
2748 space = isl_union_set_get_space(schedule_domain);
2749 isl_union_set_free(schedule_domain);
2750 space = isl_space_set_from_params(space);
2751 depth = isl_schedule_node_get_schedule_depth(node);
2752 space = isl_space_add_dims(space, isl_dim_set, depth);
2753 context = isl_set_empty(space);
2754 } else {
2755 context = isl_set_from_union_set(schedule_domain);
2757 context = isl_set_intersect_params(context,
2758 isl_set_copy(prog->context));
2760 return context;
2763 /* Return the set of outer array elements accessed by
2764 * by the statement instance in "domain" in "prog".
2766 static __isl_give isl_union_set *accessed_by_domain(
2767 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2769 isl_union_map *access;
2770 isl_union_set *arrays;
2772 access = isl_union_map_union(isl_union_map_copy(prog->read),
2773 isl_union_map_copy(prog->may_write));
2774 access = isl_union_map_intersect_domain(access, domain);
2775 arrays = isl_union_map_range(access);
2776 arrays = isl_union_set_apply(arrays,
2777 isl_union_map_copy(prog->to_outer));
2779 return arrays;
2782 /* Return the number of outer band members of the band node "node"
2783 * that are marked coincident.
2785 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2787 int i, n;
2789 n = isl_schedule_node_band_n_member(node);
2791 for (i = 0; i < n; ++i)
2792 if (!isl_schedule_node_band_member_get_coincident(node, i))
2793 break;
2795 return i;
2798 /* If the band node "node" has more than "n" members, then split off
2799 * the first "n" of them.
2801 static __isl_give isl_schedule_node *split_band(
2802 __isl_take isl_schedule_node *node, int n)
2804 int dim;
2806 dim = isl_schedule_node_band_n_member(node);
2807 if (n < dim)
2808 node = isl_schedule_node_band_split(node, n);
2810 return node;
2813 /* Scale a band node that may have been split by split_band.
2814 * "sizes" are the scaling factors for the original node.
2815 * "node" either points to the original band node, or the outer
2816 * of the two pieces after splitting.
2818 * If the number of elements in "node" is smaller than the number of
2819 * elements in "sizes", then some splitting has occurred and we split
2820 * "sizes" in the same way.
2822 static __isl_give isl_schedule_node *scale_band(
2823 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2825 int n, dim;
2827 n = isl_multi_val_dim(sizes, isl_dim_set);
2828 dim = isl_schedule_node_band_n_member(node);
2829 if (n > dim) {
2830 isl_multi_val *sizes2;
2832 sizes2 = isl_multi_val_copy(sizes);
2833 sizes = isl_multi_val_drop_dims(sizes,
2834 isl_dim_set, dim, n - dim);
2835 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2836 node = isl_schedule_node_child(node, 0);
2837 node = isl_schedule_node_band_scale(node, sizes2);
2838 node = isl_schedule_node_parent(node);
2841 return isl_schedule_node_band_scale(node, sizes);
2844 /* Return an isl_multi_aff, with as elements the parameters in "space"
2845 * that have the names specified by the elements in "names".
2846 * If (some of) these parameters do not already appear in "space",
2847 * then they are added first.
2849 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2850 __isl_keep isl_id_list *names)
2852 int i, n;
2853 isl_local_space *ls;
2854 isl_multi_aff *ma;
2856 if (!names)
2857 space = isl_space_free(space);
2859 n = isl_id_list_n_id(names);
2860 for (i = 0; i < n; ++i) {
2861 int pos;
2862 isl_id *id;
2864 id = isl_id_list_get_id(names, i);
2865 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2866 if (pos >= 0) {
2867 isl_id_free(id);
2868 continue;
2870 pos = isl_space_dim(space, isl_dim_param);
2871 space = isl_space_add_dims(space, isl_dim_param, 1);
2872 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2874 ma = isl_multi_aff_zero(isl_space_copy(space));
2875 ls = isl_local_space_from_space(isl_space_domain(space));
2876 for (i = 0; i < n; ++i) {
2877 int pos;
2878 isl_id *id;
2879 isl_aff *aff;
2881 id = isl_id_list_get_id(names, i);
2882 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2883 isl_id_free(id);
2884 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2885 isl_dim_param, pos);
2886 ma = isl_multi_aff_set_aff(ma, i, aff);
2888 isl_local_space_free(ls);
2890 return ma;
2893 /* Return constraints on the domain elements that equate a sequence of
2894 * parameters called "names", to the partial schedule
2895 * of "node" modulo the integers in "size".
2896 * The number of elements in the array "size" should be equal
2897 * to the number of elements in "names".
2898 * The number of members of the band node "node" should be smaller
2899 * than or equal to this number. If it is smaller, then the first
2900 * elements of "names" are equated to zero.
2902 static __isl_give isl_union_set *set_schedule_modulo(
2903 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2904 int *size)
2906 int n, n_zero;
2907 isl_space *space;
2908 isl_multi_aff *ma;
2909 isl_multi_union_pw_aff *mupa, *mupa2;
2910 isl_multi_val *mv;
2911 isl_union_set *domain;
2913 if (!node)
2914 return NULL;
2915 n = isl_id_list_n_id(names);
2916 if (n == 0)
2917 return isl_schedule_node_get_universe_domain(node);
2918 n_zero = n - isl_schedule_node_band_n_member(node);
2920 mupa = isl_schedule_node_band_get_partial_schedule(node);
2921 mv = construct_band_tiles_sizes(node, size + n_zero);
2922 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2924 space = isl_multi_union_pw_aff_get_space(mupa);
2925 space = isl_space_params(space);
2926 space = isl_space_set_from_params(space);
2927 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2928 ma = isl_multi_aff_zero(space);
2930 domain = isl_schedule_node_get_universe_domain(node);
2931 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2932 isl_union_set_copy(domain), ma);
2933 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2935 space = isl_multi_union_pw_aff_get_space(mupa);
2936 ma = parameter_vector(space, names);
2938 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2939 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2941 return isl_multi_union_pw_aff_zero_union_set(mupa);
2944 /* Insert a context node at "node" introducing the block and thread
2945 * identifiers along with their bounds, which are stored in kernel->grid_size
2946 * and kernel->block_dim.
2947 * Note that the bounds on the block identifiers may implicitly impose
2948 * constraints on the parameters. A guard needs to be inserted
2949 * in the schedule tree to ensure that those bounds hold at "node".
2950 * This guard is inserted in insert_guard.
2952 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2953 __isl_take isl_schedule_node *node)
2955 isl_set *context;
2957 context = isl_set_universe(isl_set_get_space(kernel->context));
2959 context = add_bounded_parameters_dynamic(context,
2960 kernel->grid_size, kernel->block_ids);
2961 context = add_bounded_parameters(context,
2962 kernel->block_dim, kernel->thread_ids);
2964 node = isl_schedule_node_insert_context(node, context);
2966 return node;
2969 /* Insert a guard that eliminates kernel launches where the kernel
2970 * obviously does not have any work to do.
2972 * In particular, eliminate kernel launches where there are obviously
2973 * zero blocks.
2974 * Use the same block size constraints that are used to create the context
2975 * to ensure that all constraints implicit in the constructed context
2976 * are imposed by the guard.
2978 * Additionally, add other constraints that are valid
2979 * for each executed instance ("context"), as long as this does not result
2980 * in a disjunction.
2982 static __isl_give isl_schedule_node *insert_guard(
2983 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2984 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2986 unsigned nparam, n;
2987 isl_set *guard;
2988 isl_id_list *ids;
2990 guard = isl_set_copy(context);
2991 guard = isl_set_compute_divs(guard);
2992 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2994 nparam = isl_set_dim(guard, isl_dim_param);
2995 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2996 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2997 guard = add_bounded_parameters_dynamic(guard, size, ids);
2998 isl_id_list_free(ids);
2999 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
3001 node = isl_schedule_node_insert_guard(node, guard);
3003 return node;
3006 /* Does any array reference group mapping require the band that is mapped
3007 * to threads to be unrolled?
3009 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
3011 int i, j;
3013 for (i = 0; i < kernel->n_array; ++i) {
3014 struct gpu_local_array_info *array = &kernel->array[i];
3016 for (j = 0; j < array->n_group; ++j) {
3017 struct gpu_array_ref_group *group = array->groups[j];
3018 if (gpu_array_ref_group_requires_unroll(group))
3019 return 1;
3023 return 0;
3026 /* Mark the given band node "node" for unrolling by the AST generator and
3027 * then sink it to the leaves of the schedule tree.
3028 * All dimensions of "node" are assumed to be coincident, such that this
3029 * sinking is a valid operation.
3031 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
3033 node = ppcg_set_schedule_node_type(node, isl_ast_loop_unroll);
3035 node = isl_schedule_node_band_sink(node);
3037 return node;
3040 /* Insert a synchronization node in the schedule tree of "node"
3041 * after the core computation of "kernel" at the level of the band
3042 * that is mapped to threads, except if that level is equal to
3043 * that of the band that is mapped to blocks or if there are no writes
3044 * to global or shared memory in the core computation that require
3045 * synchronization.
3046 * If there are any writes to shared memory and the shared memory
3047 * copying is performed at the same level, then synchronization
3048 * is needed between the core and the copying anyway, so we might
3049 * as well add it here. If the copying is performed at a higher
3050 * level, then different iterations of intermediate schedule dimensions
3051 * may have a different mapping from between shared memory elements and
3052 * threads, such that synchronization is required after the core.
3053 * "node" is assumed to point to the kernel node.
3055 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
3056 __isl_take isl_schedule_node *node)
3058 int kernel_depth;
3059 int need_sync;
3061 need_sync = any_global_or_shared_sync_writes(kernel);
3062 if (need_sync < 0)
3063 return isl_schedule_node_free(node);
3064 if (!need_sync)
3065 return node;
3067 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3069 node = gpu_tree_move_down_to_thread(node, kernel->core);
3070 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
3071 return gpu_tree_move_up_to_kernel(node);
3073 node = gpu_tree_ensure_following_sync(node, kernel);
3075 node = gpu_tree_move_up_to_kernel(node);
3077 return node;
3080 /* Return a read ("read" is 1) or write access relation for "group"
3081 * with those accesses removed that are only needed to communicate data
3082 * within the subtree of the schedule rooted at "node".
3083 * Furthermore, include the prefix schedule at "node".
3084 * That is, return a relation of the form
3086 * S -> [D -> A]
3088 * with D the outer schedule dimensions at "node".
3090 static __isl_give isl_union_map *anchored_non_local_accesses(
3091 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3092 __isl_take isl_schedule_node *node, int read)
3094 isl_union_map *access;
3095 isl_union_map *prefix;
3097 access = gpu_array_ref_group_access_relation(group, read, !read);
3098 access = remove_local_accesses_group(kernel, group, access, node, read);
3099 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3100 access = isl_union_map_range_product(prefix, access);
3102 return access;
3105 /* Given an array reference group "group", create a mapping
3107 * read[D -> A] -> [D -> A]
3109 * if "read" is set or
3111 * write[D -> A] -> [D -> A]
3113 * if "read" is not set.
3114 * D corresponds to the outer tile->depth dimensions of
3115 * the kernel schedule.
3117 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3118 struct gpu_array_ref_group *group, int read)
3120 struct gpu_array_tile *tile;
3121 isl_space *space;
3122 isl_id *id;
3124 tile = gpu_array_ref_group_tile(group);
3125 space = isl_space_copy(group->array->space);
3126 space = isl_space_from_range(space);
3127 space = isl_space_add_dims(space, isl_dim_in, tile->depth);
3128 space = isl_space_wrap(space);
3129 space = isl_space_map_from_set(space);
3131 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3132 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3134 return isl_multi_aff_identity(space);
3137 /* If any writes in "group" require synchronization, then make sure
3138 * that there is a synchronization node for "kernel" after the node
3139 * following "node" in a sequence.
3141 * If "shared" is set and no synchronization is needed for
3142 * the writes to global memory, then add synchronization before
3143 * the kernel to protect shared memory from being overwritten
3144 * by the next iteration of the core computation.
3145 * No additional synchronization is needed to protect against
3146 * the next copy into shared memory because each element of
3147 * the shared memory tile is always copied by the same thread.
3149 static __isl_give isl_schedule_node *add_group_write_sync(
3150 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3151 struct gpu_array_ref_group *group, int shared)
3153 int need_sync;
3155 need_sync = any_sync_writes_in_group(kernel, group);
3156 if (need_sync < 0)
3157 return isl_schedule_node_free(node);
3158 if (need_sync) {
3159 node = isl_schedule_node_parent(node);
3160 node = isl_schedule_node_next_sibling(node);
3161 node = isl_schedule_node_child(node, 0);
3162 node = gpu_tree_ensure_following_sync(node, kernel);
3163 } else if (shared) {
3164 struct gpu_array_tile *tile;
3166 tile = gpu_array_ref_group_tile(group);
3167 node = isl_schedule_node_parent(node);
3168 node = isl_schedule_node_parent(node);
3169 node = gpu_tree_move_down_to_depth(node, tile->depth,
3170 kernel->core);
3171 node = gpu_tree_move_left_to_sync(node, kernel);
3174 return node;
3177 /* Add copy statements to the schedule tree of "node"
3178 * for reading from global memory to private memory (if "read" is set) or
3179 * for writing back from private memory to global memory
3180 * (if "read" is not set) for the array reference group "group" that
3181 * is mapped to private memory.
3182 * On input, "node" points to the kernel node, and it is moved
3183 * back there on output.
3185 * The copies are performed in the order of the array elements.
3186 * The copy statement instances include a reference to the outer
3187 * tile->depth dimensions of the kernel schedule for ease of
3188 * combining them with the group tiling.
3190 * That is, the extra schedule is of the form
3192 * type[D -> A] -> A
3194 * where D corresponds to the outer tile->depth dimensions of
3195 * the kernel schedule and A to the global array.
3196 * This schedule is unrolled because registers are not addressable.
3198 * The copying is inserted in the schedule tree through an extension
3199 * of the form
3201 * D -> type[D -> A]
3203 * where the extra domain elements type[D -> A] are those accessed
3204 * by the group.
3205 * A filter is inserted on type[D -> A] to ensure that the element
3206 * is read/written by the same thread that needs the element.
3207 * This filter is obtained by applying
3209 * S -> type[D -> A]
3211 * to the thread filter for the core statements.
3213 * The extension is inserted before the core computation in case of a read
3214 * and after the core computation in case of a write.
3215 * In the latter case, we also make sure that there is a synchronization
3216 * node after the write to global memory, unless this write is performed
3217 * at the outer level of the kernel.
3218 * In principle, this synchronization could be inserted higher
3219 * in the schedule tree depending on where the corresponding reads
3220 * from global memory are performed.
3222 static __isl_give isl_schedule_node *add_copies_group_private(
3223 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3224 __isl_take isl_schedule_node *node, int read)
3226 struct gpu_array_tile *tile;
3227 isl_union_map *access;
3228 isl_union_map *prefix;
3229 isl_union_set *domain;
3230 isl_space *space;
3231 isl_multi_aff *from_access;
3232 isl_multi_pw_aff *mpa;
3233 isl_multi_union_pw_aff *mupa;
3234 isl_schedule_node *graft;
3235 isl_union_set *filter;
3236 int kernel_depth;
3237 int empty;
3239 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3240 tile = gpu_array_ref_group_tile(group);
3241 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3243 access = anchored_non_local_accesses(kernel, group, node, read);
3244 empty = isl_union_map_is_empty(access);
3245 if (empty < 0 || empty) {
3246 isl_union_map_free(access);
3247 if (empty < 0)
3248 return isl_schedule_node_free(node);
3249 return gpu_tree_move_up_to_kernel(node);
3252 group->array->global = 1;
3253 group->local_array->global = 1;
3255 from_access = create_from_access(kernel->ctx, group, read);
3256 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3257 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3259 filter = isl_union_set_copy(kernel->thread_filter);
3260 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3261 filter = isl_union_set_detect_equalities(filter);
3262 filter = isl_union_set_coalesce(filter);
3264 domain = isl_union_map_range(access);
3265 access = isl_union_set_wrapped_domain_map(domain);
3266 access = isl_union_map_reverse(access);
3267 access = isl_union_map_coalesce(access);
3268 graft = isl_schedule_node_from_extension(access);
3270 space = isl_space_map_from_set(space);
3271 mpa = isl_multi_pw_aff_identity(space);
3272 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3273 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3275 graft = isl_schedule_node_child(graft, 0);
3276 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3277 graft = unroll(graft);
3279 graft = isl_schedule_node_insert_filter(graft, filter);
3281 graft = isl_schedule_node_parent(graft);
3283 if (read)
3284 node = isl_schedule_node_graft_before(node, graft);
3285 else {
3286 node = isl_schedule_node_graft_after(node, graft);
3287 if (kernel_depth < tile->depth)
3288 node = add_group_write_sync(node, kernel, group, 0);
3291 node = gpu_tree_move_up_to_kernel(node);
3293 return node;
3296 /* Add copy statements to the schedule tree of "node"
3297 * for reading from global memory to shared memory (if "read" is set) or
3298 * for writing back from shared memory to global memory
3299 * (if "read" is not set) for the array reference group "group" that
3300 * is mapped to shared memory.
3301 * On input, "node" points to the kernel node, and it is moved
3302 * back there on output.
3304 * The copies are performed in the order of the corresponding shared
3305 * memory tile.
3306 * The copy statement instances include a reference to the outer
3307 * tile->depth dimensions of the kernel schedule for ease of
3308 * combining them with the group tiling.
3310 * If we are performing a read from global memory to shared memory and
3311 * if the array involved is not a scalar, then we copy
3312 * the entire tile to shared memory. This may result in some extra
3313 * elements getting copied, but it should lead to simpler code
3314 * (which means that fewer registers may be needed) and less divergence.
3316 * Otherwise, we only copy the elements that will be read or have been written
3317 * in the kernel.
3319 * That is, the extra schedule is of the form
3321 * type[D -> A] -> T
3323 * where D corresponds to the outer tile->depth dimensions of
3324 * the kernel schedule, A to the global array and T is the corresponding
3325 * shared memory tile.
3327 * The copying is inserted in the schedule tree through an extension
3328 * of the form
3330 * D -> type[D -> A]
3332 * where the extra domain elements type[D -> A] are those accessed
3333 * by the group. In the case of read from a non-scalar, this set
3334 * is replaced by the entire shared memory tile.
3336 * A filter is inserted on type[D -> A] to map the copy instances
3337 * to the threads. In particular, the thread identifiers are
3338 * equated to the position inside the shared memory tile (T)
3339 * modulo the block size.
3340 * We try to align the innermost tile dimension with the innermost
3341 * thread identifier (x) as a heuristic to improve coalescing.
3342 * In particular, if the dimension of the tile is greater than
3343 * the dimension of the block, then the schedule mapping to the tile
3344 * is broken up into two pieces and the filter is applied to the inner part.
3345 * If, on the other hand, the dimension of the tile is smaller than
3346 * the dimension of the block, then the initial thread identifiers
3347 * are equated to zero and the remaining thread identifiers are
3348 * matched to the memory tile.
3350 * The extension is inserted before the core computation in case of a read
3351 * and after the core computation in case of a write.
3352 * In the case of a read, we first need to make sure there is some
3353 * synchronization before the core computation such that we can put the read
3354 * from global memory to shared memory before that synchronization.
3355 * This ensures that all threads have finished copying into shared memory
3356 * before the shared memory is used.
3357 * We also need to make sure that there is a synchronization node after
3358 * the core computation to ensure that the next load into shared memory
3359 * only happens after all data has been used. There is no need for
3360 * this synchronization if we are at the outer level since then there
3361 * won't be a next load.
3362 * In the case of a write, we need to make sure there is some synchronization
3363 * after the core computation such taht we can put the write from shared
3364 * memory to global memory after that synchronization.
3365 * Unless we are at the outer level, we also need a synchronization node
3366 * after the write to ensure the data is saved to global memory
3367 * before the next iteration write to the same shared memory.
3368 * It also makes sure the data has arrived in global memory before
3369 * it is read in a subsequent iteration.
3371 static __isl_give isl_schedule_node *add_copies_group_shared(
3372 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3373 __isl_take isl_schedule_node *node, int read)
3375 struct gpu_array_tile *tile;
3376 isl_union_map *access;
3377 isl_union_set *domain;
3378 isl_union_set *sync;
3379 isl_multi_aff *ma;
3380 isl_multi_aff *from_access;
3381 isl_multi_pw_aff *mpa;
3382 isl_multi_union_pw_aff *mupa;
3383 isl_schedule_node *graft;
3384 isl_union_set *filter;
3385 int skip;
3386 int kernel_depth;
3387 int empty;
3389 tile = gpu_array_ref_group_tile(group);
3390 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3391 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3393 access = anchored_non_local_accesses(kernel, group, node, read);
3394 empty = isl_union_map_is_empty(access);
3395 if (empty < 0 || empty) {
3396 isl_union_map_free(access);
3397 if (empty < 0)
3398 return isl_schedule_node_free(node);
3399 return gpu_tree_move_up_to_kernel(node);
3402 group->array->global = 1;
3403 group->local_array->global = 1;
3405 from_access = create_from_access(kernel->ctx, group, read);
3407 ma = isl_multi_aff_copy(tile->tiling);
3408 ma = isl_multi_aff_pullback_multi_aff(ma,
3409 isl_multi_aff_copy(from_access));
3410 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3411 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3413 domain = isl_union_map_range(access);
3415 if (read && !gpu_array_is_scalar(group->array)) {
3416 isl_map *map;
3417 isl_union_set_free(domain);
3418 map = group_tile(group);
3419 domain = isl_union_set_from_set(isl_map_wrap(map));
3422 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3423 access = isl_union_set_wrapped_domain_map(domain);
3424 access = isl_union_map_reverse(access);
3425 access = isl_union_map_coalesce(access);
3426 graft = isl_schedule_node_from_extension(access);
3428 graft = isl_schedule_node_child(graft, 0);
3430 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3432 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3433 graft = isl_schedule_node_band_split(graft,
3434 tile->n - kernel->n_block);
3435 graft = isl_schedule_node_child(graft, 0);
3437 if (tile->n < kernel->n_block)
3438 skip = kernel->n_block - tile->n;
3439 else
3440 skip = 0;
3441 filter = set_schedule_modulo(graft, kernel->thread_ids,
3442 kernel->block_dim);
3443 if (!kernel->options->wrap)
3444 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3445 kernel->options);
3446 if (tile->n > kernel->n_block && kernel->n_block > 0)
3447 graft = isl_schedule_node_parent(graft);
3448 graft = isl_schedule_node_insert_filter(graft, filter);
3450 while (graft && isl_schedule_node_has_parent(graft))
3451 graft = isl_schedule_node_parent(graft);
3453 if (read) {
3454 if (kernel_depth < tile->depth)
3455 node = gpu_tree_ensure_sync_after_core(node, kernel);
3456 node = gpu_tree_move_left_to_sync(node, kernel);
3457 node = isl_schedule_node_graft_before(node, graft);
3458 } else {
3459 node = gpu_tree_move_right_to_sync(node, kernel);
3460 node = isl_schedule_node_graft_after(node, graft);
3461 if (kernel_depth < tile->depth)
3462 node = add_group_write_sync(node, kernel, group, 1);
3465 node = gpu_tree_move_up_to_kernel(node);
3467 return node;
3470 /* Check whether the array reference group "group" is mapped to
3471 * private or shared memory and, if so,
3472 * add copy statements to the schedule tree of "node"
3473 * for reading from global memory to private or shared memory
3474 * (if "read" is set) or for writing back from private or shared memory
3475 * to global memory (if "read" is not set) for this group.
3476 * On input, "node" points to the kernel node, and it is moved
3477 * back there on output.
3479 static __isl_give isl_schedule_node *add_copies_group(
3480 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3481 __isl_take isl_schedule_node *node, int read)
3483 enum ppcg_group_access_type type;
3485 type = gpu_array_ref_group_type(group);
3486 if (type == ppcg_access_private)
3487 return add_copies_group_private(kernel, group, node, read);
3488 if (type == ppcg_access_shared)
3489 return add_copies_group_shared(kernel, group, node, read);
3490 return node;
3493 /* For each array reference group that is mapped to private or shared memory,
3494 * add copy statements to the schedule tree of "node"
3495 * for reading from global memory to private or shared memory
3496 * and for writing back.
3497 * On input, "node" points to the kernel node, and it is moved
3498 * back there on output.
3500 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3501 __isl_take isl_schedule_node *node)
3503 int i, j;
3505 for (i = 0; i < kernel->n_array; ++i) {
3506 struct gpu_local_array_info *array = &kernel->array[i];
3508 for (j = 0; j < array->n_group; ++j) {
3509 struct gpu_array_ref_group *group = array->groups[j];
3511 node = add_copies_group(kernel, group, node, 1);
3512 if (!node)
3513 return NULL;
3514 node = add_copies_group(kernel, group, node, 0);
3515 if (!node)
3516 return NULL;
3520 return node;
3523 /* Mark all dimensions in the current band node atomic.
3525 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3527 return ppcg_set_schedule_node_type(node, isl_ast_loop_atomic);
3530 /* Mark "node" atomic, if it is a band node.
3531 * Do the same for all ancestors.
3532 * Return a pointer to "node" (in the updated schedule tree).
3534 static __isl_give isl_schedule_node *atomic_ancestors(
3535 __isl_take isl_schedule_node *node)
3537 int pos;
3539 if (!node)
3540 return NULL;
3541 if (!isl_schedule_node_has_parent(node))
3542 return node;
3544 pos = isl_schedule_node_get_child_position(node);
3545 node = isl_schedule_node_parent(node);
3546 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3547 node = atomic(node);
3548 node = atomic_ancestors(node);
3549 node = isl_schedule_node_child(node, pos);
3551 return node;
3554 /* Collect all write references that require synchronization.
3555 * "node" is assumed to point to the kernel node.
3556 * Each reference is represented by a universe set in a space
3558 * [S[i,j] -> R[]]
3560 * with S[i,j] the statement instance space and R[] the array reference.
3562 * This function should be called before block and thread filters are added.
3564 * Synchronization is needed after a write if there is a subsequent read
3565 * within the same block that may not be performed by the same thread.
3566 * There should not be any dependences between different blocks,
3567 * so we start with the flow dependences within the same kernel invocation
3568 * and we subtract from these those dependences that are mapped
3569 * to the same iteration of the bands where synchronization is inserted.
3570 * We do not remove pairs of instances that are known to map to
3571 * the same thread across different iterations of the intermediate
3572 * bands because the read may be performed by a different thread
3573 * than the one that needs the value if shared memory is involved.
3575 * We also consider all pairs of possible writes that access the same
3576 * memory location and that may be mapped to the same block but not
3577 * to the same iteration of the intermediate bands.
3578 * In theory, it would be possible for one thread to still be in
3579 * a previous iteration of a loop in these bands.
3580 * A write to global memory in this delayed thread could then overwrite
3581 * a write from another thread that has already moved on to
3582 * the next iteration.
3584 * After computing the above writes paired off with reads or writes
3585 * that depend on them, we project onto the domain writes.
3586 * Sychronization is needed after writes to global memory
3587 * through these references.
3589 static __isl_give isl_union_set *compute_sync_writes(
3590 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3592 isl_union_map *local;
3593 isl_union_map *may_writes, *shared_access;
3594 isl_union_map *kernel_prefix, *thread_prefix;
3595 isl_union_map *equal;
3596 isl_union_set *wrap;
3597 isl_union_set *domain;
3599 domain = isl_schedule_node_get_universe_domain(node);
3600 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3601 node = isl_schedule_node_copy(node);
3602 node = gpu_tree_move_down_to_thread(node, kernel->core);
3603 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3604 isl_schedule_node_free(node);
3606 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3607 may_writes = isl_union_map_curry(may_writes);
3608 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3609 may_writes = isl_union_map_uncurry(may_writes);
3610 shared_access = isl_union_map_copy(may_writes);
3611 shared_access = isl_union_map_apply_range(shared_access,
3612 isl_union_map_reverse(may_writes));
3614 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3615 local = isl_union_map_union(local, shared_access);
3616 local = isl_union_map_zip(local);
3618 equal = isl_union_map_apply_range(kernel_prefix,
3619 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3620 wrap = isl_union_map_wrap(equal);
3621 local = isl_union_map_intersect_domain(local, wrap);
3622 equal = isl_union_map_apply_range(thread_prefix,
3623 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3624 wrap = isl_union_map_wrap(equal);
3625 local = isl_union_map_subtract_domain(local, wrap);
3627 local = isl_union_map_zip(local);
3628 local = isl_union_map_universe(local);
3630 return isl_union_map_domain(local);
3633 /* Group the domain elements into a single space, named kernelX,
3634 * with X the kernel sequence number "kernel_id".
3636 static __isl_give isl_schedule_node *group_statements(
3637 __isl_take isl_schedule_node *node, int kernel_id)
3639 char buffer[20];
3640 isl_id *id;
3642 if (!node)
3643 return NULL;
3645 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3646 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3647 return isl_schedule_node_group(node, id);
3650 /* Create a ppcg_kernel representing the domain instances that reach "node"
3651 * and insert a mark node pointing to the ppcg_kernel before "node".
3652 * The band that "node" points to is the band that needs to be mapped
3653 * to block identifiers. The band that needs to be mapped to thread
3654 * identifiers should be marked by a "thread" mark by the caller.
3655 * This mark is removed by this function.
3656 * If "scale" is set, then the band that "node" points to is scaled
3657 * by "sizes".
3659 * Mark all outer band nodes as atomic to ensure each kernel is only
3660 * scheduled once.
3661 * If the domain elements that reach "node" live in more than one space,
3662 * then group the domain elements into a single space, named kernelX,
3663 * with X the kernel sequence number.
3665 * Insert a guard node governing the kernel node to ensure that
3666 * no kernels with zero blocks are launched.
3668 * Insert a context node describing the block and thread
3669 * identifiers inside the kernel mark.
3670 * The context node needs to be inserted after the effective block size
3671 * has been determined such that the bounds on the thread identifiers
3672 * would reflect the effective block size.
3673 * Insert a filter node inside the context node mapping the statement
3674 * instances to block identifiers. In particular, the block identifiers
3675 * are equated to the partial schedule of band that was marked for mapping
3676 * to blocks modulo the grid size.
3677 * Insert a filter node inside the "thread" mark mapping the statement
3678 * instances to thread identifiers. In particular, the thread identifiers
3679 * are equated to the partial schedule of band that was marked for mapping
3680 * to threads modulo the block size.
3682 * Compute array reference groups for all arrays, set the local
3683 * array bounds based on the set of domain instances that reach
3684 * the kernel node, check the total amount of shared memory used
3685 * and compute all group tilings.
3686 * The array reference groups are computed after the block filter
3687 * has been inserted because it affects the mapping to shared or
3688 * private memory. This computation also requires the thread filter
3689 * (in the ppcg_kernel object), but this thread filter should not
3690 * have been added to the schedule tree yet since the computation
3691 * requires the schedule of the band that needs to be mapped to
3692 * threads before the privatization is applied.
3694 * If any array reference group requires the band mapped to threads
3695 * to be unrolled, then we perform the required unrolling.
3697 * We save a copy of the schedule that may influence the mappings
3698 * to shared or private memory in kernel->copy_schedule.
3700 * Finally, we add synchronization and copy statements to the schedule tree,
3701 * remove the "thread" mark and create representations for the local
3702 * variables in the kernel.
3704 * We keep a copy of the isl_id that points to the kernel to ensure
3705 * that the kernel does not get destroyed if the schedule node
3706 * is freed due to some error condition.
3708 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3709 __isl_take isl_schedule_node *node, int scale,
3710 __isl_keep isl_multi_val *sizes)
3712 struct ppcg_kernel *kernel;
3713 isl_id *id;
3714 isl_schedule_node *node_thread;
3715 isl_union_map *host_schedule;
3716 isl_set *host_domain;
3717 isl_union_set *domain;
3718 int single_statement;
3720 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3721 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3722 if (!kernel)
3723 return isl_schedule_node_free(node);
3725 domain = isl_schedule_node_get_domain(node);
3726 single_statement = isl_union_set_n_set(domain) == 1;
3728 kernel->ctx = gen->ctx;
3729 kernel->prog = gen->prog;
3730 kernel->options = gen->options;
3731 kernel->context = extract_context(node, gen->prog);
3732 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3733 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3734 gen->prog);
3735 kernel->n_grid = n_outer_coincidence(node);
3736 node_thread = isl_schedule_node_copy(node);
3737 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3738 node_thread = isl_schedule_node_child(node_thread, 0);
3739 kernel->n_block = n_outer_coincidence(node_thread);
3740 isl_schedule_node_free(node_thread);
3741 kernel->id = gen->kernel_id++;
3742 read_grid_and_block_sizes(kernel, gen);
3744 kernel->sync_writes = compute_sync_writes(kernel, node);
3746 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3747 host_domain = isl_set_from_union_set(isl_union_map_range(
3748 host_schedule));
3750 node = atomic_ancestors(node);
3752 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3753 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3754 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3756 if (!single_statement)
3757 node = group_statements(node, kernel->id);
3759 node = isl_schedule_node_child(node, 0);
3760 node = split_band(node, kernel->n_grid);
3761 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3762 kernel->n_grid, "b");
3763 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3764 kernel->grid_dim);
3765 kernel->grid_size = extract_grid_size(kernel,
3766 isl_union_set_copy(domain));
3767 if (!kernel->options->wrap)
3768 node = snap_band_to_sizes(node, kernel->grid_dim,
3769 kernel->options);
3770 if (scale)
3771 node = scale_band(node, isl_multi_val_copy(sizes));
3772 node = isl_schedule_node_parent(node);
3773 if (!single_statement)
3774 node = isl_schedule_node_parent(node);
3775 node = insert_guard(node, kernel->context, kernel->grid_size,
3776 gen->prog->scop);
3777 node = gpu_tree_move_down_to_thread(node, kernel->core);
3778 node = isl_schedule_node_child(node, 0);
3779 node = split_band(node, kernel->n_block);
3780 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3781 kernel->n_block, "t");
3782 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3783 kernel->block_dim);
3784 if (extract_block_size(kernel, domain) < 0)
3785 node = isl_schedule_node_free(node);
3787 node = gpu_tree_move_up_to_kernel(node);
3788 node = isl_schedule_node_child(node, 0);
3789 node = insert_context(kernel, node);
3790 node = isl_schedule_node_child(node, 0);
3791 node = isl_schedule_node_insert_filter(node,
3792 isl_union_set_copy(kernel->block_filter));
3794 node = gpu_tree_move_up_to_kernel(node);
3796 if (gpu_group_references(kernel, node) < 0)
3797 node = isl_schedule_node_free(node);
3798 localize_bounds(kernel, host_domain);
3799 isl_set_free(host_domain);
3801 check_shared_memory_bound(kernel);
3802 mark_global_arrays(kernel);
3803 compute_group_tilings(kernel);
3805 node = gpu_tree_move_down_to_thread(node, kernel->core);
3806 node = isl_schedule_node_child(node, 0);
3807 if (!kernel->options->wrap)
3808 node = snap_band_to_sizes(node, kernel->block_dim,
3809 kernel->options);
3810 node = isl_schedule_node_insert_filter(node,
3811 isl_union_set_copy(kernel->thread_filter));
3812 if (kernel_requires_unroll(kernel)) {
3813 node = isl_schedule_node_child(node, 0);
3814 node = unroll(node);
3817 node = gpu_tree_move_up_to_thread(node);
3818 kernel->copy_schedule_dim = isl_schedule_node_get_schedule_depth(node);
3819 kernel->copy_schedule =
3820 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3822 node = gpu_tree_move_up_to_kernel(node);
3824 node = add_sync(kernel, node);
3825 node = add_copies(kernel, node);
3827 node = gpu_tree_move_down_to_thread(node, kernel->core);
3828 node = isl_schedule_node_delete(node);
3830 node = gpu_tree_move_up_to_kernel(node);
3832 if (create_kernel_vars(kernel) < 0)
3833 node = isl_schedule_node_free(node);
3835 if (!single_statement)
3836 node = isl_schedule_node_parent(node);
3837 node = isl_schedule_node_parent(node);
3839 isl_id_free(id);
3840 return node;
3843 /* Insert a zero-dimensional permutable band at "node".
3845 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3846 __isl_take isl_schedule_node *node)
3848 isl_space *space;
3849 isl_schedule *schedule;
3850 isl_union_set *domain;
3851 isl_multi_union_pw_aff *mupa;
3853 schedule = isl_schedule_node_get_schedule(node);
3854 domain = isl_schedule_get_domain(schedule);
3855 space = isl_union_set_get_space(domain);
3856 isl_union_set_free(domain);
3857 isl_schedule_free(schedule);
3859 space = isl_space_set_from_params(space);
3860 mupa = isl_multi_union_pw_aff_zero(space);
3861 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3862 node = isl_schedule_node_band_set_permutable(node, 1);
3864 return node;
3867 /* If "node" is the outermost permutable band that can be mapped to block and
3868 * thread identifiers in its branch (or the root of a subtree with
3869 * no such outer bands),
3870 * then mark the band as such, attaching a ppcg_kernel to the mark.
3872 * If "node" is the root of a subtree without permutable bands,
3873 * then insert a zero-dimensional permutable band such that
3874 * we can assume that "node" always points to a band node.
3875 * This includes the case where "node" already points to a band node,
3876 * but one without any coincident dimension. In this case,
3877 * the extra node ensures that this original node does not get tiled.
3879 * Tile "node" using user specified tile sizes, after splitting the band
3880 * if the number of specified tile sizes is smaller than the dimension
3881 * of the band. Mark the point band of this tiling as the band that
3882 * needs to be mapped to threads.
3883 * Create a kernel representing the domain instances that reach "node" and
3884 * insert a mark node pointing to the ppcg_kernel before the band node.
3886 static __isl_give isl_schedule_node *mark_outer_permutable(
3887 __isl_take isl_schedule_node *node, void *user)
3889 struct gpu_gen *gen = user;
3890 int outer;
3891 int scale;
3892 int tile_len;
3893 int *tile_size;
3894 isl_id *id;
3895 isl_multi_val *sizes;
3897 outer = is_outer_tilable(node);
3898 if (outer < 0)
3899 return isl_schedule_node_free(node);
3900 if (!outer)
3901 return node;
3903 if (isl_schedule_node_get_type(node) != isl_schedule_node_band ||
3904 !isl_schedule_node_band_member_get_coincident(node, 0))
3905 node = insert_empty_permutable_band(node);
3907 tile_len = isl_schedule_node_band_n_member(node);
3908 tile_size = read_tile_sizes(gen, &tile_len);
3909 if (!tile_size)
3910 return isl_schedule_node_free(node);
3911 if (tile_len < isl_schedule_node_band_n_member(node))
3912 node = isl_schedule_node_band_split(node, tile_len);
3913 sizes = construct_band_tiles_sizes(node, tile_size);
3914 node = tile_band(node, isl_multi_val_copy(sizes));
3915 node = isl_schedule_node_child(node, 0);
3916 id = isl_id_alloc(gen->ctx, "thread", NULL);
3917 node = isl_schedule_node_insert_mark(node, id);
3918 node = isl_schedule_node_parent(node);
3920 scale = gen->options->scale_tile_loops;
3921 node = create_kernel(gen, node, scale, sizes);
3922 isl_multi_val_free(sizes);
3923 free(tile_size);
3925 return node;
3928 /* Given a set or sequence node, return the union the filters of either all
3929 * (if "only_initial" is not set) or the initial (if "only_initial" is set)
3930 * direct subtrees that do not contain any suitably permutable bands
3931 * (according to subtree_has_permutable_bands).
3933 static __isl_give isl_union_set *get_non_parallel_subtree_filters(
3934 __isl_keep isl_schedule_node *node, int only_initial)
3936 isl_space *space;
3937 isl_union_set *filter;
3938 int i, n;
3940 n = isl_schedule_node_n_children(node);
3941 if (n < 0)
3942 return NULL;
3944 node = isl_schedule_node_copy(node);
3945 node = isl_schedule_node_child(node, 0);
3946 filter = isl_schedule_node_filter_get_filter(node);
3947 node = isl_schedule_node_parent(node);
3948 space = isl_union_set_get_space(filter);
3949 isl_union_set_free(filter);
3950 filter = isl_union_set_empty(space);
3952 for (i = 0; i < n; ++i) {
3953 int parallelism;
3955 node = isl_schedule_node_child(node, i);
3956 parallelism = subtree_has_permutable_bands(node);
3957 if (parallelism < 0) {
3958 filter = isl_union_set_free(filter);
3959 } else if (!parallelism) {
3960 isl_union_set *filter_i;
3961 filter_i = isl_schedule_node_filter_get_filter(node);
3962 filter = isl_union_set_union(filter, filter_i);
3963 } else if (only_initial)
3964 break;
3965 node = isl_schedule_node_parent(node);
3968 isl_schedule_node_free(node);
3970 return filter;
3973 /* Given a set or sequence node, return the union of the filters of
3974 * the direct subtrees that do not contain any suitably permutable bands
3975 * (according to subtree_has_permutable_bands).
3977 static __isl_give isl_union_set *get_all_non_parallel_subtree_filters(
3978 __isl_keep isl_schedule_node *node)
3980 return get_non_parallel_subtree_filters(node, 0);
3983 /* Given a set or sequence node, return the union of the filters of
3984 * the initial direct subtrees that do not contain any suitably permutable
3985 * bands (according to subtree_has_permutable_bands).
3987 static __isl_give isl_union_set *get_initial_non_parallel_subtree_filters(
3988 __isl_keep isl_schedule_node *node)
3990 return get_non_parallel_subtree_filters(node, 1);
3993 /* Mark all variables that are accessed by the statement instances in "domain"
3994 * and that are local to "prog" as requiring a declaration in the host code.
3996 static int declare_accessed_local_variables(struct gpu_prog *prog,
3997 __isl_keep isl_union_set *domain)
3999 isl_union_set *arrays;
4000 int i;
4002 if (!ppcg_scop_any_hidden_declarations(prog->scop))
4003 return 0;
4004 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
4006 for (i = 0; i < prog->n_array; ++i) {
4007 isl_space *space;
4008 isl_set *set;
4009 int empty;
4011 if (!prog->array[i].local)
4012 continue;
4013 space = isl_set_get_space(prog->array[i].extent);
4014 set = isl_union_set_extract_set(arrays, space);
4015 empty = isl_set_plain_is_empty(set);
4016 isl_set_free(set);
4017 if (empty < 0)
4018 goto error;
4019 if (!empty)
4020 prog->array[i].declare_local = 1;
4023 isl_union_set_free(arrays);
4024 return 0;
4025 error:
4026 isl_union_set_free(arrays);
4027 return -1;
4030 /* If "node" points to a set node, then separate its children
4031 * into subtrees that have suitably permutable bands and
4032 * those that do not.
4033 * Adjust the schedule tree in order to execute the second group
4034 * after the first group and return a pointer to the first group,
4035 * assuming there are any such subtrees.
4036 * If "node" points to a sequence node, then separate the initial
4037 * children that do not have suitably permutable bands and
4038 * return a pointer to the subsequence of children that do have such bands,
4039 * assuming there are any such subtrees.
4041 * In both cases, mark all local variables in "prog" that are accessed by
4042 * the group without permutable bands as requiring a declaration on the host.
4044 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
4045 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
4047 isl_union_set *filter;
4048 enum isl_schedule_node_type type;
4050 if (!node)
4051 return NULL;
4052 type = isl_schedule_node_get_type(node);
4053 if (type == isl_schedule_node_set) {
4054 filter = get_all_non_parallel_subtree_filters(node);
4055 if (!filter)
4056 node = isl_schedule_node_free(node);
4058 if (declare_accessed_local_variables(prog, filter) < 0)
4059 node = isl_schedule_node_free(node);
4060 node = isl_schedule_node_order_after(node, filter);
4061 } else if (type == isl_schedule_node_sequence) {
4062 filter = get_initial_non_parallel_subtree_filters(node);
4063 if (!filter)
4064 node = isl_schedule_node_free(node);
4066 if (declare_accessed_local_variables(prog, filter) < 0)
4067 node = isl_schedule_node_free(node);
4068 node = isl_schedule_node_order_before(node, filter);
4071 return node;
4074 /* Replace any reference to an array element in the range of "copy"
4075 * by a reference to all array elements (defined by the extent of the array).
4077 static __isl_give isl_union_map *approximate_copy_out(
4078 __isl_take isl_union_map *copy, struct gpu_prog *prog)
4080 int i;
4081 isl_union_map *res;
4083 res = isl_union_map_empty(isl_union_map_get_space(copy));
4085 for (i = 0; i < prog->n_array; ++i) {
4086 isl_space *space;
4087 isl_set *set;
4088 isl_union_map *copy_i;
4089 isl_union_set *extent, *domain;
4091 space = isl_space_copy(prog->array[i].space);
4092 extent = isl_union_set_from_set(isl_set_universe(space));
4093 copy_i = isl_union_map_copy(copy);
4094 copy_i = isl_union_map_intersect_range(copy_i, extent);
4095 set = isl_set_copy(prog->array[i].extent);
4096 extent = isl_union_set_from_set(set);
4097 domain = isl_union_map_domain(copy_i);
4098 copy_i = isl_union_map_from_domain_and_range(domain, extent);
4099 res = isl_union_map_union(res, copy_i);
4102 isl_union_map_free(copy);
4104 return res;
4107 /* Insert "kernel" marks that point to a ppcg_kernel structure
4108 * in front of all outermost tilable band that (by construction)
4109 * have at least one parallel loop.
4111 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
4112 __isl_take isl_schedule_node *node)
4114 return isl_schedule_node_map_descendant_bottom_up(node,
4115 &mark_outer_permutable, gen);
4118 /* Construct schedule constraints from the dependences in prog->scop and
4119 * the array order dependences in prog->array_order.
4121 * If live range reordering is allowed, then we need to make sure
4122 * that live ranges on arrays are not run in parallel since doing
4123 * so would require array expansion. We therefore add the array
4124 * order dependences to the coincidence dependences. Non-zero array
4125 * order dependences will then prevent a schedule dimension from being
4126 * considered parallel.
4127 * Live ranges derived from scalars are allowed to be run in parallel
4128 * since we force the scalars to be mapped to private memory in
4129 * check_scalar_live_ranges.
4130 * If live range reordering is allowed, then the false dependences
4131 * are not added to the validity constraints as that would prevent
4132 * reordering. Instead, the external false dependences that enforce that reads
4133 * from potentially live-in data precede any later write and
4134 * that writes of potentially live-out data follow any other earlier write
4135 * are added to the validity and the coincidence constraints.
4136 * The false dependences are still added to the proximity constraints
4137 * for consistency with the case where live range reordering is not allowed.
4138 * The coincidence constraints then consist of flow dependences,
4139 * external false dependences and array order dependences.
4140 * The independences can be filtered out from the first two sets.
4141 * They have already been filtered out from the array order dependences
4142 * on a per array basis in collect_order_dependences.
4143 * There is no need for a per array handling of the other two sets
4144 * as there should be no flow or external false dependence on local
4145 * variables that can be filtered out.
4147 static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4148 struct gpu_prog *prog)
4150 isl_union_set *domain;
4151 isl_union_map *dep_raw, *dep;
4152 isl_union_map *validity, *proximity, *coincidence;
4153 isl_schedule_constraints *sc;
4155 domain = isl_union_set_copy(prog->scop->domain);
4156 sc = isl_schedule_constraints_on_domain(domain);
4157 sc = isl_schedule_constraints_set_context(sc,
4158 isl_set_copy(prog->scop->context));
4159 if (prog->scop->options->live_range_reordering) {
4160 sc = isl_schedule_constraints_set_conditional_validity(sc,
4161 isl_union_map_copy(prog->scop->tagged_dep_flow),
4162 isl_union_map_copy(prog->scop->tagged_dep_order));
4163 proximity = isl_union_map_copy(prog->scop->dep_flow);
4164 validity = isl_union_map_copy(proximity);
4165 validity = isl_union_map_union(validity,
4166 isl_union_map_copy(prog->scop->dep_forced));
4167 proximity = isl_union_map_union(proximity,
4168 isl_union_map_copy(prog->scop->dep_false));
4169 coincidence = isl_union_map_copy(validity);
4170 coincidence = isl_union_map_subtract(coincidence,
4171 isl_union_map_copy(prog->scop->independence));
4172 coincidence = isl_union_map_union(coincidence,
4173 isl_union_map_copy(prog->array_order));
4174 } else {
4175 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4176 dep = isl_union_map_copy(prog->scop->dep_false);
4177 dep = isl_union_map_union(dep, dep_raw);
4178 dep = isl_union_map_coalesce(dep);
4179 proximity = isl_union_map_copy(dep);
4180 coincidence = isl_union_map_copy(dep);
4181 validity = dep;
4183 sc = isl_schedule_constraints_set_validity(sc, validity);
4184 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4185 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4187 if (prog->scop->options->debug->dump_schedule_constraints)
4188 isl_schedule_constraints_dump(sc);
4189 return sc;
4192 /* Compute an appropriate schedule based on the accesses in
4193 * gen->read and gen->write.
4195 * We derive schedule constraints from the dependences in gen->prog->scop
4196 * and then use isl to compute a schedule that has a parallel loop
4197 * in each tilable band.
4199 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4201 isl_schedule_constraints *sc;
4202 isl_schedule *schedule;
4204 sc = construct_schedule_constraints(gen->prog);
4205 schedule = isl_schedule_constraints_compute_schedule(sc);
4207 return schedule;
4210 /* If the band node "node" has exactly one member then mark it permutable.
4212 static __isl_give isl_schedule_node *band_set_permutable(
4213 __isl_take isl_schedule_node *node,
4214 __isl_keep isl_schedule_constraints *sc)
4216 if (isl_schedule_node_band_n_member(node) == 1)
4217 node = isl_schedule_node_band_set_permutable(node, 1);
4219 return node;
4222 /* Return the coincidence constraints between pairs of instances
4223 * that are scheduled together by the ancestors of "node".
4224 * That is, select those coincidence constraints that relate
4225 * pairs of instances that have the same value for the prefix schedule.
4226 * If the schedule depth is zero, then the prefix schedule does not
4227 * contain any information, so we intersect domain and range
4228 * of the schedule constraints with the reaching domain elements instead.
4230 static __isl_give isl_union_map *get_local_coincidence(
4231 __isl_keep isl_schedule_node *node,
4232 __isl_keep isl_schedule_constraints *sc)
4234 isl_union_map *coincidence;
4235 isl_multi_union_pw_aff *prefix;
4236 isl_union_pw_multi_aff *contraction;
4238 coincidence = isl_schedule_constraints_get_coincidence(sc);
4239 contraction = isl_schedule_node_get_subtree_contraction(node);
4240 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4241 isl_union_set *domain;
4243 domain = isl_schedule_node_get_domain(node);
4244 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4245 contraction);
4246 coincidence = isl_union_map_intersect_domain(coincidence,
4247 isl_union_set_copy(domain));
4248 coincidence = isl_union_map_intersect_range(coincidence,
4249 domain);
4250 return coincidence;
4253 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4254 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4255 contraction);
4256 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4259 /* For each member in the band node "node", determine whether
4260 * it is coincident with respect to the outer nodes and mark
4261 * it accordingly.
4263 * That is, for each coincidence constraint between pairs
4264 * of instances that are scheduled together by the outer nodes,
4265 * check that domain and range are assigned the same value
4266 * by the band member. This test is performed by checking
4267 * that imposing the same value for the band member does not
4268 * remove any elements from the set of coincidence constraints.
4270 static __isl_give isl_schedule_node *band_set_coincident(
4271 __isl_take isl_schedule_node *node,
4272 __isl_keep isl_schedule_constraints *sc)
4274 isl_union_map *coincidence;
4275 isl_union_pw_multi_aff *contraction;
4276 isl_multi_union_pw_aff *partial;
4277 int i, n;
4279 coincidence = get_local_coincidence(node, sc);
4281 partial = isl_schedule_node_band_get_partial_schedule(node);
4282 contraction = isl_schedule_node_get_subtree_contraction(node);
4283 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4284 contraction);
4285 n = isl_schedule_node_band_n_member(node);
4286 for (i = 0; i < n; ++i) {
4287 isl_union_map *coincidence_i;
4288 isl_union_pw_aff *upa;
4289 isl_multi_union_pw_aff *partial_i;
4290 int subset;
4292 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4293 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4294 coincidence_i = isl_union_map_copy(coincidence);
4295 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4296 coincidence_i, partial_i);
4297 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4298 isl_union_map_free(coincidence_i);
4300 if (subset < 0)
4301 break;
4302 node = isl_schedule_node_band_member_set_coincident(node, i,
4303 subset);
4305 if (i < n)
4306 node = isl_schedule_node_free(node);
4307 isl_multi_union_pw_aff_free(partial);
4308 isl_union_map_free(coincidence);
4310 return node;
4313 /* If "node" is a band, then set its properties.
4315 * In particular, if the band has exactly one member, then mark it permutable.
4316 * Mark the band member coincident based on the coincidence constraints
4317 * of "sc".
4319 static __isl_give isl_schedule_node *set_band_properties(
4320 __isl_take isl_schedule_node *node, void *user)
4322 isl_schedule_constraints *sc = user;
4324 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4325 return node;
4326 if (isl_schedule_node_band_n_member(node) == 0)
4327 return node;
4329 node = band_set_permutable(node, sc);
4330 node = band_set_coincident(node, sc);
4332 return node;
4335 /* Return the original schedule with all bands marked permutable and
4336 * all band members marked coincident based on the coincidence constraints.
4337 * The bands are explicitly marked permutable so that they will be considered
4338 * by mark_outer_permutable.
4340 static __isl_give isl_schedule *determine_properties_original_schedule(
4341 struct gpu_gen *gen)
4343 isl_schedule *schedule;
4344 isl_schedule_constraints *sc;
4346 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4347 sc = construct_schedule_constraints(gen->prog);
4348 schedule = isl_schedule_map_schedule_node_bottom_up(schedule,
4349 &set_band_properties, sc);
4350 isl_schedule_constraints_free(sc);
4352 return schedule;
4355 /* Compute a schedule or determine the properties of the original schedule
4356 * depending on the value of the "reschedule" option.
4358 static __isl_give isl_schedule *compute_or_set_properties(void *user)
4360 struct gpu_gen *gen = user;
4362 if (gen->options->reschedule)
4363 return compute_schedule(gen);
4364 else
4365 return determine_properties_original_schedule(gen);
4368 /* Obtain a schedule for the scop, by reading it from
4369 * a file, by computing one or by determining the properties
4370 * of the original schedule.
4372 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4374 return ppcg_get_schedule(gen->ctx, gen->options,
4375 &compute_or_set_properties, gen);
4378 /* Construct the string "<a>_<b>".
4380 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4382 isl_printer *p;
4383 char *s;
4385 p = isl_printer_to_str(ctx);
4386 p = isl_printer_print_str(p, a);
4387 p = isl_printer_print_str(p, "_");
4388 p = isl_printer_print_str(p, b);
4389 s = isl_printer_get_str(p);
4390 isl_printer_free(p);
4392 return s;
4395 /* For each array in "prog" of which an element appears in "accessed" and
4396 * that is not a read only scalar, create a zero-dimensional universe set
4397 * of which the tuple id has name "<prefix>_<name of array>" and a user
4398 * pointer pointing to the array (gpu_array_info).
4400 * If the array is local to "prog", then make sure it will be declared
4401 * in the host code.
4403 * Return the list of these universe sets.
4405 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4406 const char *prefix, __isl_take isl_union_set *accessed)
4408 int i;
4409 isl_ctx *ctx;
4410 isl_union_set_list *filters;
4412 ctx = prog->ctx;
4413 filters = isl_union_set_list_alloc(ctx, 0);
4414 for (i = 0; i < prog->n_array; ++i) {
4415 struct gpu_array_info *array = &prog->array[i];
4416 isl_space *space;
4417 isl_set *accessed_i;
4418 int empty;
4419 char *name;
4420 isl_id *id;
4421 isl_union_set *uset;
4423 if (gpu_array_is_read_only_scalar(array))
4424 continue;
4426 space = isl_space_copy(array->space);
4427 accessed_i = isl_union_set_extract_set(accessed, space);
4428 empty = isl_set_plain_is_empty(accessed_i);
4429 isl_set_free(accessed_i);
4430 if (empty < 0) {
4431 filters = isl_union_set_list_free(filters);
4432 break;
4434 if (empty)
4435 continue;
4437 array->global = 1;
4438 if (array->local)
4439 array->declare_local = 1;
4441 name = concat(ctx, prefix, array->name);
4442 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4443 free(name);
4444 space = isl_space_set_alloc(ctx, 0, 0);
4445 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4446 uset = isl_union_set_from_set(isl_set_universe(space));
4448 filters = isl_union_set_list_add(filters, uset);
4450 isl_union_set_free(accessed);
4452 return filters;
4455 /* Make sure that code for the statements in "filters" that
4456 * copy arrays to or from the device is only generated when
4457 * the size of the corresponding array is positive.
4458 * That is, add a set node underneath "graft" with "filters" as children
4459 * and for each child add a guard that the selects the parameter
4460 * values for which the corresponding array has a positive size.
4461 * The array is available in the user pointer of the statement identifier.
4462 * "depth" is the schedule depth of the position where "graft"
4463 * will be added.
4465 static __isl_give isl_schedule_node *insert_positive_size_guards(
4466 __isl_take isl_schedule_node *graft,
4467 __isl_take isl_union_set_list *filters, int depth)
4469 int i, n;
4471 graft = isl_schedule_node_child(graft, 0);
4472 graft = isl_schedule_node_insert_set(graft, filters);
4473 n = isl_schedule_node_n_children(graft);
4474 for (i = 0; i < n; ++i) {
4475 isl_union_set *filter;
4476 isl_set *domain, *guard;
4477 isl_id *id;
4478 struct gpu_array_info *array;
4480 graft = isl_schedule_node_child(graft, i);
4481 filter = isl_schedule_node_filter_get_filter(graft);
4482 domain = isl_set_from_union_set(filter);
4483 id = isl_set_get_tuple_id(domain);
4484 array = isl_id_get_user(id);
4485 isl_id_free(id);
4486 isl_set_free(domain);
4487 guard = gpu_array_positive_size_guard(array);
4488 guard = isl_set_from_params(guard);
4489 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4490 graft = isl_schedule_node_child(graft, 0);
4491 graft = isl_schedule_node_insert_guard(graft, guard);
4492 graft = isl_schedule_node_parent(graft);
4493 graft = isl_schedule_node_parent(graft);
4495 graft = isl_schedule_node_parent(graft);
4497 return graft;
4500 /* Create a graft for copying arrays to or from the device,
4501 * whenever the size of the array is strictly positive.
4502 * Each statement is called "<prefix>_<name of array>" and
4503 * the identifier has a user pointer pointing to the array.
4504 * The graft will be added at the position specified by "node".
4505 * "copy" contains the array elements that need to be copied.
4506 * Only arrays of which some elements need to be copied
4507 * will have a corresponding statement in the graph.
4508 * Note though that each such statement will copy the entire array.
4510 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4511 __isl_keep isl_schedule_node *node, const char *prefix,
4512 __isl_take isl_union_set *copy)
4514 int depth;
4515 isl_ctx *ctx;
4516 isl_space *space;
4517 isl_union_set *all, *domain;
4518 isl_union_set_list *filters;
4519 isl_union_map *extension;
4520 isl_schedule_node *graft;
4522 ctx = prog->ctx;
4523 depth = isl_schedule_node_get_schedule_depth(node);
4524 filters = create_copy_filters(prog, prefix, copy);
4525 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4527 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4528 domain = isl_union_set_from_set(isl_set_universe(space));
4529 extension = isl_union_map_from_domain_and_range(domain, all);
4530 graft = isl_schedule_node_from_extension(extension);
4532 if (!filters)
4533 return isl_schedule_node_free(graft);
4534 if (isl_union_set_list_n_union_set(filters) == 0) {
4535 isl_union_set_list_free(filters);
4536 return graft;
4539 return insert_positive_size_guards(graft, filters, depth);
4542 /* Return (the universe spaces of) the arrays that are declared
4543 * inside the scop corresponding to "prog" and for which all
4544 * potential writes inside the scop form a subset of "domain".
4546 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4547 __isl_keep isl_union_set *domain)
4549 int i;
4550 isl_union_set *local;
4552 local = isl_union_set_empty(isl_union_set_get_space(domain));
4554 for (i = 0; i < prog->n_array; ++i) {
4555 isl_set *set;
4556 isl_union_map *to_outer;
4557 isl_union_map *may_write;
4558 isl_union_set *write_domain;
4559 isl_union_set *fields;
4560 int subset;
4562 if (!prog->array[i].local)
4563 continue;
4565 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4566 to_outer = isl_union_map_copy(prog->to_outer);
4567 to_outer = isl_union_map_intersect_range(to_outer,
4568 isl_union_set_from_set(isl_set_copy(set)));
4569 fields = isl_union_map_domain(to_outer);
4570 may_write = isl_union_map_copy(prog->may_write);
4571 may_write = isl_union_map_intersect_range(may_write, fields);
4572 write_domain = isl_union_map_domain(may_write);
4573 subset = isl_union_set_is_subset(write_domain, domain);
4574 isl_union_set_free(write_domain);
4576 if (subset < 0) {
4577 isl_set_free(set);
4578 return isl_union_set_free(local);
4579 } else if (subset) {
4580 local = isl_union_set_add_set(local, set);
4581 } else {
4582 isl_set_free(set);
4586 return local;
4589 /* Internal data structure for node_may_persist.
4591 * "tagger" maps tagged iteration domains to the corresponding untagged
4592 * iteration domain.
4594 * "may_persist_flow" is the set of all tagged dataflow dependences
4595 * with those dependences removed that either precede or follow
4596 * the kernel launch in a sequence.
4597 * "inner_band_flow" is the set of all tagged dataflow dependences
4598 * that are local to a given iteration of the outer band nodes
4599 * with respect to the current node.
4600 * "local_flow" is equal to "inner_band_flow", except that the domain
4601 * and the range have been intersected with intermediate filters
4602 * on children of sets or sequences.
4604 struct ppcg_may_persist_data {
4605 isl_union_pw_multi_aff *tagger;
4607 isl_union_map *local_flow;
4608 isl_union_map *inner_band_flow;
4609 isl_union_map *may_persist_flow;
4612 /* Update the information in "data" based on the band ancestor "node".
4614 * In particular, we restrict the dependences in data->local_flow
4615 * to those dependence where the source and the sink occur in
4616 * the same iteration of the given band node.
4617 * We also update data->inner_band_flow to the new value of
4618 * data->local_flow.
4620 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4621 struct ppcg_may_persist_data *data)
4623 isl_multi_union_pw_aff *partial;
4624 isl_union_pw_multi_aff *contraction;
4625 isl_union_map *flow;
4627 if (isl_schedule_node_band_n_member(node) == 0)
4628 return 0;
4630 partial = isl_schedule_node_band_get_partial_schedule(node);
4631 contraction = isl_schedule_node_get_subtree_contraction(node);
4632 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4633 contraction);
4634 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4635 isl_union_pw_multi_aff_copy(data->tagger));
4637 flow = data->local_flow;
4638 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4639 data->local_flow = flow;
4641 isl_union_map_free(data->inner_band_flow);
4642 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4644 return 0;
4647 /* Given a set of local reaching domain elements "domain",
4648 * expand them to the corresponding leaf domain elements using "contraction"
4649 * and insert the array references tags using data->tagger.
4651 static __isl_give isl_union_set *expand_and_tag(
4652 __isl_take isl_union_set *domain,
4653 __isl_take isl_union_pw_multi_aff *contraction,
4654 struct ppcg_may_persist_data *data)
4656 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4657 contraction);
4658 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4659 isl_union_pw_multi_aff_copy(data->tagger));
4660 return domain;
4663 /* Given a filter node that is the child of a set or sequence node,
4664 * restrict data->local_flow to refer only to those elements
4665 * in the filter of the node.
4666 * "contraction" maps the leaf domain elements of the schedule tree
4667 * to the corresponding domain elements at (the parent of) "node".
4669 static int filter_flow(__isl_keep isl_schedule_node *node,
4670 struct ppcg_may_persist_data *data,
4671 __isl_take isl_union_pw_multi_aff *contraction)
4673 isl_union_set *filter;
4674 isl_union_map *flow;
4676 flow = data->local_flow;
4677 filter = isl_schedule_node_filter_get_filter(node);
4678 filter = expand_and_tag(filter, contraction, data);
4679 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4680 flow = isl_union_map_intersect_range(flow, filter);
4681 data->local_flow = flow;
4683 return 0;
4686 /* Given a filter node "node", collect the filters on all preceding siblings
4687 * (which are also filter nodes), add them to "filters" and return the result.
4689 static __isl_give isl_union_set *add_previous_filters(
4690 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4692 isl_schedule_node *sibling;
4694 sibling = isl_schedule_node_copy(node);
4695 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4696 isl_union_set *filter;
4698 sibling = isl_schedule_node_previous_sibling(sibling);
4699 filter = isl_schedule_node_filter_get_filter(sibling);
4700 filters = isl_union_set_union(filters, filter);
4702 isl_schedule_node_free(sibling);
4703 if (!sibling)
4704 return isl_union_set_free(filters);
4706 return filters;
4709 /* Given a filter node "node", collect the filters on all following siblings
4710 * (which are also filter nodes), add them to "filters" and return the result.
4712 static __isl_give isl_union_set *add_next_filters(
4713 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4715 isl_schedule_node *sibling;
4717 sibling = isl_schedule_node_copy(node);
4718 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4719 isl_union_set *filter;
4721 sibling = isl_schedule_node_next_sibling(sibling);
4722 filter = isl_schedule_node_filter_get_filter(sibling);
4723 filters = isl_union_set_union(filters, filter);
4725 isl_schedule_node_free(sibling);
4726 if (!sibling)
4727 return isl_union_set_free(filters);
4729 return filters;
4732 /* Remove those flow dependences from data->may_persist_flow
4733 * that flow between elements of "domain" within the same iteration
4734 * of all outer band nodes.
4735 * "contraction" maps the leaf domain elements of the schedule tree
4736 * to the corresponding elements "domain".
4738 static void remove_external_flow(struct ppcg_may_persist_data *data,
4739 __isl_take isl_union_set *domain,
4740 __isl_keep isl_union_pw_multi_aff *contraction)
4742 isl_union_map *flow;
4744 contraction = isl_union_pw_multi_aff_copy(contraction);
4745 domain = expand_and_tag(domain, contraction, data);
4746 flow = isl_union_map_copy(data->local_flow);
4747 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4748 flow = isl_union_map_intersect_range(flow, domain);
4750 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4751 flow);
4754 /* Update the information in "data" based on the filter ancestor "node".
4755 * We only need to modify anything if the filter is the child
4756 * of a set or sequence node.
4758 * In the case of a sequence, we remove the dependences between
4759 * statement instances that are both executed either before or
4760 * after the subtree that will be mapped to a kernel, within
4761 * the same iteration of outer bands.
4763 * In both cases, we restrict data->local_flow to the current child.
4765 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4766 struct ppcg_may_persist_data *data)
4768 enum isl_schedule_node_type type;
4769 isl_schedule_node *parent;
4770 isl_space *space;
4771 isl_union_pw_multi_aff *contraction;
4772 isl_union_set *before, *after, *filter;
4773 isl_union_map *flow;
4775 type = isl_schedule_node_get_parent_type(node);
4776 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4777 return 0;
4779 parent = isl_schedule_node_copy(node);
4780 parent = isl_schedule_node_parent(parent);
4781 contraction = isl_schedule_node_get_subtree_contraction(parent);
4782 isl_schedule_node_free(parent);
4784 if (type == isl_schedule_node_set)
4785 return filter_flow(node, data, contraction);
4787 filter = isl_schedule_node_filter_get_filter(node);
4788 space = isl_union_set_get_space(filter);
4789 isl_union_set_free(filter);
4790 before = isl_union_set_empty(space);
4791 after = isl_union_set_copy(before);
4792 before = add_previous_filters(before, node);
4793 after = add_next_filters(after, node);
4795 remove_external_flow(data, before, contraction);
4796 remove_external_flow(data, after, contraction);
4798 return filter_flow(node, data, contraction);
4801 /* Update the information in "data" based on the ancestor "node".
4803 static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
4804 void *user)
4806 struct ppcg_may_persist_data *data = user;
4808 switch (isl_schedule_node_get_type(node)) {
4809 case isl_schedule_node_error:
4810 return isl_stat_error;
4811 case isl_schedule_node_context:
4812 case isl_schedule_node_domain:
4813 case isl_schedule_node_expansion:
4814 case isl_schedule_node_extension:
4815 case isl_schedule_node_guard:
4816 case isl_schedule_node_leaf:
4817 case isl_schedule_node_mark:
4818 case isl_schedule_node_sequence:
4819 case isl_schedule_node_set:
4820 break;
4821 case isl_schedule_node_band:
4822 if (update_may_persist_at_band(node, data) < 0)
4823 return isl_stat_error;
4824 break;
4825 case isl_schedule_node_filter:
4826 if (update_may_persist_at_filter(node, data) < 0)
4827 return isl_stat_error;
4828 break;
4831 return isl_stat_ok;
4834 /* Determine the set of array elements that may need to be perserved
4835 * by a kernel constructed from the subtree at "node".
4836 * This includes the set of array elements that may need to be preserved
4837 * by the entire scop (prog->may_persist) and the elements for which
4838 * there is a potential flow dependence that may cross a kernel launch.
4840 * To determine the second set, we start from all flow dependences.
4841 * From this set of dependences, we remove those that cannot possibly
4842 * require data to be preserved by a kernel launch.
4843 * In particular, we consider the following sets of dependences.
4844 * - dependences of which the write occurs inside the kernel.
4845 * If the data is needed outside the kernel, then it will
4846 * be copied out immediately after the kernel launch, so there
4847 * is no need for any special care.
4848 * - dependences of which the read occurs inside the kernel and the
4849 * corresponding write occurs inside the same iteration of the
4850 * outer band nodes. This means that the data is needed in
4851 * the first kernel launch after the write, which is already
4852 * taken care of by the standard copy-in. That is, the data
4853 * do not need to be preserved by any intermediate call to
4854 * the same kernel.
4855 * - dependences of which the write and the read either both occur
4856 * before the kernel launch or both occur after the kernel launch,
4857 * within the same iteration of the outer band nodes with respect
4858 * to the sequence that determines the ordering of the dependence
4859 * and the kernel launch. Such flow dependences cannot cross
4860 * any kernel launch.
4862 * For the remaining (tagged) dependences, we take the domain
4863 * (i.e., the tagged writes) and apply the tagged access relation
4864 * to obtain the accessed data elements.
4865 * These are then combined with the elements that may need to be
4866 * preserved by the entire scop.
4868 static __isl_give isl_union_set *node_may_persist(
4869 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4871 struct ppcg_may_persist_data data;
4872 isl_schedule_node *root;
4873 isl_union_pw_multi_aff *contraction;
4874 isl_union_set *domain;
4875 isl_union_set *persist;
4876 isl_union_map *flow, *local_flow;
4878 data.tagger = prog->scop->tagger;
4880 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4881 data.local_flow = isl_union_map_copy(flow);
4882 data.inner_band_flow = isl_union_map_copy(flow);
4883 data.may_persist_flow = flow;
4884 if (isl_schedule_node_foreach_ancestor_top_down(node,
4885 &update_may_persist_at, &data) < 0)
4886 data.may_persist_flow =
4887 isl_union_map_free(data.may_persist_flow);
4888 flow = data.may_persist_flow;
4889 isl_union_map_free(data.local_flow);
4891 domain = isl_schedule_node_get_domain(node);
4892 contraction = isl_schedule_node_get_subtree_contraction(node);
4893 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4894 contraction);
4895 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4896 isl_union_pw_multi_aff_copy(data.tagger));
4897 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4898 local_flow = data.inner_band_flow;
4899 local_flow = isl_union_map_intersect_range(local_flow, domain);
4900 flow = isl_union_map_subtract(flow, local_flow);
4902 persist = isl_union_map_domain(flow);
4903 persist = isl_union_set_apply(persist,
4904 isl_union_map_copy(prog->scop->tagged_may_writes));
4905 persist = isl_union_set_union(persist,
4906 isl_union_set_copy(prog->may_persist));
4908 return persist;
4911 /* Add nodes for copying outer arrays in and out of the device
4912 * before and after the subtree "node", which contains one or more kernels.
4913 * "domain" contains the original reaching domain elements before
4914 * the kernels were created, i.e., before the contraction that
4915 * may have been performed in creating the kernels has been applied.
4916 * "prefix" contains the prefix schedule at that point, in terms
4917 * of the same original reaching domain elements.
4919 * We first compute the sets of outer array elements that need
4920 * to be copied in and out and then graft in the nodes for
4921 * performing this copying.
4923 * In particular, for each array that is possibly written anywhere in
4924 * the subtree "node" and that may be used after "node"
4925 * or that may be visible outside the corresponding scop,
4926 * we copy out its entire extent.
4928 * Any array elements that is read without first being written inside
4929 * the subtree "node" needs to be copied in.
4930 * Furthermore, if there are any array elements that
4931 * are copied out, but that may not be written inside "node, then
4932 * they also need to be copied in to ensure that the value after execution
4933 * is the same as the value before execution, at least for those array
4934 * elements that may have their values preserved by the scop or that
4935 * may be written before "node" and read after "node".
4936 * In case the array elements are structures, we need to take into
4937 * account that all members of the structures need to be written
4938 * by "node" before we can avoid copying the data structure in.
4940 * Note that the may_write relation is intersected with the domain,
4941 * which has been intersected with the context.
4942 * This helps in those cases where the arrays are declared with a fixed size,
4943 * while the accesses are parametric and the context assigns a fixed value
4944 * to the parameters.
4946 * If an element from a local array is read without first being written,
4947 * then there is no point in copying it in since it cannot have been
4948 * written prior to the scop. Warn about the uninitialized read instead.
4950 static __isl_give isl_schedule_node *add_to_from_device(
4951 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4952 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4954 isl_union_set *local;
4955 isl_union_set *to_device, *from_device, *may_persist;
4956 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4957 isl_union_map *read, *copy_in;
4958 isl_union_map *tagged;
4959 isl_union_map *local_uninitialized;
4960 isl_schedule_node *graft;
4962 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4963 tagged = isl_union_map_union(tagged,
4964 isl_union_map_copy(prog->scop->tagged_may_writes));
4966 may_write = isl_union_map_copy(prog->may_write);
4967 may_write = isl_union_map_intersect_domain(may_write,
4968 isl_union_set_copy(domain));
4969 may_write = remove_local_accesses(prog,
4970 isl_union_map_copy(tagged), may_write,
4971 isl_union_map_copy(prefix), 0);
4972 may_write = isl_union_map_apply_range(may_write,
4973 isl_union_map_copy(prog->to_outer));
4974 may_write = isl_union_map_apply_domain(may_write,
4975 isl_union_map_copy(prefix));
4976 may_write = approximate_copy_out(may_write, prog);
4977 copy_out = isl_union_map_copy(may_write);
4978 may_write = isl_union_map_apply_range(may_write,
4979 isl_union_map_copy(prog->to_inner));
4980 must_write = isl_union_map_copy(prog->must_write);
4981 must_write = isl_union_map_apply_domain(must_write,
4982 isl_union_map_copy(prefix));
4983 may_persist = node_may_persist(node, prog);
4984 may_write = isl_union_map_intersect_range(may_write, may_persist);
4985 not_written = isl_union_map_subtract(may_write, must_write);
4987 local = extract_local_accesses(prog, domain);
4988 read = isl_union_map_copy(prog->read);
4989 read = isl_union_map_intersect_domain(read, domain);
4990 read = remove_local_accesses(prog, tagged, read,
4991 isl_union_map_copy(prefix), 1);
4992 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4993 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4994 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4995 local);
4996 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4997 isl_union_map_copy(read));
4998 if (!isl_union_map_is_empty(local_uninitialized)) {
4999 fprintf(stderr,
5000 "possibly uninitialized reads (not copied in):\n");
5001 isl_union_map_dump(local_uninitialized);
5003 read = isl_union_map_subtract(read, local_uninitialized);
5004 read = isl_union_map_apply_domain(read, prefix);
5005 copy_in = isl_union_map_union(read, not_written);
5006 copy_in = isl_union_map_apply_range(copy_in,
5007 isl_union_map_copy(prog->to_outer));
5009 graft = create_copy_device(prog, node, "to_device",
5010 isl_union_map_range(copy_in));
5011 node = isl_schedule_node_graft_before(node, graft);
5012 graft = create_copy_device(prog, node, "from_device",
5013 isl_union_map_range(copy_out));
5014 node = isl_schedule_node_graft_after(node, graft);
5016 return node;
5019 /* Add nodes for initializing ("init_device") and clearing ("clear_device")
5020 * the device before and after "node".
5022 static __isl_give isl_schedule_node *add_init_clear_device(
5023 __isl_take isl_schedule_node *node)
5025 isl_ctx *ctx;
5026 isl_space *space;
5027 isl_union_set *domain;
5028 isl_schedule_node *graft;
5030 ctx = isl_schedule_node_get_ctx(node);
5032 space = isl_space_set_alloc(ctx, 0, 0);
5033 space = isl_space_set_tuple_name(space, isl_dim_set, "init_device");
5034 domain = isl_union_set_from_set(isl_set_universe(space));
5035 graft = isl_schedule_node_from_domain(domain);
5037 node = isl_schedule_node_graft_before(node, graft);
5039 space = isl_space_set_alloc(ctx, 0, 0);
5040 space = isl_space_set_tuple_name(space, isl_dim_set, "clear_device");
5041 domain = isl_union_set_from_set(isl_set_universe(space));
5042 graft = isl_schedule_node_from_domain(domain);
5044 node = isl_schedule_node_graft_after(node, graft);
5046 return node;
5049 /* Update "schedule" for mapping to a GPU device.
5051 * In particular, insert a context node, create kernels for
5052 * each outermost tilable band and introduce nodes for copying arrays
5053 * in and out of the device and for initializing and clearing the device.
5054 * If the child of the initial root points to a set node,
5055 * then children of this node that do not contain any tilable bands
5056 * are separated from the other children and are not mapped to
5057 * the device.
5059 * The GPU code is generated in a context where at least one
5060 * statement instance is executed. The corresponding guard is inserted
5061 * around the entire schedule.
5063 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
5064 __isl_take isl_schedule *schedule)
5066 isl_schedule_node *node;
5067 isl_set *context;
5068 isl_set *guard;
5069 isl_union_set *domain;
5070 isl_union_map *prefix;
5071 struct gpu_prog *prog;
5073 context = isl_set_copy(gen->prog->context);
5074 context = isl_set_from_params(context);
5075 schedule = isl_schedule_insert_context(schedule, context);
5077 prog = gen->prog;
5078 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5079 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5080 guard = isl_set_from_params(guard);
5082 node = isl_schedule_get_root(schedule);
5083 isl_schedule_free(schedule);
5084 node = isl_schedule_node_child(node, 0);
5085 node = isl_schedule_node_child(node, 0);
5086 node = isolate_permutable_subtrees(node, gen->prog);
5087 domain = isl_schedule_node_get_domain(node);
5088 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
5089 node = mark_kernels(gen, node);
5090 node = add_to_from_device(node, domain, prefix, gen->prog);
5091 node = isl_schedule_node_root(node);
5092 node = isl_schedule_node_child(node, 0);
5093 node = isl_schedule_node_child(node, 0);
5094 node = isl_schedule_node_insert_guard(node, guard);
5095 node = isl_schedule_node_child(node, 0);
5096 node = add_init_clear_device(node);
5097 schedule = isl_schedule_node_get_schedule(node);
5098 isl_schedule_node_free(node);
5100 return schedule;
5103 /* Internal data structure for extract_access.
5104 * "next_access" points to the end of a linked list that is extended
5105 * by extract_access.
5106 * "single_expression" is set if the access expressions belong to
5107 * an expression statement (i.e., a statement without internal control).
5108 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5110 struct ppcg_extract_access_data {
5111 struct gpu_stmt_access **next_access;
5112 int single_expression;
5113 isl_union_map *any_to_outer;
5116 /* Given a tagged access relation to a single array "tagged", extract it
5117 * as a map, taking into account that the input may be empty.
5118 * If the access relation is empty, then it does not contain
5119 * any space information, so we try to recover it from the index
5120 * expression.
5121 * The space of the index expression is of the form I -> A,
5122 * with I the statement instances and A the array, or [I -> F] -> A,
5123 * with F the filters corresponding to arguments.
5124 * We first drop F, if present, obtaining I -> A.
5125 * Then we construct I -> R, with R the reference tag,
5126 * combine the two into I -> [R -> A] and uncurry to obtain
5127 * the final result [I -> R] -> A.
5128 * Note that the index expression may have a lower dimension
5129 * than that of the array, but this dimension is not used
5130 * if the access relation is empty.
5132 static __isl_give isl_map *extract_single_tagged_access(
5133 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5135 int empty;
5136 isl_id *id;
5137 isl_space *space, *space2;
5138 isl_multi_pw_aff *index;
5140 empty = isl_union_map_is_empty(tagged);
5141 if (empty < 0)
5142 goto error;
5143 if (!empty)
5144 return isl_map_from_union_map(tagged);
5145 isl_union_map_free(tagged);
5147 index = pet_expr_access_get_index(expr);
5148 space = isl_multi_pw_aff_get_space(index);
5149 isl_multi_pw_aff_free(index);
5150 if (isl_space_domain_is_wrapping(space))
5151 space = isl_space_domain_factor_domain(space);
5152 space2 = isl_space_copy(space);
5153 space2 = isl_space_from_domain(isl_space_domain(space));
5154 id = pet_expr_access_get_ref_id(expr);
5155 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5156 space = isl_space_range_product(space2, space);
5157 space = isl_space_uncurry(space);
5159 return isl_map_empty(space);
5160 error:
5161 isl_union_map_free(tagged);
5162 return NULL;
5165 /* Extract a gpu_stmt_access from "expr", append it to the list
5166 * that ends in *data->next_access and update the end of the list.
5167 * If the access expression performs a write, then it is considered
5168 * exact only if it appears in a single expression statement and
5169 * if its may access relation is equal to its must access relation.
5171 * The combined set of may accesses may be union if member accesses
5172 * are involved, but the entire set is derived from a single reference and
5173 * therefore from a single index expression. These accesses therefore
5174 * all map to the same outer array.
5176 static int extract_access(__isl_keep pet_expr *expr, void *user)
5178 struct ppcg_extract_access_data *data = user;
5179 isl_union_map *tagged;
5180 struct gpu_stmt_access *access;
5181 isl_ctx *ctx = pet_expr_get_ctx(expr);
5182 isl_multi_pw_aff *index;
5184 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5185 assert(access);
5186 access->next = NULL;
5187 access->read = pet_expr_access_is_read(expr);
5188 access->write = pet_expr_access_is_write(expr);
5189 tagged = pet_expr_access_get_tagged_may_read(expr);
5190 tagged = isl_union_map_union(tagged,
5191 pet_expr_access_get_tagged_may_write(expr));
5192 tagged = isl_union_map_apply_range(tagged,
5193 isl_union_map_copy(data->any_to_outer));
5194 if (!access->write) {
5195 access->exact_write = 1;
5196 } else if (!data->single_expression) {
5197 access->exact_write = 0;
5198 } else {
5199 isl_union_map *must, *may;
5200 may = isl_union_map_copy(tagged);
5201 may = isl_union_map_domain_factor_domain(may);
5202 must = pet_expr_access_get_must_write(expr);
5203 access->exact_write = isl_union_map_is_equal(must, may);
5204 isl_union_map_free(must);
5205 isl_union_map_free(may);
5207 index = pet_expr_access_get_index(expr);
5208 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5209 isl_multi_pw_aff_free(index);
5210 access->ref_id = pet_expr_access_get_ref_id(expr);
5211 access->tagged_access = extract_single_tagged_access(tagged, expr);
5212 access->access = isl_map_copy(access->tagged_access);
5213 access->access = isl_map_domain_factor_domain(access->access);
5215 *data->next_access = access;
5216 data->next_access = &(*data->next_access)->next;
5218 if (!access->access)
5219 return -1;
5221 return 0;
5224 /* Construct a linked list of gpu_stmt_access objects,
5225 * one for each access expression in the statement body.
5226 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5228 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5229 __isl_keep isl_union_map *any_to_outer)
5231 struct ppcg_extract_access_data data;
5233 stmt->accesses = NULL;
5234 data.next_access = &stmt->accesses;
5235 data.single_expression =
5236 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5237 data.any_to_outer = any_to_outer;
5238 return pet_tree_foreach_access_expr(stmt->stmt->body,
5239 &extract_access, &data);
5242 /* Return an array of gpu_stmt representing the statements in "scop".
5244 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5245 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5247 int i;
5248 struct gpu_stmt *stmts;
5250 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5251 if (!stmts)
5252 return NULL;
5254 for (i = 0; i < scop->pet->n_stmt; ++i) {
5255 struct gpu_stmt *s = &stmts[i];
5257 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5258 s->stmt = scop->pet->stmts[i];
5259 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5260 return free_stmts(stmts, i + 1);
5263 return stmts;
5266 /* Generate CUDA code for "scop" and print it to "p".
5267 * After generating an AST for the transformed scop as explained below,
5268 * we call "gen->print" to print the AST in the desired output format
5269 * to "p".
5271 * If it turns out that it does not make sense to generate GPU code,
5272 * then we generate CPU code instead.
5274 * The declarations of the arrays that are visible outside of the scop
5275 * are printed outside of the code generated from the schedule,
5276 * because the generated code may involve a guard around the entire code.
5278 * We first compute a schedule that respects the dependences
5279 * of the original program and select the outermost bands
5280 * of tilable dimensions that have at least one parallel loop.
5281 * If the --load-schedule is specified, then the loaded schedule
5282 * is used instead of a computed schedule.
5284 * Each of these bands B is then tiled according to "tile" sizes, resulting
5285 * in two nested bands, with a kernel marker on top
5293 * We then split off at most 2 parallel dimensions from the T band and
5294 * at most 3 parallel dimension from the P band
5299 * T1
5301 * T2
5303 * P1
5305 * P2
5307 * A filter is introduced in front of T1 that maps the domain instances
5308 * to block identifiers. Similarly, a filter is introduced in front of P1
5309 * that maps the domain instances to thread identifiers.
5311 * For each iteration of the T2 band and for each array, we compute
5312 * the array elements accessed by that iteration, construct a rectangular
5313 * box around it and shift it to the origin. The result is used
5314 * as shared memory for the array.
5316 * Copying and synchronization statements are added to this schedule tree.
5317 * In principle, these are added in front of the P1 band, but some of
5318 * them may get hoisted up to higher levels.
5320 * The entire AST is then generated from the single resulting schedule tree.
5321 * During the generation the subtrees at kernel nodes (K) are saved
5322 * aside and replaced by kernel calls. The result is printed as host code
5323 * while the saved subtrees are printed as device code.
5325 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5326 struct gpu_gen *gen, struct ppcg_scop *scop,
5327 struct ppcg_options *options)
5329 struct gpu_prog *prog;
5330 isl_ctx *ctx;
5331 isl_schedule *schedule;
5332 int any_permutable;
5334 if (!scop)
5335 return isl_printer_free(p);
5337 ctx = isl_printer_get_ctx(p);
5338 prog = gpu_prog_alloc(ctx, scop);
5339 if (!prog)
5340 return isl_printer_free(p);
5342 gen->prog = prog;
5343 schedule = get_schedule(gen);
5345 any_permutable = has_any_permutable_node(schedule);
5346 if (any_permutable < 0 || !any_permutable) {
5347 if (any_permutable < 0)
5348 p = isl_printer_free(p);
5349 else
5350 p = print_cpu(p, scop, options);
5351 isl_schedule_free(schedule);
5352 } else {
5353 schedule = map_to_device(gen, schedule);
5354 gen->tree = generate_code(gen, schedule);
5355 p = ppcg_set_macro_names(p);
5356 p = ppcg_print_exposed_declarations(p, prog->scop);
5357 p = gen->print(p, gen->prog, gen->tree, &gen->types,
5358 gen->print_user);
5359 isl_ast_node_free(gen->tree);
5362 gpu_prog_free(prog);
5364 return p;
5367 /* Wrapper around generate for use as a ppcg_transform callback.
5369 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5370 struct ppcg_scop *scop, void *user)
5372 struct gpu_gen *gen = user;
5374 return generate(p, gen, scop, gen->options);
5377 /* Transform the code in the file called "input" by replacing
5378 * all scops by corresponding GPU code and write the results to "out".
5380 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5381 struct ppcg_options *options,
5382 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5383 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5384 struct gpu_types *types, void *user), void *user)
5386 struct gpu_gen gen;
5387 int r;
5388 int i;
5390 gen.ctx = ctx;
5391 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5392 gen.options = options;
5393 gen.kernel_id = 0;
5394 gen.print = print;
5395 gen.print_user = user;
5396 gen.types.n = 0;
5397 gen.types.name = NULL;
5399 if (options->debug->dump_sizes) {
5400 isl_space *space = isl_space_params_alloc(ctx, 0);
5401 gen.used_sizes = isl_union_map_empty(space);
5404 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5406 if (options->debug->dump_sizes) {
5407 isl_union_map_dump(gen.used_sizes);
5408 isl_union_map_free(gen.used_sizes);
5411 isl_union_map_free(gen.sizes);
5412 for (i = 0; i < gen.types.n; ++i)
5413 free(gen.types.name[i]);
5414 free(gen.types.name);
5416 return r;
5419 /* Compute the set of inner array elements that may have their values
5420 * preserved by "prog". In particular, collect the array elements of
5421 * arrays that are not local to "prog" and remove those elements that
5422 * are definitely killed or definitely written by "prog".
5424 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5426 int i;
5427 isl_union_set *may_persist, *killed;
5428 isl_union_map *must_kill;
5430 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5431 for (i = 0; i < prog->n_array; ++i) {
5432 isl_set *extent;
5434 if (prog->array[i].local)
5435 continue;
5437 extent = isl_set_copy(prog->array[i].extent);
5438 may_persist = isl_union_set_add_set(may_persist, extent);
5441 may_persist = isl_union_set_intersect_params(may_persist,
5442 isl_set_copy(prog->context));
5443 may_persist = isl_union_set_apply(may_persist,
5444 isl_union_map_copy(prog->to_inner));
5445 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5446 killed = isl_union_map_range(must_kill);
5447 must_kill = isl_union_map_copy(prog->must_write);
5448 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5450 may_persist = isl_union_set_subtract(may_persist, killed);
5451 return may_persist;
5454 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5456 struct gpu_prog *prog;
5457 isl_space *space;
5458 isl_map *id;
5460 if (!scop)
5461 return NULL;
5463 prog = isl_calloc_type(ctx, struct gpu_prog);
5464 assert(prog);
5466 prog->ctx = ctx;
5467 prog->scop = scop;
5468 prog->context = isl_set_copy(scop->context);
5469 prog->n_stmts = scop->pet->n_stmt;
5470 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5471 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5472 space = isl_union_map_get_space(prog->any_to_outer);
5473 space = isl_space_set_from_params(space);
5474 space = isl_space_add_dims(space, isl_dim_set, 1);
5475 space = isl_space_map_from_set(space);
5476 id = isl_map_identity(space);
5477 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5478 prog->stmts = extract_stmts(ctx, scop,
5479 prog->context, prog->any_to_outer);
5480 prog->read = isl_union_map_copy(scop->reads);
5481 prog->may_write = isl_union_map_copy(scop->may_writes);
5482 prog->must_write = isl_union_map_copy(scop->must_writes);
5483 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5484 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5485 prog->to_outer = isl_union_map_copy(prog->to_inner);
5486 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5488 if (!prog->stmts)
5489 return gpu_prog_free(prog);
5491 if (collect_array_info(prog) < 0)
5492 return gpu_prog_free(prog);
5493 prog->may_persist = compute_may_persist(prog);
5495 return prog;
5498 void *gpu_prog_free(struct gpu_prog *prog)
5500 if (!prog)
5501 return NULL;
5502 free_array_info(prog);
5503 free_stmts(prog->stmts, prog->n_stmts);
5504 isl_union_map_free(prog->any_to_outer);
5505 isl_union_map_free(prog->to_outer);
5506 isl_union_map_free(prog->to_inner);
5507 isl_union_map_free(prog->read);
5508 isl_union_map_free(prog->may_write);
5509 isl_union_map_free(prog->must_write);
5510 isl_union_map_free(prog->tagged_must_kill);
5511 isl_union_map_free(prog->array_order);
5512 isl_union_set_free(prog->may_persist);
5513 isl_set_free(prog->context);
5514 free(prog);
5515 return NULL;