gpu_group.c: can_tile: return isl_bool
[ppcg.git] / gpu.c
blob9fcb33b3501d08f04d51d29ff7804a20890b3c5d
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
4 * Copyright 2015-2016 Sven Verdoolaege
6 * Use of this software is governed by the MIT license
8 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
9 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
10 * 91893 Orsay, France
11 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
14 #include <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_hybrid.h"
32 #include "gpu_tree.h"
33 #include "hybrid.h"
34 #include "schedule.h"
35 #include "ppcg_options.h"
36 #include "print.h"
37 #include "util.h"
39 struct gpu_array_info;
41 /* Return the name of the outer array (of structs) accessed by "access".
43 static const char *get_outer_array_name(__isl_keep isl_map *access)
45 isl_space *space;
46 const char *name;
48 space = isl_space_range(isl_map_get_space(access));
49 while (space && isl_space_is_wrapping(space))
50 space = isl_space_domain(isl_space_unwrap(space));
51 name = isl_space_get_tuple_name(space, isl_dim_set);
52 isl_space_free(space);
54 return name;
57 /* Collect all references to the given array and store pointers to them
58 * in array->refs.
60 static isl_stat collect_references(struct gpu_prog *prog,
61 struct gpu_array_info *array)
63 int i;
64 int n;
66 n = 0;
67 for (i = 0; i < prog->n_stmts; ++i) {
68 struct gpu_stmt *stmt = &prog->stmts[i];
69 struct gpu_stmt_access *access;
71 for (access = stmt->accesses; access; access = access->next) {
72 const char *name;
73 name = get_outer_array_name(access->access);
74 if (name && !strcmp(array->name, name))
75 n++;
79 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
80 if (!array->refs)
81 return isl_stat_error;
82 array->n_ref = n;
84 n = 0;
85 for (i = 0; i < prog->n_stmts; ++i) {
86 struct gpu_stmt *stmt = &prog->stmts[i];
87 struct gpu_stmt_access *access;
89 for (access = stmt->accesses; access; access = access->next) {
90 const char *name;
91 name = get_outer_array_name(access->access);
92 if (!name || strcmp(array->name, name))
93 continue;
95 array->refs[n++] = access;
99 return isl_stat_ok;
102 /* Compute and return the extent of "array", taking into account the set of
103 * accessed elements.
105 * In particular, the extent in the outer dimension is taken
106 * from "accessed", while the extents in the remaining dimensions
107 * are taken from array->extent.
109 * The extent in the outer dimension cannot be taken from array->extent
110 * because that may be unbounded. Furthermore, even if it is bounded,
111 * it may be larger than the piece of the array that is being accessed.
113 static __isl_give isl_set *compute_extent(struct pet_array *array,
114 __isl_keep isl_set *accessed)
116 int n_index;
117 isl_id *id;
118 isl_set *outer;
119 isl_set *extent;
121 extent = isl_set_copy(array->extent);
123 n_index = isl_set_dim(accessed, isl_dim_set);
124 if (n_index == 0)
125 return extent;
127 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
128 outer = isl_set_copy(accessed);
129 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
130 extent = isl_set_flat_product(outer, extent);
131 id = isl_set_get_tuple_id(accessed);
132 extent = isl_set_set_tuple_id(extent, id);
134 return extent;
137 /* Is the array "array" being extracted a read-only scalar?
139 * That is, is "array" a scalar that is never possibly written to.
140 * An array containing structures is never considered to be a scalar.
142 static int is_read_only_scalar(struct gpu_array_info *array,
143 struct gpu_prog *prog)
145 isl_set *space;
146 isl_union_map *write;
147 int empty;
149 if (array->has_compound_element)
150 return 0;
151 if (array->n_index != 0)
152 return 0;
154 write = isl_union_map_copy(prog->may_write);
155 space = isl_set_universe(isl_space_copy(array->space));
156 write = isl_union_map_intersect_range(write,
157 isl_union_set_from_set(space));
158 empty = isl_union_map_is_empty(write);
159 isl_union_map_free(write);
161 return empty;
164 /* Is "array" only accessed as individual, fixed elements?
165 * That is, does each access to "array" access a single, fixed element?
167 static isl_bool only_fixed_element_accessed(struct gpu_array_info *array)
169 int i;
171 for (i = 0; i < array->n_ref; ++i)
172 if (!array->refs[i]->fixed_element)
173 return isl_bool_false;
175 return isl_bool_true;
178 /* Compute bounds on the host array "pa" based on the corresponding
179 * accessed elements in "arrays"
180 * and collect all references to the array.
181 * Store the results in "info".
183 * If the array is zero-dimensional and does not contain structures,
184 * i.e., if the array is a scalar, we check whether it is read-only.
185 * We also check whether the array is accessed at all.
187 static isl_stat extract_array_info(struct gpu_prog *prog,
188 struct gpu_array_info *info, struct pet_array *pa,
189 __isl_keep isl_union_set *arrays)
191 int empty;
192 const char *name;
193 int n_index;
194 isl_multi_pw_aff *bounds;
195 isl_set *accessed, *extent;
197 n_index = isl_set_dim(pa->extent, isl_dim_set);
198 name = isl_set_get_tuple_name(pa->extent);
200 info->space = isl_set_get_space(pa->extent);
201 info->name = strdup(name);
202 info->n_index = n_index;
203 info->linearize = prog->scop->options->linearize_device_arrays;
205 info->type = strdup(pa->element_type);
206 info->size = pa->element_size;
207 info->local = pa->declared && !pa->exposed;
208 info->has_compound_element = pa->element_is_record;
209 info->read_only_scalar = is_read_only_scalar(info, prog);
211 info->declared_extent = isl_set_copy(pa->extent);
212 accessed = isl_union_set_extract_set(arrays,
213 isl_space_copy(info->space));
214 empty = isl_set_is_empty(accessed);
215 extent = compute_extent(pa, accessed);
216 isl_set_free(accessed);
217 info->extent = extent;
218 if (empty < 0)
219 return isl_stat_error;
220 info->accessed = !empty;
221 bounds = ppcg_size_from_extent(isl_set_copy(extent));
222 bounds = isl_multi_pw_aff_gist(bounds, isl_set_copy(prog->context));
223 if (!bounds)
224 return isl_stat_error;
225 if (!isl_multi_pw_aff_is_cst(bounds))
226 info->linearize = 1;
227 info->bound = bounds;
229 if (collect_references(prog, info) < 0)
230 return isl_stat_error;
231 info->only_fixed_element = only_fixed_element_accessed(info);
233 return isl_stat_ok;
236 /* Remove independence from the order constraints "order" on array "array".
237 * Since the pairs of iterations in the filter relation of an independence
238 * are guaranteed to be completely independent by the user, there is
239 * no need to ensure that live ranges are ordered along those pairs.
240 * We make an exception for local variables, though, as the independence
241 * guarantee does not apply to those.
243 * The order constraints are used in two places.
244 * Those on scalars are used in check_scalar_live_ranges to check if
245 * we need to force the scalar to be private. Any non-local scalar
246 * should not be forced scalar if it only appears in independent loops.
247 * Those on non-scalars are added to the coincidence constraints
248 * in compute_schedule because we do not support any array expansion.
249 * Accesses to non-local arrays should not prevent a loop from being
250 * considered coincident so we should indeed remove those constraints
251 * from the order constraints.
253 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
254 struct gpu_array_info *array, __isl_take isl_union_map *order)
256 int i;
258 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
259 struct pet_independence *pi = prog->scop->pet->independences[i];
260 if (isl_union_set_contains(pi->local, array->space))
261 continue;
263 order = isl_union_map_subtract(order,
264 isl_union_map_copy(pi->filter));
267 return order;
270 /* For each array in "prog", store the (untagged) order dependences
271 * derived from the array in array->dep_order.
272 * In particular, consider all references that access the given array
273 * and take the order dependences that have one of these references
274 * as source. (Since an order dependence relates two references to
275 * the same array, the target of these order dependences will also
276 * be one of these references.)
277 * Additionally, store the union of these array->dep_order relations
278 * for all arrays that cannot be mapped to private memory in prog->array_order.
280 void collect_order_dependences(struct gpu_prog *prog)
282 int i;
283 isl_space *space;
284 isl_union_map *accesses;
286 space = isl_union_map_get_space(prog->read);
287 prog->array_order = isl_union_map_empty(space);
289 accesses = isl_union_map_copy(prog->scop->tagged_reads);
290 accesses = isl_union_map_union(accesses,
291 isl_union_map_copy(prog->scop->tagged_may_writes));
292 accesses = isl_union_map_universe(accesses);
293 accesses = isl_union_map_apply_range(accesses,
294 isl_union_map_copy(prog->to_outer));
296 for (i = 0; i < prog->n_array; ++i) {
297 struct gpu_array_info *array = &prog->array[i];
298 isl_set *set;
299 isl_union_set *uset;
300 isl_union_map *order;
302 set = isl_set_universe(isl_space_copy(array->space));
303 uset = isl_union_set_from_set(set);
304 uset = isl_union_map_domain(
305 isl_union_map_intersect_range(isl_union_map_copy(accesses),
306 uset));
307 order = isl_union_map_copy(prog->scop->tagged_dep_order);
308 order = isl_union_map_intersect_domain(order, uset);
309 order = isl_union_map_zip(order);
310 order = isl_union_set_unwrap(isl_union_map_domain(order));
311 order = remove_independences(prog, array, order);
312 array->dep_order = order;
314 if (gpu_array_can_be_private(array))
315 continue;
317 prog->array_order = isl_union_map_union(prog->array_order,
318 isl_union_map_copy(array->dep_order));
321 isl_union_map_free(accesses);
324 /* Construct a gpu_array_info for each array referenced by prog->scop and
325 * collect them in prog->array.
327 * The sizes are based on the extents and the set of possibly accessed
328 * elements by "prog".
329 * If there are any member accesses involved, then they are first mapped
330 * to the outer arrays of structs.
331 * Only extract gpu_array_info entries for these outer arrays.
333 * If we are allowing live range reordering, then also set
334 * the dep_order field. Otherwise leave it NULL.
336 static isl_stat collect_array_info(struct gpu_prog *prog)
338 int i;
339 isl_stat r = isl_stat_ok;
340 isl_union_set *arrays;
342 prog->n_array = 0;
343 prog->array = isl_calloc_array(prog->ctx,
344 struct gpu_array_info, prog->scop->pet->n_array);
345 if (!prog->array)
346 return isl_stat_error;
348 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
349 arrays = isl_union_set_union(arrays,
350 isl_union_map_range(isl_union_map_copy(prog->may_write)));
352 arrays = isl_union_set_apply(arrays,
353 isl_union_map_copy(prog->to_outer));
355 arrays = isl_union_set_coalesce(arrays);
357 for (i = 0; i < prog->scop->pet->n_array; ++i) {
358 isl_bool field;
360 field = isl_set_is_wrapping(prog->scop->pet->arrays[i]->extent);
361 if (field < 0)
362 break;
363 if (field)
364 continue;
365 if (extract_array_info(prog, &prog->array[prog->n_array++],
366 prog->scop->pet->arrays[i], arrays) < 0)
367 r = isl_stat_error;
369 if (i < prog->scop->pet->n_array)
370 r = isl_stat_error;
372 isl_union_set_free(arrays);
374 if (prog->scop->options->live_range_reordering)
375 collect_order_dependences(prog);
377 return r;
380 static void free_array_info(struct gpu_prog *prog)
382 int i;
384 for (i = 0; i < prog->n_array; ++i) {
385 free(prog->array[i].type);
386 free(prog->array[i].name);
387 isl_multi_pw_aff_free(prog->array[i].bound);
388 isl_ast_expr_free(prog->array[i].bound_expr);
389 isl_space_free(prog->array[i].space);
390 isl_set_free(prog->array[i].declared_extent);
391 isl_set_free(prog->array[i].extent);
392 isl_ast_expr_free(prog->array[i].declared_size);
393 free(prog->array[i].refs);
394 isl_union_map_free(prog->array[i].dep_order);
396 free(prog->array);
399 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
400 * as an array or through a pointer reference, but as a single data element.
401 * At the moment, scalars are represented as zero-dimensional arrays.
402 * Note that the single data element may be an entire structure.
404 int gpu_array_is_scalar(struct gpu_array_info *array)
406 return array->n_index == 0;
409 /* Can "array" be mapped to private memory?
410 * That is, is it only accessed as individual elements with
411 * constant index expressions?
413 isl_bool gpu_array_can_be_private(struct gpu_array_info *array)
415 if (!array)
416 return isl_bool_error;
417 return array->only_fixed_element;
420 /* Is "array" a read-only scalar?
422 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
424 return array->read_only_scalar;
427 /* Does "array" need to be allocated on the device?
428 * If it is a read-only scalar, then it will be passed as an argument
429 * to the kernel and therefore does not require any allocation.
430 * If this device memory is not accessed at all, then it does not
431 * need to be allocated either.
433 int gpu_array_requires_device_allocation(struct gpu_array_info *array)
435 if (gpu_array_is_read_only_scalar(array))
436 return 0;
437 if (!array->global)
438 return 0;
439 return 1;
442 /* Return the set of parameter values for which the array has a positive
443 * size in all dimensions.
444 * If the sizes are only valid for some parameter values, then those
445 * constraints are also taken into account.
447 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
449 int i;
450 isl_space *space;
451 isl_set *guard;
453 if (!array)
454 return NULL;
456 space = isl_space_params(isl_space_copy(array->space));
457 guard = isl_set_universe(space);
459 for (i = 0; i < array->n_index; ++i) {
460 isl_pw_aff *bound;
461 isl_set *guard_i, *zero;
463 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
464 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
465 zero = isl_pw_aff_zero_set(bound);
466 guard_i = isl_set_subtract(guard_i, zero);
467 guard = isl_set_intersect(guard, guard_i);
470 return guard;
473 /* Internal data structure for extract_size_of_type.
474 * "type" specifies the name of the space that we want to extract.
475 * "res" is used to store the subset of that space.
477 struct ppcg_extract_size_data {
478 const char *type;
479 isl_set *res;
482 /* This function is called for each set in a union_set.
483 * If the name of the set matches data->type, we store the
484 * set in data->res.
486 static isl_stat extract_size_of_type(__isl_take isl_set *size, void *user)
488 struct ppcg_extract_size_data *data = user;
489 const char *name;
491 name = isl_set_get_tuple_name(size);
492 if (name && !strcmp(name, data->type)) {
493 data->res = size;
494 return isl_stat_error;
497 isl_set_free(size);
498 return isl_stat_ok;
501 /* Given a union map { kernel[i] -> *[...] },
502 * return the range in the space called "type" for the kernel with
503 * sequence number "id".
505 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
506 const char *type, int id)
508 isl_space *space;
509 isl_set *dom;
510 isl_union_set *local_sizes;
511 struct ppcg_extract_size_data data = { type, NULL };
513 if (!sizes)
514 return NULL;
516 space = isl_union_map_get_space(sizes);
517 space = isl_space_set_from_params(space);
518 space = isl_space_add_dims(space, isl_dim_set, 1);
519 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
520 dom = isl_set_universe(space);
521 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
523 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
524 isl_union_map_copy(sizes));
525 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
526 isl_union_set_free(local_sizes);
527 return data.res;
530 /* Given a singleton set, extract the first (at most *len) elements
531 * of the single integer tuple into *sizes and update *len if needed.
533 * If "set" is NULL, then the "sizes" array is not updated.
535 static isl_stat read_sizes_from_set(__isl_take isl_set *set, int *sizes,
536 int *len)
538 int i;
539 int dim;
541 if (!set)
542 return isl_stat_ok;
544 dim = isl_set_dim(set, isl_dim_set);
545 if (dim < *len)
546 *len = dim;
548 for (i = 0; i < *len; ++i) {
549 isl_val *v;
551 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
552 if (!v)
553 goto error;
554 sizes[i] = isl_val_get_num_si(v);
555 isl_val_free(v);
558 isl_set_free(set);
559 return isl_stat_ok;
560 error:
561 isl_set_free(set);
562 return isl_stat_error;
565 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
566 * if the option debug->dump_sizes is set.
568 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
569 int *sizes, int len)
571 int i;
572 isl_space *space;
573 isl_map *map;
575 if (!gen->options->debug->dump_sizes)
576 return;
578 space = isl_union_map_get_space(gen->used_sizes);
579 space = isl_space_set_from_params(space);
580 space = isl_space_add_dims(space, isl_dim_set, 1);
581 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
582 space = isl_space_from_domain(space);
583 space = isl_space_add_dims(space, isl_dim_out, len);
584 space = isl_space_set_tuple_name(space, isl_dim_out, type);
586 map = isl_map_universe(space);
587 map = isl_map_fix_si(map, isl_dim_in, 0, id);
588 for (i = 0; i < len; ++i)
589 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
591 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
594 /* Extract user specified "tile" sizes from the "sizes" command line option,
595 * defaulting to option->tile_size in each dimension.
596 * *tile_len contains the maximum number of tile sizes needed.
597 * Update *tile_len to the number of specified tile sizes, if any, and
598 * return a pointer to the tile sizes (or NULL on error).
599 * Add the effectively used sizes to gen->used_sizes.
601 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
603 int n;
604 int *tile_size;
605 isl_set *size;
607 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
608 if (!tile_size)
609 return NULL;
610 for (n = 0; n < *tile_len; ++n)
611 tile_size[n] = gen->options->tile_size;
613 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
614 if (read_sizes_from_set(size, tile_size, tile_len) < 0)
615 goto error;
616 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
618 return tile_size;
619 error:
620 free(tile_size);
621 return NULL;
624 /* Extract user specified "block" sizes from the "sizes" command line option,
625 * after filling in some potentially useful defaults.
627 static isl_stat read_block_sizes(struct ppcg_kernel *kernel,
628 __isl_keep isl_union_map *sizes)
630 isl_set *size;
632 if (kernel->n_block > 3)
633 kernel->n_block = 3;
634 switch (kernel->n_block) {
635 case 1:
636 kernel->block_dim[0] = 512;
637 break;
638 case 2:
639 kernel->block_dim[0] = 32;
640 kernel->block_dim[1] = 16;
641 break;
642 default:
643 kernel->block_dim[0] = 32;
644 kernel->block_dim[1] = 4;
645 kernel->block_dim[2] = 4;
646 break;
649 size = extract_sizes(sizes, "block", kernel->id);
650 return read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
653 /* Extract user specified "grid" sizes from the "sizes" command line option,
654 * after filling in some potentially useful defaults.
656 static isl_stat read_grid_sizes(struct ppcg_kernel *kernel,
657 __isl_keep isl_union_map *sizes)
659 isl_set *size;
661 if (kernel->n_grid > 2)
662 kernel->n_grid = 2;
663 switch (kernel->n_grid) {
664 case 1:
665 kernel->grid_dim[0] = 32768;
666 break;
667 default:
668 kernel->grid_dim[0] = 256;
669 kernel->grid_dim[1] = 256;
670 break;
673 size = extract_sizes(sizes, "grid", kernel->id);
674 return read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
677 /* Extract user specified grid and block sizes from the gen->sizes
678 * command line option after filling in some potentially useful defaults.
679 * Store the extracted sizes in "kernel".
680 * Add the effectively used sizes to gen->used_sizes.
682 static isl_stat read_grid_and_block_sizes(struct ppcg_kernel *kernel,
683 struct gpu_gen *gen)
685 if (read_block_sizes(kernel, gen->sizes) < 0)
686 return isl_stat_error;
687 if (read_grid_sizes(kernel, gen->sizes) < 0)
688 return isl_stat_error;
689 set_used_sizes(gen, "block", kernel->id,
690 kernel->block_dim, kernel->n_block);
691 set_used_sizes(gen, "grid", kernel->id,
692 kernel->grid_dim, kernel->n_grid);
693 return isl_stat_ok;
696 static void *free_stmts(struct gpu_stmt *stmts, int n)
698 int i;
700 if (!stmts)
701 return NULL;
703 for (i = 0; i < n; ++i) {
704 struct gpu_stmt_access *access, *next;
706 for (access = stmts[i].accesses; access; access = next) {
707 next = access->next;
708 isl_id_free(access->ref_id);
709 isl_map_free(access->access);
710 isl_map_free(access->tagged_access);
711 free(access);
714 isl_id_free(stmts[i].id);
716 free(stmts);
718 return NULL;
721 /* Add parameters p[i] with identifiers "ids" to "set",
722 * with bounds to 0 <= p[i] < size[i].
724 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
725 int *size, __isl_keep isl_id_list *ids)
727 int i, len;
728 unsigned nparam;
730 len = isl_id_list_n_id(ids);
731 nparam = isl_set_dim(set, isl_dim_param);
732 set = isl_set_add_dims(set, isl_dim_param, len);
734 for (i = 0; i < len; ++i) {
735 isl_id *id;
737 id = isl_id_list_get_id(ids, i);
738 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
739 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
740 set = isl_set_upper_bound_si(set, isl_dim_param,
741 nparam + i, size[i] - 1);
744 return set;
747 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
748 * with
750 * { : 0 <= p[i] < size[i] }
752 * or an overapproximation.
754 static __isl_give isl_set *add_bounded_parameters_dynamic(
755 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
756 __isl_keep isl_id_list *ids)
758 int i, len;
759 unsigned nparam;
760 isl_space *space;
761 isl_local_space *ls;
763 len = isl_multi_pw_aff_dim(size, isl_dim_out);
764 nparam = isl_set_dim(set, isl_dim_param);
765 set = isl_set_add_dims(set, isl_dim_param, len);
767 for (i = 0; i < len; ++i) {
768 isl_id *id;
770 id = isl_id_list_get_id(ids, i);
771 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
774 space = isl_space_params(isl_set_get_space(set));
775 ls = isl_local_space_from_space(space);
776 for (i = 0; i < len; ++i) {
777 isl_pw_aff *param, *size_i, *zero;
778 isl_set *bound;
780 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
781 isl_dim_param, nparam + i);
783 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
784 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
785 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
786 set = isl_set_intersect_params(set, bound);
788 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
789 bound = isl_pw_aff_ge_set(param, zero);
790 set = isl_set_intersect_params(set, bound);
792 isl_local_space_free(ls);
794 return set;
797 /* Return the union of all tagged access relations in the group.
799 static __isl_give isl_union_map *group_tagged_access_relation(
800 struct gpu_array_ref_group *group)
802 int i;
803 isl_union_map *access;
805 access = isl_union_map_empty(isl_map_get_space(group->access));
806 for (i = 0; i < group->n_ref; ++i) {
807 isl_map *map_i;
809 map_i = isl_map_copy(group->refs[i]->tagged_access);
810 access = isl_union_map_union(access,
811 isl_union_map_from_map(map_i));
814 return access;
817 /* Return the extent of "array", recomputed from the bounds.
818 * The recomputed extent may be simpler than the original extent.
820 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
822 int i;
823 isl_id *id;
824 isl_space *space;
825 isl_local_space *ls;
826 isl_set *extent;
828 id = isl_set_get_tuple_id(array->extent);
829 space = isl_set_get_space(array->extent);
830 extent = isl_set_universe(isl_space_copy(space));
831 ls = isl_local_space_from_space(space);
832 for (i = 0; i < array->n_index; ++i) {
833 isl_pw_aff *bound;
834 isl_aff *aff;
835 isl_pw_aff *index;
836 isl_set *lt;
838 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
840 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
841 isl_dim_set, i);
842 index = isl_pw_aff_from_aff(aff);
843 bound = isl_multi_pw_aff_get_pw_aff(array->bound, i);
844 bound = isl_pw_aff_from_range(bound);
845 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
846 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
847 isl_id_copy(id));
848 lt = isl_pw_aff_lt_set(index, bound);
849 extent = isl_set_intersect(extent, lt);
851 isl_local_space_free(ls);
852 isl_id_free(id);
854 return extent;
857 /* Return a map from the first group->shared_tile->depth dimensions
858 * of the computed schedule to the array tile in
859 * global memory that corresponds to the shared memory copy.
861 * In particular, return a map
863 * { D[i] -> A[a] }
865 * with constraints
867 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
869 * and
871 * 0 <= a <= array_size - 1 (2)
873 * Note that if some stride has been detected (i.e., when
874 * group->shared_tile->bound[i].shift is set), then a in (1) refers
875 * to the shifted and scaled down version.
877 * Constraints (1) are obtained by mapping the size constraints on the
878 * shared/private memory tile back to the access relation.
879 * Constraints (2) are obtained from the (recomputed) extent.
881 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
883 int i;
884 int n_index = group->array->n_index;
885 isl_map *tile;
886 isl_space *space;
887 isl_set *local;
888 isl_set *extent;
890 space = isl_multi_aff_get_space(group->shared_tile->tiling);
891 space = isl_space_range(space);
892 local = isl_set_universe(space);
893 for (i = 0; i < n_index; ++i) {
894 isl_val *bound;
896 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
897 bound = isl_val_copy(group->shared_tile->bound[i].size);
898 bound = isl_val_sub_ui(bound, 1);
899 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
901 local = isl_set_preimage_multi_aff(local,
902 isl_multi_aff_copy(group->shared_tile->tiling));
903 tile = isl_set_unwrap(local);
904 extent = array_extent(group->array);
905 tile = isl_map_intersect_range(tile, extent);
907 return tile;
910 /* Given a mapping "iterator_map" from the AST schedule to a domain,
911 * return the corresponding mapping from the AST schedule
912 * to the outer kernel->copy_schedule_dim dimensions of
913 * the schedule computed by PPCG for this kernel.
915 * Note that kernel->copy_schedule_dim is at least as large as
916 * the largest depth of any array reference group associated to the kernel.
917 * This is needed as the returned schedule is used to extract a mapping
918 * to the outer tile->depth dimensions in transform_index.
920 static __isl_give isl_pw_multi_aff *compute_sched_to_copy(
921 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
923 isl_union_pw_multi_aff *upma;
924 isl_pw_multi_aff *pma;
925 isl_space *space;
927 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
928 space = isl_space_from_domain(space);
929 space = isl_space_add_dims(space, isl_dim_out,
930 kernel->copy_schedule_dim);
932 upma = isl_union_pw_multi_aff_copy(kernel->copy_schedule);
933 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
934 isl_union_pw_multi_aff_free(upma);
936 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
939 /* If max_shared_memory is not set to infinity (-1), then make
940 * sure that the total amount of shared memory required by the
941 * array reference groups mapped to shared memory by "kernel"
942 * is no larger than this maximum.
944 * We apply a greedy approach and discard (keep in global memory)
945 * those groups that would result in a total memory size that
946 * is larger than the maximum.
948 * This function should be called after any function that may
949 * affect the decision on whether to place a reference group
950 * in private, shared or global memory.
952 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
954 int i, j;
955 isl_val *left, *size;
957 if (kernel->options->max_shared_memory < 0)
958 return;
960 left = isl_val_int_from_si(kernel->ctx,
961 kernel->options->max_shared_memory);
963 for (i = 0; i < kernel->n_array; ++i) {
964 struct gpu_local_array_info *local = &kernel->array[i];
966 for (j = 0; j < local->n_group; ++j) {
967 struct gpu_array_ref_group *group;
968 enum ppcg_group_access_type type;
970 group = local->groups[j];
971 type = gpu_array_ref_group_type(group);
972 if (type != ppcg_access_shared)
973 continue;
975 size = gpu_array_tile_size(group->shared_tile);
976 size = isl_val_mul_ui(size, local->array->size);
978 if (isl_val_le(size, left)) {
979 left = isl_val_sub(left, size);
980 continue;
982 isl_val_free(size);
984 group->shared_tile =
985 gpu_array_tile_free(group->shared_tile);
989 isl_val_free(left);
992 /* Mark all arrays of "kernel" that have an array reference group
993 * that is not mapped to private or shared memory as
994 * accessing the corresponding global device memory.
996 static void mark_global_arrays(struct ppcg_kernel *kernel)
998 int i, j;
1000 for (i = 0; i < kernel->n_array; ++i) {
1001 struct gpu_local_array_info *local = &kernel->array[i];
1003 if (local->global)
1004 continue;
1005 for (j = 0; j < local->n_group; ++j) {
1006 if (gpu_array_ref_group_tile(local->groups[j]))
1007 continue;
1009 local->global = 1;
1010 local->array->global = 1;
1011 break;
1016 /* Compute a tiling for all the array reference groups in "kernel".
1018 static void compute_group_tilings(struct ppcg_kernel *kernel)
1020 int i, j;
1022 for (i = 0; i < kernel->n_array; ++i) {
1023 struct gpu_local_array_info *array = &kernel->array[i];
1025 for (j = 0; j < array->n_group; ++j)
1026 gpu_array_ref_group_compute_tiling(array->groups[j]);
1030 /* Compute the effective grid size as a list of the sizes in each dimension.
1032 * The grid size specified by the user or set by default
1033 * in read_grid_sizes() and applied by the block filter,
1034 * may be too large for the given code in the sense that
1035 * it may contain blocks that don't need to execute anything.
1036 * We therefore don't return this grid size, but instead the
1037 * smallest grid size that ensures that all blocks that actually
1038 * execute code are included in the grid.
1040 * We first extract a description of the grid, i.e., the possible values
1041 * of the block ids, from the domain elements in "domain" and
1042 * kernel->block_filter.
1043 * The block ids are parameters in kernel->block_filter.
1044 * We simply need to change them into set dimensions.
1046 * Then, for each block dimension, we compute the maximal value of the block id
1047 * and add one.
1049 static __isl_give isl_multi_pw_aff *extract_grid_size(
1050 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1052 int i;
1053 isl_set *grid;
1054 isl_set *context;
1055 isl_multi_pw_aff *size;
1057 domain = isl_union_set_intersect(domain,
1058 isl_union_set_copy(kernel->block_filter));
1059 grid = isl_union_set_params(domain);
1060 grid = isl_set_from_params(grid);
1061 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1062 for (i = 0; i < kernel->n_grid; ++i) {
1063 int pos;
1064 isl_id *id;
1066 if (!grid)
1067 return NULL;
1069 id = isl_id_list_get_id(kernel->block_ids, i);
1070 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1071 isl_id_free(id);
1072 if (pos < 0)
1073 isl_die(isl_set_get_ctx(grid), isl_error_internal,
1074 "missing constraints on block identifier",
1075 grid = isl_set_free(grid));
1076 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1077 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1080 grid = isl_set_coalesce(grid);
1081 size = ppcg_size_from_extent(grid);
1082 context = isl_set_params(isl_set_copy(kernel->context));
1083 return isl_multi_pw_aff_gist(size, context);
1086 /* Compute the size of a fixed bounding box around the origin and "set",
1087 * where "set" is assumed to contain only non-negative elements,
1088 * and store the results in "size".
1089 * In particular, compute the maximal value of "set" in each direction
1090 * and add one.
1092 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1094 int i, n;
1095 isl_local_space *ls;
1096 isl_aff *obj;
1098 n = isl_set_dim(set, isl_dim_set);
1099 ls = isl_local_space_from_space(isl_set_get_space(set));
1100 obj = isl_aff_zero_on_domain(ls);
1101 for (i = 0; i < n; ++i) {
1102 isl_val *max;
1104 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1105 max = isl_set_max_val(set, obj);
1106 size[i] = isl_val_get_num_si(max) + 1;
1107 isl_val_free(max);
1108 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1110 isl_aff_free(obj);
1111 isl_set_free(set);
1114 /* Compute the effective block size as a list of the sizes in each dimension
1115 * and store the sizes in kernel->block_dim.
1117 * The block size specified by the user or set by default
1118 * in read_block_sizes() and applied by the thread filter,
1119 * may be too large for the given code in the sense that
1120 * it may contain threads that don't need to execute anything.
1121 * We therefore update this block size in kernel->block_dim
1122 * to the smallest block size that ensures that all threads
1123 * that actually execute code are included in the block.
1125 * The set of possible values of the thread ids is obtained from
1126 * the domain elements "domain" and kernel->thread_filter.
1127 * The current implementation eliminates all parameters, ensuring
1128 * that the size is a fixed constant in each dimension.
1129 * In principle we could also compute parametric sizes.
1130 * We would have to make sure to project out all b%d and t%d parameters,
1131 * however.
1133 static isl_stat extract_block_size(struct ppcg_kernel *kernel,
1134 __isl_take isl_union_set *domain)
1136 int i;
1137 int nparam;
1138 isl_set *block;
1140 domain = isl_union_set_intersect(domain,
1141 isl_union_set_copy(kernel->thread_filter));
1142 block = isl_union_set_params(domain);
1143 block = isl_set_from_params(block);
1144 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1145 for (i = 0; i < kernel->n_block; ++i) {
1146 int pos;
1147 isl_id *id;
1149 if (!block)
1150 return isl_stat_error;
1152 id = isl_id_list_get_id(kernel->thread_ids, i);
1153 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1154 isl_id_free(id);
1155 if (pos < 0)
1156 isl_die(isl_set_get_ctx(block), isl_error_internal,
1157 "missing constraints on thread identifier",
1158 block = isl_set_free(block));
1159 block = isl_set_equate(block, isl_dim_param, pos,
1160 isl_dim_set, i);
1162 nparam = isl_set_dim(block, isl_dim_param);
1163 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1165 if (!block)
1166 return isl_stat_error;
1168 extract_fixed_size(block, kernel->block_dim);
1170 return isl_stat_ok;
1173 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1175 int i, j;
1177 if (!kernel)
1178 return NULL;
1180 isl_id_list_free(kernel->block_ids);
1181 isl_id_list_free(kernel->thread_ids);
1182 isl_multi_pw_aff_free(kernel->grid_size);
1183 isl_ast_expr_free(kernel->grid_size_expr);
1184 isl_set_free(kernel->context);
1185 isl_union_set_free(kernel->core);
1186 isl_union_set_free(kernel->arrays);
1187 isl_union_pw_multi_aff_free(kernel->contraction);
1188 isl_union_set_free(kernel->expanded_domain);
1189 isl_space_free(kernel->space);
1190 isl_ast_node_free(kernel->tree);
1191 isl_union_set_free(kernel->block_filter);
1192 isl_union_set_free(kernel->thread_filter);
1193 isl_union_pw_multi_aff_free(kernel->copy_schedule);
1194 isl_union_set_free(kernel->sync_writes);
1196 for (i = 0; i < kernel->n_array; ++i) {
1197 struct gpu_local_array_info *array = &kernel->array[i];
1199 for (j = 0; j < array->n_group; ++j)
1200 gpu_array_ref_group_free(array->groups[j]);
1201 free(array->groups);
1203 isl_multi_pw_aff_free(array->bound);
1204 isl_ast_expr_free(array->bound_expr);
1206 free(kernel->array);
1208 for (i = 0; i < kernel->n_var; ++i) {
1209 free(kernel->var[i].name);
1210 isl_vec_free(kernel->var[i].size);
1212 free(kernel->var);
1214 free(kernel);
1216 return NULL;
1219 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1221 static void ppcg_kernel_free_wrap(void *user)
1223 struct ppcg_kernel *kernel = user;
1225 ppcg_kernel_free(kernel);
1228 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1229 struct ppcg_kernel_var *var)
1231 int j;
1232 struct gpu_array_tile *tile;
1233 isl_printer *p;
1235 var->array = group->array;
1237 var->type = gpu_array_ref_group_type(group);
1238 tile = gpu_array_ref_group_tile(group);
1240 p = isl_printer_to_str(ctx);
1241 p = gpu_array_ref_group_print_name(group, p);
1242 var->name = isl_printer_get_str(p);
1243 isl_printer_free(p);
1245 var->size = isl_vec_alloc(ctx, group->array->n_index);
1247 for (j = 0; j < group->array->n_index; ++j)
1248 var->size = isl_vec_set_element_val(var->size, j,
1249 isl_val_copy(tile->bound[j].size));
1252 static isl_stat create_kernel_vars(struct ppcg_kernel *kernel)
1254 int i, j, n;
1256 n = 0;
1257 for (i = 0; i < kernel->n_array; ++i) {
1258 struct gpu_local_array_info *array = &kernel->array[i];
1260 for (j = 0; j < array->n_group; ++j) {
1261 struct gpu_array_ref_group *group = array->groups[j];
1262 enum ppcg_group_access_type type;
1264 type = gpu_array_ref_group_type(group);
1265 if (type != ppcg_access_global)
1266 ++n;
1270 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1271 if (!kernel->var)
1272 return isl_stat_error;
1273 kernel->n_var = n;
1275 n = 0;
1276 for (i = 0; i < kernel->n_array; ++i) {
1277 struct gpu_local_array_info *array = &kernel->array[i];
1279 for (j = 0; j < array->n_group; ++j) {
1280 struct gpu_array_ref_group *group = array->groups[j];
1281 enum ppcg_group_access_type type;
1283 type = gpu_array_ref_group_type(group);
1284 if (type == ppcg_access_global)
1285 continue;
1286 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1287 ++n;
1291 return isl_stat_ok;
1294 /* Replace "pa" by the zero function defined over the universe domain
1295 * in the space of "pa".
1297 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1299 isl_space *space;
1300 isl_aff *zero;
1302 space = isl_space_domain(isl_pw_aff_get_space(pa));
1303 isl_pw_aff_free(pa);
1304 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1306 return isl_pw_aff_from_aff(zero);
1309 /* The sizes of the arrays on the host that have been computed by
1310 * extract_array_info may depend on the parameters. Use the extra
1311 * constraints on the parameters that are valid at "host_domain"
1312 * to simplify these expressions and store the results in kernel->array.
1314 * We only need these localized bounds for arrays that are accessed
1315 * by the current kernel. If we have found at least one reference group
1316 * then the array is accessed by the kernel.
1318 * The resulting sizes may be functions that are nowhere defined
1319 * in case the access function cannot possibly access anything inside
1320 * the kernel for some reason. If so, they are replaced by the zero
1321 * function. Since the access function cannot actually access anything,
1322 * there is no harm in printing the array sizes as zero.
1324 static void localize_bounds(struct ppcg_kernel *kernel,
1325 __isl_keep isl_set *host_domain)
1327 int i, j;
1328 isl_set *context;
1330 context = isl_set_copy(host_domain);
1331 context = isl_set_params(context);
1333 for (i = 0; i < kernel->n_array; ++i) {
1334 struct gpu_local_array_info *local = &kernel->array[i];
1335 isl_multi_pw_aff *bound;
1336 int n_index;
1338 if (local->n_group == 0)
1339 continue;
1341 n_index = local->array->n_index;
1342 bound = isl_multi_pw_aff_copy(local->array->bound);
1344 for (j = 0; j < n_index; ++j) {
1345 isl_pw_aff *pwaff;
1346 int empty;
1348 pwaff = isl_multi_pw_aff_get_pw_aff(bound, j);
1349 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1350 empty = isl_pw_aff_is_empty(pwaff);
1351 if (empty < 0)
1352 pwaff = isl_pw_aff_free(pwaff);
1353 else if (empty)
1354 pwaff = set_universally_zero(pwaff);
1355 bound = isl_multi_pw_aff_set_pw_aff(bound, j, pwaff);
1358 local->n_index = n_index;
1359 local->bound = bound;
1361 isl_set_free(context);
1364 /* Create the array of gpu_local_array_info structures "array"
1365 * inside "kernel". The number of elements in this array is
1366 * the same as the number of arrays in "prog".
1367 * Initialize the "array" field of each local array to point
1368 * to the corresponding array in "prog".
1370 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1371 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1373 int i;
1374 isl_ctx *ctx;
1376 if (!kernel)
1377 return NULL;
1379 ctx = isl_set_get_ctx(prog->context);
1380 kernel->array = isl_calloc_array(ctx,
1381 struct gpu_local_array_info, prog->n_array);
1382 if (!kernel->array)
1383 return ppcg_kernel_free(kernel);
1384 kernel->n_array = prog->n_array;
1386 for (i = 0; i < prog->n_array; ++i)
1387 kernel->array[i].array = &prog->array[i];
1389 return kernel;
1392 /* Does "kernel" need to be passed an argument corresponding to array "i"?
1394 * The argument is only needed if the kernel accesses this device memory.
1396 int ppcg_kernel_requires_array_argument(struct ppcg_kernel *kernel, int i)
1398 return kernel->array[i].global;
1401 /* Find the element in gen->stmt that has the given "id".
1402 * Return NULL if no such gpu_stmt can be found.
1404 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1406 int i;
1408 for (i = 0; i < prog->n_stmts; ++i) {
1409 if (id == prog->stmts[i].id)
1410 break;
1413 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1416 void ppcg_kernel_stmt_free(void *user)
1418 struct ppcg_kernel_stmt *stmt = user;
1420 if (!stmt)
1421 return;
1423 switch (stmt->type) {
1424 case ppcg_kernel_copy:
1425 isl_ast_expr_free(stmt->u.c.index);
1426 isl_ast_expr_free(stmt->u.c.local_index);
1427 break;
1428 case ppcg_kernel_domain:
1429 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1430 break;
1431 case ppcg_kernel_sync:
1432 break;
1435 free(stmt);
1438 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1439 * to "ref_id".
1441 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1442 __isl_keep isl_id *ref_id)
1444 struct gpu_stmt_access *access;
1446 for (access = accesses; access; access = access->next)
1447 if (access->ref_id == ref_id)
1448 return access;
1450 return NULL;
1453 /* Return the index of the array called "name" in the list of arrays.
1455 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1457 int i;
1459 for (i = 0; i < kernel->n_array; ++i)
1460 if (!strcmp(name, kernel->array[i].array->name))
1461 return i;
1463 return -1;
1466 /* Internal data structure for the index and AST expression transformation
1467 * callbacks for pet_stmt_build_ast_exprs.
1469 * "kernel" is the kernel for which are computing AST expressions and
1470 * may be NULL if we are not inside a kernel.
1471 * "accesses" is the list of gpu_stmt_access in the statement.
1472 * "iterator_map" expresses the statement iterators in terms of
1473 * the AST loop iterators.
1474 * "sched2copy" expresses the outer copy_schedule_dim dimensions of
1475 * the kernel schedule in terms of the AST loop iterators and
1476 * may be NULL if we are not inside a kernel.
1478 * The following fields are set in transform_index and used in transform_expr.
1479 * "array" is the array that is being accessed.
1480 * "global" is set if the global array is accessed (rather than
1481 * shared/private memory).
1482 * "local_array" refers to information on the array specialized
1483 * to the current kernel.
1485 struct ppcg_transform_data {
1486 struct ppcg_kernel *kernel;
1487 struct gpu_stmt_access *accesses;
1488 isl_pw_multi_aff *iterator_map;
1489 isl_pw_multi_aff *sched2copy;
1491 struct gpu_array_info *array;
1492 int global;
1493 struct gpu_local_array_info *local_array;
1496 /* Return a pointer to the gpu_array_ref_group in "local"
1497 * that contains the reference "access".
1498 * Return NULL if no such group can be found.
1500 static struct gpu_array_ref_group *find_ref_group(
1501 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1503 int i, j;
1505 for (i = 0; i < local->n_group; ++i) {
1506 struct gpu_array_ref_group *group = local->groups[i];
1508 for (j = 0; j < group->n_ref; ++j)
1509 if (group->refs[j] == access)
1510 return group;
1513 return NULL;
1516 /* Given an index expression "index" of the form
1518 * L -> F(A),
1520 * with F(A) either A or some subfield of A and L the AST loop iterators,
1521 * and a tiling "tiling" of the form
1523 * [L -> A] -> T
1525 * apply the tiling to the outer array in the index expression to obtain
1527 * L -> T(A)
1529 * If F(A) is some subfield of A, then separate the member access
1530 * into the base index expression and the field index expression,
1531 * apply the tiling to the base index expression and combine the result
1532 * with the field index expression.
1534 * If F(A) is A, then modify index to keep track of the iterators
1536 * L -> [L -> A]
1538 * and combine the result with the tiling to obtain a tiled index expression
1539 * in terms of the AST loop iterators
1541 * L -> T
1543 static __isl_give isl_multi_pw_aff *tile_outer(
1544 __isl_take isl_multi_pw_aff *index, __isl_take isl_multi_pw_aff *tiling)
1546 isl_bool is_wrapping;
1547 isl_space *space;
1548 isl_multi_pw_aff *mpa;
1550 is_wrapping = isl_multi_pw_aff_range_is_wrapping(index);
1551 if (is_wrapping < 0)
1552 goto error;
1553 if (is_wrapping) {
1554 isl_multi_pw_aff *field;
1556 field = isl_multi_pw_aff_copy(index);
1557 field = isl_multi_pw_aff_range_factor_range(field);
1558 index = isl_multi_pw_aff_range_factor_domain(index);
1559 index = tile_outer(index, tiling);
1560 return isl_multi_pw_aff_range_product(index, field);
1563 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1564 space = isl_space_map_from_set(space);
1565 mpa = isl_multi_pw_aff_identity(space);
1566 index = isl_multi_pw_aff_range_product(mpa, index);
1567 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1569 return index;
1570 error:
1571 isl_multi_pw_aff_free(index);
1572 isl_multi_pw_aff_free(tiling);
1573 return NULL;
1576 /* Index transformation callback for pet_stmt_build_ast_exprs.
1578 * "index" expresses the array indices in terms of statement iterators
1580 * We first reformulate "index" in terms of the AST loop iterators.
1581 * Then we check if we are accessing the global array or
1582 * a shared/private copy. In particular, if we are not inside a kernel
1583 * then we must be accessing a global array.
1584 * In the former case, we simply return
1585 * the updated index. If "index" is an affine expression rather
1586 * than an array access, then we also return the updated index here.
1588 * If no reference groups have been computed for the array,
1589 * then we can only be accessing the global array.
1591 * Otherwise, we apply the tiling to the index.
1592 * This tiling is of the form
1594 * [D -> A] -> T
1596 * where D corresponds to the outer tile->depth dimensions of
1597 * the kernel schedule.
1598 * The index is of the form
1600 * L -> A
1602 * We update the tiling to refer to the AST loop iterators
1604 * [L -> A] -> T
1606 * and combine it with the index to obtain a tiled index expression in terms
1607 * of the AST loop iterators
1609 * L -> T
1611 * Note that while the tiling applies directly to an outer array.
1612 * the index may refer to some subfield of this outer array.
1613 * In such cases, the result will refer to the same subfield of the tile.
1614 * That is, an index expression of the form L -> F(A) will be transformed
1615 * into an index expression of the form L -> F(T).
1617 static __isl_give isl_multi_pw_aff *transform_index(
1618 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1619 void *user)
1621 struct ppcg_transform_data *data = user;
1622 struct gpu_stmt_access *access;
1623 struct gpu_array_ref_group *group;
1624 struct gpu_array_tile *tile;
1625 isl_pw_multi_aff *iterator_map;
1626 int i;
1627 int dim;
1628 const char *name;
1629 isl_space *space;
1630 isl_multi_pw_aff *tiling;
1631 isl_pw_multi_aff *pma;
1632 isl_pw_multi_aff *sched2depth;
1634 data->array = NULL;
1636 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1637 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1639 if (!data->kernel)
1640 return index;
1642 access = find_access(data->accesses, ref_id);
1643 if (!access)
1644 return index;
1645 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1646 return index;
1648 name = get_outer_array_name(access->access);
1649 if (!name)
1650 return isl_multi_pw_aff_free(index);
1651 i = find_array_index(data->kernel, name);
1652 if (i < 0)
1653 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1654 "cannot find array",
1655 return isl_multi_pw_aff_free(index));
1656 data->local_array = &data->kernel->array[i];
1657 data->array = data->local_array->array;
1659 group = find_ref_group(data->local_array, access);
1660 if (!group) {
1661 data->global = 1;
1662 return index;
1665 tile = gpu_array_ref_group_tile(group);
1666 data->global = !tile;
1667 if (!tile)
1668 return index;
1670 space = isl_space_domain(isl_multi_aff_get_space(tile->tiling));
1671 space = isl_space_range(isl_space_unwrap(space));
1672 space = isl_space_map_from_set(space);
1673 pma = isl_pw_multi_aff_identity(space);
1674 sched2depth = isl_pw_multi_aff_copy(data->sched2copy);
1675 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1676 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1677 tile->depth, dim - tile->depth);
1678 pma = isl_pw_multi_aff_product(sched2depth, pma);
1679 tiling = isl_multi_pw_aff_from_multi_aff(
1680 isl_multi_aff_copy(tile->tiling));
1681 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1683 index = tile_outer(index, tiling);
1685 return index;
1688 /* Dereference "expr" by adding an index [0].
1689 * The original "expr" is assumed not to have any indices.
1691 * If "expr" is a member access, then the dereferencing needs
1692 * to be applied to the structure argument of this member access.
1694 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1696 isl_ctx *ctx;
1697 isl_ast_expr *arg0, *res;
1698 isl_ast_expr_list *list;
1700 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1701 if (!arg0)
1702 return isl_ast_expr_free(expr);
1703 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1704 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1705 isl_ast_expr *arg;
1707 arg = isl_ast_expr_get_op_arg(arg0, 0);
1708 arg = dereference(arg);
1709 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1710 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1712 return expr;
1714 isl_ast_expr_free(arg0);
1716 ctx = isl_ast_expr_get_ctx(expr);
1717 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1718 list = isl_ast_expr_list_from_ast_expr(res);
1719 res = isl_ast_expr_get_op_arg(expr, 0);
1720 res = isl_ast_expr_access(res, list);
1721 isl_ast_expr_free(expr);
1723 return res;
1726 /* Linearize the index expression "expr" based on the array bounds
1727 * of "array".
1729 * That is, transform expression
1731 * A[i_0][i_1]...[i_n]
1733 * to
1735 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1737 * where b_0, b_1, ..., b_n are the bounds on the array.
1739 * If the base of "expr" is a member access, then the linearization needs
1740 * to be applied to the structure argument of this member access.
1742 * In the base case, if "expr" has no arguments (other than the name of
1743 * the array), then we are passing an entire array to a function.
1744 * In this case, there is nothing to linearize.
1745 * Note that at this point an expression with no arguments can
1746 * only be an entire array because the scalar case and
1747 * the case of single struct are handled by the caller.
1749 * If the number of specified index expressions in "expr"
1750 * is smaller than the dimension of the accessed array,
1751 * then the missing i_j also do not appear in the linearized expression.
1752 * Furthermore, since such an expression does not refer to a single
1753 * element while the default linearized expression would refer to
1754 * a single element, we return the expression
1756 * A + (..((i_0 * b_1 + i_1) ... ) * b_l + i_l)
1758 * instead. Note that because of the special case handling above,
1759 * we can assume here that there is at least one index expression.
1761 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1762 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1764 int i, n;
1765 isl_ast_expr *arg0;
1766 isl_ast_expr *res;
1767 isl_ast_expr_list *list;
1769 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1770 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1771 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1772 isl_ast_expr *arg;
1774 arg = isl_ast_expr_get_op_arg(arg0, 0);
1775 arg = gpu_local_array_info_linearize_index(array, arg);
1776 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1777 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1779 return expr;
1781 isl_ast_expr_free(arg0);
1783 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1784 return expr;
1786 n = isl_ast_expr_get_op_n_arg(expr);
1787 res = isl_ast_expr_get_op_arg(expr, 1);
1788 for (i = 1; i < array->n_index; ++i) {
1789 isl_ast_expr *expr_i;
1791 expr_i = isl_ast_expr_get_op_arg(array->bound_expr, 1 + i);
1792 res = isl_ast_expr_mul(res, expr_i);
1794 if (i + 1 >= n)
1795 continue;
1796 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1797 res = isl_ast_expr_add(res, expr_i);
1800 if (1 + array->n_index > n) {
1801 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1802 } else {
1803 list = isl_ast_expr_list_from_ast_expr(res);
1804 res = isl_ast_expr_get_op_arg(expr, 0);
1805 res = isl_ast_expr_access(res, list);
1808 isl_ast_expr_free(expr);
1810 return res;
1813 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1815 * If the AST expression refers to an array that is not accessed
1816 * at all, then this means the value of the expression is not used,
1817 * so we might as well print zero (NULL pointer) instead.
1819 * If the AST expression refers to a global scalar that is not
1820 * a read-only scalar, then its address was passed to the kernel and
1821 * we need to dereference it.
1823 * If the AST expression refers to an access to a global array,
1824 * then we linearize the access exploiting the bounds in data->local_array.
1826 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1827 __isl_keep isl_id *id, void *user)
1829 struct ppcg_transform_data *data = user;
1831 if (!data->array)
1832 return expr;
1833 if (!data->array->accessed) {
1834 isl_ctx *ctx;
1836 ctx = isl_ast_expr_get_ctx(expr);
1837 isl_ast_expr_free(expr);
1838 return isl_ast_expr_from_val(isl_val_zero(ctx));
1840 if (gpu_array_is_read_only_scalar(data->array))
1841 return expr;
1842 if (!data->global)
1843 return expr;
1844 if (data->array->n_index == 0)
1845 return dereference(expr);
1846 if (!data->array->linearize)
1847 return expr;
1849 return gpu_local_array_info_linearize_index(data->local_array, expr);
1852 /* This function is called for each instance of a user statement
1853 * in the kernel "kernel", identified by "gpu_stmt".
1854 * "kernel" may be NULL if we are not inside a kernel.
1856 * We attach a struct ppcg_kernel_stmt to the "node", containing
1857 * a computed AST expression for each access, through an annotation
1858 * with name "user".
1859 * These AST expressions are computed from iterator_map,
1860 * which expresses the domain
1861 * elements in terms of the generated loops, and sched2copy,
1862 * which expresses the outer copy_schedule_dim dimensions of
1863 * the kernel schedule computed by PPCG in terms of the generated loops.
1865 static __isl_give isl_ast_node *create_domain_leaf(
1866 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1867 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1869 struct ppcg_transform_data data;
1870 struct ppcg_kernel_stmt *stmt;
1871 isl_ctx *ctx;
1872 isl_id *id;
1873 isl_pw_multi_aff *sched2copy;
1874 isl_map *map;
1875 isl_pw_multi_aff *iterator_map;
1876 isl_union_map *schedule;
1878 if (!node)
1879 return NULL;
1880 ctx = isl_ast_node_get_ctx(node);
1882 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1883 if (!stmt)
1884 return isl_ast_node_free(node);
1886 schedule = isl_ast_build_get_schedule(build);
1887 map = isl_map_reverse(isl_map_from_union_map(schedule));
1888 iterator_map = isl_pw_multi_aff_from_map(map);
1889 if (kernel)
1890 sched2copy = compute_sched_to_copy(kernel,
1891 isl_pw_multi_aff_copy(iterator_map));
1892 else
1893 sched2copy = NULL;
1895 stmt->type = ppcg_kernel_domain;
1896 stmt->u.d.stmt = gpu_stmt;
1898 data.kernel = kernel;
1899 data.accesses = stmt->u.d.stmt->accesses;
1900 data.iterator_map = iterator_map;
1901 data.sched2copy = sched2copy;
1902 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1903 build, &transform_index, &data,
1904 &transform_expr, &data);
1906 isl_pw_multi_aff_free(iterator_map);
1907 isl_pw_multi_aff_free(sched2copy);
1909 id = isl_id_alloc(ctx, "user", stmt);
1910 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1911 if (!id)
1912 ppcg_kernel_stmt_free(stmt);
1913 return isl_ast_node_set_annotation(node, id);
1916 /* This function is called for each statement node in the AST
1917 * for copying to or from shared/private memory.
1918 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1919 * statement to the node.
1920 * The statement name is "read" or "write", depending on whether we are
1921 * reading from global memory or writing to global memory.
1923 * The schedule is of the form
1925 * type[D -> A] -> L
1927 * where D corresponds to the outer tile->depth dimensions of
1928 * the kernel schedule, A to the global array and L to the outer
1929 * generated AST schedule.
1930 * We compute the inverse and strip off the type, resulting in
1932 * L -> [D -> A]
1934 * We combine this mapping with on the one hand the projection
1936 * [D -> A] -> A
1938 * and on the other hand the group tiling
1940 * [D -> A] -> T
1942 * resulting in
1944 * L -> A and L -> T
1946 * and store the corresponding expressions in stmt->index and stmt->local_index,
1947 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1948 * stmt->index is linearized if the global memory array is linearized.
1950 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1951 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1952 __isl_keep isl_ast_build *build)
1954 struct ppcg_kernel_stmt *stmt;
1955 struct gpu_array_tile *tile;
1956 isl_id *id;
1957 isl_ast_expr *expr;
1958 isl_space *space;
1959 isl_map *access;
1960 isl_pw_multi_aff *pma, *pma2;
1961 const char *type;
1963 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1964 if (!stmt)
1965 return isl_ast_node_free(node);
1967 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1968 type = isl_map_get_tuple_name(access, isl_dim_in);
1969 stmt->u.c.read = type && !strcmp(type, "read");
1970 access = isl_map_reverse(access);
1971 pma = isl_pw_multi_aff_from_map(access);
1972 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1974 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1975 space = isl_space_unwrap(space);
1976 pma2 = isl_pw_multi_aff_range_map(space);
1977 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1978 isl_pw_multi_aff_copy(pma));
1979 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1980 if (group->array->linearize)
1981 expr = gpu_local_array_info_linearize_index(group->local_array,
1982 expr);
1983 stmt->u.c.index = expr;
1985 tile = gpu_array_ref_group_tile(group);
1986 pma2 = isl_pw_multi_aff_from_multi_aff(
1987 isl_multi_aff_copy(tile->tiling));
1988 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1989 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1990 stmt->u.c.local_index = expr;
1992 stmt->u.c.array = group->array;
1993 stmt->u.c.local_array = group->local_array;
1994 stmt->type = ppcg_kernel_copy;
1996 id = isl_id_alloc(kernel->ctx, "copy", stmt);
1997 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1998 if (!id)
1999 ppcg_kernel_stmt_free(stmt);
2000 return isl_ast_node_set_annotation(node, id);
2003 /* Create a synchronization ppcg_kernel_stmt and
2004 * attach it to the node "node" representing the synchronization.
2006 static __isl_give isl_ast_node *create_sync_leaf(
2007 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
2008 __isl_keep isl_ast_build *build)
2010 struct ppcg_kernel_stmt *stmt;
2011 isl_id *id;
2013 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
2014 if (!stmt)
2015 return isl_ast_node_free(node);
2017 stmt->type = ppcg_kernel_sync;
2018 id = isl_id_alloc(kernel->ctx, "sync", stmt);
2019 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2020 if (!id)
2021 ppcg_kernel_stmt_free(stmt);
2022 return isl_ast_node_set_annotation(node, id);
2025 /* Build AST expressions for the device array sizes of all arrays in "prog"
2026 * that require allocation on the device using "build", as well as
2027 * for the original array sizes of all arrays that need to be declared
2028 * on the host.
2029 * "node" is freed in case of error.
2031 static __isl_give isl_ast_node *build_array_bounds(
2032 __isl_take isl_ast_node *node, struct gpu_prog *prog,
2033 __isl_keep isl_ast_build *build)
2035 int i;
2037 for (i = 0; i < prog->n_array; ++i) {
2038 struct gpu_array_info *array = &prog->array[i];
2039 isl_multi_pw_aff *size;
2040 isl_ast_expr *expr;
2042 if (!gpu_array_requires_device_allocation(array))
2043 continue;
2045 size = isl_multi_pw_aff_copy(array->bound);
2046 expr = ppcg_build_size_expr(size, build);
2047 array->bound_expr = expr;
2048 if (!expr)
2049 return isl_ast_node_free(node);
2052 for (i = 0; i < prog->n_array; ++i) {
2053 struct gpu_array_info *array = &prog->array[i];
2054 isl_set *extent;
2055 isl_multi_pw_aff *size;
2056 isl_ast_expr *expr;
2058 if (!array->declare_local)
2059 continue;
2060 extent = isl_set_copy(array->declared_extent);
2061 size = ppcg_size_from_extent(extent);
2062 expr = ppcg_build_size_expr(size, build);
2063 array->declared_size = expr;
2064 if (!expr)
2065 return isl_ast_node_free(node);
2068 return node;
2071 /* Internal data structure for at_domain.
2073 * "prog" represents the entire scop.
2074 * "kernel" points to the kernel to which the current schedule node
2075 * belongs. It is set by before_mark and reset by after_mark.
2076 * It may be NULL if we are outside any kernel.
2078 struct ppcg_at_domain_data {
2079 struct gpu_prog *prog;
2080 struct ppcg_kernel *kernel;
2083 /* This function is called for each instance of a user statement
2084 * in the kernel. This may be one of the original user statements
2085 * or a statement introduced by PPCG.
2087 * We first check if the statement id corresponds to a gpu statement,
2088 * which indicates the statement is an original user statement. Any statement
2089 * that is not an original user statement has been introduced by PPCG and
2090 * requires special handling.
2092 * If the user statement is one of the original user statements, then we call
2093 * create_domain_leaf. If it is "init_device", then we call
2094 * build_array_bounds. Otherwise, we check if it is a copy or synchronization
2095 * statement and call the appropriate functions. Statements that copy an array
2096 * to/from the device do not need any further treatment.
2097 * Neither does "clear_device".
2099 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
2100 __isl_keep isl_ast_build *build, void *user)
2102 struct ppcg_at_domain_data *data = user;
2103 struct gpu_stmt *gpu_stmt;
2104 isl_ast_expr *expr, *arg;
2105 isl_id *id;
2106 int is_sync;
2107 const char *name;
2108 void *p;
2110 expr = isl_ast_node_user_get_expr(node);
2111 arg = isl_ast_expr_get_op_arg(expr, 0);
2112 id = isl_ast_expr_get_id(arg);
2113 name = isl_id_get_name(id);
2114 p = isl_id_get_user(id);
2115 isl_ast_expr_free(expr);
2116 isl_ast_expr_free(arg);
2118 gpu_stmt = find_stmt(data->prog, id);
2119 is_sync = gpu_tree_id_is_sync(id, data->kernel);
2120 isl_id_free(id);
2122 if (gpu_stmt)
2123 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
2125 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
2126 return node;
2127 if (!strcmp(name, "init_device"))
2128 return build_array_bounds(node, data->prog, build);
2129 if (!strcmp(name, "clear_device"))
2130 return node;
2131 if (is_sync < 0)
2132 return isl_ast_node_free(node);
2133 if (!strcmp(name, "read") || !strcmp(name, "write")) {
2134 struct gpu_array_ref_group *group = p;
2135 return create_access_leaf(data->kernel, group, node, build);
2137 if (!is_sync)
2138 isl_die(data->prog->ctx, isl_error_internal,
2139 "unknown statement type",
2140 return isl_ast_node_free(node));
2141 return create_sync_leaf(data->kernel, node, build);
2144 /* Given a set of wrapped references "ref", return the corresponding
2145 * access relations based on the tagged access relations "tagged".
2147 * The elements of "ref" are of the form
2149 * [D -> R]
2151 * with D an iteration domains and R a reference.
2152 * The elements of "tagged" are of the form
2154 * [D -> R] -> A
2156 * with A an array.
2158 * Extend "tagged" to include the iteration domain in the range, i.e.,
2160 * [D -> R] -> [D -> A]
2162 * apply the result to "ref" and then unwrap the resulting set
2163 * to obtain relations of the form
2165 * D -> A
2167 static __isl_give isl_union_map *wrapped_reference_to_access(
2168 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2170 isl_union_map *tag2access;
2172 tag2access = isl_union_map_copy(tagged);
2173 tag2access = isl_union_map_universe(tag2access);
2174 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2175 tag2access = isl_union_map_domain_map(tag2access);
2176 tag2access = isl_union_map_range_product(tag2access, tagged);
2178 ref = isl_union_set_coalesce(ref);
2179 ref = isl_union_set_apply(ref, tag2access);
2181 return isl_union_set_unwrap(ref);
2184 /* Given an access relation "access" from one or more array reference groups,
2185 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2186 * that are only needed to communicate data within
2187 * the same iteration of "sched".
2188 * The domain of "sched" corresponds to the original statement instances,
2189 * i.e., those that appear in the domains of the access relations.
2190 * "tagged" contains all tagged access relations to all
2191 * the array reference groups accessed by "access" from statement
2192 * instances scheduled by "sched".
2194 * If the access is a read then it is either an element of
2196 * live_in union (range flow)
2198 * where live_in and flow may be overapproximations, or
2199 * it reads an uninitialized value (that is not live-in because
2200 * there is an intermediate kill) or it reads a value that was
2201 * written within the same (compound) statement instance.
2202 * If the access is a write then it is either an element of
2204 * live_out union (domain flow)
2206 * or it writes a value that is never read (and is not live-out
2207 * because of an intermediate kill) or only
2208 * within the same (compound) statement instance.
2209 * In both cases, the access relation is also a subset of
2210 * the group access relation.
2212 * The cases where an uninitialized value is read or a value is written
2213 * that is never read or where the dataflow occurs within a statement
2214 * instance are also considered local and may also be removed.
2216 * Essentially, we compute the intersection of "access" with either
2218 * live_in union (range non-local-flow)
2220 * or
2222 * live_out union (domain non-local-flow)
2224 * We first construct a relation "local"
2226 * [[D -> R] -> [D' -> R']]
2228 * of pairs of domain iterations accessing the reference group
2229 * and references in the group that are coscheduled by "sched".
2231 * If this relation does not intersect the dataflow dependences,
2232 * then there is nothing we can possibly remove, unless the dataflow
2233 * dependences themselves only relate a subset of the accesses.
2234 * In particular, the accesses may not be involved in any dataflow
2235 * dependences, either because they are uninitialized reads/dead writes
2236 * or because the dataflow occurs inside a statement instance.
2238 * Since the computation below may break up the access relation
2239 * into smaller pieces, we only perform the intersection with
2240 * the non-local dependent accesses if the local pairs
2241 * intersect the dataflow dependences. Otherwise, we intersect
2242 * with the universe of the non-local dependent accesses.
2243 * This should at least remove accesses from statements that
2244 * do not participate in any dependences.
2246 * In particular, we remove the "local" dataflow dependences from
2247 * the set of all dataflow dependences, or at least those
2248 * that may contribute to a domain/range that intersects
2249 * the domain of "access".
2250 * Note that if the potential dataflow dependences are an overapproximation
2251 * of the actual dataflow dependences, then the result remains an
2252 * overapproximation of the non-local dataflow dependences.
2253 * Copying to/from global memory is only needed for the references
2254 * in the domain/range of the result or for accesses that are live out/in
2255 * for the entire scop.
2257 * We therefore map the domain/range of the "external" relation
2258 * to the corresponding access relation and take the union with
2259 * the live out/in relation.
2261 static __isl_give isl_union_map *remove_local_accesses(
2262 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2263 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2264 int read)
2266 int empty;
2267 isl_union_pw_multi_aff *tagger;
2268 isl_union_set *domain, *access_domain;
2269 isl_union_map *local, *external, *universe;
2270 isl_union_set *tag_set;
2272 if (isl_union_map_is_empty(access)) {
2273 isl_union_map_free(sched);
2274 isl_union_map_free(tagged);
2275 return access;
2278 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2279 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2280 tagger = isl_union_pw_multi_aff_intersect_domain(tagger,
2281 isl_union_set_copy(domain));
2282 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2284 local = isl_union_map_apply_range(sched,
2285 isl_union_map_reverse(isl_union_map_copy(sched)));
2286 local = isl_union_map_intersect(local,
2287 isl_union_map_copy(prog->scop->tagged_dep_flow));
2289 empty = isl_union_map_is_empty(local);
2291 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2292 universe = isl_union_map_universe(isl_union_map_copy(access));
2293 access_domain = isl_union_map_domain(universe);
2294 domain = isl_union_set_universe(domain);
2295 universe = isl_union_set_unwrap(domain);
2296 universe = isl_union_map_intersect_domain(universe, access_domain);
2297 domain = isl_union_map_wrap(universe);
2298 if (read)
2299 external = isl_union_map_intersect_range(external, domain);
2300 else
2301 external = isl_union_map_intersect_domain(external, domain);
2302 external = isl_union_map_intersect_params(external,
2303 isl_set_copy(prog->scop->context));
2304 external = isl_union_map_subtract(external, local);
2306 if (read) {
2307 tag_set = isl_union_map_range(external);
2308 external = wrapped_reference_to_access(tag_set, tagged);
2309 external = isl_union_map_union(external,
2310 isl_union_map_copy(prog->scop->live_in));
2311 } else {
2312 tag_set = isl_union_map_domain(external);
2313 external = wrapped_reference_to_access(tag_set, tagged);
2314 external = isl_union_map_union(external,
2315 isl_union_map_copy(prog->scop->live_out));
2318 if (empty < 0)
2319 external = isl_union_map_free(external);
2320 else if (empty)
2321 external = isl_union_map_universe(external);
2323 access = isl_union_map_intersect(access, external);
2325 return access;
2328 /* Given an access relation "access" from "group", remove those reads
2329 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2330 * communicate data within the same iteration of the schedule "prefix"
2331 * at the position where the copying of the group is inserted.
2332 * That is, the output dimension of "prefix"
2333 * is equal to tile->depth.
2334 * The domain of "prefix" corresponds to the original statement instances,
2335 * i.e., those that appear in the domains of the access relations.
2337 * Extract the tagged access relation of "group" and
2338 * then call remove_local_accesses.
2340 static __isl_give isl_union_map *remove_local_accesses_group(
2341 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2342 __isl_take isl_union_map *access, __isl_keep isl_union_map *prefix,
2343 int read)
2345 isl_union_map *sched, *tagged;
2347 if (isl_union_map_is_empty(access))
2348 return access;
2350 tagged = group_tagged_access_relation(group);
2351 sched = isl_union_map_copy(prefix);
2353 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2356 /* Build an access AST expression for the effective grid size using "build".
2357 * Store the result in kernel->grid_size_expr.
2359 static isl_stat build_grid_size(struct ppcg_kernel *kernel,
2360 __isl_keep isl_ast_build *build)
2362 isl_multi_pw_aff *size;
2364 size = isl_multi_pw_aff_copy(kernel->grid_size);
2365 size = isl_multi_pw_aff_set_tuple_name(size, isl_dim_out, "grid");
2366 kernel->grid_size_expr = ppcg_build_size_expr(size, build);
2368 if (!kernel->grid_size_expr)
2369 return isl_stat_error;
2370 return isl_stat_ok;
2373 /* Build access AST expressions for the localized array sizes using "build".
2374 * Store the result in local->bound_expr.
2375 * Only do this for arrays for which localized bounds have been computed.
2377 static isl_stat build_local_array_sizes(struct ppcg_kernel *kernel,
2378 __isl_keep isl_ast_build *build)
2380 int i;
2382 for (i = 0; i < kernel->n_array; ++i) {
2383 struct gpu_local_array_info *local = &kernel->array[i];
2384 isl_multi_pw_aff *size;
2386 if (local->n_group == 0)
2387 continue;
2388 size = isl_multi_pw_aff_copy(local->bound);
2389 local->bound_expr = ppcg_build_size_expr(size, build);
2390 if (!local->bound_expr)
2391 return isl_stat_error;
2394 return isl_stat_ok;
2397 /* Build access AST expressions for the effective grid size and
2398 * the localized array sizes using "build".
2400 static isl_stat build_grid_and_local_array_sizes(struct ppcg_kernel *kernel,
2401 __isl_keep isl_ast_build *build)
2403 if (build_grid_size(kernel, build) < 0)
2404 return isl_stat_error;
2405 if (build_local_array_sizes(kernel, build) < 0)
2406 return isl_stat_error;
2407 return isl_stat_ok;
2410 /* This function is called before the AST generator starts traversing
2411 * the schedule subtree of a node with mark "mark".
2413 * If the mark is called "kernel", store the kernel pointer in data->kernel
2414 * for use in at_domain and build AST expressions for the grid size and
2415 * the localized array sizes.
2417 static isl_stat before_mark(__isl_keep isl_id *mark,
2418 __isl_keep isl_ast_build *build, void *user)
2420 struct ppcg_at_domain_data *data = user;
2422 if (!mark)
2423 return isl_stat_error;
2424 if (!strcmp(isl_id_get_name(mark), "kernel")) {
2425 data->kernel = isl_id_get_user(mark);
2426 if (build_grid_and_local_array_sizes(data->kernel, build) < 0)
2427 return isl_stat_error;
2429 return isl_stat_ok;
2432 /* This function is called after the AST generator has finished traversing
2433 * the schedule subtree of a mark node. "node" points to the corresponding
2434 * mark AST node.
2436 * If the mark is called "kernel", then replace "node" by a user node
2437 * that "calls" the kernel, representing the launch of the kernel.
2438 * The original "node" is stored inside the kernel object so that
2439 * it can be used to print the device code.
2440 * Note that this assumes that a kernel is only launched once.
2441 * Also clear data->kernel.
2443 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2444 __isl_keep isl_ast_build *build, void *user)
2446 isl_ctx *ctx;
2447 isl_id *id;
2448 isl_ast_expr *expr;
2449 isl_ast_expr_list *list;
2450 struct ppcg_kernel *kernel;
2451 struct ppcg_at_domain_data *data = user;
2453 ctx = isl_ast_node_get_ctx(node);
2454 id = isl_ast_node_mark_get_id(node);
2455 if (!id)
2456 return isl_ast_node_free(node);
2457 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2458 isl_id_free(id);
2459 return node;
2461 kernel = data->kernel;
2462 data->kernel = NULL;
2463 kernel->space = isl_ast_build_get_schedule_space(build);
2464 kernel->tree = isl_ast_node_mark_get_node(node);
2465 isl_ast_node_free(node);
2467 expr = isl_ast_expr_from_id(isl_id_copy(id));
2468 list = isl_ast_expr_list_alloc(ctx, 0);
2469 expr = isl_ast_expr_call(expr, list);
2470 node = isl_ast_node_alloc_user(expr);
2471 node = isl_ast_node_set_annotation(node, id);
2473 return node;
2476 static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user)
2478 int *depth = user;
2479 int node_depth;
2481 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2482 return isl_bool_true;
2483 node_depth = isl_schedule_node_get_schedule_depth(node);
2484 if (node_depth > *depth)
2485 *depth = node_depth;
2487 return isl_bool_false;
2490 /* Use isl to generate code for both the host and the device
2491 * from "schedule".
2492 * The device code is marked by "kernel" mark nodes in the schedule tree,
2493 * containing a pointer to a ppcg_kernel object.
2494 * The returned AST only contains the AST for the host code.
2495 * The ASTs for the device code are embedded in ppcg_kernel objects
2496 * attached to the leaf nodes that call "kernel".
2498 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2499 __isl_take isl_schedule *schedule)
2501 struct ppcg_at_domain_data data;
2502 isl_ast_build *build;
2503 isl_ast_node *tree;
2504 isl_id_list *iterators;
2505 int depth;
2507 data.prog = gen->prog;
2508 data.kernel = NULL;
2510 depth = 0;
2511 if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth,
2512 &depth) < 0)
2513 schedule = isl_schedule_free(schedule);
2514 build = isl_ast_build_alloc(gen->prog->ctx);
2515 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2516 build = isl_ast_build_set_iterators(build, iterators);
2517 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2518 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2519 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2520 if (gen->prog->scop->options->debug->dump_final_schedule)
2521 isl_schedule_dump(schedule);
2522 tree = isl_ast_build_node_from_schedule(build, schedule);
2523 isl_ast_build_free(build);
2525 return tree;
2528 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2530 if (!str)
2531 return NULL;
2532 return isl_union_map_read_from_str(ctx, str);
2535 /* Can "node" be tiled and then mapped to block and thread identifiers?
2536 * That is, is it permutable with at least one coincident dimension?
2538 static isl_bool is_permutable(__isl_keep isl_schedule_node *node)
2540 if (!node)
2541 return isl_bool_error;
2543 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2544 return isl_bool_false;
2545 if (!isl_schedule_node_band_get_permutable(node))
2546 return isl_bool_false;
2547 if (isl_schedule_node_band_n_member(node) < 1)
2548 return isl_bool_false;
2549 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2550 return isl_bool_false;
2552 return isl_bool_true;
2555 /* Is "node" not a suitably permutable band?
2557 static isl_bool not_permutable(__isl_keep isl_schedule_node *node, void *user)
2559 return isl_bool_not(is_permutable(node));
2562 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
2563 * That is, does it have any nodes that are permutable and that
2564 * have a least one coincident dimension?
2566 static isl_bool subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
2568 isl_bool all_non_permutable;
2570 all_non_permutable = isl_schedule_node_every_descendant(node,
2571 &not_permutable, NULL);
2572 return isl_bool_not(all_non_permutable);
2575 /* Does "schedule" contain any permutable band with at least one coincident
2576 * member?
2578 static isl_bool has_any_permutable_node(__isl_keep isl_schedule *schedule)
2580 isl_schedule_node *root;
2581 isl_bool any_permutable;
2583 root = isl_schedule_get_root(schedule);
2584 any_permutable = subtree_has_permutable_bands(root);
2585 isl_schedule_node_free(root);
2587 return any_permutable;
2590 /* Is "node" a candidate for mapping to block and thread identifiers?
2591 * In particular, is it permutable with at least one coincident dimension?
2592 * Alternatively, does the subtree rooted at "node" not contain
2593 * any such permutable node? Filter nodes are skipped in this case,
2594 * because a band node will be inserted in front of the returned
2595 * node and this is not possible for filter nodes that are children
2596 * of set or sequence nodes.
2598 static int is_candidate(__isl_keep isl_schedule_node *node)
2600 isl_bool permutable;
2602 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2603 return 1;
2604 permutable = is_permutable(node);
2605 if (permutable < 0 || permutable)
2606 return permutable;
2607 if (isl_schedule_node_get_type(node) == isl_schedule_node_filter)
2608 return 0;
2609 permutable = subtree_has_permutable_bands(node);
2610 if (permutable < 0)
2611 return -1;
2612 return !permutable;
2615 /* Is "node" the outermost node in its branch that can be tiled
2616 * and then mapped to block and thread identifiers?
2617 * If there are no such nodes in the subtree at "node" and
2618 * if "node" is not a filter node, then it is accepted too.
2620 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2622 int tilable;
2623 isl_schedule_node *ancestor;
2625 tilable = is_candidate(node);
2626 if (tilable < 0)
2627 return -1;
2628 if (!tilable)
2629 return 0;
2631 tilable = 0;
2632 ancestor = isl_schedule_node_copy(node);
2633 while (isl_schedule_node_has_parent(ancestor)) {
2634 ancestor = isl_schedule_node_parent(ancestor);
2636 tilable = is_candidate(ancestor);
2637 if (tilable < 0 || tilable)
2638 break;
2641 isl_schedule_node_free(ancestor);
2642 return tilable < 0 ? -1 : !tilable;
2645 /* Collect the references to all writes in "group".
2646 * Each reference is represented by a universe set in a space
2648 * [S[i,j] -> R[]]
2650 * with S[i,j] the statement instance space and R[] the array reference.
2652 static __isl_give isl_union_set *group_tagged_writes(
2653 struct gpu_array_ref_group *group)
2655 int i;
2656 isl_space *space;
2657 isl_union_set *writes;
2659 space = isl_map_get_space(group->access);
2660 writes = isl_union_set_empty(space);
2661 for (i = 0; i < group->n_ref; ++i) {
2662 isl_space *space;
2663 isl_set *writes_i;
2665 if (!group->refs[i]->write)
2666 continue;
2668 space = isl_map_get_space(group->refs[i]->tagged_access);
2669 space = isl_space_domain(space);
2670 writes_i = isl_set_universe(space);
2671 writes = isl_union_set_add_set(writes, writes_i);
2674 return writes;
2677 /* Is there any write access in "group" that requires synchronization
2678 * on a write to global memory?
2679 * We currently take into account all writes that would require
2680 * synchronization at the thread level depth, but if the copying
2681 * for this group is performed at an outer level, then we do not
2682 * actually need to take into account dependences at intermediate levels.
2684 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2685 struct gpu_array_ref_group *group)
2687 isl_union_set *writes;
2688 int empty, disjoint;
2690 empty = isl_union_set_is_empty(kernel->sync_writes);
2691 if (empty < 0)
2692 return -1;
2693 if (empty)
2694 return 0;
2696 writes = group_tagged_writes(group);
2697 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2698 isl_union_set_free(writes);
2700 return disjoint < 0 ? -1 : !disjoint;
2703 /* Collect the references to all writes in "kernel" that write directly
2704 * to global or shared memory, i.e., that are not mapped to private memory.
2705 * Each reference is represented by a universe set in a space
2707 * [S[i,j] -> R[]]
2709 * with S[i,j] the statement instance space and R[] the array reference.
2711 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2712 struct ppcg_kernel *kernel)
2714 isl_union_set *writes;
2715 int i, j;
2717 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2719 for (i = 0; i < kernel->n_array; ++i) {
2720 struct gpu_local_array_info *array = &kernel->array[i];
2722 for (j = 0; j < array->n_group; ++j) {
2723 struct gpu_array_ref_group *group = array->groups[j];
2724 enum ppcg_group_access_type type;
2725 isl_union_set *writes_ij;
2727 if (!group->write)
2728 continue;
2729 type = gpu_array_ref_group_type(group);
2730 if (type == ppcg_access_private)
2731 continue;
2732 writes_ij = group_tagged_writes(group);
2733 writes = isl_union_set_union(writes, writes_ij);
2737 return writes;
2740 /* Are there any direct writes to global memory that require
2741 * synchronization?
2743 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2745 isl_union_set *writes;
2746 int empty, disjoint;
2748 empty = isl_union_set_is_empty(kernel->sync_writes);
2749 if (empty < 0)
2750 return -1;
2751 if (empty)
2752 return 0;
2754 writes = collect_non_private_tagged_writes(kernel);
2755 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2756 isl_union_set_free(writes);
2758 return disjoint < 0 ? -1 : !disjoint;
2761 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2762 * from the elements in "tile_size".
2764 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2765 __isl_keep isl_schedule_node *node, int *tile_size)
2767 isl_space *space;
2769 if (!node)
2770 return NULL;
2772 space = isl_schedule_node_band_get_space(node);
2773 return ppcg_multi_val_from_int_list(space, tile_size);
2776 /* Replace the partial schedule S of the band node "node" by
2778 * floor(S/f)
2780 * or
2782 * f * floor(S/f)
2784 * if scale_tile_loops is set, with f the integers in "factor".
2785 * The list that "factor" points to is assumed to contain at least
2786 * as many elements as the number of members in the band.
2788 static __isl_give isl_schedule_node *snap_band_to_sizes(
2789 __isl_take isl_schedule_node *node, int *factor,
2790 struct ppcg_options *options)
2792 isl_multi_val *mv;
2794 mv = construct_band_tiles_sizes(node, factor);
2795 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2796 if (options->scale_tile_loops)
2797 node = isl_schedule_node_band_scale(node,
2798 isl_multi_val_copy(mv));
2799 isl_multi_val_free(mv);
2801 return node;
2804 /* Tile "band" with tile size specified by "sizes".
2806 * Since the tile loops will be mapped to block ids, we forcibly
2807 * turn off tile loop scaling. We may want to enable tile loop scaling
2808 * at some later point, but then we would have to support the detection
2809 * of strides during the mapping to block ids.
2810 * Similarly, since the point loops will be mapped to thread ids,
2811 * we forcibly shift the point loops so that they start at zero.
2813 static __isl_give isl_schedule_node *tile_band(
2814 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2816 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2817 int scale_tile;
2818 int shift_point;
2820 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2821 isl_options_set_tile_scale_tile_loops(ctx, 0);
2822 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2823 isl_options_set_tile_shift_point_loops(ctx, 1);
2825 node = isl_schedule_node_band_tile(node, sizes);
2827 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2828 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2830 return node;
2833 /* Extract the set of parameter values and outer schedule dimensions
2834 * for which any statement instance
2835 * in the kernel inserted at "node" needs to be executed.
2836 * Intersect the set of parameter values derived from the host schedule
2837 * relation with the context of "prog".
2839 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2840 struct gpu_prog *prog)
2842 isl_union_map *schedule;
2843 isl_union_set *schedule_domain;
2844 isl_set *context;
2845 int empty;
2847 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2848 schedule_domain = isl_union_map_range(schedule);
2849 empty = isl_union_set_is_empty(schedule_domain);
2850 if (empty < 0) {
2851 isl_union_set_free(schedule_domain);
2852 return NULL;
2854 if (empty) {
2855 int depth;
2856 isl_space *space;
2858 space = isl_union_set_get_space(schedule_domain);
2859 isl_union_set_free(schedule_domain);
2860 space = isl_space_set_from_params(space);
2861 depth = isl_schedule_node_get_schedule_depth(node);
2862 space = isl_space_add_dims(space, isl_dim_set, depth);
2863 context = isl_set_empty(space);
2864 } else {
2865 context = isl_set_from_union_set(schedule_domain);
2867 context = isl_set_intersect_params(context,
2868 isl_set_copy(prog->context));
2870 return context;
2873 /* Return the set of outer array elements accessed by
2874 * by the statement instances in "domain" in "prog".
2875 * The instances in "domain" are those that appear
2876 * in the domains of the access relations in "prog".
2878 static __isl_give isl_union_set *accessed_by_domain(
2879 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2881 isl_union_map *access;
2882 isl_union_set *arrays;
2884 access = isl_union_map_union(isl_union_map_copy(prog->read),
2885 isl_union_map_copy(prog->may_write));
2886 access = isl_union_map_intersect_domain(access, domain);
2887 arrays = isl_union_map_range(access);
2888 arrays = isl_union_set_apply(arrays,
2889 isl_union_map_copy(prog->to_outer));
2891 return arrays;
2894 /* Return the number of outer band members of the band node "node"
2895 * that are marked coincident.
2897 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2899 int i, n;
2901 n = isl_schedule_node_band_n_member(node);
2903 for (i = 0; i < n; ++i)
2904 if (!isl_schedule_node_band_member_get_coincident(node, i))
2905 break;
2907 return i;
2910 /* If the band node "node" has more than "n" members, then split off
2911 * the first "n" of them.
2913 static __isl_give isl_schedule_node *split_band(
2914 __isl_take isl_schedule_node *node, int n)
2916 int dim;
2918 dim = isl_schedule_node_band_n_member(node);
2919 if (n < dim)
2920 node = isl_schedule_node_band_split(node, n);
2922 return node;
2925 /* Scale a band node that may have been split by split_band.
2926 * "sizes" are the scaling factors for the original node.
2927 * "node" either points to the original band node, or the outer
2928 * of the two pieces after splitting.
2930 * If the number of elements in "node" is smaller than the number of
2931 * elements in "sizes", then some splitting has occurred and we split
2932 * "sizes" in the same way.
2934 static __isl_give isl_schedule_node *scale_band(
2935 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2937 int n, dim;
2939 n = isl_multi_val_dim(sizes, isl_dim_set);
2940 dim = isl_schedule_node_band_n_member(node);
2941 if (n > dim) {
2942 isl_multi_val *sizes2;
2944 sizes2 = isl_multi_val_copy(sizes);
2945 sizes = isl_multi_val_drop_dims(sizes,
2946 isl_dim_set, dim, n - dim);
2947 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2948 node = isl_schedule_node_child(node, 0);
2949 node = isl_schedule_node_band_scale(node, sizes2);
2950 node = isl_schedule_node_parent(node);
2953 return isl_schedule_node_band_scale(node, sizes);
2956 /* Return an isl_multi_aff, with as elements the parameters in "space"
2957 * that have the names specified by the elements in "names".
2958 * If (some of) these parameters do not already appear in "space",
2959 * then they are added first.
2961 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2962 __isl_keep isl_id_list *names)
2964 int i, n;
2965 isl_local_space *ls;
2966 isl_multi_aff *ma;
2968 if (!names)
2969 space = isl_space_free(space);
2971 n = isl_id_list_n_id(names);
2972 for (i = 0; i < n; ++i) {
2973 int pos;
2974 isl_id *id;
2976 id = isl_id_list_get_id(names, i);
2977 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2978 if (pos >= 0) {
2979 isl_id_free(id);
2980 continue;
2982 pos = isl_space_dim(space, isl_dim_param);
2983 space = isl_space_add_dims(space, isl_dim_param, 1);
2984 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2986 ma = isl_multi_aff_zero(isl_space_copy(space));
2987 ls = isl_local_space_from_space(isl_space_domain(space));
2988 for (i = 0; i < n; ++i) {
2989 int pos;
2990 isl_id *id;
2991 isl_aff *aff;
2993 id = isl_id_list_get_id(names, i);
2994 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2995 isl_id_free(id);
2996 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2997 isl_dim_param, pos);
2998 ma = isl_multi_aff_set_aff(ma, i, aff);
3000 isl_local_space_free(ls);
3002 return ma;
3005 /* Return constraints on the domain elements that equate a sequence of
3006 * parameters called "names", to the partial schedule
3007 * of "node" modulo the integers in "size".
3008 * The number of elements in the array "size" should be equal
3009 * to the number of elements in "names".
3010 * The number of members of the band node "node" should be smaller
3011 * than or equal to this number. If it is smaller, then the first
3012 * elements of "names" are equated to zero.
3014 static __isl_give isl_union_set *set_schedule_modulo(
3015 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
3016 int *size)
3018 int n, n_zero;
3019 isl_space *space;
3020 isl_multi_aff *ma;
3021 isl_multi_union_pw_aff *mupa, *mupa2;
3022 isl_multi_val *mv;
3023 isl_union_set *domain;
3025 if (!node)
3026 return NULL;
3027 n = isl_id_list_n_id(names);
3028 if (n == 0)
3029 return isl_schedule_node_get_universe_domain(node);
3030 n_zero = n - isl_schedule_node_band_n_member(node);
3032 mupa = isl_schedule_node_band_get_partial_schedule(node);
3033 mv = construct_band_tiles_sizes(node, size + n_zero);
3034 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
3036 space = isl_multi_union_pw_aff_get_space(mupa);
3037 space = isl_space_params(space);
3038 space = isl_space_set_from_params(space);
3039 space = isl_space_add_dims(space, isl_dim_set, n_zero);
3040 ma = isl_multi_aff_zero(space);
3042 domain = isl_schedule_node_get_universe_domain(node);
3043 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
3044 isl_union_set_copy(domain), ma);
3045 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
3047 space = isl_multi_union_pw_aff_get_space(mupa);
3048 ma = parameter_vector(space, names);
3050 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
3051 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
3053 return isl_multi_union_pw_aff_zero_union_set(mupa);
3056 /* Insert a context node at "node" introducing the block and thread
3057 * identifiers along with their bounds, which are stored in kernel->grid_size
3058 * and kernel->block_dim.
3059 * Note that the bounds on the block identifiers may implicitly impose
3060 * constraints on the parameters. A guard needs to be inserted
3061 * in the schedule tree to ensure that those bounds hold at "node".
3062 * This guard is inserted in insert_guard.
3064 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
3065 __isl_take isl_schedule_node *node)
3067 isl_set *context;
3069 context = isl_set_universe(isl_set_get_space(kernel->context));
3071 context = add_bounded_parameters_dynamic(context,
3072 kernel->grid_size, kernel->block_ids);
3073 context = add_bounded_parameters(context,
3074 kernel->block_dim, kernel->thread_ids);
3076 node = isl_schedule_node_insert_context(node, context);
3078 return node;
3081 /* Insert a guard that eliminates kernel launches where the kernel
3082 * obviously does not have any work to do.
3084 * In particular, eliminate kernel launches where there are obviously
3085 * zero blocks.
3086 * Use the same block size constraints that are used to create the context
3087 * to ensure that all constraints implicit in the constructed context
3088 * are imposed by the guard.
3090 * Additionally, add other constraints that are valid
3091 * for each executed instance ("context"), as long as this does not result
3092 * in a disjunction.
3094 static __isl_give isl_schedule_node *insert_guard(
3095 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
3096 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
3098 unsigned nparam, n;
3099 isl_set *guard;
3100 isl_id_list *ids;
3102 guard = isl_set_copy(context);
3103 guard = isl_set_compute_divs(guard);
3104 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
3106 nparam = isl_set_dim(guard, isl_dim_param);
3107 n = isl_multi_pw_aff_dim(size, isl_dim_out);
3108 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
3109 guard = add_bounded_parameters_dynamic(guard, size, ids);
3110 isl_id_list_free(ids);
3111 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
3113 node = isl_schedule_node_insert_guard(node, guard);
3115 return node;
3118 /* Does any array reference group mapping require the band that is mapped
3119 * to threads to be unrolled?
3121 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
3123 int i, j;
3125 for (i = 0; i < kernel->n_array; ++i) {
3126 struct gpu_local_array_info *array = &kernel->array[i];
3128 for (j = 0; j < array->n_group; ++j) {
3129 struct gpu_array_ref_group *group = array->groups[j];
3130 if (gpu_array_ref_group_requires_unroll(group))
3131 return 1;
3135 return 0;
3138 /* Mark the given band node "node" for unrolling by the AST generator and
3139 * then sink it to the leaves of the schedule tree.
3140 * All dimensions of "node" are assumed to be coincident, such that this
3141 * sinking is a valid operation.
3143 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
3145 node = ppcg_set_schedule_node_type(node, isl_ast_loop_unroll);
3147 node = isl_schedule_node_band_sink(node);
3149 return node;
3152 /* Insert a synchronization node in the schedule tree of "node"
3153 * after the core computation of "kernel" at the level of the band
3154 * that is mapped to threads, except if that level is equal to
3155 * that of the band that is mapped to blocks or if there are no writes
3156 * to global or shared memory in the core computation that require
3157 * synchronization.
3158 * If there are any writes to shared memory and the shared memory
3159 * copying is performed at the same level, then synchronization
3160 * is needed between the core and the copying anyway, so we might
3161 * as well add it here. If the copying is performed at a higher
3162 * level, then different iterations of intermediate schedule dimensions
3163 * may have a different mapping from between shared memory elements and
3164 * threads, such that synchronization is required after the core.
3165 * "node" is assumed to point to the kernel node.
3167 * If the shared and the thread mark point to the same node, then make
3168 * sure the synchronization is inserted outside of the shared mark.
3170 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
3171 __isl_take isl_schedule_node *node)
3173 int depth;
3174 int need_sync;
3176 need_sync = any_global_or_shared_sync_writes(kernel);
3177 if (need_sync < 0)
3178 return isl_schedule_node_free(node);
3179 if (!need_sync)
3180 return node;
3182 node = gpu_tree_move_down_to_thread(node, kernel->core);
3183 depth = isl_schedule_node_get_schedule_depth(node);
3184 node = gpu_tree_move_up_to_kernel(node);
3185 if (depth == isl_schedule_node_get_schedule_depth(node))
3186 return node;
3188 node = gpu_tree_move_down_to_depth(node, depth, kernel->core);
3189 node = gpu_tree_ensure_following_sync(node, kernel);
3191 node = gpu_tree_move_up_to_kernel(node);
3193 return node;
3196 /* Return a read ("read" is 1) or write access relation for "group"
3197 * with those accesses removed that are only needed to communicate data
3198 * within the subtree of the schedule rooted at "node".
3199 * Furthermore, include the prefix schedule at "node".
3200 * That is, return a relation of the form
3202 * S -> [D -> A]
3204 * with D the outer schedule dimensions at "node".
3206 static __isl_give isl_union_map *anchored_non_local_accesses(
3207 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3208 __isl_take isl_schedule_node *node, int read)
3210 isl_union_map *access;
3211 isl_union_map *prefix;
3213 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
3214 prefix = isl_union_map_preimage_domain_union_pw_multi_aff(prefix,
3215 isl_union_pw_multi_aff_copy(kernel->contraction));
3216 access = gpu_array_ref_group_access_relation(group, read, !read);
3217 access = remove_local_accesses_group(kernel, group, access, prefix,
3218 read);
3219 access = isl_union_map_range_product(prefix, access);
3221 return access;
3224 /* Given an array reference group "group", create a mapping
3226 * read[D -> A] -> [D -> A]
3228 * if "read" is set or
3230 * write[D -> A] -> [D -> A]
3232 * if "read" is not set.
3233 * D corresponds to the outer tile->depth dimensions of
3234 * the kernel schedule.
3236 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
3237 struct gpu_array_ref_group *group, int read)
3239 struct gpu_array_tile *tile;
3240 isl_space *space;
3241 isl_id *id;
3243 tile = gpu_array_ref_group_tile(group);
3244 space = isl_space_copy(group->array->space);
3245 space = isl_space_from_range(space);
3246 space = isl_space_add_dims(space, isl_dim_in, tile->depth);
3247 space = isl_space_wrap(space);
3248 space = isl_space_map_from_set(space);
3250 id = isl_id_alloc(ctx, read ? "read" : "write", group);
3251 space = isl_space_set_tuple_id(space, isl_dim_in, id);
3253 return isl_multi_aff_identity(space);
3256 /* If any writes in "group" require synchronization, then make sure
3257 * that there is a synchronization node for "kernel" after the node
3258 * following "node" in a sequence.
3260 * If "shared" is set and no synchronization is needed for
3261 * the writes to global memory, then add synchronization before
3262 * the kernel to protect shared memory from being overwritten
3263 * by the next iteration of the core computation.
3264 * No additional synchronization is needed to protect against
3265 * the next copy into shared memory because each element of
3266 * the shared memory tile is always copied by the same thread.
3268 static __isl_give isl_schedule_node *add_group_write_sync(
3269 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3270 struct gpu_array_ref_group *group, int shared)
3272 int need_sync;
3274 need_sync = any_sync_writes_in_group(kernel, group);
3275 if (need_sync < 0)
3276 return isl_schedule_node_free(node);
3277 if (need_sync) {
3278 node = isl_schedule_node_parent(node);
3279 node = isl_schedule_node_next_sibling(node);
3280 node = isl_schedule_node_child(node, 0);
3281 node = gpu_tree_ensure_following_sync(node, kernel);
3282 } else if (shared) {
3283 struct gpu_array_tile *tile;
3285 tile = gpu_array_ref_group_tile(group);
3286 node = isl_schedule_node_parent(node);
3287 node = isl_schedule_node_parent(node);
3288 node = gpu_tree_move_down_to_depth(node, tile->depth,
3289 kernel->core);
3290 node = gpu_tree_move_left_to_sync(node, kernel);
3293 return node;
3296 /* Add copy statements to the schedule tree of "node"
3297 * for reading from global memory to private memory (if "read" is set) or
3298 * for writing back from private memory to global memory
3299 * (if "read" is not set) for the array reference group "group" that
3300 * is mapped to private 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 array elements.
3305 * The copy statement instances include a reference to the outer
3306 * tile->depth dimensions of the kernel schedule for ease of
3307 * combining them with the group tiling.
3309 * That is, the extra schedule is of the form
3311 * type[D -> A] -> A
3313 * where D corresponds to the outer tile->depth dimensions of
3314 * the kernel schedule and A to the global array.
3315 * This schedule is unrolled because registers are not addressable.
3317 * The copying is inserted in the schedule tree through an extension
3318 * of the form
3320 * D -> type[D -> A]
3322 * where the extra domain elements type[D -> A] are those accessed
3323 * by the group.
3324 * A filter is inserted on type[D -> A] to ensure that the element
3325 * is read/written by the same thread that needs the element.
3326 * This filter is obtained by applying
3328 * S -> type[D -> A]
3330 * to the thread filter for the core statements.
3332 * The extension is inserted before the core computation in case of a read
3333 * and after the core computation in case of a write.
3334 * In the latter case, we also make sure that there is a synchronization
3335 * node after the write to global memory, unless this write is performed
3336 * at the outer level of the kernel.
3337 * In principle, this synchronization could be inserted higher
3338 * in the schedule tree depending on where the corresponding reads
3339 * from global memory are performed.
3341 static __isl_give isl_schedule_node *add_copies_group_private(
3342 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3343 __isl_take isl_schedule_node *node, int read)
3345 struct gpu_array_tile *tile;
3346 isl_union_map *access;
3347 isl_union_set *domain;
3348 isl_space *space;
3349 isl_multi_aff *from_access;
3350 isl_multi_pw_aff *mpa;
3351 isl_multi_union_pw_aff *mupa;
3352 isl_union_pw_multi_aff *contraction;
3353 isl_schedule_node *graft;
3354 isl_union_set *filter;
3355 int kernel_depth;
3356 int empty;
3358 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3359 tile = gpu_array_ref_group_tile(group);
3360 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3362 access = anchored_non_local_accesses(kernel, group, node, read);
3363 empty = isl_union_map_is_empty(access);
3364 if (empty < 0 || empty) {
3365 isl_union_map_free(access);
3366 if (empty < 0)
3367 return isl_schedule_node_free(node);
3368 return gpu_tree_move_up_to_kernel(node);
3371 group->array->global = 1;
3372 group->local_array->global = 1;
3374 from_access = create_from_access(kernel->ctx, group, read);
3375 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3376 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3378 filter = isl_union_set_copy(kernel->thread_filter);
3379 contraction = isl_union_pw_multi_aff_copy(kernel->contraction);
3380 filter = isl_union_set_preimage_union_pw_multi_aff(filter, contraction);
3381 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3382 filter = isl_union_set_detect_equalities(filter);
3383 filter = isl_union_set_coalesce(filter);
3385 domain = isl_union_map_range(access);
3386 access = isl_union_set_wrapped_domain_map(domain);
3387 access = isl_union_map_reverse(access);
3388 access = isl_union_map_coalesce(access);
3389 graft = isl_schedule_node_from_extension(access);
3391 space = isl_space_map_from_set(space);
3392 mpa = isl_multi_pw_aff_identity(space);
3393 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3394 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3396 graft = isl_schedule_node_child(graft, 0);
3397 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3398 graft = unroll(graft);
3400 graft = isl_schedule_node_insert_filter(graft, filter);
3402 graft = isl_schedule_node_parent(graft);
3404 if (read)
3405 node = isl_schedule_node_graft_before(node, graft);
3406 else {
3407 node = isl_schedule_node_graft_after(node, graft);
3408 if (kernel_depth < tile->depth)
3409 node = add_group_write_sync(node, kernel, group, 0);
3412 node = gpu_tree_move_up_to_kernel(node);
3414 return node;
3417 /* Add copy statements to the schedule tree of "node"
3418 * for reading from global memory to shared memory (if "read" is set) or
3419 * for writing back from shared memory to global memory
3420 * (if "read" is not set) for the array reference group "group" that
3421 * is mapped to shared memory.
3422 * On input, "node" points to the kernel node, and it is moved
3423 * back there on output.
3425 * The copies are performed in the order of the corresponding shared
3426 * memory tile.
3427 * The copy statement instances include a reference to the outer
3428 * tile->depth dimensions of the kernel schedule for ease of
3429 * combining them with the group tiling.
3431 * If we are performing a read from global memory to shared memory and
3432 * if the array involved is not a scalar, then we copy
3433 * the entire tile to shared memory. This may result in some extra
3434 * elements getting copied, but it should lead to simpler code
3435 * (which means that fewer registers may be needed) and less divergence.
3437 * Otherwise, we only copy the elements that will be read or have been written
3438 * in the kernel.
3440 * That is, the extra schedule is of the form
3442 * type[D -> A] -> T
3444 * where D corresponds to the outer tile->depth dimensions of
3445 * the kernel schedule, A to the global array and T is the corresponding
3446 * shared memory tile.
3448 * The copying is inserted in the schedule tree through an extension
3449 * of the form
3451 * D -> type[D -> A]
3453 * where the extra domain elements type[D -> A] are those accessed
3454 * by the group. In the case of read from a non-scalar, this set
3455 * is replaced by the entire shared memory tile.
3457 * If the "unroll_copy_shared" option is set, then the AST generator
3458 * is instructed to unroll the copying code.
3460 * A filter is inserted on type[D -> A] to map the copy instances
3461 * to the threads. In particular, the thread identifiers are
3462 * equated to the position inside the shared memory tile (T)
3463 * modulo the block size.
3464 * We try to align the innermost tile dimension with the innermost
3465 * thread identifier (x) as a heuristic to improve coalescing.
3466 * In particular, if the dimension of the tile is greater than
3467 * the dimension of the block, then the schedule mapping to the tile
3468 * is broken up into two pieces and the filter is applied to the inner part.
3469 * If, on the other hand, the dimension of the tile is smaller than
3470 * the dimension of the block, then the initial thread identifiers
3471 * are equated to zero and the remaining thread identifiers are
3472 * matched to the memory tile.
3474 * The extension is inserted before the core computation in case of a read
3475 * and after the core computation in case of a write.
3476 * In the case of a read, we first need to make sure there is some
3477 * synchronization before the core computation such that we can put the read
3478 * from global memory to shared memory before that synchronization.
3479 * This ensures that all threads have finished copying into shared memory
3480 * before the shared memory is used.
3481 * We also need to make sure that there is a synchronization node after
3482 * the core computation to ensure that the next load into shared memory
3483 * only happens after all data has been used. There is no need for
3484 * this synchronization if we are at the outer level since then there
3485 * won't be a next load.
3486 * In the case of a write, we need to make sure there is some synchronization
3487 * after the core computation such that we can put the write from shared
3488 * memory to global memory after that synchronization.
3489 * Unless we are at the outer level, we also need a synchronization node
3490 * after the write to ensure the data is saved to global memory
3491 * before the next iteration writes to the same shared memory.
3492 * It also makes sure the data has arrived in global memory before
3493 * it is read in a subsequent iteration.
3495 static __isl_give isl_schedule_node *add_copies_group_shared(
3496 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3497 __isl_take isl_schedule_node *node, int read)
3499 struct gpu_array_tile *tile;
3500 isl_union_map *access;
3501 isl_union_set *domain;
3502 isl_multi_aff *ma;
3503 isl_multi_aff *from_access;
3504 isl_multi_pw_aff *mpa;
3505 isl_multi_union_pw_aff *mupa;
3506 isl_schedule_node *graft;
3507 isl_union_set *filter;
3508 int skip;
3509 int kernel_depth;
3510 int empty;
3512 tile = gpu_array_ref_group_tile(group);
3513 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3514 node = gpu_tree_move_down_to_depth(node, tile->depth, kernel->core);
3516 access = anchored_non_local_accesses(kernel, group, node, read);
3517 empty = isl_union_map_is_empty(access);
3518 if (empty < 0 || empty) {
3519 isl_union_map_free(access);
3520 if (empty < 0)
3521 return isl_schedule_node_free(node);
3522 return gpu_tree_move_up_to_kernel(node);
3525 group->array->global = 1;
3526 group->local_array->global = 1;
3528 from_access = create_from_access(kernel->ctx, group, read);
3530 ma = isl_multi_aff_copy(tile->tiling);
3531 ma = isl_multi_aff_pullback_multi_aff(ma,
3532 isl_multi_aff_copy(from_access));
3533 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3534 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3536 domain = isl_union_map_range(access);
3538 if (read && !gpu_array_is_scalar(group->array)) {
3539 isl_map *map;
3540 isl_union_set_free(domain);
3541 map = group_tile(group);
3542 domain = isl_union_set_from_set(isl_map_wrap(map));
3545 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3546 access = isl_union_set_wrapped_domain_map(domain);
3547 access = isl_union_map_reverse(access);
3548 access = isl_union_map_coalesce(access);
3549 graft = isl_schedule_node_from_extension(access);
3551 graft = isl_schedule_node_child(graft, 0);
3553 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3554 if (kernel->options->unroll_copy_shared)
3555 graft = ppcg_set_schedule_node_type(graft, isl_ast_loop_unroll);
3557 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3558 graft = isl_schedule_node_band_split(graft,
3559 tile->n - kernel->n_block);
3560 graft = isl_schedule_node_child(graft, 0);
3562 if (tile->n < kernel->n_block)
3563 skip = kernel->n_block - tile->n;
3564 else
3565 skip = 0;
3566 filter = set_schedule_modulo(graft, kernel->thread_ids,
3567 kernel->block_dim);
3568 if (!kernel->options->wrap)
3569 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3570 kernel->options);
3571 if (tile->n > kernel->n_block && kernel->n_block > 0)
3572 graft = isl_schedule_node_parent(graft);
3573 graft = isl_schedule_node_insert_filter(graft, filter);
3575 while (graft && isl_schedule_node_has_parent(graft))
3576 graft = isl_schedule_node_parent(graft);
3578 if (read) {
3579 if (kernel_depth < tile->depth)
3580 node = gpu_tree_ensure_sync_after_core(node, kernel);
3581 node = gpu_tree_move_left_to_sync(node, kernel);
3582 node = isl_schedule_node_graft_before(node, graft);
3583 } else {
3584 node = gpu_tree_move_right_to_sync(node, kernel);
3585 node = isl_schedule_node_graft_after(node, graft);
3586 if (kernel_depth < tile->depth)
3587 node = add_group_write_sync(node, kernel, group, 1);
3590 node = gpu_tree_move_up_to_kernel(node);
3592 return node;
3595 /* Check whether the array reference group "group" is mapped to
3596 * private or shared memory and, if so,
3597 * add copy statements to the schedule tree of "node"
3598 * for reading from global memory to private or shared memory
3599 * (if "read" is set) or for writing back from private or shared memory
3600 * to global memory (if "read" is not set) for this group.
3601 * On input, "node" points to the kernel node, and it is moved
3602 * back there on output.
3604 static __isl_give isl_schedule_node *add_copies_group(
3605 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3606 __isl_take isl_schedule_node *node, int read)
3608 enum ppcg_group_access_type type;
3610 type = gpu_array_ref_group_type(group);
3611 if (type == ppcg_access_private)
3612 return add_copies_group_private(kernel, group, node, read);
3613 if (type == ppcg_access_shared)
3614 return add_copies_group_shared(kernel, group, node, read);
3615 return node;
3618 /* For each array reference group that is mapped to private or shared memory,
3619 * add copy statements to the schedule tree of "node"
3620 * for reading from global memory to private or shared memory
3621 * and for writing back.
3622 * On input, "node" points to the kernel node, and it is moved
3623 * back there on output.
3625 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3626 __isl_take isl_schedule_node *node)
3628 int i, j;
3630 for (i = 0; i < kernel->n_array; ++i) {
3631 struct gpu_local_array_info *array = &kernel->array[i];
3633 for (j = 0; j < array->n_group; ++j) {
3634 struct gpu_array_ref_group *group = array->groups[j];
3636 node = add_copies_group(kernel, group, node, 1);
3637 if (!node)
3638 return NULL;
3639 node = add_copies_group(kernel, group, node, 0);
3640 if (!node)
3641 return NULL;
3645 return node;
3648 /* Mark all dimensions in the current band node atomic.
3650 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3652 return ppcg_set_schedule_node_type(node, isl_ast_loop_atomic);
3655 /* Mark "node" atomic, if it is a band node.
3656 * Do the same for all ancestors.
3657 * Return a pointer to "node" (in the updated schedule tree).
3659 static __isl_give isl_schedule_node *atomic_ancestors(
3660 __isl_take isl_schedule_node *node)
3662 int pos;
3664 if (!node)
3665 return NULL;
3666 if (!isl_schedule_node_has_parent(node))
3667 return node;
3669 pos = isl_schedule_node_get_child_position(node);
3670 node = isl_schedule_node_parent(node);
3671 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3672 node = atomic(node);
3673 node = atomic_ancestors(node);
3674 node = isl_schedule_node_child(node, pos);
3676 return node;
3679 /* Collect all write references that require synchronization.
3680 * "node" is assumed to point to the kernel node.
3681 * Each reference is represented by a universe set in a space
3683 * [S[i,j] -> R[]]
3685 * with S[i,j] the statement instance space and R[] the array reference.
3687 * This function should be called before block and thread filters are added.
3689 * Synchronization is needed after a write if there is a subsequent read
3690 * within the same block that may not be performed by the same thread.
3691 * There should not be any dependences between different blocks,
3692 * so we start with the flow dependences within the same kernel invocation
3693 * and we subtract from these those dependences that are mapped
3694 * to the same iteration of the bands where synchronization is inserted.
3695 * We do not remove pairs of instances that are known to map to
3696 * the same thread across different iterations of the intermediate
3697 * bands because the read may be performed by a different thread
3698 * than the one that needs the value if shared memory is involved.
3700 * We also consider all pairs of possible writes that access the same
3701 * memory location and that may be mapped to the same block but not
3702 * to the same iteration of the intermediate bands.
3703 * In theory, it would be possible for one thread to still be in
3704 * a previous iteration of a loop in these bands.
3705 * A write to global memory in this delayed thread could then overwrite
3706 * a write from another thread that has already moved on to
3707 * the next iteration.
3709 * After computing the above writes paired off with reads or writes
3710 * that depend on them, we project onto the domain writes.
3711 * Sychronization is needed after writes to global memory
3712 * through these references.
3714 static __isl_give isl_union_set *compute_sync_writes(
3715 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3717 isl_union_map *local;
3718 isl_union_map *may_writes, *shared_access;
3719 isl_union_map *kernel_prefix, *thread_prefix;
3720 isl_union_map *equal;
3721 isl_union_set *wrap;
3722 isl_union_set *domain;
3723 isl_union_pw_multi_aff *contraction;
3725 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3726 node = isl_schedule_node_copy(node);
3727 node = gpu_tree_move_down_to_thread(node, kernel->core);
3728 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3729 isl_schedule_node_free(node);
3731 contraction = kernel->contraction;
3732 kernel_prefix = isl_union_map_preimage_domain_union_pw_multi_aff(
3733 kernel_prefix, isl_union_pw_multi_aff_copy(contraction));
3734 thread_prefix = isl_union_map_preimage_domain_union_pw_multi_aff(
3735 thread_prefix, isl_union_pw_multi_aff_copy(contraction));
3736 domain = isl_union_set_copy(kernel->expanded_domain);
3737 domain = isl_union_set_universe(domain);
3739 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3740 may_writes = isl_union_map_curry(may_writes);
3741 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3742 may_writes = isl_union_map_uncurry(may_writes);
3743 shared_access = isl_union_map_copy(may_writes);
3744 shared_access = isl_union_map_apply_range(shared_access,
3745 isl_union_map_reverse(may_writes));
3747 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3748 local = isl_union_map_union(local, shared_access);
3749 local = isl_union_map_zip(local);
3751 equal = isl_union_map_apply_range(kernel_prefix,
3752 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3753 wrap = isl_union_map_wrap(equal);
3754 local = isl_union_map_intersect_domain(local, wrap);
3755 equal = isl_union_map_apply_range(thread_prefix,
3756 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3757 wrap = isl_union_map_wrap(equal);
3758 local = isl_union_map_subtract_domain(local, wrap);
3760 local = isl_union_map_zip(local);
3761 local = isl_union_map_universe(local);
3763 return isl_union_map_domain(local);
3766 /* Group the domain elements into a single space, named kernelX,
3767 * with X the kernel sequence number "kernel_id".
3769 static __isl_give isl_schedule_node *group_statements(
3770 __isl_take isl_schedule_node *node, int kernel_id)
3772 char buffer[20];
3773 isl_id *id;
3775 if (!node)
3776 return NULL;
3778 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3779 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3780 return isl_schedule_node_group(node, id);
3783 /* Create a ppcg_kernel representing the domain instances that reach "node"
3784 * and insert a mark node pointing to the ppcg_kernel before "node".
3785 * The band that "node" points to is the band that needs to be mapped
3786 * to block identifiers. The band that needs to be mapped to thread
3787 * identifiers should be marked by a "thread" mark by the caller.
3788 * The linear branch between the current node and the "thread" mark
3789 * may also have a "shared" mark. If present, the mapping to shared
3790 * memory is computed at that point.
3791 * Both marks are removed by this function.
3792 * If "scale" is set, then the band that "node" points to is scaled
3793 * by "sizes".
3795 * Mark all outer band nodes as atomic to ensure each kernel is only
3796 * scheduled once.
3797 * If the domain elements that reach "node" live in more than one space,
3798 * then group the domain elements into a single space, named kernelX,
3799 * with X the kernel sequence number.
3801 * Insert a guard node governing the kernel node to ensure that
3802 * no kernels with zero blocks are launched.
3804 * Insert a context node describing the block and thread
3805 * identifiers inside the kernel mark.
3806 * The context node needs to be inserted after the effective block size
3807 * has been determined such that the bounds on the thread identifiers
3808 * would reflect the effective block size.
3809 * Insert a filter node inside the context node mapping the statement
3810 * instances to block identifiers. In particular, the block identifiers
3811 * are equated to the partial schedule of band that was marked for mapping
3812 * to blocks modulo the grid size.
3813 * Insert a filter node inside the "thread" mark mapping the statement
3814 * instances to thread identifiers. In particular, the thread identifiers
3815 * are equated to the partial schedule of band that was marked for mapping
3816 * to threads modulo the block size.
3818 * Compute array reference groups for all arrays, set the local
3819 * array bounds based on the set of domain instances that reach
3820 * the kernel node, check the total amount of shared memory used
3821 * and compute all group tilings.
3822 * The array reference groups are computed after the block filter
3823 * has been inserted because it affects the mapping to shared or
3824 * private memory. This computation also requires the thread filter
3825 * (in the ppcg_kernel object), but this thread filter should not
3826 * have been added to the schedule tree yet since the computation
3827 * requires the schedule of the band that needs to be mapped to
3828 * threads before the privatization is applied.
3830 * If any array reference group requires the band mapped to threads
3831 * to be unrolled, then we perform the required unrolling.
3833 * We save a copy of the schedule that may influence the mappings
3834 * to shared or private memory in kernel->copy_schedule.
3836 * Finally, we add synchronization and copy statements to the schedule tree,
3837 * remove the "thread" mark and create representations for the local
3838 * variables in the kernel.
3840 * We keep a copy of the isl_id that points to the kernel to ensure
3841 * that the kernel does not get destroyed if the schedule node
3842 * is freed due to some error condition.
3844 __isl_give isl_schedule_node *gpu_create_kernel(struct gpu_gen *gen,
3845 __isl_take isl_schedule_node *node, int scale,
3846 __isl_keep isl_multi_val *sizes)
3848 struct ppcg_kernel *kernel;
3849 isl_id *id;
3850 isl_schedule_node *node_thread;
3851 isl_union_map *host_schedule;
3852 isl_union_pw_multi_aff *contraction;
3853 isl_set *host_domain;
3854 isl_union_set *domain, *expanded;
3855 int single_statement;
3857 node = gpu_tree_insert_shared_before_thread(node);
3858 if (!node)
3859 return NULL;
3861 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3862 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3863 if (!kernel)
3864 return isl_schedule_node_free(node);
3866 domain = isl_schedule_node_get_domain(node);
3867 single_statement = isl_union_set_n_set(domain) == 1;
3869 kernel->ctx = gen->ctx;
3870 kernel->prog = gen->prog;
3871 kernel->options = gen->options;
3872 kernel->context = extract_context(node, gen->prog);
3873 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3874 contraction = isl_schedule_node_get_subtree_contraction(node);
3875 kernel->contraction = isl_union_pw_multi_aff_copy(contraction);
3876 expanded = isl_union_set_copy(domain);
3877 expanded = isl_union_set_preimage_union_pw_multi_aff(expanded,
3878 contraction);
3879 kernel->expanded_domain = isl_union_set_copy(expanded);
3880 kernel->arrays = accessed_by_domain(expanded, gen->prog);
3881 kernel->n_grid = n_outer_coincidence(node);
3882 node_thread = isl_schedule_node_copy(node);
3883 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3884 node_thread = isl_schedule_node_child(node_thread, 0);
3885 kernel->n_block = n_outer_coincidence(node_thread);
3886 isl_schedule_node_free(node_thread);
3887 kernel->id = gen->kernel_id++;
3888 if (read_grid_and_block_sizes(kernel, gen) < 0)
3889 node = isl_schedule_node_free(node);
3891 kernel->sync_writes = compute_sync_writes(kernel, node);
3893 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3894 host_domain = isl_set_from_union_set(isl_union_map_range(
3895 host_schedule));
3897 node = atomic_ancestors(node);
3899 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3900 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3901 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3903 if (!single_statement)
3904 node = group_statements(node, kernel->id);
3906 node = isl_schedule_node_child(node, 0);
3907 node = split_band(node, kernel->n_grid);
3908 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3909 kernel->n_grid, "b");
3910 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3911 kernel->grid_dim);
3912 kernel->grid_size = extract_grid_size(kernel,
3913 isl_union_set_copy(domain));
3914 if (!kernel->options->wrap)
3915 node = snap_band_to_sizes(node, kernel->grid_dim,
3916 kernel->options);
3917 if (scale)
3918 node = scale_band(node, isl_multi_val_copy(sizes));
3919 node = isl_schedule_node_parent(node);
3920 if (!single_statement)
3921 node = isl_schedule_node_parent(node);
3922 node = insert_guard(node, kernel->context, kernel->grid_size,
3923 gen->prog->scop);
3924 node = gpu_tree_move_down_to_thread(node, kernel->core);
3925 node = isl_schedule_node_child(node, 0);
3926 node = split_band(node, kernel->n_block);
3927 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3928 kernel->n_block, "t");
3929 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3930 kernel->block_dim);
3931 if (extract_block_size(kernel, domain) < 0)
3932 node = isl_schedule_node_free(node);
3934 node = gpu_tree_move_up_to_kernel(node);
3935 node = isl_schedule_node_child(node, 0);
3936 node = insert_context(kernel, node);
3937 node = isl_schedule_node_child(node, 0);
3938 node = isl_schedule_node_insert_filter(node,
3939 isl_union_set_copy(kernel->block_filter));
3941 node = gpu_tree_move_up_to_kernel(node);
3943 if (gpu_group_references(kernel, node) < 0)
3944 node = isl_schedule_node_free(node);
3945 localize_bounds(kernel, host_domain);
3946 isl_set_free(host_domain);
3948 check_shared_memory_bound(kernel);
3949 mark_global_arrays(kernel);
3950 compute_group_tilings(kernel);
3952 node = gpu_tree_move_down_to_thread(node, kernel->core);
3953 node = isl_schedule_node_child(node, 0);
3954 if (!kernel->options->wrap)
3955 node = snap_band_to_sizes(node, kernel->block_dim,
3956 kernel->options);
3957 node = isl_schedule_node_insert_filter(node,
3958 isl_union_set_copy(kernel->thread_filter));
3959 if (kernel_requires_unroll(kernel)) {
3960 node = isl_schedule_node_child(node, 0);
3961 node = unroll(node);
3964 node = gpu_tree_move_up_to_thread(node);
3965 kernel->copy_schedule_dim = isl_schedule_node_get_schedule_depth(node);
3966 kernel->copy_schedule =
3967 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3968 contraction = isl_union_pw_multi_aff_copy(kernel->contraction);
3969 kernel->copy_schedule =
3970 isl_union_pw_multi_aff_pullback_union_pw_multi_aff(
3971 kernel->copy_schedule, contraction);
3973 node = gpu_tree_move_up_to_kernel(node);
3975 node = add_sync(kernel, node);
3976 node = add_copies(kernel, node);
3978 node = gpu_tree_move_down_to_shared(node, kernel->core);
3979 node = isl_schedule_node_delete(node);
3981 node = gpu_tree_move_down_to_thread(node, kernel->core);
3982 node = isl_schedule_node_delete(node);
3984 node = gpu_tree_move_up_to_kernel(node);
3986 if (create_kernel_vars(kernel) < 0)
3987 node = isl_schedule_node_free(node);
3989 if (!single_statement)
3990 node = isl_schedule_node_parent(node);
3991 node = isl_schedule_node_parent(node);
3993 isl_id_free(id);
3994 if (!id)
3995 ppcg_kernel_free(kernel);
3996 return node;
3999 /* Insert a zero-dimensional permutable band at "node".
4001 static __isl_give isl_schedule_node *insert_empty_permutable_band(
4002 __isl_take isl_schedule_node *node)
4004 isl_space *space;
4005 isl_schedule *schedule;
4006 isl_union_set *domain;
4007 isl_multi_union_pw_aff *mupa;
4009 schedule = isl_schedule_node_get_schedule(node);
4010 domain = isl_schedule_get_domain(schedule);
4011 space = isl_union_set_get_space(domain);
4012 isl_union_set_free(domain);
4013 isl_schedule_free(schedule);
4015 space = isl_space_set_from_params(space);
4016 mupa = isl_multi_union_pw_aff_zero(space);
4017 node = isl_schedule_node_insert_partial_schedule(node, mupa);
4018 node = isl_schedule_node_band_set_permutable(node, 1);
4020 return node;
4023 /* See if hybrid tiling can be performed on "node" and its parent.
4024 * If so, apply hybrid tiling and return the updated schedule tree.
4025 * If not, return the original schedule tree.
4026 * Return NULL on error.
4028 * First check if "node", together with its parent, meets
4029 * the basic requirements for hybrid tiling.
4030 * If so, compute the relative dependence distances of "node"
4031 * with respect to its parent and check if they are sufficiently bounded.
4032 * If so, apply hybrid tiling using user specified tile sizes.
4034 * The tile sizes are read before the dependence distance bounds are
4035 * computed, because the user may have specified fewer dimensions
4036 * than are available. In this case, the remaining schedule dimensions
4037 * are split off and the dependence distances should be computed
4038 * after these dimensions have been split off.
4040 static __isl_give isl_schedule_node *try_hybrid_tile(struct gpu_gen *gen,
4041 __isl_take isl_schedule_node *node)
4043 int tile_len;
4044 int *tile_size;
4045 isl_bool ok;
4046 isl_schedule_node *orig = node;
4047 ppcg_ht_bounds *bounds;
4049 ok = ppcg_ht_parent_has_input_pattern(node);
4050 if (ok < 0)
4051 return isl_schedule_node_free(node);
4052 if (!ok)
4053 return orig;
4055 tile_len = 1 + isl_schedule_node_band_n_member(node);
4056 tile_size = read_tile_sizes(gen, &tile_len);
4057 if (!tile_size)
4058 return isl_schedule_node_free(node);
4060 node = isl_schedule_node_copy(node);
4061 node = split_band(node, tile_len - 1);
4062 node = isl_schedule_node_parent(node);
4063 bounds = ppcg_ht_compute_bounds(gen->prog->scop, node);
4064 node = isl_schedule_node_child(node, 0);
4066 ok = ppcg_ht_bounds_is_valid(bounds);
4067 if (ok >= 0 && ok)
4068 node = gpu_hybrid_tile(gen, node, bounds, tile_size);
4069 else
4070 ppcg_ht_bounds_free(bounds);
4071 free(tile_size);
4073 if (ok >= 0 && !ok) {
4074 isl_schedule_node_free(node);
4075 return orig;
4077 isl_schedule_node_free(orig);
4078 if (ok < 0)
4079 return isl_schedule_node_free(node);
4080 return node;
4083 /* If "node" is the outermost permutable band that can be mapped to block and
4084 * thread identifiers in its branch (or the root of a subtree with
4085 * no such outer bands),
4086 * then mark the band as such, attaching a ppcg_kernel to the mark.
4088 * If hybrid tiling is allowed, then first try and apply it
4089 * to "node" and its parent.
4091 * If "node" is the root of a subtree without permutable bands,
4092 * then insert a zero-dimensional permutable band such that
4093 * we can assume that "node" always points to a band node.
4094 * This includes the case where "node" already points to a band node,
4095 * but one without any coincident dimension. In this case,
4096 * the extra node ensures that this original node does not get tiled.
4098 * Tile "node" using user specified tile sizes, after splitting the band
4099 * if the number of specified tile sizes is smaller than the dimension
4100 * of the band. Mark the point band of this tiling as the band that
4101 * needs to be mapped to threads and instruct the AST generator to unroll
4102 * the band if the "unroll_gpu_tile" option is set.
4103 * Create a kernel representing the domain instances that reach "node" and
4104 * insert a mark node pointing to the ppcg_kernel before the band node.
4106 static __isl_give isl_schedule_node *mark_outer_permutable(
4107 __isl_take isl_schedule_node *node, void *user)
4109 struct gpu_gen *gen = user;
4110 int outer;
4111 int scale;
4112 int tile_len;
4113 int *tile_size;
4114 isl_id *id;
4115 isl_multi_val *sizes;
4117 outer = is_outer_tilable(node);
4118 if (outer < 0)
4119 return isl_schedule_node_free(node);
4120 if (!outer)
4121 return node;
4123 if (gen->options->hybrid) {
4124 isl_schedule_node *saved = isl_schedule_node_copy(node);
4125 node = try_hybrid_tile(gen, node);
4126 isl_schedule_node_free(saved);
4127 if (node != saved)
4128 return node;
4131 if (isl_schedule_node_get_type(node) != isl_schedule_node_band ||
4132 !isl_schedule_node_band_member_get_coincident(node, 0))
4133 node = insert_empty_permutable_band(node);
4135 tile_len = isl_schedule_node_band_n_member(node);
4136 tile_size = read_tile_sizes(gen, &tile_len);
4137 if (!tile_size)
4138 return isl_schedule_node_free(node);
4139 if (tile_len < isl_schedule_node_band_n_member(node))
4140 node = isl_schedule_node_band_split(node, tile_len);
4141 sizes = construct_band_tiles_sizes(node, tile_size);
4142 node = tile_band(node, isl_multi_val_copy(sizes));
4143 node = isl_schedule_node_child(node, 0);
4144 if (gen->options->unroll_gpu_tile)
4145 node = ppcg_set_schedule_node_type(node, isl_ast_loop_unroll);
4146 id = isl_id_alloc(gen->ctx, "thread", NULL);
4147 node = isl_schedule_node_insert_mark(node, id);
4148 node = isl_schedule_node_parent(node);
4150 scale = gen->options->scale_tile_loops;
4151 node = gpu_create_kernel(gen, node, scale, sizes);
4152 isl_multi_val_free(sizes);
4153 free(tile_size);
4155 return node;
4158 /* Given a set or sequence node, return the union the filters of either all
4159 * (if "only_initial" is not set) or the initial (if "only_initial" is set)
4160 * direct subtrees that do not contain any suitably permutable bands
4161 * (according to subtree_has_permutable_bands).
4163 static __isl_give isl_union_set *get_non_parallel_subtree_filters(
4164 __isl_keep isl_schedule_node *node, int only_initial)
4166 isl_space *space;
4167 isl_union_set *filter;
4168 int i, n;
4170 n = isl_schedule_node_n_children(node);
4171 if (n < 0)
4172 return NULL;
4174 node = isl_schedule_node_copy(node);
4175 node = isl_schedule_node_child(node, 0);
4176 filter = isl_schedule_node_filter_get_filter(node);
4177 node = isl_schedule_node_parent(node);
4178 space = isl_union_set_get_space(filter);
4179 isl_union_set_free(filter);
4180 filter = isl_union_set_empty(space);
4182 for (i = 0; i < n; ++i) {
4183 int parallelism;
4185 node = isl_schedule_node_child(node, i);
4186 parallelism = subtree_has_permutable_bands(node);
4187 if (parallelism < 0) {
4188 filter = isl_union_set_free(filter);
4189 } else if (!parallelism) {
4190 isl_union_set *filter_i;
4191 filter_i = isl_schedule_node_filter_get_filter(node);
4192 filter = isl_union_set_union(filter, filter_i);
4193 } else if (only_initial)
4194 break;
4195 node = isl_schedule_node_parent(node);
4198 isl_schedule_node_free(node);
4200 return filter;
4203 /* Given a set or sequence node, return the union of the filters of
4204 * the direct subtrees that do not contain any suitably permutable bands
4205 * (according to subtree_has_permutable_bands).
4207 static __isl_give isl_union_set *get_all_non_parallel_subtree_filters(
4208 __isl_keep isl_schedule_node *node)
4210 return get_non_parallel_subtree_filters(node, 0);
4213 /* Given a set or sequence node, return the union of the filters of
4214 * the initial direct subtrees that do not contain any suitably permutable
4215 * bands (according to subtree_has_permutable_bands).
4217 static __isl_give isl_union_set *get_initial_non_parallel_subtree_filters(
4218 __isl_keep isl_schedule_node *node)
4220 return get_non_parallel_subtree_filters(node, 1);
4223 /* Mark all variables that are accessed by the statement instances in "domain"
4224 * and that are local to "prog" as requiring a declaration in the host code.
4225 * The statement instances in "domain" correspond to (a subset of)
4226 * the active instances at "node".
4227 * "node" is not modified by this function, except that NULL is returned
4228 * in case of error.
4230 static __isl_give isl_schedule_node *declare_accessed_local_variables(
4231 __isl_take isl_schedule_node *node, struct gpu_prog *prog,
4232 __isl_keep isl_union_set *domain)
4234 isl_union_pw_multi_aff *contraction;
4235 isl_union_set *arrays;
4236 int i;
4238 if (!ppcg_scop_any_hidden_declarations(prog->scop))
4239 return node;
4240 contraction = isl_schedule_node_get_subtree_contraction(node);
4241 domain = isl_union_set_copy(domain);
4242 domain = isl_union_set_preimage_union_pw_multi_aff(domain, contraction);
4243 arrays = accessed_by_domain(domain, prog);
4245 for (i = 0; i < prog->n_array; ++i) {
4246 isl_space *space;
4247 isl_set *set;
4248 int empty;
4250 if (!prog->array[i].local)
4251 continue;
4252 space = isl_set_get_space(prog->array[i].extent);
4253 set = isl_union_set_extract_set(arrays, space);
4254 empty = isl_set_plain_is_empty(set);
4255 isl_set_free(set);
4256 if (empty < 0)
4257 goto error;
4258 if (!empty)
4259 prog->array[i].declare_local = 1;
4262 isl_union_set_free(arrays);
4263 return node;
4264 error:
4265 isl_union_set_free(arrays);
4266 return isl_schedule_node_free(node);
4269 /* If "node" points to a set node, then separate its children
4270 * into subtrees that have suitably permutable bands and
4271 * those that do not.
4272 * Adjust the schedule tree in order to execute the second group
4273 * after the first group and return a pointer to the first group,
4274 * assuming there are any such subtrees.
4275 * If "node" points to a sequence node, then separate the initial
4276 * children that do not have suitably permutable bands and
4277 * return a pointer to the subsequence of children that do have such bands,
4278 * assuming there are any such subtrees.
4280 * In both cases, mark all local variables in "prog" that are accessed by
4281 * the group without permutable bands as requiring a declaration on the host.
4283 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
4284 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
4286 isl_union_set *filter;
4287 enum isl_schedule_node_type type;
4289 if (!node)
4290 return NULL;
4291 type = isl_schedule_node_get_type(node);
4292 if (type == isl_schedule_node_set) {
4293 filter = get_all_non_parallel_subtree_filters(node);
4294 node = declare_accessed_local_variables(node, prog, filter);
4295 node = isl_schedule_node_order_after(node, filter);
4296 } else if (type == isl_schedule_node_sequence) {
4297 filter = get_initial_non_parallel_subtree_filters(node);
4298 node = declare_accessed_local_variables(node, prog, filter);
4299 node = isl_schedule_node_order_before(node, filter);
4302 return node;
4305 /* Replace any reference to an array element in the range of "copy"
4306 * by a reference to all array elements (defined by the extent of the array).
4308 static __isl_give isl_union_map *approximate_copy_out(
4309 __isl_take isl_union_map *copy, struct gpu_prog *prog)
4311 int i;
4312 isl_union_map *res;
4314 res = isl_union_map_empty(isl_union_map_get_space(copy));
4316 for (i = 0; i < prog->n_array; ++i) {
4317 isl_space *space;
4318 isl_set *set;
4319 isl_union_map *copy_i;
4320 isl_union_set *extent, *domain;
4322 space = isl_space_copy(prog->array[i].space);
4323 extent = isl_union_set_from_set(isl_set_universe(space));
4324 copy_i = isl_union_map_copy(copy);
4325 copy_i = isl_union_map_intersect_range(copy_i, extent);
4326 set = isl_set_copy(prog->array[i].extent);
4327 extent = isl_union_set_from_set(set);
4328 domain = isl_union_map_domain(copy_i);
4329 copy_i = isl_union_map_from_domain_and_range(domain, extent);
4330 res = isl_union_map_union(res, copy_i);
4333 isl_union_map_free(copy);
4335 return res;
4338 /* Insert "kernel" marks that point to a ppcg_kernel structure
4339 * in front of all outermost tilable band that (by construction)
4340 * have at least one parallel loop.
4342 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
4343 __isl_take isl_schedule_node *node)
4345 return isl_schedule_node_map_descendant_bottom_up(node,
4346 &mark_outer_permutable, gen);
4349 /* Construct schedule constraints from the dependences in prog->scop and
4350 * the array order dependences in prog->array_order.
4352 * If live range reordering is allowed, then we need to make sure
4353 * that live ranges on arrays are not run in parallel since doing
4354 * so would require array expansion. We therefore add the array
4355 * order dependences to the coincidence dependences. Non-zero array
4356 * order dependences will then prevent a schedule dimension from being
4357 * considered parallel.
4358 * Live ranges derived from scalars are allowed to be run in parallel
4359 * since we force the scalars to be mapped to private memory in
4360 * check_scalar_live_ranges.
4361 * If live range reordering is allowed, then the false dependences
4362 * are not added to the validity constraints as that would prevent
4363 * reordering. Instead, the external false dependences that enforce that reads
4364 * from potentially live-in data precede any later write and
4365 * that writes of potentially live-out data follow any other earlier write
4366 * are added to the validity and the coincidence constraints.
4367 * The false dependences are still added to the proximity constraints
4368 * for consistency with the case where live range reordering is not allowed.
4369 * The coincidence constraints then consist of flow dependences,
4370 * external false dependences and array order dependences.
4371 * The independences can be filtered out from the first two sets.
4372 * They have already been filtered out from the array order dependences
4373 * on a per array basis in collect_order_dependences.
4374 * There is no need for a per array handling of the other two sets
4375 * as there should be no flow or external false dependence on local
4376 * variables that can be filtered out.
4378 static __isl_give isl_schedule_constraints *construct_schedule_constraints(
4379 struct gpu_prog *prog)
4381 isl_union_set *domain;
4382 isl_union_map *dep_raw, *dep;
4383 isl_union_map *validity, *proximity, *coincidence;
4384 isl_schedule_constraints *sc;
4386 domain = isl_union_set_copy(prog->scop->domain);
4387 sc = isl_schedule_constraints_on_domain(domain);
4388 sc = isl_schedule_constraints_set_context(sc,
4389 isl_set_copy(prog->scop->context));
4390 if (prog->scop->options->live_range_reordering) {
4391 sc = isl_schedule_constraints_set_conditional_validity(sc,
4392 isl_union_map_copy(prog->scop->tagged_dep_flow),
4393 isl_union_map_copy(prog->scop->tagged_dep_order));
4394 proximity = isl_union_map_copy(prog->scop->dep_flow);
4395 validity = isl_union_map_copy(proximity);
4396 validity = isl_union_map_union(validity,
4397 isl_union_map_copy(prog->scop->dep_forced));
4398 proximity = isl_union_map_union(proximity,
4399 isl_union_map_copy(prog->scop->dep_false));
4400 coincidence = isl_union_map_copy(validity);
4401 coincidence = isl_union_map_subtract(coincidence,
4402 isl_union_map_copy(prog->scop->independence));
4403 coincidence = isl_union_map_union(coincidence,
4404 isl_union_map_copy(prog->array_order));
4405 } else {
4406 dep_raw = isl_union_map_copy(prog->scop->dep_flow);
4407 dep = isl_union_map_copy(prog->scop->dep_false);
4408 dep = isl_union_map_union(dep, dep_raw);
4409 dep = isl_union_map_coalesce(dep);
4410 proximity = isl_union_map_copy(dep);
4411 coincidence = isl_union_map_copy(dep);
4412 validity = dep;
4414 sc = isl_schedule_constraints_set_validity(sc, validity);
4415 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4416 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4418 return sc;
4421 /* Compute an appropriate schedule based on the accesses in
4422 * gen->read and gen->write.
4424 * We derive schedule constraints from the dependences in gen->prog->scop
4425 * and then use isl to compute a schedule that has a parallel loop
4426 * in each tilable band.
4427 * During the schedule construction, some statement instances
4428 * may be grouped first based on the input schedule.
4430 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4432 isl_schedule_constraints *sc;
4433 isl_schedule *schedule;
4435 sc = construct_schedule_constraints(gen->prog);
4436 schedule = gen->prog->scop->schedule;
4437 schedule = ppcg_compute_schedule(sc, schedule, gen->options);
4439 return schedule;
4442 /* If the band node "node" has exactly one member then mark it permutable.
4444 static __isl_give isl_schedule_node *band_set_permutable(
4445 __isl_take isl_schedule_node *node,
4446 __isl_keep isl_schedule_constraints *sc)
4448 if (isl_schedule_node_band_n_member(node) == 1)
4449 node = isl_schedule_node_band_set_permutable(node, 1);
4451 return node;
4454 /* Return the coincidence constraints between pairs of instances
4455 * that are scheduled together by the ancestors of "node".
4456 * That is, select those coincidence constraints that relate
4457 * pairs of instances that have the same value for the prefix schedule.
4458 * If the schedule depth is zero, then the prefix schedule does not
4459 * contain any information, so we intersect domain and range
4460 * of the schedule constraints with the reaching domain elements instead.
4462 static __isl_give isl_union_map *get_local_coincidence(
4463 __isl_keep isl_schedule_node *node,
4464 __isl_keep isl_schedule_constraints *sc)
4466 isl_union_map *coincidence;
4467 isl_multi_union_pw_aff *prefix;
4468 isl_union_pw_multi_aff *contraction;
4470 coincidence = isl_schedule_constraints_get_coincidence(sc);
4471 contraction = isl_schedule_node_get_subtree_contraction(node);
4472 if (isl_schedule_node_get_schedule_depth(node) == 0) {
4473 isl_union_set *domain;
4475 domain = isl_schedule_node_get_domain(node);
4476 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4477 contraction);
4478 coincidence = isl_union_map_intersect_domain(coincidence,
4479 isl_union_set_copy(domain));
4480 coincidence = isl_union_map_intersect_range(coincidence,
4481 domain);
4482 return coincidence;
4485 prefix = isl_schedule_node_get_prefix_schedule_multi_union_pw_aff(node);
4486 prefix = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(prefix,
4487 contraction);
4488 return isl_union_map_eq_at_multi_union_pw_aff(coincidence, prefix);
4491 /* For each member in the band node "node", determine whether
4492 * it is coincident with respect to the outer nodes and mark
4493 * it accordingly.
4495 * That is, for each coincidence constraint between pairs
4496 * of instances that are scheduled together by the outer nodes,
4497 * check that domain and range are assigned the same value
4498 * by the band member. This test is performed by checking
4499 * that imposing the same value for the band member does not
4500 * remove any elements from the set of coincidence constraints.
4502 static __isl_give isl_schedule_node *band_set_coincident(
4503 __isl_take isl_schedule_node *node,
4504 __isl_keep isl_schedule_constraints *sc)
4506 isl_union_map *coincidence;
4507 isl_union_pw_multi_aff *contraction;
4508 isl_multi_union_pw_aff *partial;
4509 int i, n;
4511 coincidence = get_local_coincidence(node, sc);
4513 partial = isl_schedule_node_band_get_partial_schedule(node);
4514 contraction = isl_schedule_node_get_subtree_contraction(node);
4515 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4516 contraction);
4517 n = isl_schedule_node_band_n_member(node);
4518 for (i = 0; i < n; ++i) {
4519 isl_union_map *coincidence_i;
4520 isl_union_pw_aff *upa;
4521 isl_multi_union_pw_aff *partial_i;
4522 int subset;
4524 upa = isl_multi_union_pw_aff_get_union_pw_aff(partial, i);
4525 partial_i = isl_multi_union_pw_aff_from_union_pw_aff(upa);
4526 coincidence_i = isl_union_map_copy(coincidence);
4527 coincidence_i = isl_union_map_eq_at_multi_union_pw_aff(
4528 coincidence_i, partial_i);
4529 subset = isl_union_map_is_subset(coincidence, coincidence_i);
4530 isl_union_map_free(coincidence_i);
4532 if (subset < 0)
4533 break;
4534 node = isl_schedule_node_band_member_set_coincident(node, i,
4535 subset);
4537 if (i < n)
4538 node = isl_schedule_node_free(node);
4539 isl_multi_union_pw_aff_free(partial);
4540 isl_union_map_free(coincidence);
4542 return node;
4545 /* If "node" is a band, then set its properties.
4547 * In particular, if the band has exactly one member, then mark it permutable.
4548 * Mark the band members coincident based on the coincidence constraints
4549 * of "sc".
4551 static __isl_give isl_schedule_node *set_band_properties(
4552 __isl_take isl_schedule_node *node, void *user)
4554 isl_schedule_constraints *sc = user;
4556 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
4557 return node;
4558 if (isl_schedule_node_band_n_member(node) == 0)
4559 return node;
4561 node = band_set_permutable(node, sc);
4562 node = band_set_coincident(node, sc);
4564 return node;
4567 /* Return the original schedule with all bands marked permutable and
4568 * all band members marked coincident based on the coincidence constraints.
4569 * The bands are explicitly marked permutable so that they will be considered
4570 * by mark_outer_permutable.
4572 static __isl_give isl_schedule *determine_properties_original_schedule(
4573 struct gpu_gen *gen)
4575 isl_schedule *schedule;
4576 isl_schedule_constraints *sc;
4578 schedule = isl_schedule_copy(gen->prog->scop->schedule);
4579 sc = construct_schedule_constraints(gen->prog);
4580 schedule = isl_schedule_map_schedule_node_bottom_up(schedule,
4581 &set_band_properties, sc);
4582 isl_schedule_constraints_free(sc);
4584 return schedule;
4587 /* Compute a schedule or determine the properties of the original schedule
4588 * depending on the value of the "reschedule" option.
4590 static __isl_give isl_schedule *compute_or_set_properties(void *user)
4592 struct gpu_gen *gen = user;
4594 if (gen->options->reschedule)
4595 return compute_schedule(gen);
4596 else
4597 return determine_properties_original_schedule(gen);
4600 /* Obtain a schedule for the scop, by reading it from
4601 * a file, by computing one or by determining the properties
4602 * of the original schedule.
4604 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4606 return ppcg_get_schedule(gen->ctx, gen->options,
4607 &compute_or_set_properties, gen);
4610 /* Construct the string "<a>_<b>".
4612 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4614 isl_printer *p;
4615 char *s;
4617 p = isl_printer_to_str(ctx);
4618 p = isl_printer_print_str(p, a);
4619 p = isl_printer_print_str(p, "_");
4620 p = isl_printer_print_str(p, b);
4621 s = isl_printer_get_str(p);
4622 isl_printer_free(p);
4624 return s;
4627 /* For each array in "prog" of which an element appears in "accessed" and
4628 * that is not a read only scalar, create a zero-dimensional universe set
4629 * of which the tuple id has name "<prefix>_<name of array>" and a user
4630 * pointer pointing to the array (gpu_array_info).
4632 * If the array is local to "prog", then make sure it will be declared
4633 * in the host code.
4635 * Return the list of these universe sets.
4637 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4638 const char *prefix, __isl_take isl_union_set *accessed)
4640 int i;
4641 isl_ctx *ctx;
4642 isl_union_set_list *filters;
4644 ctx = prog->ctx;
4645 filters = isl_union_set_list_alloc(ctx, 0);
4646 for (i = 0; i < prog->n_array; ++i) {
4647 struct gpu_array_info *array = &prog->array[i];
4648 isl_space *space;
4649 isl_set *accessed_i;
4650 int empty;
4651 char *name;
4652 isl_id *id;
4653 isl_union_set *uset;
4655 if (gpu_array_is_read_only_scalar(array))
4656 continue;
4658 space = isl_space_copy(array->space);
4659 accessed_i = isl_union_set_extract_set(accessed, space);
4660 empty = isl_set_plain_is_empty(accessed_i);
4661 isl_set_free(accessed_i);
4662 if (empty < 0) {
4663 filters = isl_union_set_list_free(filters);
4664 break;
4666 if (empty)
4667 continue;
4669 array->global = 1;
4670 if (array->local)
4671 array->declare_local = 1;
4673 name = concat(ctx, prefix, array->name);
4674 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4675 free(name);
4676 space = isl_space_set_alloc(ctx, 0, 0);
4677 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4678 uset = isl_union_set_from_set(isl_set_universe(space));
4680 filters = isl_union_set_list_add(filters, uset);
4682 isl_union_set_free(accessed);
4684 return filters;
4687 /* Make sure that code for the statements in "filters" that
4688 * copy arrays to or from the device is only generated when
4689 * the size of the corresponding array is positive.
4690 * That is, add a set node underneath "graft" with "filters" as children
4691 * and for each child add a guard that the selects the parameter
4692 * values for which the corresponding array has a positive size.
4693 * The array is available in the user pointer of the statement identifier.
4694 * "depth" is the schedule depth of the position where "graft"
4695 * will be added.
4697 static __isl_give isl_schedule_node *insert_positive_size_guards(
4698 __isl_take isl_schedule_node *graft,
4699 __isl_take isl_union_set_list *filters, int depth)
4701 int i, n;
4703 graft = isl_schedule_node_child(graft, 0);
4704 graft = isl_schedule_node_insert_set(graft, filters);
4705 n = isl_schedule_node_n_children(graft);
4706 for (i = 0; i < n; ++i) {
4707 isl_union_set *filter;
4708 isl_set *domain, *guard;
4709 isl_id *id;
4710 struct gpu_array_info *array;
4712 graft = isl_schedule_node_child(graft, i);
4713 filter = isl_schedule_node_filter_get_filter(graft);
4714 domain = isl_set_from_union_set(filter);
4715 id = isl_set_get_tuple_id(domain);
4716 array = isl_id_get_user(id);
4717 isl_id_free(id);
4718 isl_set_free(domain);
4719 guard = gpu_array_positive_size_guard(array);
4720 guard = isl_set_from_params(guard);
4721 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4722 graft = isl_schedule_node_child(graft, 0);
4723 graft = isl_schedule_node_insert_guard(graft, guard);
4724 graft = isl_schedule_node_parent(graft);
4725 graft = isl_schedule_node_parent(graft);
4727 graft = isl_schedule_node_parent(graft);
4729 return graft;
4732 /* Create a graft for copying arrays to or from the device,
4733 * whenever the size of the array is strictly positive.
4734 * Each statement is called "<prefix>_<name of array>" and
4735 * the identifier has a user pointer pointing to the array.
4736 * The graft will be added at the position specified by "node".
4737 * "copy" contains the array elements that need to be copied.
4738 * Only arrays of which some elements need to be copied
4739 * will have a corresponding statement in the graph.
4740 * Note though that each such statement will copy the entire array.
4742 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4743 __isl_keep isl_schedule_node *node, const char *prefix,
4744 __isl_take isl_union_set *copy)
4746 int depth;
4747 isl_ctx *ctx;
4748 isl_space *space;
4749 isl_union_set *all, *domain;
4750 isl_union_set_list *filters;
4751 isl_union_map *extension;
4752 isl_schedule_node *graft;
4754 ctx = prog->ctx;
4755 depth = isl_schedule_node_get_schedule_depth(node);
4756 filters = create_copy_filters(prog, prefix, copy);
4757 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4759 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4760 domain = isl_union_set_from_set(isl_set_universe(space));
4761 extension = isl_union_map_from_domain_and_range(domain, all);
4762 graft = isl_schedule_node_from_extension(extension);
4764 if (!filters)
4765 return isl_schedule_node_free(graft);
4766 if (isl_union_set_list_n_union_set(filters) == 0) {
4767 isl_union_set_list_free(filters);
4768 return graft;
4771 return insert_positive_size_guards(graft, filters, depth);
4774 /* Return (the universe spaces of) the arrays that are declared
4775 * inside the scop corresponding to "prog" and for which all
4776 * potential writes inside the scop form a subset of "domain".
4778 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4779 __isl_keep isl_union_set *domain)
4781 int i;
4782 isl_union_set *local;
4784 local = isl_union_set_empty(isl_union_set_get_space(domain));
4786 for (i = 0; i < prog->n_array; ++i) {
4787 isl_set *set;
4788 isl_union_map *to_outer;
4789 isl_union_map *may_write;
4790 isl_union_set *write_domain;
4791 isl_union_set *fields;
4792 int subset;
4794 if (!prog->array[i].local)
4795 continue;
4797 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4798 to_outer = isl_union_map_copy(prog->to_outer);
4799 to_outer = isl_union_map_intersect_range(to_outer,
4800 isl_union_set_from_set(isl_set_copy(set)));
4801 fields = isl_union_map_domain(to_outer);
4802 may_write = isl_union_map_copy(prog->may_write);
4803 may_write = isl_union_map_intersect_range(may_write, fields);
4804 write_domain = isl_union_map_domain(may_write);
4805 subset = isl_union_set_is_subset(write_domain, domain);
4806 isl_union_set_free(write_domain);
4808 if (subset < 0) {
4809 isl_set_free(set);
4810 return isl_union_set_free(local);
4811 } else if (subset) {
4812 local = isl_union_set_add_set(local, set);
4813 } else {
4814 isl_set_free(set);
4818 return local;
4821 /* Internal data structure for node_may_persist.
4823 * "tagger" maps tagged iteration domains to the corresponding untagged
4824 * iteration domain.
4826 * "may_persist_flow" is the set of all tagged dataflow dependences
4827 * with those dependences removed that either precede or follow
4828 * the kernel launch in a sequence.
4829 * "inner_band_flow" is the set of all tagged dataflow dependences
4830 * that are local to a given iteration of the outer band nodes
4831 * with respect to the current node.
4832 * "local_flow" is equal to "inner_band_flow", except that the domain
4833 * and the range have been intersected with intermediate filters
4834 * on children of sets or sequences.
4836 struct ppcg_may_persist_data {
4837 isl_union_pw_multi_aff *tagger;
4839 isl_union_map *local_flow;
4840 isl_union_map *inner_band_flow;
4841 isl_union_map *may_persist_flow;
4844 /* Update the information in "data" based on the band ancestor "node".
4846 * In particular, we restrict the dependences in data->local_flow
4847 * to those dependence where the source and the sink occur in
4848 * the same iteration of the given band node.
4849 * We also update data->inner_band_flow to the new value of
4850 * data->local_flow.
4852 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4853 struct ppcg_may_persist_data *data)
4855 isl_multi_union_pw_aff *partial;
4856 isl_union_pw_multi_aff *contraction;
4857 isl_union_map *flow;
4859 if (isl_schedule_node_band_n_member(node) == 0)
4860 return 0;
4862 partial = isl_schedule_node_band_get_partial_schedule(node);
4863 contraction = isl_schedule_node_get_subtree_contraction(node);
4864 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4865 contraction);
4866 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4867 isl_union_pw_multi_aff_copy(data->tagger));
4869 flow = data->local_flow;
4870 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4871 data->local_flow = flow;
4873 isl_union_map_free(data->inner_band_flow);
4874 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4876 return 0;
4879 /* Given a set of local reaching domain elements "domain",
4880 * expand them to the corresponding leaf domain elements using "contraction"
4881 * and insert the array references tags using data->tagger.
4883 static __isl_give isl_union_set *expand_and_tag(
4884 __isl_take isl_union_set *domain,
4885 __isl_take isl_union_pw_multi_aff *contraction,
4886 struct ppcg_may_persist_data *data)
4888 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4889 contraction);
4890 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4891 isl_union_pw_multi_aff_copy(data->tagger));
4892 return domain;
4895 /* Given a filter node that is the child of a set or sequence node,
4896 * restrict data->local_flow to refer only to those elements
4897 * in the filter of the node.
4898 * "contraction" maps the leaf domain elements of the schedule tree
4899 * to the corresponding domain elements at (the parent of) "node".
4901 static int filter_flow(__isl_keep isl_schedule_node *node,
4902 struct ppcg_may_persist_data *data,
4903 __isl_take isl_union_pw_multi_aff *contraction)
4905 isl_union_set *filter;
4906 isl_union_map *flow;
4908 flow = data->local_flow;
4909 filter = isl_schedule_node_filter_get_filter(node);
4910 filter = expand_and_tag(filter, contraction, data);
4911 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4912 flow = isl_union_map_intersect_range(flow, filter);
4913 data->local_flow = flow;
4915 return 0;
4918 /* Given a filter node "node", collect the filters on all preceding siblings
4919 * (which are also filter nodes), add them to "filters" and return the result.
4921 static __isl_give isl_union_set *add_previous_filters(
4922 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4924 isl_schedule_node *sibling;
4926 sibling = isl_schedule_node_copy(node);
4927 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4928 isl_union_set *filter;
4930 sibling = isl_schedule_node_previous_sibling(sibling);
4931 filter = isl_schedule_node_filter_get_filter(sibling);
4932 filters = isl_union_set_union(filters, filter);
4934 isl_schedule_node_free(sibling);
4935 if (!sibling)
4936 return isl_union_set_free(filters);
4938 return filters;
4941 /* Given a filter node "node", collect the filters on all following siblings
4942 * (which are also filter nodes), add them to "filters" and return the result.
4944 static __isl_give isl_union_set *add_next_filters(
4945 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4947 isl_schedule_node *sibling;
4949 sibling = isl_schedule_node_copy(node);
4950 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4951 isl_union_set *filter;
4953 sibling = isl_schedule_node_next_sibling(sibling);
4954 filter = isl_schedule_node_filter_get_filter(sibling);
4955 filters = isl_union_set_union(filters, filter);
4957 isl_schedule_node_free(sibling);
4958 if (!sibling)
4959 return isl_union_set_free(filters);
4961 return filters;
4964 /* Remove those flow dependences from data->may_persist_flow
4965 * that flow between elements of "domain" within the same iteration
4966 * of all outer band nodes.
4967 * "contraction" maps the leaf domain elements of the schedule tree
4968 * to the corresponding elements "domain".
4970 static void remove_external_flow(struct ppcg_may_persist_data *data,
4971 __isl_take isl_union_set *domain,
4972 __isl_keep isl_union_pw_multi_aff *contraction)
4974 isl_union_map *flow;
4976 contraction = isl_union_pw_multi_aff_copy(contraction);
4977 domain = expand_and_tag(domain, contraction, data);
4978 flow = isl_union_map_copy(data->local_flow);
4979 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4980 flow = isl_union_map_intersect_range(flow, domain);
4982 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4983 flow);
4986 /* Update the information in "data" based on the filter ancestor "node".
4987 * We only need to modify anything if the filter is the child
4988 * of a set or sequence node.
4990 * In the case of a sequence, we remove the dependences between
4991 * statement instances that are both executed either before or
4992 * after the subtree that will be mapped to a kernel, within
4993 * the same iteration of outer bands.
4995 * In both cases, we restrict data->local_flow to the current child.
4997 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4998 struct ppcg_may_persist_data *data)
5000 enum isl_schedule_node_type type;
5001 isl_schedule_node *parent;
5002 isl_space *space;
5003 isl_union_pw_multi_aff *contraction;
5004 isl_union_set *before, *after, *filter;
5006 type = isl_schedule_node_get_parent_type(node);
5007 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
5008 return 0;
5010 parent = isl_schedule_node_copy(node);
5011 parent = isl_schedule_node_parent(parent);
5012 contraction = isl_schedule_node_get_subtree_contraction(parent);
5013 isl_schedule_node_free(parent);
5015 if (type == isl_schedule_node_set)
5016 return filter_flow(node, data, contraction);
5018 filter = isl_schedule_node_filter_get_filter(node);
5019 space = isl_union_set_get_space(filter);
5020 isl_union_set_free(filter);
5021 before = isl_union_set_empty(space);
5022 after = isl_union_set_copy(before);
5023 before = add_previous_filters(before, node);
5024 after = add_next_filters(after, node);
5026 remove_external_flow(data, before, contraction);
5027 remove_external_flow(data, after, contraction);
5029 return filter_flow(node, data, contraction);
5032 /* Update the information in "data" based on the ancestor "node".
5034 static isl_stat update_may_persist_at(__isl_keep isl_schedule_node *node,
5035 void *user)
5037 struct ppcg_may_persist_data *data = user;
5039 switch (isl_schedule_node_get_type(node)) {
5040 case isl_schedule_node_error:
5041 return isl_stat_error;
5042 case isl_schedule_node_context:
5043 case isl_schedule_node_domain:
5044 case isl_schedule_node_expansion:
5045 case isl_schedule_node_extension:
5046 case isl_schedule_node_guard:
5047 case isl_schedule_node_leaf:
5048 case isl_schedule_node_mark:
5049 case isl_schedule_node_sequence:
5050 case isl_schedule_node_set:
5051 break;
5052 case isl_schedule_node_band:
5053 if (update_may_persist_at_band(node, data) < 0)
5054 return isl_stat_error;
5055 break;
5056 case isl_schedule_node_filter:
5057 if (update_may_persist_at_filter(node, data) < 0)
5058 return isl_stat_error;
5059 break;
5062 return isl_stat_ok;
5065 /* Determine the set of array elements that may need to be perserved
5066 * by a kernel constructed from the subtree at "node".
5067 * This includes the set of array elements that may need to be preserved
5068 * by the entire scop (prog->may_persist) and the elements for which
5069 * there is a potential flow dependence that may cross a kernel launch.
5071 * To determine the second set, we start from all flow dependences.
5072 * From this set of dependences, we remove those that cannot possibly
5073 * require data to be preserved by a kernel launch.
5074 * In particular, we consider the following sets of dependences.
5075 * - dependences of which the write occurs inside the kernel.
5076 * If the data is needed outside the kernel, then it will
5077 * be copied out immediately after the kernel launch, so there
5078 * is no need for any special care.
5079 * - dependences of which the read occurs inside the kernel and the
5080 * corresponding write occurs inside the same iteration of the
5081 * outer band nodes. This means that the data is needed in
5082 * the first kernel launch after the write, which is already
5083 * taken care of by the standard copy-in. That is, the data
5084 * do not need to be preserved by any intermediate call to
5085 * the same kernel.
5086 * - dependences of which the write and the read either both occur
5087 * before the kernel launch or both occur after the kernel launch,
5088 * within the same iteration of the outer band nodes with respect
5089 * to the sequence that determines the ordering of the dependence
5090 * and the kernel launch. Such flow dependences cannot cross
5091 * any kernel launch.
5093 * For the remaining (tagged) dependences, we take the domain
5094 * (i.e., the tagged writes) and apply the tagged access relation
5095 * to obtain the accessed data elements.
5096 * These are then combined with the elements that may need to be
5097 * preserved by the entire scop.
5099 static __isl_give isl_union_set *node_may_persist(
5100 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
5102 struct ppcg_may_persist_data data;
5103 isl_union_pw_multi_aff *contraction;
5104 isl_union_set *domain;
5105 isl_union_set *persist;
5106 isl_union_map *flow, *local_flow;
5108 data.tagger = prog->scop->tagger;
5110 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
5111 data.local_flow = isl_union_map_copy(flow);
5112 data.inner_band_flow = isl_union_map_copy(flow);
5113 data.may_persist_flow = flow;
5114 if (isl_schedule_node_foreach_ancestor_top_down(node,
5115 &update_may_persist_at, &data) < 0)
5116 data.may_persist_flow =
5117 isl_union_map_free(data.may_persist_flow);
5118 flow = data.may_persist_flow;
5119 isl_union_map_free(data.local_flow);
5121 domain = isl_schedule_node_get_domain(node);
5122 contraction = isl_schedule_node_get_subtree_contraction(node);
5123 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5124 contraction);
5125 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5126 isl_union_pw_multi_aff_copy(data.tagger));
5127 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
5128 local_flow = data.inner_band_flow;
5129 local_flow = isl_union_map_intersect_range(local_flow, domain);
5130 flow = isl_union_map_subtract(flow, local_flow);
5132 persist = isl_union_map_domain(flow);
5133 persist = isl_union_set_apply(persist,
5134 isl_union_map_copy(prog->scop->tagged_may_writes));
5135 persist = isl_union_set_union(persist,
5136 isl_union_set_copy(prog->may_persist));
5138 return persist;
5141 /* Add nodes for copying outer arrays in and out of the device
5142 * before and after the subtree "node", which contains one or more kernels.
5143 * "domain" contains the original statement instances, i.e.,
5144 * those that correspond to the domains of the access relations in "prog".
5145 * In particular, the domain has not been contracted in any way.
5146 * "prefix" contains the prefix schedule at that point, in terms
5147 * of the same original statement instances.
5149 * We first compute the sets of outer array elements that need
5150 * to be copied in and out and then graft in the nodes for
5151 * performing this copying.
5153 * In particular, for each array that is possibly written anywhere in
5154 * the subtree "node" and that may be used after "node"
5155 * or that may be visible outside the corresponding scop,
5156 * we copy out its entire extent.
5158 * Any array elements that is read without first being written inside
5159 * the subtree "node" needs to be copied in.
5160 * Furthermore, if there are any array elements that
5161 * are copied out, but that may not be written inside "node, then
5162 * they also need to be copied in to ensure that the value after execution
5163 * is the same as the value before execution, at least for those array
5164 * elements that may have their values preserved by the scop or that
5165 * may be written before "node" and read after "node".
5166 * In case the array elements are structures, we need to take into
5167 * account that all members of the structures need to be written
5168 * by "node" before we can avoid copying the data structure in.
5170 * Note that the may_write relation is intersected with the domain,
5171 * which has been intersected with the context.
5172 * This helps in those cases where the arrays are declared with a fixed size,
5173 * while the accesses are parametric and the context assigns a fixed value
5174 * to the parameters.
5176 * If an element from a local array is read without first being written,
5177 * then there is no point in copying it in since it cannot have been
5178 * written prior to the scop. Warn about the uninitialized read instead.
5180 static __isl_give isl_schedule_node *add_to_from_device(
5181 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
5182 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
5184 isl_union_set *local;
5185 isl_union_set *may_persist;
5186 isl_union_map *may_write, *must_write, *copy_out, *not_written;
5187 isl_union_map *read, *copy_in;
5188 isl_union_map *tagged;
5189 isl_union_map *local_uninitialized;
5190 isl_schedule_node *graft;
5192 tagged = isl_union_map_copy(prog->scop->tagged_reads);
5193 tagged = isl_union_map_union(tagged,
5194 isl_union_map_copy(prog->scop->tagged_may_writes));
5196 may_write = isl_union_map_copy(prog->may_write);
5197 may_write = isl_union_map_intersect_domain(may_write,
5198 isl_union_set_copy(domain));
5199 may_write = remove_local_accesses(prog,
5200 isl_union_map_copy(tagged), may_write,
5201 isl_union_map_copy(prefix), 0);
5202 may_write = isl_union_map_apply_range(may_write,
5203 isl_union_map_copy(prog->to_outer));
5204 may_write = isl_union_map_apply_domain(may_write,
5205 isl_union_map_copy(prefix));
5206 may_write = approximate_copy_out(may_write, prog);
5207 copy_out = isl_union_map_copy(may_write);
5208 may_write = isl_union_map_apply_range(may_write,
5209 isl_union_map_copy(prog->to_inner));
5210 must_write = isl_union_map_copy(prog->must_write);
5211 must_write = isl_union_map_apply_domain(must_write,
5212 isl_union_map_copy(prefix));
5213 may_persist = node_may_persist(node, prog);
5214 may_write = isl_union_map_intersect_range(may_write, may_persist);
5215 not_written = isl_union_map_subtract(may_write, must_write);
5217 local = extract_local_accesses(prog, domain);
5218 read = isl_union_map_copy(prog->read);
5219 read = isl_union_map_intersect_domain(read, domain);
5220 read = remove_local_accesses(prog, tagged, read,
5221 isl_union_map_copy(prefix), 1);
5222 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
5223 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
5224 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5225 local);
5226 local_uninitialized = isl_union_map_intersect(local_uninitialized,
5227 isl_union_map_copy(read));
5228 if (!isl_union_map_is_empty(local_uninitialized)) {
5229 fprintf(stderr,
5230 "possibly uninitialized reads (not copied in):\n");
5231 isl_union_map_dump(local_uninitialized);
5233 read = isl_union_map_subtract(read, local_uninitialized);
5234 read = isl_union_map_apply_domain(read, prefix);
5235 copy_in = isl_union_map_union(read, not_written);
5236 copy_in = isl_union_map_apply_range(copy_in,
5237 isl_union_map_copy(prog->to_outer));
5239 graft = create_copy_device(prog, node, "to_device",
5240 isl_union_map_range(copy_in));
5241 node = isl_schedule_node_graft_before(node, graft);
5242 graft = create_copy_device(prog, node, "from_device",
5243 isl_union_map_range(copy_out));
5244 node = isl_schedule_node_graft_after(node, graft);
5246 return node;
5249 /* Add nodes for initializing ("init_device") and clearing ("clear_device")
5250 * the device before and after "node".
5252 static __isl_give isl_schedule_node *add_init_clear_device(
5253 __isl_take isl_schedule_node *node)
5255 isl_ctx *ctx;
5256 isl_space *space;
5257 isl_union_set *domain;
5258 isl_schedule_node *graft;
5260 ctx = isl_schedule_node_get_ctx(node);
5262 space = isl_space_set_alloc(ctx, 0, 0);
5263 space = isl_space_set_tuple_name(space, isl_dim_set, "init_device");
5264 domain = isl_union_set_from_set(isl_set_universe(space));
5265 graft = isl_schedule_node_from_domain(domain);
5267 node = isl_schedule_node_graft_before(node, graft);
5269 space = isl_space_set_alloc(ctx, 0, 0);
5270 space = isl_space_set_tuple_name(space, isl_dim_set, "clear_device");
5271 domain = isl_union_set_from_set(isl_set_universe(space));
5272 graft = isl_schedule_node_from_domain(domain);
5274 node = isl_schedule_node_graft_after(node, graft);
5276 return node;
5279 /* Update "schedule" for mapping to a GPU device.
5281 * In particular, insert a context node, create kernels for
5282 * each outermost tilable band and introduce nodes for copying arrays
5283 * in and out of the device and for initializing and clearing the device.
5284 * If the child of the initial root points to a set node,
5285 * then children of this node that do not contain any tilable bands
5286 * are separated from the other children and are not mapped to
5287 * the device.
5289 * The GPU code is generated in a context where at least one
5290 * statement instance is executed. The corresponding guard is inserted
5291 * around the entire schedule.
5293 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
5294 __isl_take isl_schedule *schedule)
5296 isl_schedule_node *node;
5297 isl_set *context;
5298 isl_set *guard;
5299 isl_union_set *domain;
5300 isl_union_map *prefix;
5301 isl_union_pw_multi_aff *contraction;
5302 struct gpu_prog *prog;
5304 context = isl_set_copy(gen->prog->context);
5305 context = isl_set_from_params(context);
5306 schedule = isl_schedule_insert_context(schedule, context);
5308 prog = gen->prog;
5309 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5310 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5311 guard = isl_set_from_params(guard);
5313 node = isl_schedule_get_root(schedule);
5314 isl_schedule_free(schedule);
5315 node = isl_schedule_node_child(node, 0);
5316 node = isl_schedule_node_child(node, 0);
5317 node = isolate_permutable_subtrees(node, gen->prog);
5318 domain = isl_schedule_node_get_domain(node);
5319 contraction = isl_schedule_node_get_subtree_contraction(node);
5320 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
5321 isl_union_pw_multi_aff_copy(contraction));
5322 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
5323 prefix = isl_union_map_preimage_domain_union_pw_multi_aff(prefix,
5324 contraction);
5325 node = mark_kernels(gen, node);
5326 node = add_to_from_device(node, domain, prefix, gen->prog);
5327 node = isl_schedule_node_root(node);
5328 node = isl_schedule_node_child(node, 0);
5329 node = isl_schedule_node_child(node, 0);
5330 node = isl_schedule_node_insert_guard(node, guard);
5331 node = isl_schedule_node_child(node, 0);
5332 node = add_init_clear_device(node);
5333 schedule = isl_schedule_node_get_schedule(node);
5334 isl_schedule_node_free(node);
5336 return schedule;
5339 /* Internal data structure for extract_access.
5340 * "next_access" points to the end of a linked list that is extended
5341 * by extract_access.
5342 * "single_expression" is set if the access expressions belong to
5343 * an expression statement (i.e., a statement without internal control).
5344 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5346 struct ppcg_extract_access_data {
5347 struct gpu_stmt_access **next_access;
5348 int single_expression;
5349 isl_union_map *any_to_outer;
5352 /* Given a tagged access relation to a single array "tagged", extract it
5353 * as a map, taking into account that the input may be empty.
5354 * If the access relation is empty, then it does not contain
5355 * any space information, so we try to recover it from the index
5356 * expression.
5357 * The space of the index expression is of the form I -> A,
5358 * with I the statement instances and A the array, or [I -> F] -> A,
5359 * with F the filters corresponding to arguments.
5360 * We first drop F, if present, obtaining I -> A.
5361 * Then we construct I -> R, with R the reference tag,
5362 * combine the two into I -> [R -> A] and uncurry to obtain
5363 * the final result [I -> R] -> A.
5364 * Note that the index expression may have a lower dimension
5365 * than that of the array, but this dimension is not used
5366 * if the access relation is empty.
5368 static __isl_give isl_map *extract_single_tagged_access(
5369 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
5371 int empty;
5372 isl_id *id;
5373 isl_space *space, *space2;
5374 isl_multi_pw_aff *index;
5376 empty = isl_union_map_is_empty(tagged);
5377 if (empty < 0)
5378 goto error;
5379 if (!empty)
5380 return isl_map_from_union_map(tagged);
5381 isl_union_map_free(tagged);
5383 index = pet_expr_access_get_index(expr);
5384 space = isl_multi_pw_aff_get_space(index);
5385 isl_multi_pw_aff_free(index);
5386 if (isl_space_domain_is_wrapping(space))
5387 space = isl_space_domain_factor_domain(space);
5388 space2 = isl_space_copy(space);
5389 space2 = isl_space_from_domain(isl_space_domain(space));
5390 id = pet_expr_access_get_ref_id(expr);
5391 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
5392 space = isl_space_range_product(space2, space);
5393 space = isl_space_uncurry(space);
5395 return isl_map_empty(space);
5396 error:
5397 isl_union_map_free(tagged);
5398 return NULL;
5401 /* Does the index expression "index" of "expr" represent an access
5402 * to a single element?
5403 * That is, is "index" completely specified?
5405 * If "expr" accesses elements from different spaces (i.e., fields
5406 * of a structure), then it does not access a single element.
5407 * Otherwise, if the single space of the access matches the space
5408 * of "index", then the index expression is completely specified
5409 * (no pointer to a lower-dimensional slice of the accessed array)
5410 * and a single element is being accessed.
5412 static isl_bool complete_index(__isl_keep pet_expr *expr,
5413 __isl_keep isl_multi_pw_aff *index)
5415 isl_union_map *read, *write, *all;
5416 isl_map *map;
5417 isl_space *space1, *space2;
5418 isl_bool complete;
5420 read = pet_expr_access_get_may_read(expr);
5421 write = pet_expr_access_get_may_write(expr);
5422 all = isl_union_map_union(read, write);
5423 if (!all)
5424 return isl_bool_error;
5425 if (isl_union_map_n_map(all) != 1) {
5426 isl_union_map_free(all);
5427 return isl_bool_false;
5429 map = isl_map_from_union_map(all);
5430 space1 = isl_map_get_space(map);
5431 isl_map_free(map);
5432 space2 = isl_multi_pw_aff_get_space(index);
5433 complete = isl_space_tuple_is_equal(space1, isl_dim_out,
5434 space2, isl_dim_out);
5435 isl_space_free(space1);
5436 isl_space_free(space2);
5438 return complete;
5441 /* Does "expr" access a single, fixed element (independently of the statement
5442 * instance)?
5443 * That is, does it have a completely specified constant index expression?
5445 * Note that it is not sufficient for the index expression to be
5446 * piecewise constant. isl_multi_pw_aff_is_cst can therefore not be used.
5448 static isl_bool accesses_fixed_element(__isl_keep pet_expr *expr)
5450 int i, n;
5451 isl_multi_pw_aff *index;
5452 isl_bool fixed = isl_bool_true;
5454 index = pet_expr_access_get_index(expr);
5455 if (index < 0)
5456 return isl_bool_error;
5457 n = isl_multi_pw_aff_dim(index, isl_dim_out);
5458 for (i = 0; i < n; ++i) {
5459 isl_pw_aff *pa;
5461 pa = isl_multi_pw_aff_get_pw_aff(index, 0);
5462 fixed = isl_pw_aff_n_piece(pa) == 1;
5463 if (fixed)
5464 fixed = isl_pw_aff_is_cst(pa);
5465 isl_pw_aff_free(pa);
5466 if (fixed < 0 || !fixed)
5467 break;
5469 if (fixed >= 0 && fixed)
5470 fixed = complete_index(expr, index);
5471 isl_multi_pw_aff_free(index);
5473 return fixed;
5476 /* Extract a gpu_stmt_access from "expr", append it to the list
5477 * that ends in *data->next_access and update the end of the list.
5478 * If the access expression performs a write, then it is considered
5479 * exact only if it appears in a single expression statement and
5480 * if its may access relation is equal to its must access relation.
5482 * The combined set of may accesses may be a union if member accesses
5483 * are involved, but the entire set is derived from a single reference and
5484 * therefore from a single index expression. These accesses therefore
5485 * all map to the same outer array.
5487 static int extract_access(__isl_keep pet_expr *expr, void *user)
5489 struct ppcg_extract_access_data *data = user;
5490 isl_union_map *tagged;
5491 struct gpu_stmt_access *access;
5492 isl_ctx *ctx = pet_expr_get_ctx(expr);
5493 isl_multi_pw_aff *index;
5495 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5496 if (!access)
5497 return -1;
5498 access->next = NULL;
5499 access->read = pet_expr_access_is_read(expr);
5500 access->write = pet_expr_access_is_write(expr);
5501 tagged = pet_expr_access_get_tagged_may_read(expr);
5502 tagged = isl_union_map_union(tagged,
5503 pet_expr_access_get_tagged_may_write(expr));
5504 tagged = isl_union_map_apply_range(tagged,
5505 isl_union_map_copy(data->any_to_outer));
5506 if (!access->write) {
5507 access->exact_write = 1;
5508 } else if (!data->single_expression) {
5509 access->exact_write = 0;
5510 } else {
5511 isl_union_map *must, *may;
5512 may = isl_union_map_copy(tagged);
5513 may = isl_union_map_domain_factor_domain(may);
5514 must = pet_expr_access_get_must_write(expr);
5515 access->exact_write = isl_union_map_is_equal(must, may);
5516 isl_union_map_free(must);
5517 isl_union_map_free(may);
5519 index = pet_expr_access_get_index(expr);
5520 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5521 isl_multi_pw_aff_free(index);
5522 access->ref_id = pet_expr_access_get_ref_id(expr);
5523 access->tagged_access = extract_single_tagged_access(tagged, expr);
5524 access->access = isl_map_copy(access->tagged_access);
5525 access->access = isl_map_domain_factor_domain(access->access);
5526 access->fixed_element = accesses_fixed_element(expr);
5528 *data->next_access = access;
5529 data->next_access = &(*data->next_access)->next;
5531 if (!access->access || access->fixed_element < 0)
5532 return -1;
5534 return 0;
5537 /* Construct a linked list of gpu_stmt_access objects,
5538 * one for each access expression in the statement body.
5539 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5541 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5542 __isl_keep isl_union_map *any_to_outer)
5544 struct ppcg_extract_access_data data;
5546 stmt->accesses = NULL;
5547 data.next_access = &stmt->accesses;
5548 data.single_expression =
5549 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5550 data.any_to_outer = any_to_outer;
5551 return pet_tree_foreach_access_expr(stmt->stmt->body,
5552 &extract_access, &data);
5555 /* Has statement "stmt" been killed from "scop"?
5556 * That is, is the instance set of "scop" free from any
5557 * instances of "stmt"?
5559 static isl_bool is_stmt_killed(struct ppcg_scop *scop, struct pet_stmt *stmt)
5561 isl_space *space;
5562 isl_set *left;
5563 isl_bool empty;
5565 if (!scop || !stmt)
5566 return isl_bool_error;
5567 space = isl_set_get_space(stmt->domain);
5568 left = isl_union_set_extract_set(scop->domain, space);
5569 empty = isl_set_plain_is_empty(left);
5570 isl_set_free(left);
5572 return empty;
5575 /* Return an array of gpu_stmt representing the statements in "scop".
5576 * Do not collect array accesses for statements that have been killed.
5578 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5579 __isl_keep isl_union_map *any_to_outer)
5581 int i;
5582 struct gpu_stmt *stmts;
5584 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5585 if (!stmts)
5586 return NULL;
5588 for (i = 0; i < scop->pet->n_stmt; ++i) {
5589 struct gpu_stmt *s = &stmts[i];
5590 isl_bool killed;
5592 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5593 s->stmt = scop->pet->stmts[i];
5594 killed = is_stmt_killed(scop, scop->pet->stmts[i]);
5595 if (killed < 0)
5596 return free_stmts(stmts, i + 1);
5597 if (killed)
5598 continue;
5599 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
5600 return free_stmts(stmts, i + 1);
5603 return stmts;
5606 /* Generate CUDA code for "scop" and print it to "p".
5607 * After generating an AST for the transformed scop as explained below,
5608 * we call "gen->print" to print the AST in the desired output format
5609 * to "p".
5611 * If it turns out that it does not make sense to generate GPU code,
5612 * then we generate CPU code instead.
5614 * The declarations of the arrays that are visible outside of the scop
5615 * are printed outside of the code generated from the schedule,
5616 * because the generated code may involve a guard around the entire code.
5618 * We first compute a schedule that respects the dependences
5619 * of the original program and select the outermost bands
5620 * of tilable dimensions that have at least one parallel loop.
5621 * If the --load-schedule is specified, then the loaded schedule
5622 * is used instead of a computed schedule.
5624 * Each of these bands B is then tiled according to "tile" sizes, resulting
5625 * in two nested bands, with a kernel marker on top
5633 * We then split off at most 2 parallel dimensions from the T band and
5634 * at most 3 parallel dimension from the P band
5639 * T1
5641 * T2
5643 * P1
5645 * P2
5647 * A filter is introduced in front of T1 that maps the domain instances
5648 * to block identifiers. Similarly, a filter is introduced in front of P1
5649 * that maps the domain instances to thread identifiers.
5651 * For each iteration of the T2 band and for each array, we compute
5652 * the array elements accessed by that iteration, construct a rectangular
5653 * box around it and shift it to the origin. The result is used
5654 * as shared memory for the array.
5656 * Copying and synchronization statements are added to this schedule tree.
5657 * In principle, these are added in front of the P1 band, but some of
5658 * them may get hoisted up to higher levels.
5660 * The entire AST is then generated from the single resulting schedule tree.
5661 * During the generation the subtrees at kernel nodes (K) are saved
5662 * aside and replaced by kernel calls. The result is printed as host code
5663 * while the saved subtrees are printed as device code.
5665 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5666 struct gpu_gen *gen, struct ppcg_scop *scop,
5667 struct ppcg_options *options)
5669 struct gpu_prog *prog;
5670 isl_ctx *ctx;
5671 isl_schedule *schedule;
5672 isl_bool any_permutable;
5674 if (!scop)
5675 return isl_printer_free(p);
5677 ctx = isl_printer_get_ctx(p);
5678 prog = gpu_prog_alloc(ctx, scop);
5679 if (!prog)
5680 return isl_printer_free(p);
5682 gen->prog = prog;
5683 schedule = get_schedule(gen);
5685 any_permutable = has_any_permutable_node(schedule);
5686 if (any_permutable < 0 || !any_permutable) {
5687 if (any_permutable < 0)
5688 p = isl_printer_free(p);
5689 else
5690 p = print_cpu(p, scop, options);
5691 isl_schedule_free(schedule);
5692 } else {
5693 schedule = map_to_device(gen, schedule);
5694 gen->tree = generate_code(gen, schedule);
5695 p = ppcg_set_macro_names(p);
5696 p = ppcg_print_exposed_declarations(p, prog->scop);
5697 p = gen->print(p, gen->prog, gen->tree, &gen->types,
5698 gen->print_user);
5699 isl_ast_node_free(gen->tree);
5702 gpu_prog_free(prog);
5704 return p;
5707 /* Wrapper around generate for use as a ppcg_transform callback.
5709 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5710 struct ppcg_scop *scop, void *user)
5712 struct gpu_gen *gen = user;
5714 return generate(p, gen, scop, gen->options);
5717 /* Transform the code in the file called "input" by replacing
5718 * all scops by corresponding GPU code and write the results to "out".
5720 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5721 struct ppcg_options *options,
5722 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5723 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5724 struct gpu_types *types, void *user), void *user)
5726 struct gpu_gen gen;
5727 int r;
5728 int i;
5730 gen.ctx = ctx;
5731 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5732 gen.options = options;
5733 gen.kernel_id = 0;
5734 gen.print = print;
5735 gen.print_user = user;
5736 gen.types.n = 0;
5737 gen.types.name = NULL;
5739 if (options->debug->dump_sizes) {
5740 isl_space *space = isl_space_params_alloc(ctx, 0);
5741 gen.used_sizes = isl_union_map_empty(space);
5744 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5746 if (options->debug->dump_sizes) {
5747 isl_union_map_dump(gen.used_sizes);
5748 isl_union_map_free(gen.used_sizes);
5751 isl_union_map_free(gen.sizes);
5752 for (i = 0; i < gen.types.n; ++i)
5753 free(gen.types.name[i]);
5754 free(gen.types.name);
5756 return r;
5759 /* Compute the set of inner array elements that may have their values
5760 * preserved by "prog". In particular, collect the array elements of
5761 * arrays that are not local to "prog" and remove those elements that
5762 * are definitely killed or definitely written by "prog".
5764 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5766 int i;
5767 isl_union_set *may_persist, *killed;
5768 isl_union_map *must_kill;
5770 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5771 for (i = 0; i < prog->n_array; ++i) {
5772 isl_set *extent;
5774 if (prog->array[i].local)
5775 continue;
5777 extent = isl_set_copy(prog->array[i].extent);
5778 may_persist = isl_union_set_add_set(may_persist, extent);
5781 may_persist = isl_union_set_intersect_params(may_persist,
5782 isl_set_copy(prog->context));
5783 may_persist = isl_union_set_apply(may_persist,
5784 isl_union_map_copy(prog->to_inner));
5785 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5786 killed = isl_union_map_range(must_kill);
5787 must_kill = isl_union_map_copy(prog->must_write);
5788 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5790 may_persist = isl_union_set_subtract(may_persist, killed);
5791 return may_persist;
5794 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5796 struct gpu_prog *prog;
5797 isl_space *space;
5798 isl_map *id;
5800 if (!scop)
5801 return NULL;
5803 prog = isl_calloc_type(ctx, struct gpu_prog);
5804 if (!prog)
5805 return NULL;
5807 prog->ctx = ctx;
5808 prog->scop = scop;
5809 prog->context = isl_set_copy(scop->context);
5810 prog->n_stmts = scop->pet->n_stmt;
5811 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5812 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5813 space = isl_union_map_get_space(prog->any_to_outer);
5814 space = isl_space_set_from_params(space);
5815 space = isl_space_add_dims(space, isl_dim_set, 1);
5816 space = isl_space_map_from_set(space);
5817 id = isl_map_identity(space);
5818 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5819 prog->stmts = extract_stmts(ctx, scop, prog->any_to_outer);
5820 prog->read = isl_union_map_copy(scop->reads);
5821 prog->may_write = isl_union_map_copy(scop->may_writes);
5822 prog->must_write = isl_union_map_copy(scop->must_writes);
5823 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5824 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5825 prog->to_outer = isl_union_map_copy(prog->to_inner);
5826 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5828 if (!prog->stmts)
5829 return gpu_prog_free(prog);
5831 if (collect_array_info(prog) < 0)
5832 return gpu_prog_free(prog);
5833 prog->may_persist = compute_may_persist(prog);
5835 return prog;
5838 void *gpu_prog_free(struct gpu_prog *prog)
5840 if (!prog)
5841 return NULL;
5842 free_array_info(prog);
5843 free_stmts(prog->stmts, prog->n_stmts);
5844 isl_union_map_free(prog->any_to_outer);
5845 isl_union_map_free(prog->to_outer);
5846 isl_union_map_free(prog->to_inner);
5847 isl_union_map_free(prog->read);
5848 isl_union_map_free(prog->may_write);
5849 isl_union_map_free(prog->must_write);
5850 isl_union_map_free(prog->tagged_must_kill);
5851 isl_union_map_free(prog->array_order);
5852 isl_union_set_free(prog->may_persist);
5853 isl_set_free(prog->context);
5854 free(prog);
5855 return NULL;