gpu: avoid mapping independent non-permutable bands to the device
[ppcg.git] / gpu.c
blob5ee06e6c302ec28f3f5b19c4456d0ae258a3c31e
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012-2013 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/schedule.h>
23 #include <isl/schedule_node.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "gpu_array_tile.h"
30 #include "gpu_group.h"
31 #include "gpu_tree.h"
32 #include "schedule.h"
33 #include "ppcg_options.h"
34 #include "print.h"
35 #include "util.h"
37 struct gpu_array_info;
39 /* Collect all references to the given array and store pointers to them
40 * in array->refs.
42 * If the array contains structures, then there is no need to collect
43 * the references since we will not be computing any reference groups.
45 static void collect_references(struct gpu_prog *prog,
46 struct gpu_array_info *array)
48 int i;
49 int n;
51 if (array->has_compound_element)
52 return;
54 n = 0;
55 for (i = 0; i < prog->n_stmts; ++i) {
56 struct gpu_stmt *stmt = &prog->stmts[i];
57 struct gpu_stmt_access *access;
59 for (access = stmt->accesses; access; access = access->next) {
60 const char *name;
61 name = isl_map_get_tuple_name(access->access,
62 isl_dim_out);
63 if (name && !strcmp(array->name, name))
64 n++;
68 array->n_ref = n;
69 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
70 assert(array->refs);
72 n = 0;
73 for (i = 0; i < prog->n_stmts; ++i) {
74 struct gpu_stmt *stmt = &prog->stmts[i];
75 struct gpu_stmt_access *access;
77 for (access = stmt->accesses; access; access = access->next) {
78 const char *name;
79 name = isl_map_get_tuple_name(access->access,
80 isl_dim_out);
81 if (!name || strcmp(array->name, name))
82 continue;
84 array->refs[n++] = access;
89 /* Compute and return the extent of "array", taking into account the set of
90 * accessed elements.
92 * In particular, the extent in the outer dimension is taken
93 * from "accessed", while the extents in the remaining dimensions
94 * are taken from array->extent.
96 * The extent in the outer dimension cannot be taken from array->extent
97 * because that may be unbounded. Furthermore, even if it is bounded,
98 * it may be larger than the piece of the array that is being accessed.
100 static __isl_give isl_set *compute_extent(struct pet_array *array,
101 __isl_keep isl_set *accessed)
103 int n_index;
104 isl_id *id;
105 isl_set *outer;
106 isl_set *extent;
108 extent = isl_set_copy(array->extent);
110 n_index = isl_set_dim(accessed, isl_dim_set);
111 if (n_index == 0)
112 return extent;
114 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
115 outer = isl_set_copy(accessed);
116 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
117 extent = isl_set_flat_product(outer, extent);
118 id = isl_set_get_tuple_id(accessed);
119 extent = isl_set_set_tuple_id(extent, id);
121 return extent;
124 /* Is the array "array" being extracted a read-only scalar?
126 * That is, is "array" a scalar that is never possibly written to.
127 * An array containing structures is never considered to be a scalar.
129 static int is_read_only_scalar(struct gpu_array_info *array,
130 struct gpu_prog *prog)
132 isl_set *space;
133 isl_union_map *write;
134 int empty;
136 if (array->has_compound_element)
137 return 0;
138 if (array->n_index != 0)
139 return 0;
141 write = isl_union_map_copy(prog->may_write);
142 space = isl_set_universe(isl_space_copy(array->space));
143 write = isl_union_map_intersect_range(write,
144 isl_union_set_from_set(space));
145 empty = isl_union_map_is_empty(write);
146 isl_union_map_free(write);
148 return empty;
151 /* Compute bounds on the host array "pa" based on the corresponding
152 * accessed elements in "arrays"
153 * and collect all references to the array.
154 * Store the results in "info".
156 * If the array is zero-dimensional and does not contain structures,
157 * i.e., if the array is a scalar, we check whether it is read-only.
158 * We also check whether the array is accessed at all.
160 static int extract_array_info(struct gpu_prog *prog,
161 struct gpu_array_info *info, struct pet_array *pa,
162 __isl_keep isl_union_set *arrays)
164 int i, empty;
165 const char *name;
166 int n_index;
167 isl_pw_aff **bounds;
168 isl_set *accessed, *extent;
170 n_index = isl_set_dim(pa->extent, isl_dim_set);
171 name = isl_set_get_tuple_name(pa->extent);
172 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index);
173 if (!bounds)
174 return -1;
176 info->space = isl_set_get_space(pa->extent);
177 info->name = strdup(name);
178 info->n_index = n_index;
179 info->bound = bounds;
180 info->linearize = prog->scop->options->linearize_device_arrays;
182 info->type = strdup(pa->element_type);
183 info->size = pa->element_size;
184 info->local = pa->declared && !pa->exposed;
185 info->has_compound_element = pa->element_is_record;
186 info->read_only_scalar = is_read_only_scalar(info, prog);
188 accessed = isl_union_set_extract_set(arrays,
189 isl_space_copy(info->space));
190 empty = isl_set_is_empty(accessed);
191 extent = compute_extent(pa, accessed);
192 isl_set_free(accessed);
193 info->extent = extent;
194 if (empty < 0)
195 return -1;
196 info->accessed = !empty;
197 for (i = 0; i < n_index; ++i) {
198 isl_set *dom;
199 isl_local_space *ls;
200 isl_aff *one;
201 isl_pw_aff *bound;
203 dom = isl_set_copy(extent);
204 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
205 n_index - (i + 1));
206 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
207 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
208 fprintf(stderr, "unable to determine extent of '%s' "
209 "in dimension %d\n", info->name, i);
210 dom = isl_set_free(dom);
212 bound = isl_set_dim_max(dom, 0);
213 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
214 ls = isl_local_space_from_space(isl_set_get_space(dom));
215 one = isl_aff_zero_on_domain(ls);
216 one = isl_aff_add_constant_si(one, 1);
217 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
218 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
220 bounds[i] = bound;
221 if (!isl_pw_aff_is_cst(bound))
222 info->linearize = 1;
225 collect_references(prog, info);
227 return 0;
230 /* Remove independence from the order constraints "order" on array "array".
231 * Since the pairs of iterations in the filter relation of an independence
232 * are guaranteed to be completely independent by the user, there is
233 * no need to ensure that live ranges are ordered along thong pairs.
234 * We make an exception for local variables, though, as the independence
235 * guarantee does not apply to those.
237 * The order constraints are used in two places.
238 * Those on scalars are used in check_scalar_live_ranges to check if
239 * we need to force the scalar to be private. Any non-local scalar
240 * should not be forced scalar if it only appears in independent loops.
241 * Those on non-scalars are added to the coincidence constraints
242 * in compute_schedule because we do not support any array expansion.
243 * Accesses to non-local arrays should not prevent a loop from being
244 * considered coincident so we should indeed remove those constraints
245 * from the order constraints.
247 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
248 struct gpu_array_info *array, __isl_take isl_union_map *order)
250 int i;
252 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
253 struct pet_independence *pi = prog->scop->pet->independences[i];
254 if (isl_union_set_contains(pi->local, array->space))
255 continue;
257 order = isl_union_map_subtract(order,
258 isl_union_map_copy(pi->filter));
261 return order;
264 /* For each array in "prog", store the (untagged) order dependences
265 * derived from the array in array->dep_order.
266 * In particular, consider all references that access the given array
267 * and take the order dependences that have one of these references
268 * as source. (Since an order dependence relates two references to
269 * the same array, the target of these order dependences will also
270 * be one of these references.)
271 * Additionally, store the union of these array->dep_order relations
272 * for all non-scalar arrays in prog->array_order.
274 void collect_order_dependences(struct gpu_prog *prog)
276 int i;
277 isl_space *space;
278 isl_union_map *accesses;
280 space = isl_union_map_get_space(prog->read);
281 prog->array_order = isl_union_map_empty(space);
283 accesses = isl_union_map_copy(prog->scop->tagged_reads);
284 accesses = isl_union_map_union(accesses,
285 isl_union_map_copy(prog->scop->tagged_may_writes));
286 accesses = isl_union_map_universe(accesses);
287 accesses = isl_union_map_apply_range(accesses,
288 isl_union_map_copy(prog->to_outer));
290 for (i = 0; i < prog->n_array; ++i) {
291 struct gpu_array_info *array = &prog->array[i];
292 isl_set *set;
293 isl_union_set *uset;
294 isl_union_map *order;
296 set = isl_set_universe(isl_space_copy(array->space));
297 uset = isl_union_set_from_set(set);
298 uset = isl_union_map_domain(
299 isl_union_map_intersect_range(isl_union_map_copy(accesses),
300 uset));
301 order = isl_union_map_copy(prog->scop->tagged_dep_order);
302 order = isl_union_map_intersect_domain(order, uset);
303 order = isl_union_map_zip(order);
304 order = isl_union_set_unwrap(isl_union_map_domain(order));
305 order = remove_independences(prog, array, order);
306 array->dep_order = order;
308 if (gpu_array_is_scalar(array) && !array->has_compound_element)
309 continue;
311 prog->array_order = isl_union_map_union(prog->array_order,
312 isl_union_map_copy(array->dep_order));
315 isl_union_map_free(accesses);
318 /* Construct a gpu_array_info for each array referenced by prog->scop and
319 * collect them in prog->array.
321 * The sizes are based on the extents and the set of possibly accessed
322 * elements by "prog".
323 * If there are any member accesses involved, then they are first mapped
324 * to the outer arrays of structs.
326 * If we are allowing live range reordering, then also set
327 * the dep_order field. Otherwise leave it NULL.
329 static int collect_array_info(struct gpu_prog *prog)
331 int i;
332 int r = 0;
333 isl_union_set *arrays;
335 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
336 arrays = isl_union_set_union(arrays,
337 isl_union_map_range(isl_union_map_copy(prog->may_write)));
339 arrays = isl_union_set_apply(arrays,
340 isl_union_map_copy(prog->to_outer));
342 arrays = isl_union_set_coalesce(arrays);
344 prog->n_array = prog->scop->pet->n_array;
345 prog->array = isl_calloc_array(prog->ctx,
346 struct gpu_array_info, prog->n_array);
347 assert(prog->array);
348 for (i = 0; i < prog->scop->pet->n_array; ++i)
349 if (extract_array_info(prog, &prog->array[i],
350 prog->scop->pet->arrays[i], arrays) < 0)
351 r = -1;
353 isl_union_set_free(arrays);
355 if (prog->scop->options->live_range_reordering)
356 collect_order_dependences(prog);
358 return r;
361 static void free_array_info(struct gpu_prog *prog)
363 int i, j;
365 for (i = 0; i < prog->n_array; ++i) {
366 int n_index = prog->array[i].n_index;
367 free(prog->array[i].type);
368 free(prog->array[i].name);
369 for (j = 0; j < n_index; ++j)
370 isl_pw_aff_free(prog->array[i].bound[j]);
371 isl_space_free(prog->array[i].space);
372 isl_set_free(prog->array[i].extent);
373 free(prog->array[i].bound);
374 free(prog->array[i].refs);
375 isl_union_map_free(prog->array[i].dep_order);
377 free(prog->array);
380 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
381 * as an array or through a pointer reference, but as a single data element.
382 * At the moment, scalars are represented as zero-dimensional arrays.
383 * Note that the single data element may be an entire structure.
385 int gpu_array_is_scalar(struct gpu_array_info *array)
387 return array->n_index == 0;
390 /* Is "array" a read-only scalar?
392 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
394 return array->read_only_scalar;
397 /* Return the set of parameter values for which the array has a positive
398 * size in all dimensions.
399 * If the sizes are only valid for some parameter values, then those
400 * constraints are also taken into account.
402 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
404 int i;
405 isl_space *space;
406 isl_set *guard;
408 if (!array)
409 return NULL;
411 space = isl_space_params(isl_space_copy(array->space));
412 guard = isl_set_universe(space);
414 for (i = 0; i < array->n_index; ++i) {
415 isl_pw_aff *bound;
416 isl_set *guard_i, *zero;
418 bound = isl_pw_aff_copy(array->bound[i]);
419 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
420 zero = isl_pw_aff_zero_set(bound);
421 guard_i = isl_set_subtract(guard_i, zero);
422 guard = isl_set_intersect(guard, guard_i);
425 return guard;
428 /* Internal data structure for extract_size_of_type.
429 * "type" specifies the name of the space that we want to extract.
430 * "res" is used to store the subset of that space.
432 struct ppcg_extract_size_data {
433 const char *type;
434 isl_set *res;
437 /* This function is called for each set in a union_set.
438 * If the name of the set matches data->type, we store the
439 * set in data->res.
441 static int extract_size_of_type(__isl_take isl_set *size, void *user)
443 struct ppcg_extract_size_data *data = user;
444 const char *name;
446 name = isl_set_get_tuple_name(size);
447 if (name && !strcmp(name, data->type)) {
448 data->res = size;
449 return -1;
452 isl_set_free(size);
453 return 0;
456 /* Given a union map { kernel[i] -> *[...] },
457 * return the range in the space called "type" for the kernel with
458 * sequence number "id".
460 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
461 const char *type, int id)
463 isl_space *space;
464 isl_set *dom;
465 isl_union_set *local_sizes;
466 struct ppcg_extract_size_data data = { type, NULL };
468 if (!sizes)
469 return NULL;
471 space = isl_union_map_get_space(sizes);
472 space = isl_space_set_from_params(space);
473 space = isl_space_add_dims(space, isl_dim_set, 1);
474 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
475 dom = isl_set_universe(space);
476 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
478 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
479 isl_union_map_copy(sizes));
480 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
481 isl_union_set_free(local_sizes);
482 return data.res;
485 /* Given a singleton set, extract the first (at most *len) elements
486 * of the single integer tuple into *sizes and update *len if needed.
488 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
490 int i;
491 int dim;
493 if (!set)
494 return;
496 dim = isl_set_dim(set, isl_dim_set);
497 if (dim < *len)
498 *len = dim;
500 for (i = 0; i < *len; ++i) {
501 isl_val *v;
503 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
504 assert(v);
506 sizes[i] = isl_val_get_num_si(v);
507 isl_val_free(v);
510 isl_set_free(set);
513 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
514 * if the option debug->dump_sizes is set.
516 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
517 int *sizes, int len)
519 int i;
520 isl_space *space;
521 isl_map *map;
523 if (!gen->options->debug->dump_sizes)
524 return;
526 space = isl_union_map_get_space(gen->used_sizes);
527 space = isl_space_set_from_params(space);
528 space = isl_space_add_dims(space, isl_dim_set, 1);
529 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
530 space = isl_space_from_domain(space);
531 space = isl_space_add_dims(space, isl_dim_out, len);
532 space = isl_space_set_tuple_name(space, isl_dim_out, type);
534 map = isl_map_universe(space);
535 map = isl_map_fix_si(map, isl_dim_in, 0, id);
536 for (i = 0; i < len; ++i)
537 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
539 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
542 /* Extract user specified "tile" sizes from the "sizes" command line option,
543 * defaulting to option->tile_size in each dimension.
544 * *tile_len contains the maximum number of tile sizes needed.
545 * Update *tile_len to the number of specified tile sizes, if any, and
546 * return a pointer to the tile sizes (or NULL on error).
547 * Add the effectively used sizes to gen->used_sizes.
549 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
551 int n;
552 int *tile_size;
553 isl_set *size;
555 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
556 if (!tile_size)
557 return NULL;
558 for (n = 0; n < *tile_len; ++n)
559 tile_size[n] = gen->options->tile_size;
561 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
562 read_sizes_from_set(size, tile_size, tile_len);
563 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
565 return tile_size;
568 /* Extract user specified "block" sizes from the "sizes" command line option,
569 * after filling in some potentially useful defaults.
571 static void read_block_sizes(struct ppcg_kernel *kernel,
572 __isl_keep isl_union_map *sizes)
574 isl_set *size;
576 if (kernel->n_block > 3)
577 kernel->n_block = 3;
578 switch (kernel->n_block) {
579 case 1:
580 kernel->block_dim[0] = 512;
581 break;
582 case 2:
583 kernel->block_dim[0] = 32;
584 kernel->block_dim[1] = 16;
585 break;
586 default:
587 kernel->block_dim[0] = 32;
588 kernel->block_dim[1] = 4;
589 kernel->block_dim[2] = 4;
590 break;
593 size = extract_sizes(sizes, "block", kernel->id);
594 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
597 /* Extract user specified "grid" sizes from the "sizes" command line option,
598 * after filling in some potentially useful defaults.
600 static void read_grid_sizes(struct ppcg_kernel *kernel,
601 __isl_keep isl_union_map *sizes)
603 isl_set *size;
605 if (kernel->n_grid > 2)
606 kernel->n_grid = 2;
607 switch (kernel->n_grid) {
608 case 1:
609 kernel->grid_dim[0] = 32768;
610 break;
611 default:
612 kernel->grid_dim[0] = 256;
613 kernel->grid_dim[1] = 256;
614 break;
617 size = extract_sizes(sizes, "grid", kernel->id);
618 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
621 /* Extract user specified grid and block sizes from the gen->sizes
622 * command line option after filling in some potentially useful defaults.
623 * Store the extracted sizes in "kernel".
624 * Add the effectively used sizes to gen->used_sizes.
626 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
627 struct gpu_gen *gen)
629 read_block_sizes(kernel, gen->sizes);
630 read_grid_sizes(kernel, gen->sizes);
631 set_used_sizes(gen, "block", kernel->id,
632 kernel->block_dim, kernel->n_block);
633 set_used_sizes(gen, "grid", kernel->id,
634 kernel->grid_dim, kernel->n_grid);
637 static void *free_stmts(struct gpu_stmt *stmts, int n)
639 int i;
641 if (!stmts)
642 return NULL;
644 for (i = 0; i < n; ++i) {
645 struct gpu_stmt_access *access, *next;
647 for (access = stmts[i].accesses; access; access = next) {
648 next = access->next;
649 isl_id_free(access->ref_id);
650 isl_map_free(access->access);
651 isl_map_free(access->tagged_access);
652 free(access);
655 isl_id_free(stmts[i].id);
657 free(stmts);
659 return NULL;
662 /* Add parameters p[i] with identifiers "ids" to "set",
663 * with bounds to 0 <= p[i] < size[i].
665 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
666 int *size, __isl_keep isl_id_list *ids)
668 int i, len;
669 unsigned nparam;
671 len = isl_id_list_n_id(ids);
672 nparam = isl_set_dim(set, isl_dim_param);
673 set = isl_set_add_dims(set, isl_dim_param, len);
675 for (i = 0; i < len; ++i) {
676 isl_id *id;
678 id = isl_id_list_get_id(ids, i);
679 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
680 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
681 set = isl_set_upper_bound_si(set, isl_dim_param,
682 nparam + i, size[i] - 1);
685 return set;
688 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
689 * with
691 * { : 0 <= p[i] < size[i] }
693 * or an overapproximation.
695 static __isl_give isl_set *add_bounded_parameters_dynamic(
696 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
697 __isl_keep isl_id_list *ids)
699 int i, len;
700 unsigned nparam;
701 isl_space *space;
702 isl_local_space *ls;
704 len = isl_multi_pw_aff_dim(size, isl_dim_out);
705 nparam = isl_set_dim(set, isl_dim_param);
706 set = isl_set_add_dims(set, isl_dim_param, len);
708 for (i = 0; i < len; ++i) {
709 isl_id *id;
711 id = isl_id_list_get_id(ids, i);
712 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
715 space = isl_space_params(isl_set_get_space(set));
716 ls = isl_local_space_from_space(space);
717 for (i = 0; i < len; ++i) {
718 isl_pw_aff *param, *size_i, *zero;
719 isl_set *bound;
721 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
722 isl_dim_param, nparam + i);
724 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
725 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
726 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
727 set = isl_set_intersect_params(set, bound);
729 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
730 bound = isl_pw_aff_ge_set(param, zero);
731 set = isl_set_intersect_params(set, bound);
733 isl_local_space_free(ls);
735 return set;
738 /* Return the union of all tagged access relations in the group.
740 static __isl_give isl_union_map *group_tagged_access_relation(
741 struct gpu_array_ref_group *group)
743 int i;
744 isl_union_map *access;
746 access = isl_union_map_empty(isl_map_get_space(group->access));
747 for (i = 0; i < group->n_ref; ++i) {
748 isl_map *map_i;
750 map_i = isl_map_copy(group->refs[i]->tagged_access);
751 access = isl_union_map_union(access,
752 isl_union_map_from_map(map_i));
755 return access;
758 /* Return the extent of "array", recomputed from the bounds.
759 * The recomputed extent may be simpler than the original extent.
761 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
763 int i;
764 isl_id *id;
765 isl_space *space;
766 isl_local_space *ls;
767 isl_set *extent;
769 id = isl_set_get_tuple_id(array->extent);
770 space = isl_set_get_space(array->extent);
771 extent = isl_set_universe(isl_space_copy(space));
772 ls = isl_local_space_from_space(space);
773 for (i = 0; i < array->n_index; ++i) {
774 isl_pw_aff *bound;
775 isl_aff *aff;
776 isl_pw_aff *index;
777 isl_set *lt;
779 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
781 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
782 isl_dim_set, i);
783 index = isl_pw_aff_from_aff(aff);
784 bound = isl_pw_aff_copy(array->bound[i]);
785 bound = isl_pw_aff_from_range(bound);
786 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
787 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
788 isl_id_copy(id));
789 lt = isl_pw_aff_lt_set(index, bound);
790 extent = isl_set_intersect(extent, lt);
792 isl_local_space_free(ls);
793 isl_id_free(id);
795 return extent;
798 /* Return a map from the first group->depth dimensions of the computed
799 * schedule to the array tile in
800 * global memory that corresponds to the shared memory copy.
802 * In particular, return a map
804 * { D[i] -> A[a] }
806 * with constraints
808 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
810 * and
812 * 0 <= a <= array_size - 1 (2)
814 * Note that if some stride has been detected (i.e., when
815 * group->shared_tile->bound[i].shift is set), then a in (1) refers
816 * to the shifted and scaled down version.
818 * Constraints (1) are obtained by mapping the size constraints on the
819 * shared/private memory tile back to the access relation.
820 * Constraints (2) are obtained from the (recomputed) extent.
822 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
824 int i;
825 int n_index = group->array->n_index;
826 isl_map *tile;
827 isl_space *space;
828 isl_set *local;
829 isl_set *extent;
831 space = isl_multi_aff_get_space(group->shared_tile->tiling);
832 space = isl_space_range(space);
833 local = isl_set_universe(space);
834 for (i = 0; i < n_index; ++i) {
835 isl_val *bound;
837 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
838 bound = isl_val_copy(group->shared_tile->bound[i].size);
839 bound = isl_val_sub_ui(bound, 1);
840 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
842 local = isl_set_preimage_multi_aff(local,
843 isl_multi_aff_copy(group->shared_tile->tiling));
844 tile = isl_set_unwrap(local);
845 extent = array_extent(group->array);
846 tile = isl_map_intersect_range(tile, extent);
848 return tile;
851 /* Given a mapping "iterator_map" from the AST schedule to a domain,
852 * return the corresponding mapping from the AST schedule to
853 * to the outer kernel->shared_schedule_dim dimensions of
854 * the schedule computed by PPCG for this kernel.
856 * Note that kernel->shared_schedule_dim is at least as large as
857 * the largest depth of any array reference group associated to the kernel.
858 * This is needed as the returned schedule is used to extract a mapping
859 * to the outer group->depth dimensions in transform_index.
861 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
862 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
864 isl_union_pw_multi_aff *upma;
865 isl_pw_multi_aff *pma;
866 isl_space *space;
868 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
869 space = isl_space_from_domain(space);
870 space = isl_space_add_dims(space, isl_dim_out,
871 kernel->shared_schedule_dim);
873 upma = isl_union_pw_multi_aff_copy(kernel->shared_schedule);
874 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
875 isl_union_pw_multi_aff_free(upma);
877 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
880 /* If max_shared_memory is not set to infinity (-1), then make
881 * sure that the total amount of shared memory required by the
882 * array reference groups mapped to shared memory by "kernel"
883 * is no larger than this maximum.
885 * We apply a greedy approach and discard (keep in global memory)
886 * those groups that would result in a total memory size that
887 * is larger than the maximum.
889 * This function should be called after any function that may
890 * affect the decision on whether to place a reference group
891 * in private, shared or global memory.
893 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
895 int i, j;
896 isl_val *left, *size;
898 if (kernel->options->max_shared_memory < 0)
899 return;
901 left = isl_val_int_from_si(kernel->ctx,
902 kernel->options->max_shared_memory);
904 for (i = 0; i < kernel->n_array; ++i) {
905 struct gpu_local_array_info *local = &kernel->array[i];
907 for (j = 0; j < local->n_group; ++j) {
908 struct gpu_array_ref_group *group;
910 group = local->groups[j];
911 if (group->private_tile)
912 continue;
913 if (!group->shared_tile)
914 continue;
916 size = gpu_array_tile_size(group->shared_tile);
917 size = isl_val_mul_ui(size, local->array->size);
919 if (isl_val_le(size, left)) {
920 left = isl_val_sub(left, size);
921 continue;
923 isl_val_free(size);
925 group->shared_tile =
926 gpu_array_tile_free(group->shared_tile);
930 isl_val_free(left);
933 /* Compute a tiling for all the array reference groups in "kernel".
935 static void compute_group_tilings(struct ppcg_kernel *kernel)
937 int i, j;
939 for (i = 0; i < kernel->n_array; ++i) {
940 struct gpu_local_array_info *array = &kernel->array[i];
942 for (j = 0; j < array->n_group; ++j)
943 gpu_array_ref_group_compute_tiling(array->groups[j]);
947 /* Compute the size of a bounding box around the origin and "set",
948 * where "set" is assumed to contain only non-negative elements.
949 * In particular, compute the maximal value of "set" in each direction
950 * and add one.
952 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
953 __isl_take isl_set *context)
955 int i, n;
956 isl_multi_pw_aff *mpa;
958 context = isl_set_params(context);
959 n = isl_set_dim(set, isl_dim_set);
960 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
961 for (i = 0; i < n; ++i) {
962 isl_space *space;
963 isl_aff *one;
964 isl_pw_aff *bound;
966 bound = isl_set_dim_max(isl_set_copy(set), i);
967 bound = isl_pw_aff_coalesce(bound);
968 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
970 space = isl_pw_aff_get_domain_space(bound);
971 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
972 one = isl_aff_add_constant_si(one, 1);
973 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
974 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
976 isl_set_free(set);
977 isl_set_free(context);
979 return mpa;
982 /* Compute the effective grid size as a list of the sizes in each dimension.
984 * The grid size specified by the user or set by default
985 * in read_grid_sizes() and applied by the block filter,
986 * may be too large for the given code in the sense that
987 * it may contain blocks that don't need to execute anything.
988 * We therefore don't return this grid size, but instead the
989 * smallest grid size that ensures that all blocks that actually
990 * execute code are included in the grid.
992 * We first extract a description of the grid, i.e., the possible values
993 * of the block ids, from the domain elements in "domain" and
994 * kernel->block_filter.
995 * The block ids are parameters in kernel->block_filter.
996 * We simply need to change them into set dimensions.
998 * Then, for each block dimension, we compute the maximal value of the block id
999 * and add one.
1001 static __isl_give isl_multi_pw_aff *extract_grid_size(
1002 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1004 int i;
1005 isl_set *grid;
1007 domain = isl_union_set_intersect(domain,
1008 isl_union_set_copy(kernel->block_filter));
1009 grid = isl_union_set_params(domain);
1010 grid = isl_set_from_params(grid);
1011 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1012 for (i = 0; i < kernel->n_grid; ++i) {
1013 int pos;
1014 isl_id *id;
1016 id = isl_id_list_get_id(kernel->block_ids, i);
1017 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1018 isl_id_free(id);
1019 assert(pos >= 0);
1020 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1021 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1024 return extract_size(grid, isl_set_copy(kernel->context));
1027 /* Compute the size of a fixed bounding box around the origin and "set",
1028 * where "set" is assumed to contain only non-negative elements,
1029 * and store the results in "size".
1030 * In particular, compute the maximal value of "set" in each direction
1031 * and add one.
1033 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1035 int i, n;
1036 isl_local_space *ls;
1037 isl_aff *obj;
1039 n = isl_set_dim(set, isl_dim_set);
1040 ls = isl_local_space_from_space(isl_set_get_space(set));
1041 obj = isl_aff_zero_on_domain(ls);
1042 for (i = 0; i < n; ++i) {
1043 isl_val *max;
1045 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1046 max = isl_set_max_val(set, obj);
1047 size[i] = isl_val_get_num_si(max) + 1;
1048 isl_val_free(max);
1049 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1051 isl_aff_free(obj);
1052 isl_set_free(set);
1055 /* Compute the effective block size as a list of the sizes in each dimension
1056 * and store the sizes in kernel->block_dim.
1058 * The block size specified by the user or set by default
1059 * in read_block_sizes() and applied by the thread filter,
1060 * may be too large for the given code in the sense that
1061 * it may contain threads that don't need to execute anything.
1062 * We therefore update this block size in kernel->block_dim
1063 * to the smallest block size that ensures that all threads
1064 * that actually execute code are included in the block.
1066 * The possible values of the thread ids is obtained from
1067 * the domain elements "domain" and kernel->thread_filter.
1068 * The current implementation eliminates all parameters, ensuring
1069 * that the size is a fixed constant in each dimension.
1070 * In principle we could also compute parametric sizes.
1071 * We would have to make sure to project out all b%d and t%d parameters,
1072 * however.
1074 static void extract_block_size(struct ppcg_kernel *kernel,
1075 __isl_take isl_union_set *domain)
1077 int i;
1078 int nparam;
1079 isl_set *block;
1081 domain = isl_union_set_intersect(domain,
1082 isl_union_set_copy(kernel->thread_filter));
1083 block = isl_union_set_params(domain);
1084 block = isl_set_from_params(block);
1085 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1086 for (i = 0; i < kernel->n_block; ++i) {
1087 int pos;
1088 isl_id *id;
1090 id = isl_id_list_get_id(kernel->thread_ids, i);
1091 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1092 isl_id_free(id);
1093 assert(pos >= 0);
1094 block = isl_set_equate(block, isl_dim_param, pos,
1095 isl_dim_set, i);
1097 nparam = isl_set_dim(block, isl_dim_param);
1098 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1100 extract_fixed_size(block, kernel->block_dim);
1103 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1105 int i, j;
1107 if (!kernel)
1108 return NULL;
1110 isl_id_list_free(kernel->block_ids);
1111 isl_id_list_free(kernel->thread_ids);
1112 isl_multi_pw_aff_free(kernel->grid_size);
1113 isl_set_free(kernel->context);
1114 isl_union_set_free(kernel->core);
1115 isl_union_set_free(kernel->arrays);
1116 isl_space_free(kernel->space);
1117 isl_ast_node_free(kernel->tree);
1118 isl_union_set_free(kernel->block_filter);
1119 isl_union_set_free(kernel->thread_filter);
1120 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1121 isl_union_set_free(kernel->sync_writes);
1123 for (i = 0; i < kernel->n_array; ++i) {
1124 struct gpu_local_array_info *array = &kernel->array[i];
1126 for (j = 0; j < array->n_group; ++j)
1127 gpu_array_ref_group_free(array->groups[j]);
1128 free(array->groups);
1130 isl_pw_aff_list_free(array->bound);
1132 free(kernel->array);
1134 for (i = 0; i < kernel->n_var; ++i) {
1135 free(kernel->var[i].name);
1136 isl_vec_free(kernel->var[i].size);
1138 free(kernel->var);
1140 free(kernel);
1142 return NULL;
1145 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1147 static void ppcg_kernel_free_wrap(void *user)
1149 struct ppcg_kernel *kernel = user;
1151 ppcg_kernel_free(kernel);
1154 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1155 struct ppcg_kernel_var *var)
1157 int j;
1158 struct gpu_array_tile *tile;
1159 isl_printer *p;
1160 char *name;
1162 var->array = group->array;
1164 tile = group->private_tile;
1165 var->type = ppcg_access_private;
1166 if (!tile) {
1167 tile = group->shared_tile;
1168 var->type = ppcg_access_shared;
1171 p = isl_printer_to_str(ctx);
1172 p = gpu_array_ref_group_print_name(group, p);
1173 var->name = isl_printer_get_str(p);
1174 isl_printer_free(p);
1176 var->size = isl_vec_alloc(ctx, group->array->n_index);
1178 for (j = 0; j < group->array->n_index; ++j)
1179 var->size = isl_vec_set_element_val(var->size, j,
1180 isl_val_copy(tile->bound[j].size));
1183 static int create_kernel_vars(struct ppcg_kernel *kernel)
1185 int i, j, n;
1187 n = 0;
1188 for (i = 0; i < kernel->n_array; ++i) {
1189 struct gpu_local_array_info *array = &kernel->array[i];
1191 for (j = 0; j < array->n_group; ++j) {
1192 struct gpu_array_ref_group *group = array->groups[j];
1193 if (group->private_tile || group->shared_tile)
1194 ++n;
1198 kernel->n_var = n;
1199 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1200 if (!kernel->var)
1201 return -1;
1203 n = 0;
1204 for (i = 0; i < kernel->n_array; ++i) {
1205 struct gpu_local_array_info *array = &kernel->array[i];
1207 for (j = 0; j < array->n_group; ++j) {
1208 struct gpu_array_ref_group *group = array->groups[j];
1209 if (!group->private_tile && !group->shared_tile)
1210 continue;
1211 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1212 ++n;
1216 return 0;
1219 /* Replace "pa" by the zero function defined over the universe domain
1220 * in the space of "pa".
1222 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1224 isl_space *space;
1225 isl_aff *zero;
1227 space = isl_space_domain(isl_pw_aff_get_space(pa));
1228 isl_pw_aff_free(pa);
1229 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1231 return isl_pw_aff_from_aff(zero);
1234 /* The sizes of the arrays on the host that have been computed by
1235 * extract_array_info may depend on the parameters. Use the extra
1236 * constraints on the parameters that are valid at "host_domain"
1237 * to simplify these expressions and store the results in kernel->array.
1239 * We only need these localized bounds for arrays that are accessed
1240 * by the current kernel. If we have found at least one reference group
1241 * then the array is accessed by the kernel. If the array has compound
1242 * elements then we skipped the construction of array reference groups.
1244 * The resulting sizes may be functions that are nowhere defined
1245 * in case the access function cannot possibly access anything inside
1246 * the kernel for some reason. If so, they are replaced by the zero
1247 * function. Since the access function cannot actually access anything,
1248 * there is no harm in printing the array sizes as zero.
1250 static void localize_bounds(struct ppcg_kernel *kernel,
1251 __isl_keep isl_set *host_domain)
1253 int i, j;
1254 isl_set *context;
1256 context = isl_set_copy(host_domain);
1257 context = isl_set_params(context);
1259 for (i = 0; i < kernel->n_array; ++i) {
1260 struct gpu_local_array_info *local = &kernel->array[i];
1261 isl_pw_aff_list *bound;
1262 int n_index;
1264 if (local->n_group == 0 && !local->array->has_compound_element)
1265 continue;
1267 n_index = local->array->n_index;
1268 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1270 for (j = 0; j < n_index; ++j) {
1271 isl_pw_aff *pwaff;
1272 int empty;
1274 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1275 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1276 empty = isl_pw_aff_is_empty(pwaff);
1277 if (empty < 0)
1278 pwaff = isl_pw_aff_free(pwaff);
1279 else if (empty)
1280 pwaff = set_universally_zero(pwaff);
1281 bound = isl_pw_aff_list_add(bound, pwaff);
1284 local->n_index = n_index;
1285 local->bound = bound;
1287 isl_set_free(context);
1290 /* Create the array of gpu_local_array_info structures "array"
1291 * inside "kernel". The number of elements in this array is
1292 * the same as the number of arrays in "prog".
1293 * Initialize the "array" field of each local array to point
1294 * to the corresponding array in "prog".
1296 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1297 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1299 int i;
1300 isl_ctx *ctx;
1302 ctx = isl_set_get_ctx(prog->context);
1303 kernel->array = isl_calloc_array(ctx,
1304 struct gpu_local_array_info, prog->n_array);
1305 if (!kernel->array)
1306 return ppcg_kernel_free(kernel);
1307 kernel->n_array = prog->n_array;
1309 for (i = 0; i < prog->n_array; ++i)
1310 kernel->array[i].array = &prog->array[i];
1312 return kernel;
1315 /* Find the element in gen->stmt that has the given "id".
1316 * Return NULL if no such gpu_stmt can be found.
1318 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1320 int i;
1322 for (i = 0; i < prog->n_stmts; ++i) {
1323 if (id == prog->stmts[i].id)
1324 break;
1327 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1330 void ppcg_kernel_stmt_free(void *user)
1332 int i;
1333 struct ppcg_kernel_stmt *stmt = user;
1335 if (!stmt)
1336 return;
1338 switch (stmt->type) {
1339 case ppcg_kernel_copy:
1340 isl_ast_expr_free(stmt->u.c.index);
1341 isl_ast_expr_free(stmt->u.c.local_index);
1342 break;
1343 case ppcg_kernel_domain:
1344 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1345 break;
1346 case ppcg_kernel_sync:
1347 break;
1350 free(stmt);
1353 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1354 * to "ref_id".
1356 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1357 __isl_keep isl_id *ref_id)
1359 struct gpu_stmt_access *access;
1361 for (access = accesses; access; access = access->next)
1362 if (access->ref_id == ref_id)
1363 return access;
1365 return NULL;
1368 /* Return the index of the array called "name" in the list of arrays.
1370 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1372 int i;
1374 for (i = 0; i < kernel->n_array; ++i)
1375 if (!strcmp(name, kernel->array[i].array->name))
1376 return i;
1378 return -1;
1381 /* Internal data structure for the index and AST expression transformation
1382 * callbacks for pet_stmt_build_ast_exprs.
1384 * "kernel" is the kernel for which are computing AST expressions and
1385 * may be NULL if we are not inside a kernel.
1386 * "accesses" is the list of gpu_stmt_access in the statement.
1387 * "iterator_map" expresses the statement iterators in terms of
1388 * the AST loop iterators.
1389 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1390 * the kernel schedule in terms of the AST loop iterators and
1391 * may be NULL if we are not inside a kernel.
1393 * The following fields are set in transform_index and used in transform_expr.
1394 * "array" is the array that is being accessed.
1395 * "global" is set if the global array is accessed (rather than
1396 * shared/private memory).
1397 * "local_array" refers to information on the array specialized
1398 * to the current kernel.
1400 struct ppcg_transform_data {
1401 struct ppcg_kernel *kernel;
1402 struct gpu_stmt_access *accesses;
1403 isl_pw_multi_aff *iterator_map;
1404 isl_pw_multi_aff *sched2shared;
1406 struct gpu_array_info *array;
1407 int global;
1408 struct gpu_local_array_info *local_array;
1411 /* Return the name of the outer array (of structs) accessed by "access".
1413 static const char *get_outer_array_name(__isl_keep isl_map *access)
1415 isl_space *space;
1416 const char *name;
1418 space = isl_space_range(isl_map_get_space(access));
1419 while (space && isl_space_is_wrapping(space))
1420 space = isl_space_domain(isl_space_unwrap(space));
1421 name = isl_space_get_tuple_name(space, isl_dim_set);
1422 isl_space_free(space);
1424 return name;
1427 /* Return a pointer to the gpu_array_ref_group in "local"
1428 * that contains the reference "access".
1429 * Return NULL if no such group can be found.
1431 static struct gpu_array_ref_group *find_ref_group(
1432 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1434 int i, j;
1436 for (i = 0; i < local->n_group; ++i) {
1437 struct gpu_array_ref_group *group = local->groups[i];
1439 for (j = 0; j < group->n_ref; ++j)
1440 if (group->refs[j] == access)
1441 return group;
1444 return NULL;
1447 /* Index transformation callback for pet_stmt_build_ast_exprs.
1449 * "index" expresses the array indices in terms of statement iterators
1451 * We first reformulate "index" in terms of the AST loop iterators.
1452 * Then we check if we are accessing the global array or
1453 * a shared/private copy. In particular, if we are not inside a kernel
1454 * then we must be accessing a global array.
1455 * In the former case, we simply return
1456 * the updated index. If "index" is an affine expression rather
1457 * than an array access, then we also return the updated index here.
1459 * If no reference groups have been computed for the array,
1460 * then we can only be accessing the global array.
1462 * Otherwise, we apply the tiling to the index.
1463 * This tiling is of the form
1465 * [D -> A] -> T
1467 * where D corresponds to the outer group->depth dimensions of
1468 * the kernel schedule.
1469 * The index is of the form
1471 * L -> A
1473 * We update the tiling to refer to the AST loop iterators
1475 * [L -> A] -> T
1477 * and modify index to keep track of those iterators
1479 * L -> [L -> A]
1481 * Combining these two yields a tiled index expression in terms
1482 * of the AST loop iterators
1484 * L -> T
1486 static __isl_give isl_multi_pw_aff *transform_index(
1487 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1488 void *user)
1490 struct ppcg_transform_data *data = user;
1491 struct gpu_stmt_access *access;
1492 struct gpu_array_ref_group *group;
1493 struct gpu_array_tile *tile;
1494 isl_pw_multi_aff *iterator_map;
1495 int i;
1496 int dim;
1497 const char *name;
1498 isl_space *space;
1499 isl_multi_pw_aff *tiling;
1500 isl_pw_multi_aff *pma;
1501 isl_multi_pw_aff *mpa;
1502 isl_pw_multi_aff *sched2depth;
1504 data->array = NULL;
1506 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1507 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1509 if (!data->kernel)
1510 return index;
1512 access = find_access(data->accesses, ref_id);
1513 if (!access)
1514 return index;
1515 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1516 return index;
1518 name = get_outer_array_name(access->access);
1519 i = find_array_index(data->kernel, name);
1520 if (i < 0)
1521 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1522 "cannot find array",
1523 return isl_multi_pw_aff_free(index));
1524 data->local_array = &data->kernel->array[i];
1525 data->array = data->local_array->array;
1527 group = find_ref_group(data->local_array, access);
1528 if (!group) {
1529 data->global = 1;
1530 return index;
1533 tile = group->private_tile;
1534 if (!tile)
1535 tile = group->shared_tile;
1536 data->global = !tile;
1537 if (!tile)
1538 return index;
1540 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1541 space = isl_space_map_from_set(space);
1542 pma = isl_pw_multi_aff_identity(space);
1543 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1544 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1545 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1546 group->depth, dim - group->depth);
1547 pma = isl_pw_multi_aff_product(sched2depth, pma);
1548 tiling = isl_multi_pw_aff_from_multi_aff(
1549 isl_multi_aff_copy(tile->tiling));
1550 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1552 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1553 space = isl_space_map_from_set(space);
1554 mpa = isl_multi_pw_aff_identity(space);
1555 index = isl_multi_pw_aff_range_product(mpa, index);
1556 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1558 return index;
1561 /* Dereference "expr" by adding an index [0].
1562 * The original "expr" is assumed not to have any indices.
1564 * If "expr" is a member access, then the dereferencing needs
1565 * to be applied to the structure argument of this member access.
1567 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1569 isl_ctx *ctx;
1570 isl_ast_expr *arg0, *res;
1571 isl_ast_expr_list *list;
1573 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1574 if (!arg0)
1575 return isl_ast_expr_free(expr);
1576 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1577 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1578 isl_ast_expr *arg;
1580 arg = isl_ast_expr_get_op_arg(arg0, 0);
1581 arg = dereference(arg);
1582 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1583 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1585 return expr;
1587 isl_ast_expr_free(arg0);
1589 ctx = isl_ast_expr_get_ctx(expr);
1590 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1591 list = isl_ast_expr_list_from_ast_expr(res);
1592 res = isl_ast_expr_get_op_arg(expr, 0);
1593 res = isl_ast_expr_access(res, list);
1594 isl_ast_expr_free(expr);
1596 return res;
1599 /* Linearize the index expression "expr" based on the array bounds
1600 * of "array".
1602 * That is, transform expression
1604 * A[i_0][i_1]...[i_n]
1606 * to
1608 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1610 * where b_0, b_1, ..., b_n are the bounds on the array.
1612 * If the base of "expr" is a member access, then the linearization needs
1613 * to be applied to the structure argument of this member access.
1615 * In the base case, if "expr" has no arguments (other than the name of
1616 * the array), then we are passing an entire array to a function.
1617 * In this case, there is nothing to linearize.
1618 * Note that at this point an expression with no arguments can
1619 * only be an entire array because the scalar case and
1620 * the case of single struct are handled by the caller.
1622 * If the number of specified index expressions in "expr"
1623 * is smaller than the dimension of the accessed array,
1624 * then the missing i_j also do not appear in the linearized expression.
1625 * Furthermore, since such an expression does not refer to a single
1626 * element while the default linearized expression would refer to
1627 * a single element, we return the expression
1629 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1631 * instead. Note that because of the special case handling above,
1632 * we can assume here that here that there is at least one index expression.
1634 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1635 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1637 int i, n;
1638 isl_ctx *ctx;
1639 isl_set *context;
1640 isl_ast_expr *arg0;
1641 isl_ast_expr *res;
1642 isl_ast_expr_list *list;
1643 isl_ast_build *build;
1645 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1646 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1647 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1648 isl_ast_expr *arg;
1650 arg = isl_ast_expr_get_op_arg(arg0, 0);
1651 arg = gpu_local_array_info_linearize_index(array, arg);
1652 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1653 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1655 return expr;
1657 isl_ast_expr_free(arg0);
1659 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1660 return expr;
1662 ctx = isl_ast_expr_get_ctx(expr);
1663 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1664 build = isl_ast_build_from_context(context);
1666 n = isl_ast_expr_get_op_n_arg(expr);
1667 res = isl_ast_expr_get_op_arg(expr, 1);
1668 for (i = 1; i < array->n_index; ++i) {
1669 isl_pw_aff *bound_i;
1670 isl_ast_expr *expr_i;
1672 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1673 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1674 res = isl_ast_expr_mul(res, expr_i);
1676 if (i + 1 >= n)
1677 continue;
1678 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1679 res = isl_ast_expr_add(res, expr_i);
1682 isl_ast_build_free(build);
1684 if (1 + array->n_index > n) {
1685 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1686 } else {
1687 list = isl_ast_expr_list_from_ast_expr(res);
1688 res = isl_ast_expr_get_op_arg(expr, 0);
1689 res = isl_ast_expr_access(res, list);
1692 isl_ast_expr_free(expr);
1694 return res;
1697 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1699 * If the AST expression refers to an array that is not accessed
1700 * at all, then this means the value of the expression is not used,
1701 * so we might as well print zero (NULL pointer) instead.
1703 * If the AST expression refers to a global scalar that is not
1704 * a read-only scalar, then its address was passed to the kernel and
1705 * we need to dereference it.
1707 * If the AST expression refers to an access to a global array,
1708 * then we linearize the access exploiting the bounds in data->local_array.
1710 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1711 __isl_keep isl_id *id, void *user)
1713 struct ppcg_transform_data *data = user;
1715 if (!data->array)
1716 return expr;
1717 if (!data->array->accessed) {
1718 isl_ctx *ctx;
1720 ctx = isl_ast_expr_get_ctx(expr);
1721 isl_ast_expr_free(expr);
1722 return isl_ast_expr_from_val(isl_val_zero(ctx));
1724 if (gpu_array_is_read_only_scalar(data->array))
1725 return expr;
1726 if (!data->global)
1727 return expr;
1728 if (data->array->n_index == 0)
1729 return dereference(expr);
1730 if (!data->array->linearize)
1731 return expr;
1733 return gpu_local_array_info_linearize_index(data->local_array, expr);
1736 /* This function is called for each instance of a user statement
1737 * in the kernel "kernel", identified by "gpu_stmt".
1738 * "kernel" may be NULL if we are not inside a kernel.
1740 * We attach a struct ppcg_kernel_stmt to the "node", containing
1741 * a computed AST expression for each access, through an annotation
1742 * with name "user".
1743 * These AST expressions are computed from iterator_map,
1744 * which expresses the domain
1745 * elements in terms of the generated loops, and sched2shared,
1746 * which expresses the outer shared_schedule_dim dimensions of
1747 * the kernel schedule computed by PPCG in terms of the generated loops.
1749 static __isl_give isl_ast_node *create_domain_leaf(
1750 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1751 __isl_keep isl_ast_build *build, struct gpu_stmt *gpu_stmt)
1753 struct ppcg_transform_data data;
1754 struct ppcg_kernel_stmt *stmt;
1755 isl_ctx *ctx;
1756 isl_id *id;
1757 isl_pw_multi_aff *sched2shared;
1758 isl_map *map;
1759 isl_pw_multi_aff *iterator_map;
1760 isl_union_map *schedule;
1762 if (!node)
1763 return NULL;
1764 ctx = isl_ast_node_get_ctx(node);
1766 stmt = isl_calloc_type(ctx, struct ppcg_kernel_stmt);
1767 if (!stmt)
1768 return isl_ast_node_free(node);
1770 schedule = isl_ast_build_get_schedule(build);
1771 map = isl_map_reverse(isl_map_from_union_map(schedule));
1772 iterator_map = isl_pw_multi_aff_from_map(map);
1773 if (kernel)
1774 sched2shared = compute_sched_to_shared(kernel,
1775 isl_pw_multi_aff_copy(iterator_map));
1776 else
1777 sched2shared = NULL;
1779 stmt->type = ppcg_kernel_domain;
1780 stmt->u.d.stmt = gpu_stmt;
1782 data.kernel = kernel;
1783 data.accesses = stmt->u.d.stmt->accesses;
1784 data.iterator_map = iterator_map;
1785 data.sched2shared = sched2shared;
1786 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1787 build, &transform_index, &data,
1788 &transform_expr, &data);
1790 isl_pw_multi_aff_free(iterator_map);
1791 isl_pw_multi_aff_free(sched2shared);
1793 id = isl_id_alloc(ctx, "user", stmt);
1794 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1795 return isl_ast_node_set_annotation(node, id);
1798 /* This function is called for each statement node in the AST
1799 * for copying to or from shared/private memory.
1800 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1801 * statement to the node.
1802 * The statement name is "read" or "write", depending on whether we are
1803 * reading from global memory or writing to global memory.
1805 * The schedule is of the form
1807 * type[D -> A] -> L
1809 * where D corresponds to the outer group->depth dimensions of
1810 * the kernel schedule, A to the global array and L to the outer
1811 * generated AST schedule.
1812 * We compute the inverse and strip off the type, resulting in
1814 * L -> [D -> A]
1816 * We combine this mapping with on the one hand the projection
1818 * [D -> A] -> A
1820 * and on the other hand the group tiling
1822 * [D -> A] -> T
1824 * resulting in
1826 * L -> A and L -> T
1828 * and store the corresponding expressions in stmt->index and stmt->local_index,
1829 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1831 static __isl_give isl_ast_node *create_access_leaf(struct ppcg_kernel *kernel,
1832 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1833 __isl_keep isl_ast_build *build)
1835 struct ppcg_kernel_stmt *stmt;
1836 struct gpu_array_tile *tile;
1837 isl_id *id;
1838 isl_ast_expr *expr;
1839 isl_space *space;
1840 isl_map *access;
1841 isl_pw_multi_aff *pma, *pma2;
1842 const char *type;
1844 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1845 if (!stmt)
1846 return isl_ast_node_free(node);
1848 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1849 type = isl_map_get_tuple_name(access, isl_dim_in);
1850 stmt->u.c.read = !strcmp(type, "read");
1851 access = isl_map_reverse(access);
1852 pma = isl_pw_multi_aff_from_map(access);
1853 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1855 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1856 space = isl_space_unwrap(space);
1857 pma2 = isl_pw_multi_aff_range_map(space);
1858 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1859 isl_pw_multi_aff_copy(pma));
1860 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1861 stmt->u.c.index = expr;
1863 tile = gpu_array_ref_group_tile(group);
1864 pma2 = isl_pw_multi_aff_from_multi_aff(
1865 isl_multi_aff_copy(tile->tiling));
1866 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1867 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1868 stmt->u.c.local_index = expr;
1870 stmt->u.c.array = group->array;
1871 stmt->u.c.local_array = group->local_array;
1872 stmt->type = ppcg_kernel_copy;
1874 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1875 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1876 return isl_ast_node_set_annotation(node, id);
1879 /* Create a synchronization ppcg_kernel_stmt and
1880 * attach it to the node "node" representing the synchronization.
1882 static __isl_give isl_ast_node *create_sync_leaf(
1883 struct ppcg_kernel *kernel, __isl_take isl_ast_node *node,
1884 __isl_keep isl_ast_build *build)
1886 struct ppcg_kernel_stmt *stmt;
1887 isl_id *id;
1889 stmt = isl_calloc_type(kernel->ctx, struct ppcg_kernel_stmt);
1890 if (!stmt)
1891 return isl_ast_node_free(node);
1893 stmt->type = ppcg_kernel_sync;
1894 id = isl_id_alloc(kernel->ctx, NULL, stmt);
1895 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1896 return isl_ast_node_set_annotation(node, id);
1899 /* Internal data structure for at_domain.
1901 * "prog" represents the entire scop.
1902 * "kernel" points to the kernel to which the current schedule node
1903 * belongs. It is set by before_mark and reset by after_mark.
1904 * It may be NULL if we are outside any kernel.
1906 struct ppcg_at_domain_data {
1907 struct gpu_prog *prog;
1908 struct ppcg_kernel *kernel;
1911 /* This function is called for each instance of a user statement
1912 * in the kernel. This may be one of the original user statements
1913 * or a statement introduced by PPCG.
1915 * We assume that the original user statements only have a name
1916 * and no user pointer. The statements introduced by PPCG
1917 * on the other hand all have a user pointer.
1919 * If the user statement is one of the original user statements
1920 * (one with no user pointer), then we call create_domain_leaf. Otherwise,
1921 * we check if it is a copy or synchronization statement and
1922 * call the appropriate functions.
1923 * Statements that copy an array to/from the device do not need
1924 * any further treatment.
1926 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1927 __isl_keep isl_ast_build *build, void *user)
1929 struct ppcg_at_domain_data *data = user;
1930 isl_ast_expr *expr, *arg;
1931 isl_id *id;
1932 int is_sync;
1933 const char *name;
1934 void *p;
1936 expr = isl_ast_node_user_get_expr(node);
1937 arg = isl_ast_expr_get_op_arg(expr, 0);
1938 id = isl_ast_expr_get_id(arg);
1939 name = isl_id_get_name(id);
1940 p = isl_id_get_user(id);
1941 isl_ast_expr_free(expr);
1942 isl_ast_expr_free(arg);
1944 if (!p) {
1945 struct gpu_stmt *gpu_stmt;
1947 gpu_stmt = find_stmt(data->prog, id);
1948 isl_id_free(id);
1949 if (!gpu_stmt)
1950 isl_die(data->prog->ctx, isl_error_internal,
1951 "statement not found",
1952 return isl_ast_node_free(node));
1954 return create_domain_leaf(data->kernel, node, build, gpu_stmt);
1957 is_sync = gpu_tree_id_is_sync(id, data->kernel);
1958 isl_id_free(id);
1959 if (!prefixcmp(name, "to_device_") || !prefixcmp(name, "from_device_"))
1960 return node;
1961 if (is_sync < 0)
1962 return isl_ast_node_free(node);
1963 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1964 struct gpu_array_ref_group *group = p;
1965 return create_access_leaf(data->kernel, group, node, build);
1967 if (!is_sync)
1968 isl_die(data->prog->ctx, isl_error_internal,
1969 "unknown statement type",
1970 return isl_ast_node_free(node));
1971 return create_sync_leaf(data->kernel, node, build);
1974 /* Given a set of wrapped references "ref", return the corresponding
1975 * access relations based on the tagged access relations "tagged".
1977 * The elements of "ref" are of the form
1979 * [D -> R]
1981 * with D an iteration domains and R a reference.
1982 * The elements of "tagged" are of the form
1984 * [D -> R] -> A
1986 * with A an array.
1988 * Extend "tagged" to include the iteration domain in the range, i.e.,
1990 * [D -> R] -> [D -> A]
1992 * apply the result to "ref" and then unwrap the resulting set
1993 * to obtain relations of the form
1995 * D -> A
1997 static __isl_give isl_union_map *wrapped_reference_to_access(
1998 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
2000 isl_union_map *tag2access;
2002 tag2access = isl_union_map_copy(tagged);
2003 tag2access = isl_union_map_universe(tag2access);
2004 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
2005 tag2access = isl_union_map_domain_map(tag2access);
2006 tag2access = isl_union_map_range_product(tag2access, tagged);
2008 ref = isl_union_set_coalesce(ref);
2009 ref = isl_union_set_apply(ref, tag2access);
2011 return isl_union_set_unwrap(ref);
2014 /* Given an access relation "access" from one or more array reference groups,
2015 * remove those reads if ("read" is 1) or writes (if "read" is 0)
2016 * that are only needed to communicate data within
2017 * the same iteration of "sched".
2018 * "tagged" contains all tagged access relations to all
2019 * the array reference groups accessed by "access" from statement
2020 * instances scheduled by "sched".
2022 * If the access is a read then it is either an element of
2024 * live_in union (range flow)
2026 * where live_in and flow may be overapproximations, or
2027 * it reads an uninitialized value (that is not live-in because
2028 * there is an intermediate kill) or it reads a value that was
2029 * written within the same (compound) statement instance.
2030 * If the access is a write then it is either an element of
2032 * live_out union (domain flow)
2034 * or it writes a value that is never read (and is not live-out
2035 * because of an intermediate kill) or only
2036 * within the same (compound) statement instance.
2037 * In both cases, the access relation is also a subset of
2038 * the group access relation.
2040 * The cases where an uninitialized value is read or a value is written
2041 * that is never read or where the dataflow occurs within a statement
2042 * instance are also considered local and may also be removed.
2044 * Essentially, we compute the intersection of "access" with either
2046 * live_in union (range non-local-flow)
2048 * or
2050 * live_out union (domain non-local-flow)
2052 * We first construct a relation "local"
2054 * [[D -> R] -> [D' -> R']]
2056 * of pairs of domain iterations accessing the reference group
2057 * and references in the group that are coscheduled by "sched".
2059 * If this relation does not intersect the dataflow dependences,
2060 * then there is nothing we can possibly remove, unless the dataflow
2061 * dependences themselves only relate a subset of the accesses.
2062 * In particular, the accesses may not be involved in any dataflow
2063 * dependences, either because they are uninitialized reads/dead writes
2064 * or because the dataflow occurs inside a statement instance.
2066 * Since the computation below may break up the access relation
2067 * into smaller pieces, we only perform the intersection with
2068 * the non-local dependent accesses if the local pairs
2069 * intersect the dataflow dependences. Otherwise, we intersect
2070 * with the universe of the non-local dependent accesses.
2071 * This should at least remove accesses from statements that
2072 * do not participate in any dependences.
2074 * In particular, we remove the "local" dataflow dependences from
2075 * the set of all dataflow dependences.
2076 * Note that if the potential dataflow dependences are an overapproximation
2077 * of the actual dataflow dependences, then the result remains an
2078 * overapproximation of the non-local dataflow dependences.
2079 * Copying to/from global memory is only needed for the references
2080 * in the domain/range of the result or for accesses that are live out/in
2081 * for the entire scop.
2083 * We therefore map the domain/range of the "external" relation
2084 * to the corresponding access relation and take the union with
2085 * the live out/in relation.
2087 static __isl_give isl_union_map *remove_local_accesses(
2088 struct gpu_prog *prog, __isl_take isl_union_map *tagged,
2089 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2090 int read)
2092 int empty;
2093 isl_union_pw_multi_aff *tagger;
2094 isl_union_set *domain;
2095 isl_union_map *local, *external;
2096 isl_union_set *tag_set;
2098 if (isl_union_map_is_empty(access)) {
2099 isl_union_map_free(sched);
2100 isl_union_map_free(tagged);
2101 return access;
2104 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2105 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2106 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
2107 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2109 local = isl_union_map_apply_range(sched,
2110 isl_union_map_reverse(isl_union_map_copy(sched)));
2111 local = isl_union_map_intersect(local,
2112 isl_union_map_copy(prog->scop->tagged_dep_flow));
2114 empty = isl_union_map_is_empty(local);
2116 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2117 external = isl_union_map_intersect_params(external,
2118 isl_set_copy(prog->scop->context));
2119 external = isl_union_map_subtract(external, local);
2121 if (read) {
2122 tag_set = isl_union_map_range(external);
2123 external = wrapped_reference_to_access(tag_set, tagged);
2124 external = isl_union_map_union(external,
2125 isl_union_map_copy(prog->scop->live_in));
2126 } else {
2127 tag_set = isl_union_map_domain(external);
2128 external = wrapped_reference_to_access(tag_set, tagged);
2129 external = isl_union_map_union(external,
2130 isl_union_map_copy(prog->scop->live_out));
2133 if (empty < 0)
2134 external = isl_union_map_free(external);
2135 else if (empty)
2136 external = isl_union_map_universe(external);
2138 access = isl_union_map_intersect(access, external);
2140 return access;
2143 /* Given an access relation "access" from "group", remove those reads
2144 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2145 * communicate data within the same iteration of the schedule at the
2146 * position where the copying of the group is inserted.
2147 * "node" points to this position, i.e., the depth at "node"
2148 * is equal to group->depth.
2150 * We extract a schedule that picks out the iterations of the outer
2151 * group->depth dimensions and call remove_local_accesses.
2153 static __isl_give isl_union_map *remove_local_accesses_group(
2154 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2155 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2156 int read)
2158 isl_union_map *sched, *tagged;
2160 if (isl_union_map_is_empty(access))
2161 return access;
2163 tagged = group_tagged_access_relation(group);
2164 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2166 return remove_local_accesses(kernel->prog, tagged, access, sched, read);
2169 /* This function is called before the AST generator starts traversing
2170 * the schedule subtree of a node with mark "mark".
2172 * If the mark is called "kernel", store the kernel pointer in data->kernel
2173 * for use in at_domain.
2175 static int before_mark(__isl_keep isl_id *mark,
2176 __isl_keep isl_ast_build *build, void *user)
2178 struct ppcg_at_domain_data *data = user;
2180 if (!mark)
2181 return -1;
2182 if (!strcmp(isl_id_get_name(mark), "kernel"))
2183 data->kernel = isl_id_get_user(mark);
2184 return 0;
2187 /* This function is called after the AST generator has finished traversing
2188 * the schedule subtree of a mark node. "node" points to the corresponding
2189 * mark AST node.
2191 * If the mark is called "kernel", then replace "node" by a user node
2192 * that "calls" the kernel, representing the launch of the kernel.
2193 * The original "node" is stored inside the kernel object so that
2194 * it can be used to print the device code.
2195 * Note that this assumes that a kernel is only launched once.
2196 * Also clear data->kernel.
2198 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2199 __isl_keep isl_ast_build *build, void *user)
2201 isl_ctx *ctx;
2202 isl_id *id;
2203 isl_ast_expr *expr;
2204 isl_ast_expr_list *list;
2205 struct ppcg_kernel *kernel;
2206 struct ppcg_at_domain_data *data = user;
2208 ctx = isl_ast_node_get_ctx(node);
2209 id = isl_ast_node_mark_get_id(node);
2210 if (!id)
2211 return isl_ast_node_free(node);
2212 if (strcmp(isl_id_get_name(id), "kernel") || !data->kernel) {
2213 isl_id_free(id);
2214 return node;
2216 kernel = data->kernel;
2217 data->kernel = NULL;
2218 kernel->space = isl_ast_build_get_schedule_space(build);
2219 kernel->tree = isl_ast_node_mark_get_node(node);
2220 isl_ast_node_free(node);
2222 expr = isl_ast_expr_from_id(isl_id_copy(id));
2223 list = isl_ast_expr_list_alloc(ctx, 0);
2224 expr = isl_ast_expr_call(expr, list);
2225 node = isl_ast_node_alloc_user(expr);
2226 node = isl_ast_node_set_annotation(node, id);
2228 return node;
2231 static int update_depth(__isl_keep isl_schedule_node *node, void *user)
2233 int *depth = user;
2234 int node_depth;
2236 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2237 return 1;
2238 node_depth = isl_schedule_node_get_schedule_depth(node);
2239 if (node_depth > *depth)
2240 *depth = node_depth;
2242 return 0;
2245 /* Use isl to generate code for both the host and the device
2246 * from "schedule".
2247 * The device code is marked by "kernel" mark nodes in the schedule tree,
2248 * containing a pointer to a ppcg_kernel object.
2249 * The returned AST only contains the AST for the host code.
2250 * The ASTs for the device code are embedded in ppcg_kernel objects
2251 * attached to the leaf nodes that call "kernel".
2253 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen,
2254 __isl_take isl_schedule *schedule)
2256 struct ppcg_at_domain_data data;
2257 isl_ast_build *build;
2258 isl_ast_node *tree;
2259 isl_id_list *iterators;
2260 int depth;
2262 data.prog = gen->prog;
2263 data.kernel = NULL;
2265 depth = 0;
2266 if (isl_schedule_foreach_schedule_node(schedule, &update_depth,
2267 &depth) < 0)
2268 return NULL;
2269 build = isl_ast_build_alloc(gen->prog->ctx);
2270 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2271 build = isl_ast_build_set_iterators(build, iterators);
2272 build = isl_ast_build_set_at_each_domain(build, &at_domain, &data);
2273 build = isl_ast_build_set_before_each_mark(build, &before_mark, &data);
2274 build = isl_ast_build_set_after_each_mark(build, &after_mark, &data);
2275 if (gen->prog->scop->options->debug->dump_final_schedule)
2276 isl_schedule_dump(schedule);
2277 tree = isl_ast_build_node_from_schedule(build, schedule);
2278 isl_ast_build_free(build);
2280 return tree;
2283 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2285 if (!str)
2286 return NULL;
2287 return isl_union_map_read_from_str(ctx, str);
2290 /* Can "node" be tiled and then mapped to block and thread identifiers?
2291 * That is, is it permutable with at least one coincident dimension?
2293 static int is_permutable(__isl_keep isl_schedule_node *node)
2295 if (!node)
2296 return -1;
2298 if (isl_schedule_node_get_type(node) != isl_schedule_node_band)
2299 return 0;
2300 if (!isl_schedule_node_band_get_permutable(node))
2301 return 0;
2302 if (isl_schedule_node_band_n_member(node) < 1)
2303 return 0;
2304 if (!isl_schedule_node_band_member_get_coincident(node, 0))
2305 return 0;
2307 return 1;
2310 /* A isl_schedule_foreach_schedule_node callback
2311 * for setting *any_permutable and aborting the search
2312 * if "node" is a permutable band with coincident dimensions.
2313 * Otherwise, continue searching.
2315 static int set_permutable(__isl_keep isl_schedule_node *node, void *user)
2317 int *any_permutable = user;
2318 int permutable;
2320 permutable = is_permutable(node);
2321 if (permutable < 0)
2322 return -1;
2323 if (!permutable)
2324 return 1;
2326 *any_permutable = 1;
2328 return -1;
2331 /* Does "schedule" contain any permutable band with at least one coincident
2332 * member?
2334 static int has_any_permutable_node(__isl_keep isl_schedule *schedule)
2336 int any_permutable = 0;
2338 if (isl_schedule_foreach_schedule_node(schedule, &set_permutable,
2339 &any_permutable) < 0 &&
2340 !any_permutable)
2341 return -1;
2343 return any_permutable;
2346 /* Is "node" a leaf or can it be tiled and then mapped to
2347 * block and thread identifiers?
2349 static int is_leaf_or_tilable(__isl_keep isl_schedule_node *node)
2351 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
2352 return 1;
2353 return is_permutable(node);
2356 /* Is "node" the outermost node in its branch that can be tiled
2357 * and then mapped to block and thread identifiers?
2358 * If there are no such nodes in the branch and if "node" is a leaf,
2359 * then it is accepted too.
2361 static int is_outer_tilable(__isl_keep isl_schedule_node *node)
2363 int tilable;
2364 isl_schedule_node *ancestor;
2366 tilable = is_leaf_or_tilable(node);
2367 if (tilable < 0)
2368 return -1;
2369 if (!tilable)
2370 return 0;
2372 tilable = 0;
2373 ancestor = isl_schedule_node_copy(node);
2374 while (isl_schedule_node_has_parent(ancestor)) {
2375 ancestor = isl_schedule_node_parent(ancestor);
2377 tilable = is_permutable(ancestor);
2378 if (tilable < 0 || tilable)
2379 break;
2382 isl_schedule_node_free(ancestor);
2383 return tilable < 0 ? -1 : !tilable;
2386 /* Collect the references to all writes in "group".
2387 * Each reference is represented by a universe set in a space
2389 * [S[i,j] -> R[]]
2391 * with S[i,j] the statement instance space and R[] the array reference.
2393 static __isl_give isl_union_set *group_tagged_writes(
2394 struct gpu_array_ref_group *group)
2396 int i;
2397 isl_space *space;
2398 isl_union_set *writes;
2400 space = isl_map_get_space(group->access);
2401 writes = isl_union_set_empty(space);
2402 for (i = 0; i < group->n_ref; ++i) {
2403 isl_space *space;
2404 isl_set *writes_i;
2406 if (!group->refs[i]->write)
2407 continue;
2409 space = isl_map_get_space(group->refs[i]->tagged_access);
2410 space = isl_space_domain(space);
2411 writes_i = isl_set_universe(space);
2412 writes = isl_union_set_add_set(writes, writes_i);
2415 return writes;
2418 /* Is there any write access in "group" that requires synchronization
2419 * on a write to global memory?
2420 * We currently take into account all writes that would require
2421 * synchronization at the thread level depth, but if the copying
2422 * for this group is performed at an outer level, then we do not
2423 * actually need to take into account dependences at intermediate levels.
2425 static int any_sync_writes_in_group(struct ppcg_kernel *kernel,
2426 struct gpu_array_ref_group *group)
2428 isl_union_set *writes;
2429 int empty, disjoint;
2431 empty = isl_union_set_is_empty(kernel->sync_writes);
2432 if (empty < 0)
2433 return -1;
2434 if (empty)
2435 return 0;
2437 writes = group_tagged_writes(group);
2438 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2439 isl_union_set_free(writes);
2441 return disjoint < 0 ? -1 : !disjoint;
2444 /* Collect the references to all writes in "kernel" that write directly
2445 * to global or shared memory, i.e., that are not mapped to private memory.
2446 * Each reference is represented by a universe set in a space
2448 * [S[i,j] -> R[]]
2450 * with S[i,j] the statement instance space and R[] the array reference.
2452 static __isl_give isl_union_set *collect_non_private_tagged_writes(
2453 struct ppcg_kernel *kernel)
2455 isl_union_set *writes;
2456 int i, j;
2458 writes = isl_union_set_empty(isl_union_set_get_space(kernel->arrays));
2460 for (i = 0; i < kernel->n_array; ++i) {
2461 struct gpu_local_array_info *array = &kernel->array[i];
2463 for (j = 0; j < array->n_group; ++j) {
2464 struct gpu_array_ref_group *group = array->groups[j];
2465 isl_union_set *writes_ij;
2467 if (!group->write)
2468 continue;
2469 if (group->private_tile)
2470 continue;
2471 writes_ij = group_tagged_writes(group);
2472 writes = isl_union_set_union(writes, writes_ij);
2476 return writes;
2479 /* Are there any direct writes to global memory that require
2480 * synchronization?
2482 static int any_global_or_shared_sync_writes(struct ppcg_kernel *kernel)
2484 isl_union_set *writes;
2485 int empty, disjoint;
2487 empty = isl_union_set_is_empty(kernel->sync_writes);
2488 if (empty < 0)
2489 return -1;
2490 if (empty)
2491 return 0;
2493 writes = collect_non_private_tagged_writes(kernel);
2494 disjoint = isl_union_set_is_disjoint(kernel->sync_writes, writes);
2495 isl_union_set_free(writes);
2497 return disjoint < 0 ? -1 : !disjoint;
2500 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2501 * from the elements in "tile_size".
2503 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2504 __isl_keep isl_schedule_node *node, int *tile_size)
2506 int i, n;
2507 isl_ctx *ctx;
2508 isl_space *space;
2509 isl_multi_val *mv;
2511 if (!node)
2512 return NULL;
2514 ctx = isl_schedule_node_get_ctx(node);
2515 space = isl_schedule_node_band_get_space(node);
2516 n = isl_schedule_node_band_n_member(node);
2517 mv = isl_multi_val_zero(space);
2518 for (i = 0; i < n; ++i) {
2519 isl_val *v;
2521 v = isl_val_int_from_si(ctx, tile_size[i]);
2522 mv = isl_multi_val_set_val(mv, i, v);
2525 return mv;
2528 /* Replace the partial schedule S of the band node "node" by
2530 * floor(S/f)
2532 * or
2534 * f * floor(S/f)
2536 * if scale_tile_loops is set, with f the integers in "factor".
2537 * The list that "factor" points to is assumed to contain at least
2538 * as many elements as the number of members in the band.
2540 static __isl_give isl_schedule_node *snap_band_to_sizes(
2541 __isl_take isl_schedule_node *node, int *factor,
2542 struct ppcg_options *options)
2544 isl_multi_val *mv;
2546 mv = construct_band_tiles_sizes(node, factor);
2547 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2548 if (options->scale_tile_loops)
2549 node = isl_schedule_node_band_scale(node,
2550 isl_multi_val_copy(mv));
2551 isl_multi_val_free(mv);
2553 return node;
2556 /* Tile "band" with tile size specified by "sizes".
2558 * Since the tile loops will be mapped to block ids, we forcibly
2559 * turn off tile loop scaling. We may want to enable tile loop scaling
2560 * at some later point, but then we would have to support the detection
2561 * of strides during the mapping to block ids.
2562 * Similarly, since the point loops will be mapped to thread ids,
2563 * we forcibly shift the point loops so that they start at zero.
2565 static __isl_give isl_schedule_node *tile_band(
2566 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2568 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2569 int scale_tile;
2570 int shift_point;
2572 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2573 isl_options_set_tile_scale_tile_loops(ctx, 0);
2574 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2575 isl_options_set_tile_shift_point_loops(ctx, 1);
2577 node = isl_schedule_node_band_tile(node, sizes);
2579 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2580 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2582 return node;
2585 /* Extract the set of parameter values and outer schedule dimensions
2586 * for which any statement instance
2587 * in the kernel inserted at "node" needs to be executed.
2588 * Intersect the set of parameter values derived from the host schedule
2589 * relation with the context of "prog".
2591 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2592 struct gpu_prog *prog)
2594 isl_union_map *schedule;
2595 isl_union_set *schedule_domain;
2596 isl_set *context;
2597 int empty;
2599 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2600 schedule_domain = isl_union_map_range(schedule);
2601 empty = isl_union_set_is_empty(schedule_domain);
2602 if (empty < 0) {
2603 isl_union_set_free(schedule_domain);
2604 return NULL;
2606 if (empty) {
2607 int depth;
2608 isl_space *space;
2610 space = isl_union_set_get_space(schedule_domain);
2611 isl_union_set_free(schedule_domain);
2612 space = isl_space_set_from_params(space);
2613 depth = isl_schedule_node_get_schedule_depth(node);
2614 space = isl_space_add_dims(space, isl_dim_set, depth);
2615 context = isl_set_empty(space);
2616 } else {
2617 context = isl_set_from_union_set(schedule_domain);
2619 context = isl_set_intersect_params(context,
2620 isl_set_copy(prog->context));
2622 return context;
2625 /* Return the set of outer array elements accessed by
2626 * by the statement instance in "domain" in "prog".
2628 static __isl_give isl_union_set *accessed_by_domain(
2629 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2631 isl_union_map *access;
2632 isl_union_set *arrays;
2634 access = isl_union_map_union(isl_union_map_copy(prog->read),
2635 isl_union_map_copy(prog->may_write));
2636 access = isl_union_map_intersect_domain(access, domain);
2637 arrays = isl_union_map_range(access);
2638 arrays = isl_union_set_apply(arrays,
2639 isl_union_map_copy(prog->to_outer));
2641 return arrays;
2644 /* Return the number of outer band members of the band node "node"
2645 * that are marked coincident.
2647 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2649 int i, n;
2651 n = isl_schedule_node_band_n_member(node);
2653 for (i = 0; i < n; ++i)
2654 if (!isl_schedule_node_band_member_get_coincident(node, i))
2655 break;
2657 return i;
2660 /* If the band node "node" has more than "n" members, then split off
2661 * the first "n" of them.
2663 static __isl_give isl_schedule_node *split_band(
2664 __isl_take isl_schedule_node *node, int n)
2666 int dim;
2668 dim = isl_schedule_node_band_n_member(node);
2669 if (n < dim)
2670 node = isl_schedule_node_band_split(node, n);
2672 return node;
2675 /* Scale a band node that may have been split by split_band.
2676 * "sizes" are the scaling factors for the original node.
2677 * "node" either points to the original band node, or the outer
2678 * of the two pieces after splitting.
2680 * If the number of elements in "node" is smaller than the number of
2681 * elements in "sizes", then some splitting has occurred and we split
2682 * "sizes" in the same way.
2684 static __isl_give isl_schedule_node *scale_band(
2685 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2687 int n, dim;
2689 n = isl_multi_val_dim(sizes, isl_dim_set);
2690 dim = isl_schedule_node_band_n_member(node);
2691 if (n > dim) {
2692 isl_multi_val *sizes2;
2694 sizes2 = isl_multi_val_copy(sizes);
2695 sizes = isl_multi_val_drop_dims(sizes,
2696 isl_dim_set, dim, n - dim);
2697 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2698 node = isl_schedule_node_child(node, 0);
2699 node = isl_schedule_node_band_scale(node, sizes2);
2700 node = isl_schedule_node_parent(node);
2703 return isl_schedule_node_band_scale(node, sizes);
2706 /* Return an isl_multi_aff, with as elements the parameters in "space"
2707 * that have the names specified by the elements in "names".
2708 * If (some of) these parameters do not already appear in "space",
2709 * then they are added first.
2711 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2712 __isl_keep isl_id_list *names)
2714 int i, n;
2715 isl_local_space *ls;
2716 isl_multi_aff *ma;
2718 if (!names)
2719 space = isl_space_free(space);
2721 n = isl_id_list_n_id(names);
2722 for (i = 0; i < n; ++i) {
2723 int pos;
2724 isl_id *id;
2726 id = isl_id_list_get_id(names, i);
2727 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2728 if (pos >= 0) {
2729 isl_id_free(id);
2730 continue;
2732 pos = isl_space_dim(space, isl_dim_param);
2733 space = isl_space_add_dims(space, isl_dim_param, 1);
2734 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2736 ma = isl_multi_aff_zero(isl_space_copy(space));
2737 ls = isl_local_space_from_space(isl_space_domain(space));
2738 for (i = 0; i < n; ++i) {
2739 int pos;
2740 isl_id *id;
2741 isl_aff *aff;
2743 id = isl_id_list_get_id(names, i);
2744 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2745 isl_id_free(id);
2746 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2747 isl_dim_param, pos);
2748 ma = isl_multi_aff_set_aff(ma, i, aff);
2750 isl_local_space_free(ls);
2752 return ma;
2755 /* Return constraints on the domain elements that equate a sequence of
2756 * parameters called "names", to the partial schedule
2757 * of "node" modulo the integers in "size".
2758 * The number of elements in the array "size" should be equal
2759 * to the number of elements in "names".
2760 * The number of members of the band node "node" should be smaller
2761 * than or equal to this number. If it is smaller, then the first
2762 * elements of "names" are equated to zero.
2764 static __isl_give isl_union_set *set_schedule_modulo(
2765 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2766 int *size)
2768 int n, n_zero;
2769 isl_space *space;
2770 isl_multi_aff *ma;
2771 isl_multi_union_pw_aff *mupa, *mupa2;
2772 isl_multi_val *mv;
2773 isl_union_set *domain;
2775 if (!node)
2776 return NULL;
2777 n = isl_id_list_n_id(names);
2778 if (n == 0)
2779 return isl_schedule_node_get_universe_domain(node);
2780 n_zero = n - isl_schedule_node_band_n_member(node);
2782 mupa = isl_schedule_node_band_get_partial_schedule(node);
2783 mv = construct_band_tiles_sizes(node, size + n_zero);
2784 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2786 space = isl_multi_union_pw_aff_get_space(mupa);
2787 space = isl_space_params(space);
2788 space = isl_space_set_from_params(space);
2789 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2790 ma = isl_multi_aff_zero(space);
2792 domain = isl_schedule_node_get_universe_domain(node);
2793 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2794 isl_union_set_copy(domain), ma);
2795 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2797 space = isl_multi_union_pw_aff_get_space(mupa);
2798 ma = parameter_vector(space, names);
2800 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2801 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2803 return isl_multi_union_pw_aff_zero_union_set(mupa);
2806 /* Insert a context node at "node" introducing the block and thread
2807 * identifiers along with their bounds, which are stored in kernel->grid_size
2808 * and kernel->block_dim.
2809 * Note that the bounds on the block identifiers may implicitly impose
2810 * constraints on the parameters. A guard needs to be inserted
2811 * in the schedule tree to ensure that those bounds hold at "node".
2812 * This guard is inserted in insert_guard.
2814 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2815 __isl_take isl_schedule_node *node)
2817 isl_set *context;
2819 context = isl_set_universe(isl_set_get_space(kernel->context));
2821 context = add_bounded_parameters_dynamic(context,
2822 kernel->grid_size, kernel->block_ids);
2823 context = add_bounded_parameters(context,
2824 kernel->block_dim, kernel->thread_ids);
2826 node = isl_schedule_node_insert_context(node, context);
2828 return node;
2831 /* Insert a guard that eliminates kernel launches where the kernel
2832 * obviously does not have any work to do.
2834 * In particular, eliminate kernel launches where there are obviously
2835 * zero blocks.
2836 * Use the same block size constraints that are used to create the context
2837 * to ensure that all constraints implicit in the constructed context
2838 * are imposed by the guard.
2840 * Additionally, add other constraints that are valid
2841 * for each executed instance ("context"), as long as this does not result
2842 * in a disjunction.
2844 static __isl_give isl_schedule_node *insert_guard(
2845 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2846 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2848 unsigned nparam, n;
2849 isl_set *guard;
2850 isl_id_list *ids;
2852 guard = isl_set_copy(context);
2853 guard = isl_set_compute_divs(guard);
2854 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2856 nparam = isl_set_dim(guard, isl_dim_param);
2857 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2858 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2859 guard = add_bounded_parameters_dynamic(guard, size, ids);
2860 isl_id_list_free(ids);
2861 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2863 node = isl_schedule_node_insert_guard(node, guard);
2865 return node;
2868 /* Does any array reference group mapping require the band that is mapped
2869 * to threads to be unrolled?
2871 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2873 int i, j;
2875 for (i = 0; i < kernel->n_array; ++i) {
2876 struct gpu_local_array_info *array = &kernel->array[i];
2878 for (j = 0; j < array->n_group; ++j) {
2879 struct gpu_array_ref_group *group = array->groups[j];
2880 if (gpu_array_ref_group_requires_unroll(group))
2881 return 1;
2885 return 0;
2888 /* Mark the given band node "node" for unrolling by the AST generator and
2889 * then sink it to the leaves of the schedule tree.
2890 * All dimensions of "node" are assumed to be coincident, such that this
2891 * sinking is a valid operation.
2893 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2895 int i, n;
2897 n = isl_schedule_node_band_n_member(node);
2898 for (i = 0; i < n; ++i)
2899 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2900 isl_ast_loop_unroll);
2902 node = isl_schedule_node_band_sink(node);
2904 return node;
2907 /* Insert a synchronization node in the schedule tree of "node"
2908 * after the core computation of "kernel" at the level of the band
2909 * that is mapped to threads, except if that level is equal to
2910 * that of the band that is mapped to blocks or if there are no writes
2911 * to global or shared memory in the core computation that require
2912 * synchronization.
2913 * If there are any writes to shared memory and the shared memory
2914 * copying is performed at the same level, then synchronization
2915 * is needed between the core and the copying anyway, so we might
2916 * as well add it here. If the copying is performed at a higher
2917 * level, then different iterations of intermediate schedule dimensions
2918 * may have a different mapping from between shared memory elements and
2919 * threads, such that synchronization is required after the core.
2920 * "node" is assumed to point to the kernel node.
2922 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2923 __isl_take isl_schedule_node *node)
2925 int kernel_depth;
2926 int need_sync;
2928 need_sync = any_global_or_shared_sync_writes(kernel);
2929 if (need_sync < 0)
2930 return isl_schedule_node_free(node);
2931 if (!need_sync)
2932 return node;
2934 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2936 node = gpu_tree_move_down_to_thread(node, kernel->core);
2937 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2938 return gpu_tree_move_up_to_kernel(node);
2940 node = gpu_tree_ensure_following_sync(node, kernel);
2942 node = gpu_tree_move_up_to_kernel(node);
2944 return node;
2947 /* Return a read ("read" is 1) or write access relation for "group"
2948 * with those accesses removed that are only needed to communicate data
2949 * within the subtree of the schedule rooted at "node".
2950 * Furthermore, include the prefix schedule at "node".
2951 * That is, return a relation of the form
2953 * S -> [D -> A]
2955 * with D the outer schedule dimensions at "node".
2957 static __isl_give isl_union_map *anchored_non_local_accesses(
2958 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2959 __isl_take isl_schedule_node *node, int read)
2961 isl_union_map *access;
2962 isl_union_map *prefix;
2964 access = gpu_array_ref_group_access_relation(group, read, !read);
2965 access = remove_local_accesses_group(kernel, group, access, node, read);
2966 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
2967 access = isl_union_map_range_product(prefix, access);
2969 return access;
2972 /* Given an array reference group "group", create a mapping
2974 * read[D -> A] -> [D -> A]
2976 * if "read" is set or
2978 * write[D -> A] -> [D -> A]
2980 * if "read" is not set.
2981 * D corresponds to the outer group->depth dimensions of
2982 * the kernel schedule.
2984 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
2985 struct gpu_array_ref_group *group, int read)
2987 isl_space *space;
2988 isl_id *id;
2990 space = isl_space_copy(group->array->space);
2991 space = isl_space_from_range(space);
2992 space = isl_space_add_dims(space, isl_dim_in, group->depth);
2993 space = isl_space_wrap(space);
2994 space = isl_space_map_from_set(space);
2996 id = isl_id_alloc(ctx, read ? "read" : "write", group);
2997 space = isl_space_set_tuple_id(space, isl_dim_in, id);
2999 return isl_multi_aff_identity(space);
3002 /* If any writes in "group" require synchronization, then make sure
3003 * that there is a synchronization node for "kernel" after the node
3004 * following "node" in a sequence.
3006 * If "shared" is set and no synchronization is needed for
3007 * the writes to global memory, then add synchronization before
3008 * the kernel to protect shared memory from being overwritten
3009 * by the next iteration of the core computation.
3010 * No additional synchronization is needed to protect against
3011 * the next copy into shared memory because each element of
3012 * the shared memory tile is always copied by the same thread.
3014 static __isl_give isl_schedule_node *add_group_write_sync(
3015 __isl_take isl_schedule_node *node, struct ppcg_kernel *kernel,
3016 struct gpu_array_ref_group *group, int shared)
3018 int need_sync;
3020 need_sync = any_sync_writes_in_group(kernel, group);
3021 if (need_sync < 0)
3022 return isl_schedule_node_free(node);
3023 if (need_sync) {
3024 node = isl_schedule_node_parent(node);
3025 node = isl_schedule_node_next_sibling(node);
3026 node = isl_schedule_node_child(node, 0);
3027 node = gpu_tree_ensure_following_sync(node, kernel);
3028 } else if (shared) {
3029 node = isl_schedule_node_parent(node);
3030 node = isl_schedule_node_parent(node);
3031 node = gpu_tree_move_down_to_depth(node, group->depth,
3032 kernel->core);
3033 node = gpu_tree_move_left_to_sync(node, kernel);
3036 return node;
3039 /* Add copy statements to the schedule tree of "node"
3040 * for reading from global memory to private memory (if "read" is set) or
3041 * for writing back from private memory to global memory
3042 * (if "read" is not set) for the array reference group "group" that
3043 * is mapped to private memory.
3044 * On input, "node" points to the kernel node, and it is moved
3045 * back there on output.
3047 * The copies are performed in the order of the array elements.
3048 * The copy statement instances include a reference to the outer
3049 * group->depth dimensions of the kernel schedule for ease of
3050 * combining them with the group tiling.
3052 * That is, the extra schedule is of the form
3054 * type[D -> A] -> A
3056 * where D corresponds to the outer group->depth dimensions of
3057 * the kernel schedule and A to the global array.
3058 * This schedule is unrolled because registers are not addressable.
3060 * The copying is inserted in the schedule tree through an extension
3061 * of the form
3063 * D -> type[D -> A]
3065 * where the extra domain elements type[D -> A] are those accessed
3066 * by the group.
3067 * A filter is inserted on type[D -> A] to ensure that the element
3068 * is read/written by the same thread that needs the element.
3069 * This filter is obtained by applying
3071 * S -> type[D -> A]
3073 * to the thread filter for the core statements.
3075 * The extension is inserted before the core computation in case of a read
3076 * and after the core computation in case of a write.
3077 * In the latter case, we also make sure that there is a synchronization
3078 * node after the write to global memory, unless this write is performed
3079 * at the outer level of the kernel.
3080 * In principle, this synchronization could be inserted higher
3081 * in the schedule tree depending on where the corresponding reads
3082 * from global memory are performed.
3084 static __isl_give isl_schedule_node *add_copies_group_private(
3085 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3086 __isl_take isl_schedule_node *node, int read)
3088 isl_union_map *access;
3089 isl_union_map *prefix;
3090 isl_union_set *domain;
3091 isl_space *space;
3092 isl_multi_aff *from_access;
3093 isl_multi_pw_aff *mpa;
3094 isl_multi_union_pw_aff *mupa;
3095 isl_schedule_node *graft;
3096 isl_union_set *filter;
3097 int kernel_depth;
3098 int empty;
3100 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3101 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3103 access = anchored_non_local_accesses(kernel, group, node, read);
3104 empty = isl_union_map_is_empty(access);
3105 if (empty < 0 || empty) {
3106 isl_union_map_free(access);
3107 if (empty < 0)
3108 return isl_schedule_node_free(node);
3109 return gpu_tree_move_up_to_kernel(node);
3112 from_access = create_from_access(kernel->ctx, group, read);
3113 space = isl_space_domain(isl_multi_aff_get_space(from_access));
3114 access = isl_union_map_preimage_range_multi_aff(access, from_access);
3116 filter = isl_union_set_copy(kernel->thread_filter);
3117 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
3118 filter = isl_union_set_detect_equalities(filter);
3119 filter = isl_union_set_coalesce(filter);
3121 domain = isl_union_map_range(access);
3122 access = isl_union_set_wrapped_domain_map(domain);
3123 access = isl_union_map_reverse(access);
3124 access = isl_union_map_coalesce(access);
3125 graft = isl_schedule_node_from_extension(access);
3127 space = isl_space_map_from_set(space);
3128 mpa = isl_multi_pw_aff_identity(space);
3129 mpa = isl_multi_pw_aff_range_factor_range(mpa);
3130 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3132 graft = isl_schedule_node_child(graft, 0);
3133 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3134 graft = unroll(graft);
3136 graft = isl_schedule_node_insert_filter(graft, filter);
3138 graft = isl_schedule_node_parent(graft);
3140 if (read)
3141 node = isl_schedule_node_graft_before(node, graft);
3142 else {
3143 node = isl_schedule_node_graft_after(node, graft);
3144 if (kernel_depth < group->depth)
3145 node = add_group_write_sync(node, kernel, group, 0);
3148 node = gpu_tree_move_up_to_kernel(node);
3150 return node;
3153 /* Add copy statements to the schedule tree of "node"
3154 * for reading from global memory to shared memory (if "read" is set) or
3155 * for writing back from shared memory to global memory
3156 * (if "read" is not set) for the array reference group "group" that
3157 * is mapped to shared memory.
3158 * On input, "node" points to the kernel node, and it is moved
3159 * back there on output.
3161 * The copies are performed in the order of the corresponding shared
3162 * memory tile.
3163 * The copy statement instances include a reference to the outer
3164 * group->depth dimensions of the kernel schedule for ease of
3165 * combining them with the group tiling.
3167 * If we are performing a read from global memory to shared memory and
3168 * if the array involved is not a scalar, then we copy
3169 * the entire tile to shared memory. This may result in some extra
3170 * elements getting copied, but it should lead to simpler code
3171 * (which means that fewer registers may be needed) and less divergence.
3173 * Otherwise, we only copy the elements that will be read or have been written
3174 * in the kernel.
3176 * That is, the extra schedule is of the form
3178 * type[D -> A] -> T
3180 * where D corresponds to the outer group->depth dimensions of
3181 * the kernel schedule, A to the global array and T is the corresponding
3182 * shared memory tile.
3184 * The copying is inserted in the schedule tree through an extension
3185 * of the form
3187 * D -> type[D -> A]
3189 * where the extra domain elements type[D -> A] are those accessed
3190 * by the group. In the case of read from a non-scalar, this set
3191 * is replaced by the entire shared memory tile.
3193 * A filter is inserted on type[D -> A] to map the copy instances
3194 * to the threads. In particular, the thread identifiers are
3195 * equated to the position inside the shared memory tile (T)
3196 * modulo the block size.
3197 * We try to align the innermost tile dimension with the innermost
3198 * thread identifier (x) as a heuristic to improve coalescing.
3199 * In particular, if the dimension of the tile is greater than
3200 * the dimension of the block, then the schedule mapping to the tile
3201 * is broken up into two pieces and the filter is applied to the inner part.
3202 * If, on the other hand, the dimension of the tile is smaller than
3203 * the dimension of the block, then the initial thread identifiers
3204 * are equated to zero and the remaining thread identifiers are
3205 * matched to the memory tile.
3207 * The extension is inserted before the core computation in case of a read
3208 * and after the core computation in case of a write.
3209 * In the case of a read, we first need to make sure there is some
3210 * synchronization before the core computation such that we can put the read
3211 * from global memory to shared memory before that synchronization.
3212 * This ensures that all threads have finished copying into shared memory
3213 * before the shared memory is used.
3214 * We also need to make sure that there is a synchronization node after
3215 * the core computation to ensure that the next load into shared memory
3216 * only happens after all data has been used. There is no need for
3217 * this synchronization if we are at the outer level since then there
3218 * won't be a next load.
3219 * In the case of a write, we need to make sure there is some synchronization
3220 * after the core computation such taht we can put the write from shared
3221 * memory to global memory after that synchronization.
3222 * Unless we are at the outer level, we also need a synchronization node
3223 * after the write to ensure the data is saved to global memory
3224 * before the next iteration write to the same shared memory.
3225 * It also makes sure the data has arrived in global memory before
3226 * it is read in a subsequent iteration.
3228 static __isl_give isl_schedule_node *add_copies_group_shared(
3229 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3230 __isl_take isl_schedule_node *node, int read)
3232 struct gpu_array_tile *tile;
3233 isl_union_map *access;
3234 isl_union_set *domain;
3235 isl_union_set *sync;
3236 isl_multi_aff *ma;
3237 isl_multi_aff *from_access;
3238 isl_multi_pw_aff *mpa;
3239 isl_multi_union_pw_aff *mupa;
3240 isl_schedule_node *graft;
3241 isl_union_set *filter;
3242 int skip;
3243 int kernel_depth;
3244 int empty;
3246 kernel_depth = isl_schedule_node_get_schedule_depth(node);
3247 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
3249 access = anchored_non_local_accesses(kernel, group, node, read);
3250 empty = isl_union_map_is_empty(access);
3251 if (empty < 0 || empty) {
3252 isl_union_map_free(access);
3253 if (empty < 0)
3254 return isl_schedule_node_free(node);
3255 return gpu_tree_move_up_to_kernel(node);
3258 from_access = create_from_access(kernel->ctx, group, read);
3260 tile = gpu_array_ref_group_tile(group);
3261 ma = isl_multi_aff_copy(tile->tiling);
3262 ma = isl_multi_aff_pullback_multi_aff(ma,
3263 isl_multi_aff_copy(from_access));
3264 mpa = isl_multi_pw_aff_from_multi_aff(ma);
3265 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
3267 domain = isl_union_map_range(access);
3269 if (read && !gpu_array_is_scalar(group->array)) {
3270 isl_map *map;
3271 isl_union_set_free(domain);
3272 map = group_tile(group);
3273 domain = isl_union_set_from_set(isl_map_wrap(map));
3276 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3277 access = isl_union_set_wrapped_domain_map(domain);
3278 access = isl_union_map_reverse(access);
3279 access = isl_union_map_coalesce(access);
3280 graft = isl_schedule_node_from_extension(access);
3282 graft = isl_schedule_node_child(graft, 0);
3284 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3286 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3287 graft = isl_schedule_node_band_split(graft,
3288 tile->n - kernel->n_block);
3289 graft = isl_schedule_node_child(graft, 0);
3291 if (tile->n < kernel->n_block)
3292 skip = kernel->n_block - tile->n;
3293 else
3294 skip = 0;
3295 filter = set_schedule_modulo(graft, kernel->thread_ids,
3296 kernel->block_dim);
3297 if (!kernel->options->wrap)
3298 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3299 kernel->options);
3300 if (tile->n > kernel->n_block && kernel->n_block > 0)
3301 graft = isl_schedule_node_parent(graft);
3302 graft = isl_schedule_node_insert_filter(graft, filter);
3304 while (graft && isl_schedule_node_has_parent(graft))
3305 graft = isl_schedule_node_parent(graft);
3307 if (read) {
3308 if (kernel_depth < group->depth)
3309 node = gpu_tree_ensure_sync_after_core(node, kernel);
3310 node = gpu_tree_move_left_to_sync(node, kernel);
3311 node = isl_schedule_node_graft_before(node, graft);
3312 } else {
3313 node = gpu_tree_move_right_to_sync(node, kernel);
3314 node = isl_schedule_node_graft_after(node, graft);
3315 if (kernel_depth < group->depth)
3316 node = add_group_write_sync(node, kernel, group, 1);
3319 node = gpu_tree_move_up_to_kernel(node);
3321 return node;
3324 /* Check whether the array reference group "group" is mapped to
3325 * private or shared memory and, if so,
3326 * add copy statements to the schedule tree of "node"
3327 * for reading from global memory to private or shared memory
3328 * (if "read" is set) or for writing back from private or shared memory
3329 * to global memory (if "read" is not set) for this group.
3330 * On input, "node" points to the kernel node, and it is moved
3331 * back there on output.
3333 static __isl_give isl_schedule_node *add_copies_group(
3334 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3335 __isl_take isl_schedule_node *node, int read)
3337 if (group->private_tile)
3338 return add_copies_group_private(kernel, group, node, read);
3339 if (group->shared_tile)
3340 return add_copies_group_shared(kernel, group, node, read);
3341 return node;
3344 /* For each array reference group that is mapped to private or shared memory,
3345 * add copy statements to the schedule tree of "node"
3346 * for reading from global memory to private or shared memory
3347 * and for writing back.
3348 * On input, "node" points to the kernel node, and it is moved
3349 * back there on output.
3351 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3352 __isl_take isl_schedule_node *node)
3354 int i, j;
3356 for (i = 0; i < kernel->n_array; ++i) {
3357 struct gpu_local_array_info *array = &kernel->array[i];
3359 for (j = 0; j < array->n_group; ++j) {
3360 struct gpu_array_ref_group *group = array->groups[j];
3362 node = add_copies_group(kernel, group, node, 1);
3363 if (!node)
3364 return NULL;
3365 node = add_copies_group(kernel, group, node, 0);
3366 if (!node)
3367 return NULL;
3371 return node;
3374 /* Mark all dimensions in the current band node atomic.
3376 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3378 int i, n;
3380 n = isl_schedule_node_band_n_member(node);
3381 for (i = 0; i < n; ++i)
3382 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3383 isl_ast_loop_atomic);
3385 return node;
3388 /* Mark "node" atomic, if it is a band node.
3389 * Do the same for all ancestors.
3390 * Return a pointer to "node" (in the updated schedule tree).
3392 static __isl_give isl_schedule_node *atomic_ancestors(
3393 __isl_take isl_schedule_node *node)
3395 int pos;
3397 if (!node)
3398 return NULL;
3399 if (!isl_schedule_node_has_parent(node))
3400 return node;
3402 pos = isl_schedule_node_get_child_position(node);
3403 node = isl_schedule_node_parent(node);
3404 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3405 node = atomic(node);
3406 node = atomic_ancestors(node);
3407 node = isl_schedule_node_child(node, pos);
3409 return node;
3412 /* Collect all write references that require synchronization.
3413 * "node" is assumed to point to the kernel node.
3414 * Each reference is represented by a universe set in a space
3416 * [S[i,j] -> R[]]
3418 * with S[i,j] the statement instance space and R[] the array reference.
3420 * This function should be called before block and thread filters are added.
3422 * Synchronization is needed after a write if there is a subsequent read
3423 * within the same block that may not be performed by the same thread.
3424 * There should not be any dependences between different blocks,
3425 * so we start with the flow dependences within the same kernel invocation
3426 * and we subtract from these those dependences that are mapped
3427 * to the same iteration of the bands where synchronization is inserted.
3428 * We do not remove pairs of instances that are known to map to
3429 * the same thread across different iterations of the intermediate
3430 * bands because the read may be performed by a different thread
3431 * than the one that needs the value if shared memory is involved.
3433 * We also consider all pairs of possible writes that access the same
3434 * memory location and that may be mapped to the same block but not
3435 * to the same iteration of the intermediate bands.
3436 * In theory, it would be possible for one thread to still be in
3437 * a previous iteration of a loop in these bands.
3438 * A write to global memory in this delayed thread could then overwrite
3439 * a write from another thread that has already moved on to
3440 * the next iteration.
3442 * After computing the above writes paired off with reads or writes
3443 * that depend on them, we project onto the domain writes.
3444 * Sychronization is needed after writes to global memory
3445 * through these references.
3447 static __isl_give isl_union_set *compute_sync_writes(
3448 struct ppcg_kernel *kernel, __isl_keep isl_schedule_node *node)
3450 isl_union_map *local;
3451 isl_union_map *may_writes, *shared_access;
3452 isl_union_map *kernel_prefix, *thread_prefix;
3453 isl_union_map *equal;
3454 isl_union_set *wrap;
3455 isl_union_set *domain;
3457 domain = isl_schedule_node_get_universe_domain(node);
3458 kernel_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3459 node = isl_schedule_node_copy(node);
3460 node = gpu_tree_move_down_to_thread(node, kernel->core);
3461 thread_prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3462 isl_schedule_node_free(node);
3464 may_writes = isl_union_map_copy(kernel->prog->scop->tagged_may_writes);
3465 may_writes = isl_union_map_curry(may_writes);
3466 may_writes = isl_union_map_intersect_domain(may_writes, domain);
3467 may_writes = isl_union_map_uncurry(may_writes);
3468 shared_access = isl_union_map_copy(may_writes);
3469 shared_access = isl_union_map_apply_range(shared_access,
3470 isl_union_map_reverse(may_writes));
3472 local = isl_union_map_copy(kernel->prog->scop->tagged_dep_flow);
3473 local = isl_union_map_union(local, shared_access);
3474 local = isl_union_map_zip(local);
3476 equal = isl_union_map_apply_range(kernel_prefix,
3477 isl_union_map_reverse(isl_union_map_copy(kernel_prefix)));
3478 wrap = isl_union_map_wrap(equal);
3479 local = isl_union_map_intersect_domain(local, wrap);
3480 equal = isl_union_map_apply_range(thread_prefix,
3481 isl_union_map_reverse(isl_union_map_copy(thread_prefix)));
3482 wrap = isl_union_map_wrap(equal);
3483 local = isl_union_map_subtract_domain(local, wrap);
3485 local = isl_union_map_zip(local);
3486 local = isl_union_map_universe(local);
3488 return isl_union_map_domain(local);
3491 /* Group the domain elements into a single space, named kernelX,
3492 * with X the kernel sequence number "kernel_id".
3494 static __isl_give isl_schedule_node *group_statements(
3495 __isl_take isl_schedule_node *node, int kernel_id)
3497 char buffer[20];
3498 isl_id *id;
3500 if (!node)
3501 return NULL;
3503 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3504 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3505 return isl_schedule_node_group(node, id);
3508 /* Create a ppcg_kernel representing the domain instances that reach "node"
3509 * and insert a mark node pointing to the ppcg_kernel before "node".
3510 * The band that "node" points to is the band that needs to be mapped
3511 * to block identifiers. The band that needs to be mapped to thread
3512 * identifiers should be marked by a "thread" mark by the caller.
3513 * This mark is removed by this function.
3514 * If "scale" is set, then the band that "node" points to is scaled
3515 * by "sizes".
3517 * Mark all outer band nodes as atomic to ensure each kernel is only
3518 * scheduled once.
3519 * If the domain elements that reach "node" live in more than one space,
3520 * then group the domain elements into a single space, named kernelX,
3521 * with X the kernel sequence number.
3523 * Insert a guard node governing the kernel node to ensure that
3524 * no kernels with zero blocks are launched.
3526 * Insert a context node describing the block and thread
3527 * identifiers inside the kernel mark.
3528 * The context node needs to be inserted after the effective block size
3529 * has been determined such that the bounds on the thread identifiers
3530 * would reflect the effective block size.
3531 * Insert a filter node inside the context node mapping the statement
3532 * instances to block identifiers. In particular, the block identifiers
3533 * are equated to the partial schedule of band that was marked for mapping
3534 * to blocks modulo the grid size.
3535 * Insert a filter node inside the "thread" mark mapping the statement
3536 * instances to thread identifiers. In particular, the thread identifiers
3537 * are equated to the partial schedule of band that was marked for mapping
3538 * to threads modulo the block size.
3540 * Compute array reference groups for all arrays, set the local
3541 * array bounds based on the set of domain instances that reach
3542 * the kernel node, check the total amount of shared memory used
3543 * and compute all group tilings.
3544 * The array reference groups are computed after the block filter
3545 * has been inserted because it affects the mapping to shared or
3546 * private memory. This computation also requires the thread filter
3547 * (in the ppcg_kernel object), but this thread filter should not
3548 * have been added to the schedule tree yet since the computation
3549 * requires the schedule of the band that needs to be mapped to
3550 * threads before the privatization is applied.
3552 * If any array reference group requires the band mapped to threads
3553 * to be unrolled, then we perform the required unrolling.
3555 * We save a copy of the schedule that may influence the mappings
3556 * to shared or private memory in kernel->shared_schedule.
3558 * Finally, we add synchronization and copy statements to the schedule tree,
3559 * remove the "thread" mark and create representations for the local
3560 * variables in the kernel.
3562 * We keep a copy of the isl_id that points to the kernel to ensure
3563 * that the kernel does not get destroyed if the schedule node
3564 * is freed due to some error condition.
3566 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3567 __isl_take isl_schedule_node *node, int scale,
3568 __isl_keep isl_multi_val *sizes)
3570 struct ppcg_kernel *kernel;
3571 isl_id *id;
3572 isl_schedule_node *node_thread;
3573 isl_union_map *host_schedule;
3574 isl_set *host_domain;
3575 isl_union_set *domain;
3576 int single_statement;
3578 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3579 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3580 if (!kernel)
3581 return isl_schedule_node_free(node);
3583 domain = isl_schedule_node_get_domain(node);
3584 single_statement = isl_union_set_n_set(domain) == 1;
3586 kernel->ctx = gen->ctx;
3587 kernel->prog = gen->prog;
3588 kernel->options = gen->options;
3589 kernel->context = extract_context(node, gen->prog);
3590 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3591 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3592 gen->prog);
3593 kernel->n_grid = n_outer_coincidence(node);
3594 node_thread = isl_schedule_node_copy(node);
3595 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3596 node_thread = isl_schedule_node_child(node_thread, 0);
3597 kernel->n_block = n_outer_coincidence(node_thread);
3598 isl_schedule_node_free(node_thread);
3599 kernel->id = gen->kernel_id++;
3600 read_grid_and_block_sizes(kernel, gen);
3602 kernel->sync_writes = compute_sync_writes(kernel, node);
3604 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3605 host_domain = isl_set_from_union_set(isl_union_map_range(
3606 host_schedule));
3608 node = atomic_ancestors(node);
3610 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3611 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3612 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3614 if (!single_statement)
3615 node = group_statements(node, kernel->id);
3617 node = isl_schedule_node_child(node, 0);
3618 node = split_band(node, kernel->n_grid);
3619 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3620 kernel->n_grid, "b");
3621 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3622 kernel->grid_dim);
3623 kernel->grid_size = extract_grid_size(kernel,
3624 isl_union_set_copy(domain));
3625 if (!kernel->options->wrap)
3626 node = snap_band_to_sizes(node, kernel->grid_dim,
3627 kernel->options);
3628 if (scale)
3629 node = scale_band(node, isl_multi_val_copy(sizes));
3630 node = isl_schedule_node_parent(node);
3631 if (!single_statement)
3632 node = isl_schedule_node_parent(node);
3633 node = insert_guard(node, kernel->context, kernel->grid_size,
3634 gen->prog->scop);
3635 node = gpu_tree_move_down_to_thread(node, kernel->core);
3636 node = isl_schedule_node_child(node, 0);
3637 node = split_band(node, kernel->n_block);
3638 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3639 kernel->n_block, "t");
3640 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3641 kernel->block_dim);
3642 extract_block_size(kernel, domain);
3644 node = gpu_tree_move_up_to_kernel(node);
3645 node = isl_schedule_node_child(node, 0);
3646 node = insert_context(kernel, node);
3647 node = isl_schedule_node_child(node, 0);
3648 node = isl_schedule_node_insert_filter(node,
3649 isl_union_set_copy(kernel->block_filter));
3651 node = gpu_tree_move_up_to_kernel(node);
3653 if (gpu_group_references(kernel, node) < 0)
3654 node = isl_schedule_node_free(node);
3655 localize_bounds(kernel, host_domain);
3656 isl_set_free(host_domain);
3658 check_shared_memory_bound(kernel);
3659 compute_group_tilings(kernel);
3661 node = gpu_tree_move_down_to_thread(node, kernel->core);
3662 node = isl_schedule_node_child(node, 0);
3663 if (!kernel->options->wrap)
3664 node = snap_band_to_sizes(node, kernel->block_dim,
3665 kernel->options);
3666 node = isl_schedule_node_insert_filter(node,
3667 isl_union_set_copy(kernel->thread_filter));
3668 if (kernel_requires_unroll(kernel)) {
3669 node = isl_schedule_node_child(node, 0);
3670 node = unroll(node);
3673 node = gpu_tree_move_up_to_thread(node);
3674 kernel->shared_schedule_dim =
3675 isl_schedule_node_get_schedule_depth(node);
3676 kernel->shared_schedule =
3677 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3679 node = gpu_tree_move_up_to_kernel(node);
3681 node = add_sync(kernel, node);
3682 node = add_copies(kernel, node);
3684 node = gpu_tree_move_down_to_thread(node, kernel->core);
3685 node = isl_schedule_node_delete(node);
3687 node = gpu_tree_move_up_to_kernel(node);
3689 if (create_kernel_vars(kernel) < 0)
3690 node = isl_schedule_node_free(node);
3692 if (!single_statement)
3693 node = isl_schedule_node_parent(node);
3694 node = isl_schedule_node_parent(node);
3696 isl_id_free(id);
3697 return node;
3700 /* Insert a zero-dimensional permutable band at "node".
3702 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3703 __isl_take isl_schedule_node *node)
3705 isl_space *space;
3706 isl_schedule *schedule;
3707 isl_union_set *domain;
3708 isl_multi_union_pw_aff *mupa;
3710 schedule = isl_schedule_node_get_schedule(node);
3711 domain = isl_schedule_get_domain(schedule);
3712 space = isl_union_set_get_space(domain);
3713 isl_union_set_free(domain);
3714 isl_schedule_free(schedule);
3716 space = isl_space_set_from_params(space);
3717 mupa = isl_multi_union_pw_aff_zero(space);
3718 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3719 node = isl_schedule_node_band_set_permutable(node, 1);
3721 return node;
3724 /* If "node" is the outermost permutable band that can be mapped to block and
3725 * thread identifiers in its branch (or a leaf with no such outer bands),
3726 * then mark the band as such, attaching a ppcg_kernel to the mark.
3728 * If "node" originally points to a leaf, then insert a zero-dimensional
3729 * permutable band such that we can assume that "node" always
3730 * points to a band node.
3732 * Tile "node" using user specified tile sizes, after splitting the band
3733 * if the number of specified tile sizes is smaller than the dimension
3734 * of the band. Mark the point band of this tiling as the band that
3735 * needs to be mapped to threads.
3736 * Create a kernel representing the domain instances that reach "node" and
3737 * insert a mark node pointing to the ppcg_kernel before the band node.
3739 static __isl_give isl_schedule_node *mark_outer_permutable(
3740 __isl_take isl_schedule_node *node, void *user)
3742 struct gpu_gen *gen = user;
3743 int outer;
3744 int scale;
3745 int tile_len;
3746 int *tile_size;
3747 isl_id *id;
3748 isl_multi_val *sizes;
3750 outer = is_outer_tilable(node);
3751 if (outer < 0)
3752 return isl_schedule_node_free(node);
3753 if (!outer)
3754 return node;
3756 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3757 node = insert_empty_permutable_band(node);
3759 tile_len = isl_schedule_node_band_n_member(node);
3760 tile_size = read_tile_sizes(gen, &tile_len);
3761 if (!tile_size)
3762 return isl_schedule_node_free(node);
3763 if (tile_len < isl_schedule_node_band_n_member(node))
3764 node = isl_schedule_node_band_split(node, tile_len);
3765 sizes = construct_band_tiles_sizes(node, tile_size);
3766 node = tile_band(node, isl_multi_val_copy(sizes));
3767 node = isl_schedule_node_child(node, 0);
3768 id = isl_id_alloc(gen->ctx, "thread", NULL);
3769 node = isl_schedule_node_insert_mark(node, id);
3770 node = isl_schedule_node_parent(node);
3772 scale = gen->options->scale_tile_loops;
3773 node = create_kernel(gen, node, scale, sizes);
3774 isl_multi_val_free(sizes);
3775 free(tile_size);
3777 return node;
3780 /* Does the subtree rooted at "node" have any suitably permutable band nodes?
3781 * That is, does it have any nodes that are permutable and that
3782 * have a least one coincident dimension?
3784 static int subtree_has_permutable_bands(__isl_keep isl_schedule_node *node)
3786 int any_parallelism = 0;
3788 if (isl_schedule_node_foreach_descendant(node, &set_permutable,
3789 &any_parallelism) < 0 &&
3790 !any_parallelism)
3791 return -1;
3793 return any_parallelism;
3796 /* Mark all variables that are accessed by the statement instances in "domain"
3797 * and that are local to "prog" as requiring a declaration in the host code.
3799 static int declare_accessed_local_variables(struct gpu_prog *prog,
3800 __isl_keep isl_union_set *domain)
3802 isl_union_set *arrays;
3803 int i;
3805 if (!ppcg_scop_any_hidden_declarations(prog->scop))
3806 return 0;
3807 arrays = accessed_by_domain(isl_union_set_copy(domain), prog);
3809 for (i = 0; i < prog->n_array; ++i) {
3810 isl_space *space;
3811 isl_set *set;
3812 int empty;
3814 if (!prog->array[i].local)
3815 continue;
3816 space = isl_set_get_space(prog->array[i].extent);
3817 set = isl_union_set_extract_set(arrays, space);
3818 empty = isl_set_plain_is_empty(set);
3819 isl_set_free(set);
3820 if (empty < 0)
3821 goto error;
3822 if (!empty)
3823 prog->array[i].declare_local = 1;
3826 isl_union_set_free(arrays);
3827 return 0;
3828 error:
3829 isl_union_set_free(arrays);
3830 return -1;
3833 /* If "node" points to a set node, then separate its children
3834 * into subtrees that have suitably permutable bands and
3835 * those that do not.
3836 * Adjust the schedule tree in order to execute the second group
3837 * after the first group and return a pointer to the first group,
3838 * assuming there are any such subtrees.
3839 * Mark all local variables in "prog" that are accessed by
3840 * the second group as requiring a declaration on the host.
3842 static __isl_give isl_schedule_node *isolate_permutable_subtrees(
3843 __isl_take isl_schedule_node *node, struct gpu_prog *prog)
3845 isl_space *space;
3846 isl_union_set *filter;
3847 int i, n;
3849 if (!node)
3850 return NULL;
3851 if (isl_schedule_node_get_type(node) != isl_schedule_node_set)
3852 return node;
3854 n = isl_schedule_node_n_children(node);
3855 if (n < 0)
3856 return isl_schedule_node_free(node);
3858 node = isl_schedule_node_child(node, 0);
3859 filter = isl_schedule_node_filter_get_filter(node);
3860 node = isl_schedule_node_parent(node);
3861 space = isl_union_set_get_space(filter);
3862 isl_union_set_free(filter);
3863 filter = isl_union_set_empty(space);
3865 for (i = 0; i < n; ++i) {
3866 int parallelism;
3868 node = isl_schedule_node_child(node, i);
3869 parallelism = subtree_has_permutable_bands(node);
3870 if (parallelism < 0) {
3871 node = isl_schedule_node_free(node);
3872 } else if (!parallelism) {
3873 isl_union_set *filter_i;
3874 filter_i = isl_schedule_node_filter_get_filter(node);
3875 filter = isl_union_set_union(filter, filter_i);
3877 node = isl_schedule_node_parent(node);
3880 if (declare_accessed_local_variables(prog, filter) < 0)
3881 node = isl_schedule_node_free(node);
3882 node = isl_schedule_node_order_after(node, filter);
3884 return node;
3887 /* Replace any reference to an array element in the range of "copy"
3888 * by a reference to all array elements (defined by the extent of the array).
3890 static __isl_give isl_union_map *approximate_copy_out(
3891 __isl_take isl_union_map *copy, struct gpu_prog *prog)
3893 int i;
3894 isl_union_map *res;
3896 res = isl_union_map_empty(isl_union_map_get_space(copy));
3898 for (i = 0; i < prog->n_array; ++i) {
3899 isl_space *space;
3900 isl_set *set;
3901 isl_union_map *copy_i;
3902 isl_union_set *extent, *domain;
3904 space = isl_space_copy(prog->array[i].space);
3905 extent = isl_union_set_from_set(isl_set_universe(space));
3906 copy_i = isl_union_map_copy(copy);
3907 copy_i = isl_union_map_intersect_range(copy_i, extent);
3908 set = isl_set_copy(prog->array[i].extent);
3909 extent = isl_union_set_from_set(set);
3910 domain = isl_union_map_domain(copy_i);
3911 copy_i = isl_union_map_from_domain_and_range(domain, extent);
3912 res = isl_union_map_union(res, copy_i);
3915 isl_union_map_free(copy);
3917 return res;
3920 /* Insert "kernel" marks that point to a ppcg_kernel structure
3921 * in front of all outermost tilable band that (by construction)
3922 * have at least one parallel loop.
3924 static __isl_give isl_schedule_node *mark_kernels(struct gpu_gen *gen,
3925 __isl_take isl_schedule_node *node)
3927 return isl_schedule_node_map_descendant(node,
3928 &mark_outer_permutable, gen);
3931 /* Save the schedule "schedule" to a file called "filename".
3932 * The schedule is printed in block style.
3934 static void save_schedule(__isl_keep isl_schedule *schedule,
3935 const char *filename)
3937 FILE *file;
3938 isl_ctx *ctx;
3939 isl_printer *p;
3941 if (!schedule)
3942 return;
3944 file = fopen(filename, "w");
3945 if (!file) {
3946 fprintf(stderr, "Unable to open '%s' for writing\n", filename);
3947 return;
3949 ctx = isl_schedule_get_ctx(schedule);
3950 p = isl_printer_to_file(ctx, file);
3951 p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
3952 p = isl_printer_print_schedule(p, schedule);
3953 isl_printer_free(p);
3954 fclose(file);
3957 /* Load and return a schedule from a file called "filename".
3959 static __isl_give isl_schedule *load_schedule(isl_ctx *ctx,
3960 const char *filename)
3962 FILE *file;
3963 isl_schedule *schedule;
3965 file = fopen(filename, "r");
3966 if (!file) {
3967 fprintf(stderr, "Unable to open '%s' for reading\n", filename);
3968 return NULL;
3970 schedule = isl_schedule_read_from_file(ctx, file);
3971 fclose(file);
3973 return schedule;
3976 /* Compute an appropriate schedule based on the accesses in
3977 * gen->read and gen->write.
3979 * We use the dependences in gen->prog->scop to compute
3980 * a schedule that has a parallel loop in each tilable band and
3981 * return this schedule.
3983 * If live range reordering is allowed, then we need to make sure
3984 * that live ranges on arrays are not run in parallel since doing
3985 * so would require array expansion. We therefore add the array
3986 * order dependences to the coincidence dependences. Non-zero array
3987 * order dependences will then prevent a schedule dimension from being
3988 * considered parallel.
3989 * Live ranges derived from scalars are allowed to be run in parallel
3990 * since we force the scalars to be mapped to private memory in
3991 * check_scalar_live_ranges.
3992 * If live range reordering is allowed, then the false dependences
3993 * are not added to the validity constraints as that would prevent
3994 * reordering. Instead, the external false dependences that enforce that reads
3995 * from potentially live-in data precede any later write and
3996 * that writes of potentially live-out data follow any other earlier write
3997 * are added to the validity and the coincidence constraints.
3998 * The false dependences are still added to the proximity constraints
3999 * for consistency with the case where live range reordering is not allowed.
4000 * The coincidence constraints then consist of flow dependences,
4001 * external false dependences and array order dependences.
4002 * The independences can be filtered out from the first two sets.
4003 * They have already been filtered out from the array order dependences
4004 * on a per array basis in collect_order_dependences.
4005 * There is no need for a per array handling of the other two sets
4006 * as there should be no flow or external false dependence on local
4007 * variables that can be filtered out.
4009 static __isl_give isl_schedule *compute_schedule(struct gpu_gen *gen)
4011 isl_union_set *domain;
4012 isl_union_map *dep_raw, *dep;
4013 isl_union_map *validity, *proximity, *coincidence;
4014 isl_schedule_constraints *sc;
4015 isl_schedule *schedule;
4017 domain = isl_union_set_copy(gen->prog->scop->domain);
4018 sc = isl_schedule_constraints_on_domain(domain);
4019 sc = isl_schedule_constraints_set_context(sc,
4020 isl_set_copy(gen->prog->scop->context));
4021 if (gen->options->live_range_reordering) {
4022 sc = isl_schedule_constraints_set_conditional_validity(sc,
4023 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
4024 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
4025 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
4026 validity = isl_union_map_copy(proximity);
4027 validity = isl_union_map_union(validity,
4028 isl_union_map_copy(gen->prog->scop->dep_forced));
4029 proximity = isl_union_map_union(proximity,
4030 isl_union_map_copy(gen->prog->scop->dep_false));
4031 coincidence = isl_union_map_copy(validity);
4032 coincidence = isl_union_map_subtract(coincidence,
4033 isl_union_map_copy(gen->prog->scop->independence));
4034 coincidence = isl_union_map_union(coincidence,
4035 isl_union_map_copy(gen->prog->array_order));
4036 } else {
4037 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4038 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4039 dep = isl_union_map_union(dep, dep_raw);
4040 dep = isl_union_map_coalesce(dep);
4041 proximity = isl_union_map_copy(dep);
4042 coincidence = isl_union_map_copy(dep);
4043 validity = dep;
4045 sc = isl_schedule_constraints_set_validity(sc, validity);
4046 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4047 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4049 if (gen->options->debug->dump_schedule_constraints)
4050 isl_schedule_constraints_dump(sc);
4051 schedule = isl_schedule_constraints_compute_schedule(sc);
4053 return schedule;
4056 /* Obtain a schedule for the scop, either by reading it from
4057 * a file or by computing one.
4059 static __isl_give isl_schedule *get_schedule(struct gpu_gen *gen)
4061 isl_schedule *schedule;
4063 if (gen->options->load_schedule_file) {
4064 schedule = load_schedule(gen->ctx,
4065 gen->options->load_schedule_file);
4066 } else {
4067 schedule = compute_schedule(gen);
4068 if (gen->options->save_schedule_file)
4069 save_schedule(schedule,
4070 gen->options->save_schedule_file);
4072 if (gen->options->debug->dump_schedule)
4073 isl_schedule_dump(schedule);
4075 return schedule;
4078 /* Construct the string "<a>_<b>".
4080 static char *concat(isl_ctx *ctx, const char *a, const char *b)
4082 isl_printer *p;
4083 char *s;
4085 p = isl_printer_to_str(ctx);
4086 p = isl_printer_print_str(p, a);
4087 p = isl_printer_print_str(p, "_");
4088 p = isl_printer_print_str(p, b);
4089 s = isl_printer_get_str(p);
4090 isl_printer_free(p);
4092 return s;
4095 /* For each array in "prog" of which an element appears in "accessed" and
4096 * that is not a read only scalar, create a zero-dimensional universe set
4097 * of which the tuple id has name "<prefix>_<name of array>" and a user
4098 * pointer pointing to the array (gpu_array_info).
4100 * If the array is local to "prog", then make sure it will be declared
4101 * in the host code.
4103 * Return the list of these universe sets.
4105 static __isl_give isl_union_set_list *create_copy_filters(struct gpu_prog *prog,
4106 const char *prefix, __isl_take isl_union_set *accessed)
4108 int i;
4109 isl_ctx *ctx;
4110 isl_union_set_list *filters;
4112 ctx = prog->ctx;
4113 filters = isl_union_set_list_alloc(ctx, 0);
4114 for (i = 0; i < prog->n_array; ++i) {
4115 struct gpu_array_info *array = &prog->array[i];
4116 isl_space *space;
4117 isl_set *accessed_i;
4118 int empty;
4119 char *name;
4120 isl_id *id;
4121 isl_union_set *uset;
4123 if (gpu_array_is_read_only_scalar(array))
4124 continue;
4126 space = isl_space_copy(array->space);
4127 accessed_i = isl_union_set_extract_set(accessed, space);
4128 empty = isl_set_plain_is_empty(accessed_i);
4129 isl_set_free(accessed_i);
4130 if (empty < 0) {
4131 filters = isl_union_set_list_free(filters);
4132 break;
4134 if (empty)
4135 continue;
4137 if (array->local)
4138 array->declare_local = 1;
4140 name = concat(ctx, prefix, array->name);
4141 id = name ? isl_id_alloc(ctx, name, array) : NULL;
4142 free(name);
4143 space = isl_space_set_alloc(ctx, 0, 0);
4144 space = isl_space_set_tuple_id(space, isl_dim_set, id);
4145 uset = isl_union_set_from_set(isl_set_universe(space));
4147 filters = isl_union_set_list_add(filters, uset);
4149 isl_union_set_free(accessed);
4151 return filters;
4154 /* Make sure that code for the statements in "filters" that
4155 * copy arrays to or from the device is only generated when
4156 * the size of the corresponding array is positive.
4157 * That is, add a set node underneath "graft" with "filters" as children
4158 * and for each child add a guard that the selects the parameter
4159 * values for which the corresponding array has a positive size.
4160 * The array is available in the user pointer of the statement identifier.
4161 * "depth" is the schedule depth of the position where "graft"
4162 * will be added.
4164 static __isl_give isl_schedule_node *insert_positive_size_guards(
4165 __isl_take isl_schedule_node *graft,
4166 __isl_take isl_union_set_list *filters, int depth)
4168 int i, n;
4170 graft = isl_schedule_node_child(graft, 0);
4171 graft = isl_schedule_node_insert_set(graft, filters);
4172 n = isl_schedule_node_n_children(graft);
4173 for (i = 0; i < n; ++i) {
4174 isl_union_set *filter;
4175 isl_set *domain, *guard;
4176 isl_id *id;
4177 struct gpu_array_info *array;
4179 graft = isl_schedule_node_child(graft, i);
4180 filter = isl_schedule_node_filter_get_filter(graft);
4181 domain = isl_set_from_union_set(filter);
4182 id = isl_set_get_tuple_id(domain);
4183 array = isl_id_get_user(id);
4184 isl_id_free(id);
4185 isl_set_free(domain);
4186 guard = gpu_array_positive_size_guard(array);
4187 guard = isl_set_from_params(guard);
4188 guard = isl_set_add_dims(guard, isl_dim_set, depth);
4189 graft = isl_schedule_node_child(graft, 0);
4190 graft = isl_schedule_node_insert_guard(graft, guard);
4191 graft = isl_schedule_node_parent(graft);
4192 graft = isl_schedule_node_parent(graft);
4194 graft = isl_schedule_node_parent(graft);
4196 return graft;
4199 /* Create a graft for copying arrays to or from the device,
4200 * whenever the size of the array is strictly positive.
4201 * Each statement is called "<prefix>_<name of array>" and
4202 * the identifier has a user pointer pointing to the array.
4203 * The graft will be added at the position specified by "node".
4204 * "copy" contains the array elements that need to be copied.
4205 * Only arrays of which some elements need to be copied
4206 * will have a corresponding statement in the graph.
4207 * Note though that each such statement will copy the entire array.
4209 static __isl_give isl_schedule_node *create_copy_device(struct gpu_prog *prog,
4210 __isl_keep isl_schedule_node *node, const char *prefix,
4211 __isl_take isl_union_set *copy)
4213 int depth;
4214 isl_ctx *ctx;
4215 isl_space *space;
4216 isl_union_set *all, *domain;
4217 isl_union_set_list *filters;
4218 isl_union_map *extension;
4219 isl_schedule_node *graft;
4221 ctx = prog->ctx;
4222 depth = isl_schedule_node_get_schedule_depth(node);
4223 filters = create_copy_filters(prog, prefix, copy);
4224 all = isl_union_set_list_union(isl_union_set_list_copy(filters));
4226 space = depth < 0 ? NULL : isl_space_set_alloc(ctx, 0, depth);
4227 domain = isl_union_set_from_set(isl_set_universe(space));
4228 extension = isl_union_map_from_domain_and_range(domain, all);
4229 graft = isl_schedule_node_from_extension(extension);
4231 if (!filters)
4232 return isl_schedule_node_free(graft);
4233 if (isl_union_set_list_n_union_set(filters) == 0) {
4234 isl_union_set_list_free(filters);
4235 return graft;
4238 return insert_positive_size_guards(graft, filters, depth);
4241 /* Return (the universe spaces of) the arrays that are declared
4242 * inside the scop corresponding to "prog" and for which all
4243 * potential writes inside the scop form a subset of "domain".
4245 static __isl_give isl_union_set *extract_local_accesses(struct gpu_prog *prog,
4246 __isl_keep isl_union_set *domain)
4248 int i;
4249 isl_union_set *local;
4251 local = isl_union_set_empty(isl_union_set_get_space(domain));
4253 for (i = 0; i < prog->n_array; ++i) {
4254 isl_set *set;
4255 isl_union_map *to_outer;
4256 isl_union_map *may_write;
4257 isl_union_set *write_domain;
4258 isl_union_set *fields;
4259 int subset;
4261 if (!prog->array[i].local)
4262 continue;
4264 set = isl_set_universe(isl_space_copy(prog->array[i].space));
4265 to_outer = isl_union_map_copy(prog->to_outer);
4266 to_outer = isl_union_map_intersect_range(to_outer,
4267 isl_union_set_from_set(isl_set_copy(set)));
4268 fields = isl_union_map_domain(to_outer);
4269 may_write = isl_union_map_copy(prog->may_write);
4270 may_write = isl_union_map_intersect_range(may_write, fields);
4271 write_domain = isl_union_map_domain(may_write);
4272 subset = isl_union_set_is_subset(write_domain, domain);
4273 isl_union_set_free(write_domain);
4275 if (subset < 0) {
4276 isl_set_free(set);
4277 return isl_union_set_free(local);
4278 } else if (subset) {
4279 local = isl_union_set_add_set(local, set);
4280 } else {
4281 isl_set_free(set);
4285 return local;
4288 /* Internal data structure for node_may_persist.
4290 * "tagger" maps tagged iteration domains to the corresponding untagged
4291 * iteration domain.
4293 * "may_persist_flow" is the set of all tagged dataflow dependences
4294 * with those dependences removed that either precede or follow
4295 * the kernel launch in a sequence.
4296 * "inner_band_flow" is the set of all tagged dataflow dependences
4297 * that are local to a given iteration of the outer band nodes
4298 * with respect to the current node.
4299 * "local_flow" is equal to "inner_band_flow", except that the domain
4300 * and the range have been intersected with intermediate filters
4301 * on children of sets or sequences.
4303 struct ppcg_may_persist_data {
4304 isl_union_pw_multi_aff *tagger;
4306 isl_union_map *local_flow;
4307 isl_union_map *inner_band_flow;
4308 isl_union_map *may_persist_flow;
4311 /* Update the information in "data" based on the band ancestor "node".
4313 * In particular, we restrict the dependences in data->local_flow
4314 * to those dependence where the source and the sink occur in
4315 * the same iteration of the given band node.
4316 * We also update data->inner_band_flow to the new value of
4317 * data->local_flow.
4319 static int update_may_persist_at_band(__isl_keep isl_schedule_node *node,
4320 struct ppcg_may_persist_data *data)
4322 isl_multi_union_pw_aff *partial;
4323 isl_union_pw_multi_aff *contraction;
4324 isl_union_map *flow;
4326 if (isl_schedule_node_band_n_member(node) == 0)
4327 return 0;
4329 partial = isl_schedule_node_band_get_partial_schedule(node);
4330 contraction = isl_schedule_node_get_subtree_contraction(node);
4331 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4332 contraction);
4333 partial = isl_multi_union_pw_aff_pullback_union_pw_multi_aff(partial,
4334 isl_union_pw_multi_aff_copy(data->tagger));
4336 flow = data->local_flow;
4337 flow = isl_union_map_eq_at_multi_union_pw_aff(flow, partial);
4338 data->local_flow = flow;
4340 isl_union_map_free(data->inner_band_flow);
4341 data->inner_band_flow = isl_union_map_copy(data->local_flow);
4343 return 0;
4346 /* Given a set of local reaching domain elements "domain",
4347 * expand them to the corresponding leaf domain elements using "contraction"
4348 * and insert the array references tags using data->tagger.
4350 static __isl_give isl_union_set *expand_and_tag(
4351 __isl_take isl_union_set *domain,
4352 __isl_take isl_union_pw_multi_aff *contraction,
4353 struct ppcg_may_persist_data *data)
4355 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4356 contraction);
4357 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4358 isl_union_pw_multi_aff_copy(data->tagger));
4359 return domain;
4362 /* Given a filter node that is the child of a set or sequence node,
4363 * restrict data->local_flow to refer only to those elements
4364 * in the filter of the node.
4365 * "contraction" maps the leaf domain elements of the schedule tree
4366 * to the corresponding domain elements at (the parent of) "node".
4368 static int filter_flow(__isl_keep isl_schedule_node *node,
4369 struct ppcg_may_persist_data *data,
4370 __isl_take isl_union_pw_multi_aff *contraction)
4372 isl_union_set *filter;
4373 isl_union_map *flow;
4375 flow = data->local_flow;
4376 filter = isl_schedule_node_filter_get_filter(node);
4377 filter = expand_and_tag(filter, contraction, data);
4378 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(filter));
4379 flow = isl_union_map_intersect_range(flow, filter);
4380 data->local_flow = flow;
4382 return 0;
4385 /* Given a filter node "node", collect the filters on all preceding siblings
4386 * (which are also filter nodes), add them to "filters" and return the result.
4388 static __isl_give isl_union_set *add_previous_filters(
4389 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4391 isl_schedule_node *sibling;
4393 sibling = isl_schedule_node_copy(node);
4394 while (sibling && isl_schedule_node_has_previous_sibling(sibling)) {
4395 isl_union_set *filter;
4397 sibling = isl_schedule_node_previous_sibling(sibling);
4398 filter = isl_schedule_node_filter_get_filter(sibling);
4399 filters = isl_union_set_union(filters, filter);
4401 isl_schedule_node_free(sibling);
4402 if (!sibling)
4403 return isl_union_set_free(filters);
4405 return filters;
4408 /* Given a filter node "node", collect the filters on all following siblings
4409 * (which are also filter nodes), add them to "filters" and return the result.
4411 static __isl_give isl_union_set *add_next_filters(
4412 __isl_take isl_union_set *filters, __isl_keep isl_schedule_node *node)
4414 isl_schedule_node *sibling;
4416 sibling = isl_schedule_node_copy(node);
4417 while (sibling && isl_schedule_node_has_next_sibling(sibling)) {
4418 isl_union_set *filter;
4420 sibling = isl_schedule_node_next_sibling(sibling);
4421 filter = isl_schedule_node_filter_get_filter(sibling);
4422 filters = isl_union_set_union(filters, filter);
4424 isl_schedule_node_free(sibling);
4425 if (!sibling)
4426 return isl_union_set_free(filters);
4428 return filters;
4431 /* Remove those flow dependences from data->may_persist_flow
4432 * that flow between elements of "domain" within the same iteration
4433 * of all outer band nodes.
4434 * "contraction" maps the leaf domain elements of the schedule tree
4435 * to the corresponding elements "domain".
4437 static void remove_external_flow(struct ppcg_may_persist_data *data,
4438 __isl_take isl_union_set *domain,
4439 __isl_keep isl_union_pw_multi_aff *contraction)
4441 isl_union_map *flow;
4443 contraction = isl_union_pw_multi_aff_copy(contraction);
4444 domain = expand_and_tag(domain, contraction, data);
4445 flow = isl_union_map_copy(data->local_flow);
4446 flow = isl_union_map_intersect_domain(flow, isl_union_set_copy(domain));
4447 flow = isl_union_map_intersect_range(flow, domain);
4449 data->may_persist_flow = isl_union_map_subtract(data->may_persist_flow,
4450 flow);
4453 /* Update the information in "data" based on the filter ancestor "node".
4454 * We only need to modify anything if the filter is the child
4455 * of a set or sequence node.
4457 * In the case of a sequence, we remove the dependences between
4458 * statement instances that are both executed either before or
4459 * after the subtree that will be mapped to a kernel, within
4460 * the same iteration of outer bands.
4462 * In both cases, we restrict data->local_flow to the current child.
4464 static int update_may_persist_at_filter(__isl_keep isl_schedule_node *node,
4465 struct ppcg_may_persist_data *data)
4467 enum isl_schedule_node_type type;
4468 isl_schedule_node *parent;
4469 isl_space *space;
4470 isl_union_pw_multi_aff *contraction;
4471 isl_union_set *before, *after, *filter;
4472 isl_union_map *flow;
4474 type = isl_schedule_node_get_parent_type(node);
4475 if (type != isl_schedule_node_sequence && type != isl_schedule_node_set)
4476 return 0;
4478 parent = isl_schedule_node_copy(node);
4479 parent = isl_schedule_node_parent(parent);
4480 contraction = isl_schedule_node_get_subtree_contraction(parent);
4481 isl_schedule_node_free(parent);
4483 if (type == isl_schedule_node_set)
4484 return filter_flow(node, data, contraction);
4486 filter = isl_schedule_node_filter_get_filter(node);
4487 space = isl_union_set_get_space(filter);
4488 isl_union_set_free(filter);
4489 before = isl_union_set_empty(space);
4490 after = isl_union_set_copy(before);
4491 before = add_previous_filters(before, node);
4492 after = add_next_filters(after, node);
4494 remove_external_flow(data, before, contraction);
4495 remove_external_flow(data, after, contraction);
4497 return filter_flow(node, data, contraction);
4500 /* Update the information in "data" based on the ancestor "node".
4502 static int update_may_persist_at(__isl_keep isl_schedule_node *node, void *user)
4504 struct ppcg_may_persist_data *data = user;
4506 switch (isl_schedule_node_get_type(node)) {
4507 case isl_schedule_node_error:
4508 return -1;
4509 case isl_schedule_node_context:
4510 case isl_schedule_node_domain:
4511 case isl_schedule_node_expansion:
4512 case isl_schedule_node_extension:
4513 case isl_schedule_node_guard:
4514 case isl_schedule_node_leaf:
4515 case isl_schedule_node_mark:
4516 case isl_schedule_node_sequence:
4517 case isl_schedule_node_set:
4518 break;
4519 case isl_schedule_node_band:
4520 if (update_may_persist_at_band(node, data) < 0)
4521 return -1;
4522 break;
4523 case isl_schedule_node_filter:
4524 if (update_may_persist_at_filter(node, data) < 0)
4525 return -1;
4526 break;
4529 return 0;
4532 /* Determine the set of array elements that may need to be perserved
4533 * by a kernel constructed from the subtree at "node".
4534 * This includes the set of array elements that may need to be preserved
4535 * by the entire scop (prog->may_persist) and the elements for which
4536 * there is a potential flow dependence that may cross a kernel launch.
4538 * To determine the second set, we start from all flow dependences.
4539 * From this set of dependences, we remove those that cannot possibly
4540 * require data to be preserved by a kernel launch.
4541 * In particular, we consider the following sets of dependences.
4542 * - dependences of which the write occurs inside the kernel.
4543 * If the data is needed outside the kernel, then it will
4544 * be copied out immediately after the kernel launch, so there
4545 * is no need for any special care.
4546 * - dependences of which the read occurs inside the kernel and the
4547 * corresponding write occurs inside the same iteration of the
4548 * outer band nodes. This means that the data is needed in
4549 * the first kernel launch after the write, which is already
4550 * taken care of by the standard copy-in. That is, the data
4551 * do not need to be preserved by any intermediate call to
4552 * the same kernel.
4553 * - dependences of which the write and the read either both occur
4554 * before the kernel launch or both occur after the kernel launch,
4555 * within the same iteration of the outer band nodes with respect
4556 * to the sequence that determines the ordering of the dependence
4557 * and the kernel launch. Such flow dependences cannot cross
4558 * any kernel launch.
4560 * For the remaining (tagged) dependences, we take the domain
4561 * (i.e., the tagged writes) and apply the tagged access relation
4562 * to obtain the accessed data elements.
4563 * These are then combined with the elements that may need to be
4564 * preserved by the entire scop.
4566 static __isl_give isl_union_set *node_may_persist(
4567 __isl_keep isl_schedule_node *node, struct gpu_prog *prog)
4569 struct ppcg_may_persist_data data;
4570 isl_schedule_node *root;
4571 isl_union_pw_multi_aff *contraction;
4572 isl_union_set *domain;
4573 isl_union_set *persist;
4574 isl_union_map *flow, *local_flow;
4576 data.tagger = prog->scop->tagger;
4578 flow = isl_union_map_copy(prog->scop->tagged_dep_flow);
4579 data.local_flow = isl_union_map_copy(flow);
4580 data.inner_band_flow = isl_union_map_copy(flow);
4581 data.may_persist_flow = flow;
4582 if (isl_schedule_node_foreach_ancestor_top_down(node,
4583 &update_may_persist_at, &data) < 0)
4584 data.may_persist_flow =
4585 isl_union_map_free(data.may_persist_flow);
4586 flow = data.may_persist_flow;
4587 isl_union_map_free(data.local_flow);
4589 domain = isl_schedule_node_get_domain(node);
4590 contraction = isl_schedule_node_get_subtree_contraction(node);
4591 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4592 contraction);
4593 domain = isl_union_set_preimage_union_pw_multi_aff(domain,
4594 isl_union_pw_multi_aff_copy(data.tagger));
4595 flow = isl_union_map_subtract_domain(flow, isl_union_set_copy(domain));
4596 local_flow = data.inner_band_flow;
4597 local_flow = isl_union_map_intersect_range(local_flow, domain);
4598 flow = isl_union_map_subtract(flow, local_flow);
4600 persist = isl_union_map_domain(flow);
4601 persist = isl_union_set_apply(persist,
4602 isl_union_map_copy(prog->scop->tagged_may_writes));
4603 persist = isl_union_set_union(persist,
4604 isl_union_set_copy(prog->may_persist));
4606 return persist;
4609 /* Add nodes for copying outer arrays in and out of the device
4610 * before and after the subtree "node", which contains one or more kernels.
4611 * "domain" contains the original reaching domain elements before
4612 * the kernels were created, i.e., before the contraction that
4613 * may have been performed in creating the kernels has been applied.
4614 * "prefix" contains the prefix schedule at that point, in terms
4615 * of the same original reaching domain elements.
4617 * We first compute the sets of outer array elements that need
4618 * to be copied in and out and then graft in the nodes for
4619 * performing this copying.
4621 * In particular, for each array that is possibly written anywhere in
4622 * the subtree "node" and that may be used after "node"
4623 * or that may be visible outside the corresponding scop,
4624 * we copy out its entire extent.
4626 * Any array elements that is read without first being written inside
4627 * the subtree "node" needs to be copied in.
4628 * Furthermore, if there are any array elements that
4629 * are copied out, but that may not be written inside "node, then
4630 * they also need to be copied in to ensure that the value after execution
4631 * is the same as the value before execution, at least for those array
4632 * elements that may have their values preserved by the scop or that
4633 * may be written before "node" and read after "node".
4634 * In case the array elements are structures, we need to take into
4635 * account that all members of the structures need to be written
4636 * by "node" before we can avoid copying the data structure in.
4638 * Note that the may_write relation is intersected with the domain,
4639 * which has been intersected with the context.
4640 * This helps in those cases where the arrays are declared with a fixed size,
4641 * while the accesses are parametric and the context assigns a fixed value
4642 * to the parameters.
4644 * If an element from a local array is read without first being written,
4645 * then there is no point in copying it in since it cannot have been
4646 * written prior to the scop. Warn about the uninitialized read instead.
4648 static __isl_give isl_schedule_node *add_to_from_device(
4649 __isl_take isl_schedule_node *node, __isl_take isl_union_set *domain,
4650 __isl_take isl_union_map *prefix, struct gpu_prog *prog)
4652 isl_union_set *local;
4653 isl_union_set *to_device, *from_device, *may_persist;
4654 isl_union_map *may_write, *must_write, *copy_out, *not_written;
4655 isl_union_map *read, *copy_in;
4656 isl_union_map *tagged;
4657 isl_union_map *local_uninitialized;
4658 isl_schedule_node *graft;
4660 tagged = isl_union_map_copy(prog->scop->tagged_reads);
4661 tagged = isl_union_map_union(tagged,
4662 isl_union_map_copy(prog->scop->tagged_may_writes));
4664 may_write = isl_union_map_copy(prog->may_write);
4665 may_write = isl_union_map_intersect_domain(may_write,
4666 isl_union_set_copy(domain));
4667 may_write = remove_local_accesses(prog,
4668 isl_union_map_copy(tagged), may_write,
4669 isl_union_map_copy(prefix), 0);
4670 may_write = isl_union_map_apply_range(may_write,
4671 isl_union_map_copy(prog->to_outer));
4672 may_write = isl_union_map_apply_domain(may_write,
4673 isl_union_map_copy(prefix));
4674 may_write = approximate_copy_out(may_write, prog);
4675 copy_out = isl_union_map_copy(may_write);
4676 may_write = isl_union_map_apply_range(may_write,
4677 isl_union_map_copy(prog->to_inner));
4678 must_write = isl_union_map_copy(prog->must_write);
4679 must_write = isl_union_map_apply_domain(must_write,
4680 isl_union_map_copy(prefix));
4681 may_persist = node_may_persist(node, prog);
4682 may_write = isl_union_map_intersect_range(may_write, may_persist);
4683 not_written = isl_union_map_subtract(may_write, must_write);
4685 local = extract_local_accesses(prog, domain);
4686 read = isl_union_map_copy(prog->read);
4687 read = isl_union_map_intersect_domain(read, domain);
4688 read = remove_local_accesses(prog, tagged, read,
4689 isl_union_map_copy(prefix), 1);
4690 local = isl_union_set_apply(local, isl_union_map_copy(prog->to_inner));
4691 local_uninitialized = isl_union_map_copy(prog->scop->live_in);
4692 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4693 local);
4694 local_uninitialized = isl_union_map_intersect(local_uninitialized,
4695 isl_union_map_copy(read));
4696 if (!isl_union_map_is_empty(local_uninitialized)) {
4697 fprintf(stderr,
4698 "possibly uninitialized reads (not copied in):\n");
4699 isl_union_map_dump(local_uninitialized);
4701 read = isl_union_map_subtract(read, local_uninitialized);
4702 read = isl_union_map_apply_domain(read, prefix);
4703 copy_in = isl_union_map_union(read, not_written);
4704 copy_in = isl_union_map_apply_range(copy_in,
4705 isl_union_map_copy(prog->to_outer));
4707 graft = create_copy_device(prog, node, "to_device",
4708 isl_union_map_range(copy_in));
4709 node = isl_schedule_node_graft_before(node, graft);
4710 graft = create_copy_device(prog, node, "from_device",
4711 isl_union_map_range(copy_out));
4712 node = isl_schedule_node_graft_after(node, graft);
4714 return node;
4717 /* Update "schedule" for mapping to a GPU device.
4719 * In particular, insert a context node, create kernels for
4720 * each outermost tilable band and introduce node for copying array
4721 * in and out of the device.
4722 * If the child of the initial root points to a set node,
4723 * then children of this node that do not contain any tilable bands
4724 * are separated from the other children and are not mapped to
4725 * the device.
4727 static __isl_give isl_schedule *map_to_device(struct gpu_gen *gen,
4728 __isl_take isl_schedule *schedule)
4730 isl_schedule_node *node;
4731 isl_set *context;
4732 isl_union_set *domain;
4733 isl_union_map *prefix;
4735 context = isl_set_copy(gen->prog->context);
4736 context = isl_set_from_params(context);
4737 schedule = isl_schedule_insert_context(schedule, context);
4739 node = isl_schedule_get_root(schedule);
4740 isl_schedule_free(schedule);
4741 node = isl_schedule_node_child(node, 0);
4742 if (isl_schedule_node_get_type(node) == isl_schedule_node_context)
4743 node = isl_schedule_node_child(node, 0);
4744 node = isolate_permutable_subtrees(node, gen->prog);
4745 domain = isl_schedule_node_get_domain(node);
4746 prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4747 node = mark_kernels(gen, node);
4748 node = add_to_from_device(node, domain, prefix, gen->prog);
4749 schedule = isl_schedule_node_get_schedule(node);
4750 isl_schedule_node_free(node);
4752 return schedule;
4755 /* Internal data structure for extract_access.
4756 * "next_access" points to the end of a linked list that is extended
4757 * by extract_access.
4758 * "single_expression" is set if the access expressions belong to
4759 * an expression statement (i.e., a statement without internal control).
4760 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4762 struct ppcg_extract_access_data {
4763 struct gpu_stmt_access **next_access;
4764 int single_expression;
4765 isl_union_map *any_to_outer;
4768 /* Given a tagged access relation to a single array "tagged", extract it
4769 * as a map, taking into account that the input may be empty.
4770 * If the access relation is empty, then it does not contain
4771 * any space information, so we try to recover it from the index
4772 * expression.
4773 * The space of the index expression is of the form I -> A,
4774 * with I the statement instances and A the array, or [I -> F] -> A,
4775 * with F the filters corresponding to arguments.
4776 * We first drop F, if present, obtaining I -> A.
4777 * Then we construct I -> R, with R the reference tag,
4778 * combine the two into I -> [R -> A] and uncurry to obtain
4779 * the final result [I -> R] -> A.
4780 * Note that the index expression may have a lower dimension
4781 * than that of the array, but this dimension is not used
4782 * if the access relation is empty.
4784 static __isl_give isl_map *extract_single_tagged_access(
4785 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4787 int empty;
4788 isl_id *id;
4789 isl_space *space, *space2;
4790 isl_multi_pw_aff *index;
4792 empty = isl_union_map_is_empty(tagged);
4793 if (empty < 0)
4794 goto error;
4795 if (!empty)
4796 return isl_map_from_union_map(tagged);
4797 isl_union_map_free(tagged);
4799 index = pet_expr_access_get_index(expr);
4800 space = isl_multi_pw_aff_get_space(index);
4801 isl_multi_pw_aff_free(index);
4802 if (isl_space_domain_is_wrapping(space))
4803 space = isl_space_domain_factor_domain(space);
4804 space2 = isl_space_copy(space);
4805 space2 = isl_space_from_domain(isl_space_domain(space));
4806 id = pet_expr_access_get_ref_id(expr);
4807 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4808 space = isl_space_range_product(space2, space);
4809 space = isl_space_uncurry(space);
4811 return isl_map_empty(space);
4812 error:
4813 isl_union_map_free(tagged);
4814 return NULL;
4817 /* Extract a gpu_stmt_access from "expr", append it to the list
4818 * that ends in *data->next_access and update the end of the list.
4819 * If the access expression performs a write, then it is considered
4820 * exact only if it appears in a single expression statement and
4821 * if its may access relation is equal to its must access relation.
4823 * The combined set of may accesses may be union if member accesses
4824 * are involved, but the entire set is derived from a single reference and
4825 * therefore from a single index expression. These accesses therefore
4826 * all map to the same outer array.
4828 static int extract_access(__isl_keep pet_expr *expr, void *user)
4830 struct ppcg_extract_access_data *data = user;
4831 isl_union_map *tagged;
4832 struct gpu_stmt_access *access;
4833 isl_ctx *ctx = pet_expr_get_ctx(expr);
4834 isl_multi_pw_aff *index;
4836 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4837 assert(access);
4838 access->next = NULL;
4839 access->read = pet_expr_access_is_read(expr);
4840 access->write = pet_expr_access_is_write(expr);
4841 tagged = pet_expr_access_get_tagged_may_read(expr);
4842 tagged = isl_union_map_union(tagged,
4843 pet_expr_access_get_tagged_may_write(expr));
4844 tagged = isl_union_map_apply_range(tagged,
4845 isl_union_map_copy(data->any_to_outer));
4846 if (!access->write) {
4847 access->exact_write = 1;
4848 } else if (!data->single_expression) {
4849 access->exact_write = 0;
4850 } else {
4851 isl_union_map *must, *may;
4852 may = isl_union_map_copy(tagged);
4853 may = isl_union_map_domain_factor_domain(may);
4854 must = pet_expr_access_get_must_write(expr);
4855 access->exact_write = isl_union_map_is_equal(must, may);
4856 isl_union_map_free(must);
4857 isl_union_map_free(may);
4859 index = pet_expr_access_get_index(expr);
4860 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4861 isl_multi_pw_aff_free(index);
4862 access->ref_id = pet_expr_access_get_ref_id(expr);
4863 access->tagged_access = extract_single_tagged_access(tagged, expr);
4864 access->access = isl_map_copy(access->tagged_access);
4865 access->access = isl_map_domain_factor_domain(access->access);
4867 *data->next_access = access;
4868 data->next_access = &(*data->next_access)->next;
4870 if (!access->access)
4871 return -1;
4873 return 0;
4876 /* Construct a linked list of gpu_stmt_access objects,
4877 * one for each access expression in the statement body.
4878 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4880 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4881 __isl_keep isl_union_map *any_to_outer)
4883 struct ppcg_extract_access_data data;
4885 stmt->accesses = NULL;
4886 data.next_access = &stmt->accesses;
4887 data.single_expression =
4888 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4889 data.any_to_outer = any_to_outer;
4890 return pet_tree_foreach_access_expr(stmt->stmt->body,
4891 &extract_access, &data);
4894 /* Return an array of gpu_stmt representing the statements in "scop".
4896 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4897 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4899 int i;
4900 struct gpu_stmt *stmts;
4902 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4903 if (!stmts)
4904 return NULL;
4906 for (i = 0; i < scop->pet->n_stmt; ++i) {
4907 struct gpu_stmt *s = &stmts[i];
4909 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4910 s->stmt = scop->pet->stmts[i];
4911 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4912 return free_stmts(stmts, i + 1);
4915 return stmts;
4918 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4920 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4922 struct gpu_gen *gen = user;
4924 return gen->print(p, gen->prog, gen->tree, &gen->types,
4925 gen->print_user);
4928 /* Generate CUDA code for "scop" and print it to "p".
4929 * After generating an AST for the transformed scop as explained below,
4930 * we call "gen->print" to print the AST in the desired output format
4931 * to "p".
4933 * If it turns out that it does not make sense to generate GPU code,
4934 * then we generate CPU code instead.
4936 * The GPU code is generated in a context where at least one
4937 * statement instance is executed. The corresponding guard (if any) is printed
4938 * around the entire generated GPU code, except for the declaration
4939 * of the arrays that are visible outside of the scop and that therefore
4940 * cannot be declared inside the body of any possible guard.
4942 * We first compute a schedule that respects the dependences
4943 * of the original program and select the outermost bands
4944 * of tilable dimensions that have at least one parallel loop.
4945 * If the --load-schedule is specified, then the loaded schedule
4946 * is used instead of a computed schedule.
4948 * Each of these bands B is then tiled according to "tile" sizes, resulting
4949 * in two nested bands, with a kernel marker on top
4957 * We then split off at most 2 parallel dimensions from the T band and
4958 * at most 3 parallel dimension from the P band
4963 * T1
4965 * T2
4967 * P1
4969 * P2
4971 * A filter is introduced in front of T1 that maps the domain instances
4972 * to block identifiers. Similarly, a filter is introduced in front of P1
4973 * that maps the domain instances to thread identifiers.
4975 * For each iteration of the T2 band and for each array, we compute
4976 * the array elements accessed by that iteration, construct a rectangular
4977 * box around it and shift it to the origin. The result is used
4978 * as shared memory for the array.
4980 * Copying and synchronization statements are added to this schedule tree.
4981 * In principle, these are added in front of the P1 band, but some of
4982 * them may get hoisted up to higher levels.
4984 * The entire AST is then generated from the single resulting schedule tree.
4985 * During the generation the subtrees at kernel nodes (K) are saved
4986 * aside and replaced by kernel calls. The result is printed as host code
4987 * while the saved subtrees are printed as device code.
4989 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4990 struct gpu_gen *gen, struct ppcg_scop *scop,
4991 struct ppcg_options *options)
4993 struct gpu_prog *prog;
4994 isl_ctx *ctx;
4995 isl_set *context, *guard;
4996 isl_schedule *schedule;
4997 int any_permutable;
4999 if (!scop)
5000 return isl_printer_free(p);
5002 ctx = isl_printer_get_ctx(p);
5003 prog = gpu_prog_alloc(ctx, scop);
5004 if (!prog)
5005 return isl_printer_free(p);
5007 context = isl_set_copy(prog->context);
5008 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5009 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5011 gen->prog = prog;
5012 schedule = get_schedule(gen);
5014 any_permutable = has_any_permutable_node(schedule);
5015 if (any_permutable < 0 || !any_permutable) {
5016 isl_set_free(context);
5017 isl_set_free(guard);
5018 if (any_permutable < 0)
5019 p = isl_printer_free(p);
5020 else
5021 p = print_cpu(p, scop, options);
5022 isl_schedule_free(schedule);
5023 } else {
5024 schedule = map_to_device(gen, schedule);
5025 gen->tree = generate_code(gen, schedule);
5026 p = ppcg_print_exposed_declarations(p, prog->scop);
5027 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5028 isl_ast_node_free(gen->tree);
5031 gpu_prog_free(prog);
5033 return p;
5036 /* Wrapper around generate for use as a ppcg_transform callback.
5038 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5039 struct ppcg_scop *scop, void *user)
5041 struct gpu_gen *gen = user;
5043 return generate(p, gen, scop, gen->options);
5046 /* Transform the code in the file called "input" by replacing
5047 * all scops by corresponding GPU code and write the results to "out".
5049 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5050 struct ppcg_options *options,
5051 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5052 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5053 struct gpu_types *types, void *user), void *user)
5055 struct gpu_gen gen;
5056 int r;
5057 int i;
5059 gen.ctx = ctx;
5060 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5061 gen.options = options;
5062 gen.kernel_id = 0;
5063 gen.print = print;
5064 gen.print_user = user;
5065 gen.types.n = 0;
5066 gen.types.name = NULL;
5068 if (options->debug->dump_sizes) {
5069 isl_space *space = isl_space_params_alloc(ctx, 0);
5070 gen.used_sizes = isl_union_map_empty(space);
5073 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5075 if (options->debug->dump_sizes) {
5076 isl_union_map_dump(gen.used_sizes);
5077 isl_union_map_free(gen.used_sizes);
5080 isl_union_map_free(gen.sizes);
5081 for (i = 0; i < gen.types.n; ++i)
5082 free(gen.types.name[i]);
5083 free(gen.types.name);
5085 return r;
5088 /* Compute the set of inner array elements that may have their values
5089 * preserved by "prog". In particular, collect the array elements of
5090 * arrays that are not local to "prog" and remove those elements that
5091 * are definitely killed or definitely written by "prog".
5093 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5095 int i;
5096 isl_union_set *may_persist, *killed;
5097 isl_union_map *must_kill;
5099 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5100 for (i = 0; i < prog->n_array; ++i) {
5101 isl_set *extent;
5103 if (prog->array[i].local)
5104 continue;
5106 extent = isl_set_copy(prog->array[i].extent);
5107 may_persist = isl_union_set_add_set(may_persist, extent);
5110 may_persist = isl_union_set_intersect_params(may_persist,
5111 isl_set_copy(prog->context));
5112 may_persist = isl_union_set_apply(may_persist,
5113 isl_union_map_copy(prog->to_inner));
5114 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5115 killed = isl_union_map_range(must_kill);
5116 must_kill = isl_union_map_copy(prog->must_write);
5117 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
5119 may_persist = isl_union_set_subtract(may_persist, killed);
5120 return may_persist;
5123 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5125 struct gpu_prog *prog;
5126 isl_space *space;
5127 isl_map *id;
5129 if (!scop)
5130 return NULL;
5132 prog = isl_calloc_type(ctx, struct gpu_prog);
5133 assert(prog);
5135 prog->ctx = ctx;
5136 prog->scop = scop;
5137 prog->context = isl_set_copy(scop->context);
5138 prog->n_stmts = scop->pet->n_stmt;
5139 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5140 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5141 space = isl_union_map_get_space(prog->any_to_outer);
5142 space = isl_space_set_from_params(space);
5143 space = isl_space_add_dims(space, isl_dim_set, 1);
5144 space = isl_space_map_from_set(space);
5145 id = isl_map_identity(space);
5146 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
5147 prog->stmts = extract_stmts(ctx, scop,
5148 prog->context, prog->any_to_outer);
5149 prog->read = isl_union_map_copy(scop->reads);
5150 prog->may_write = isl_union_map_copy(scop->may_writes);
5151 prog->must_write = isl_union_map_copy(scop->must_writes);
5152 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
5153 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
5154 prog->to_outer = isl_union_map_copy(prog->to_inner);
5155 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5157 if (!prog->stmts)
5158 return gpu_prog_free(prog);
5160 if (collect_array_info(prog) < 0)
5161 return gpu_prog_free(prog);
5162 prog->may_persist = compute_may_persist(prog);
5164 return prog;
5167 void *gpu_prog_free(struct gpu_prog *prog)
5169 if (!prog)
5170 return NULL;
5171 free_array_info(prog);
5172 free_stmts(prog->stmts, prog->n_stmts);
5173 isl_union_map_free(prog->any_to_outer);
5174 isl_union_map_free(prog->to_outer);
5175 isl_union_map_free(prog->to_inner);
5176 isl_union_map_free(prog->read);
5177 isl_union_map_free(prog->may_write);
5178 isl_union_map_free(prog->must_write);
5179 isl_union_map_free(prog->tagged_must_kill);
5180 isl_union_map_free(prog->array_order);
5181 isl_union_set_free(prog->may_persist);
5182 isl_set_free(prog->context);
5183 free(prog);
5184 return NULL;