gpu.c: remove nested AST generation code
[ppcg.git] / gpu.c
blob6fb761ddcb1b70c7b3bf60a369fc55c16484f915
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"
36 struct gpu_array_info;
38 /* Collect all references to the given array and store pointers to them
39 * in array->refs.
41 * If the array contains structures, then there is no need to collect
42 * the references since we will not be computing any reference groups.
44 static void collect_references(struct gpu_prog *prog,
45 struct gpu_array_info *array)
47 int i;
48 int n;
50 if (array->has_compound_element)
51 return;
53 n = 0;
54 for (i = 0; i < prog->n_stmts; ++i) {
55 struct gpu_stmt *stmt = &prog->stmts[i];
56 struct gpu_stmt_access *access;
58 for (access = stmt->accesses; access; access = access->next) {
59 const char *name;
60 name = isl_map_get_tuple_name(access->access,
61 isl_dim_out);
62 if (name && !strcmp(array->name, name))
63 n++;
67 array->n_ref = n;
68 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
69 assert(array->refs);
71 n = 0;
72 for (i = 0; i < prog->n_stmts; ++i) {
73 struct gpu_stmt *stmt = &prog->stmts[i];
74 struct gpu_stmt_access *access;
76 for (access = stmt->accesses; access; access = access->next) {
77 const char *name;
78 name = isl_map_get_tuple_name(access->access,
79 isl_dim_out);
80 if (!name || strcmp(array->name, name))
81 continue;
83 array->refs[n++] = access;
88 /* Compute and return the extent of "array", taking into account the set of
89 * accessed elements.
91 * In particular, the extent in the outer dimension is taken
92 * from "accessed", while the extents in the remaining dimensions
93 * are taken from array->extent.
95 * The extent in the outer dimension cannot be taken from array->extent
96 * because that may be unbounded. Furthermore, even if it is bounded,
97 * it may be larger than the piece of the array that is being accessed.
99 static __isl_give isl_set *compute_extent(struct pet_array *array,
100 __isl_keep isl_set *accessed)
102 int n_index;
103 isl_id *id;
104 isl_set *outer;
105 isl_set *extent;
107 extent = isl_set_copy(array->extent);
109 n_index = isl_set_dim(accessed, isl_dim_set);
110 if (n_index == 0)
111 return extent;
113 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
114 outer = isl_set_copy(accessed);
115 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
116 extent = isl_set_flat_product(outer, extent);
117 id = isl_set_get_tuple_id(accessed);
118 extent = isl_set_set_tuple_id(extent, id);
120 return extent;
123 /* Is the array "array" being extracted a read-only scalar?
125 * That is, is "array" a scalar that is never possibly written to.
126 * An array containing structures is never considered to be a scalar.
128 static int is_read_only_scalar(struct gpu_array_info *array,
129 struct gpu_prog *prog)
131 isl_set *space;
132 isl_union_map *write;
133 int empty;
135 if (array->has_compound_element)
136 return 0;
137 if (array->n_index != 0)
138 return 0;
140 write = isl_union_map_copy(prog->may_write);
141 space = isl_set_universe(isl_space_copy(array->space));
142 write = isl_union_map_intersect_range(write,
143 isl_union_set_from_set(space));
144 empty = isl_union_map_is_empty(write);
145 isl_union_map_free(write);
147 return empty;
150 /* Compute bounds on the host array "pa" based on the corresponding
151 * accessed elements in "arrays"
152 * and collect all references to the array.
153 * Store the results in "info".
155 * If the array is zero-dimensional and does not contain structures,
156 * i.e., if the array is a scalar, we check whether it is read-only.
157 * We also check whether the array is accessed at all.
159 static int extract_array_info(struct gpu_prog *prog,
160 struct gpu_array_info *info, struct pet_array *pa,
161 __isl_keep isl_union_set *arrays)
163 int i, empty;
164 const char *name;
165 int n_index;
166 isl_pw_aff **bounds;
167 isl_set *accessed, *extent;
169 n_index = isl_set_dim(pa->extent, isl_dim_set);
170 name = isl_set_get_tuple_name(pa->extent);
171 bounds = isl_alloc_array(prog->ctx, isl_pw_aff *, n_index);
172 if (!bounds)
173 return -1;
175 info->space = isl_set_get_space(pa->extent);
176 info->name = strdup(name);
177 info->n_index = n_index;
178 info->bound = bounds;
179 info->linearize = prog->scop->options->linearize_device_arrays;
181 info->type = strdup(pa->element_type);
182 info->size = pa->element_size;
183 info->local = pa->declared && !pa->exposed;
184 info->has_compound_element = pa->element_is_record;
185 info->read_only_scalar = is_read_only_scalar(info, prog);
187 accessed = isl_union_set_extract_set(arrays,
188 isl_space_copy(info->space));
189 empty = isl_set_is_empty(accessed);
190 extent = compute_extent(pa, accessed);
191 isl_set_free(accessed);
192 info->extent = extent;
193 if (empty < 0)
194 return -1;
195 info->accessed = !empty;
196 for (i = 0; i < n_index; ++i) {
197 isl_set *dom;
198 isl_local_space *ls;
199 isl_aff *one;
200 isl_pw_aff *bound;
202 dom = isl_set_copy(extent);
203 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
204 n_index - (i + 1));
205 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
206 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
207 fprintf(stderr, "unable to determine extent of '%s' "
208 "in dimension %d\n", info->name, i);
209 dom = isl_set_free(dom);
211 bound = isl_set_dim_max(dom, 0);
212 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
213 ls = isl_local_space_from_space(isl_set_get_space(dom));
214 one = isl_aff_zero_on_domain(ls);
215 one = isl_aff_add_constant_si(one, 1);
216 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
217 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
219 bounds[i] = bound;
220 if (!isl_pw_aff_is_cst(bound))
221 info->linearize = 1;
224 collect_references(prog, info);
226 return 0;
229 /* Remove independence from the order constraints "order" on array "array".
230 * Since the pairs of iterations in the filter relation of an independence
231 * are guaranteed to be completely independent by the user, there is
232 * no need to ensure that live ranges are ordered along thong pairs.
233 * We make an exception for local variables, though, as the independence
234 * guarantee does not apply to those.
236 * The order constraints are used in two places.
237 * Those on scalars are used in check_scalar_live_ranges to check if
238 * we need to force the scalar to be private. Any non-local scalar
239 * should not be forced scalar if it only appears in independent loops.
240 * Those on non-scalars are added to the coincidence constraints
241 * in compute_schedule because we do not support any array expansion.
242 * Accesses to non-local arrays should not prevent a loop from being
243 * considered coincident so we should indeed remove those constraints
244 * from the order constraints.
246 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
247 struct gpu_array_info *array, __isl_take isl_union_map *order)
249 int i;
251 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
252 struct pet_independence *pi = prog->scop->pet->independences[i];
253 if (isl_union_set_contains(pi->local, array->space))
254 continue;
256 order = isl_union_map_subtract(order,
257 isl_union_map_copy(pi->filter));
260 return order;
263 /* For each array in "prog", store the (untagged) order dependences
264 * derived from the array in array->dep_order.
265 * In particular, consider all references that access the given array
266 * and take the order dependences that have one of these references
267 * as source. (Since an order dependence relates two references to
268 * the same array, the target of these order dependences will also
269 * be one of these references.)
270 * Additionally, store the union of these array->dep_order relations
271 * for all non-scalar arrays in prog->array_order.
273 void collect_order_dependences(struct gpu_prog *prog)
275 int i;
276 isl_space *space;
277 isl_union_map *accesses;
279 space = isl_union_map_get_space(prog->read);
280 prog->array_order = isl_union_map_empty(space);
282 accesses = isl_union_map_copy(prog->scop->tagged_reads);
283 accesses = isl_union_map_union(accesses,
284 isl_union_map_copy(prog->scop->tagged_may_writes));
285 accesses = isl_union_map_universe(accesses);
286 accesses = isl_union_map_apply_range(accesses,
287 isl_union_map_copy(prog->to_outer));
289 for (i = 0; i < prog->n_array; ++i) {
290 struct gpu_array_info *array = &prog->array[i];
291 isl_set *set;
292 isl_union_set *uset;
293 isl_union_map *order;
295 set = isl_set_universe(isl_space_copy(array->space));
296 uset = isl_union_set_from_set(set);
297 uset = isl_union_map_domain(
298 isl_union_map_intersect_range(isl_union_map_copy(accesses),
299 uset));
300 order = isl_union_map_copy(prog->scop->tagged_dep_order);
301 order = isl_union_map_intersect_domain(order, uset);
302 order = isl_union_map_zip(order);
303 order = isl_union_set_unwrap(isl_union_map_domain(order));
304 order = remove_independences(prog, array, order);
305 array->dep_order = order;
307 if (gpu_array_is_scalar(array) && !array->has_compound_element)
308 continue;
310 prog->array_order = isl_union_map_union(prog->array_order,
311 isl_union_map_copy(array->dep_order));
314 isl_union_map_free(accesses);
317 /* Construct a gpu_array_info for each array referenced by prog->scop and
318 * collect them in prog->array.
320 * The sizes are based on the extents and the set of possibly accessed
321 * elements by "prog".
322 * If there are any member accesses involved, then they are first mapped
323 * to the outer arrays of structs.
325 * If we are allowing live range reordering, then also set
326 * the dep_order field. Otherwise leave it NULL.
328 static int collect_array_info(struct gpu_prog *prog)
330 int i;
331 int r = 0;
332 isl_union_set *arrays;
334 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
335 arrays = isl_union_set_union(arrays,
336 isl_union_map_range(isl_union_map_copy(prog->may_write)));
338 arrays = isl_union_set_apply(arrays,
339 isl_union_map_copy(prog->to_outer));
341 arrays = isl_union_set_coalesce(arrays);
343 prog->n_array = prog->scop->pet->n_array;
344 prog->array = isl_calloc_array(prog->ctx,
345 struct gpu_array_info, prog->n_array);
346 assert(prog->array);
347 for (i = 0; i < prog->scop->pet->n_array; ++i)
348 if (extract_array_info(prog, &prog->array[i],
349 prog->scop->pet->arrays[i], arrays) < 0)
350 r = -1;
352 isl_union_set_free(arrays);
354 if (prog->scop->options->live_range_reordering)
355 collect_order_dependences(prog);
357 return r;
360 static void free_array_info(struct gpu_prog *prog)
362 int i, j;
364 for (i = 0; i < prog->n_array; ++i) {
365 int n_index = prog->array[i].n_index;
366 free(prog->array[i].type);
367 free(prog->array[i].name);
368 for (j = 0; j < n_index; ++j)
369 isl_pw_aff_free(prog->array[i].bound[j]);
370 isl_space_free(prog->array[i].space);
371 isl_set_free(prog->array[i].extent);
372 free(prog->array[i].bound);
373 free(prog->array[i].refs);
374 isl_union_map_free(prog->array[i].dep_order);
376 free(prog->array);
379 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
380 * as an array or through a pointer reference, but as a single data element.
381 * At the moment, scalars are represented as zero-dimensional arrays.
382 * Note that the single data element may be an entire structure.
384 int gpu_array_is_scalar(struct gpu_array_info *array)
386 return array->n_index == 0;
389 /* Is "array" a read-only scalar?
391 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
393 return array->read_only_scalar;
396 /* Return the set of parameter values for which the array has a positive
397 * size in all dimensions.
398 * If the sizes are only valid for some parameter values, then those
399 * constraints are also taken into account.
401 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
403 int i;
404 isl_space *space;
405 isl_set *guard;
407 space = isl_space_params(isl_space_copy(array->space));
408 guard = isl_set_universe(space);
410 for (i = 0; i < array->n_index; ++i) {
411 isl_pw_aff *bound;
412 isl_set *guard_i, *zero;
414 bound = isl_pw_aff_copy(array->bound[i]);
415 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
416 zero = isl_pw_aff_zero_set(bound);
417 guard_i = isl_set_subtract(guard_i, zero);
418 guard = isl_set_intersect(guard, guard_i);
421 return guard;
424 /* Internal data structure for extract_size_of_type.
425 * "type" specifies the name of the space that we want to extract.
426 * "res" is used to store the subset of that space.
428 struct ppcg_extract_size_data {
429 const char *type;
430 isl_set *res;
433 /* This function is called for each set in a union_set.
434 * If the name of the set matches data->type, we store the
435 * set in data->res.
437 static int extract_size_of_type(__isl_take isl_set *size, void *user)
439 struct ppcg_extract_size_data *data = user;
440 const char *name;
442 name = isl_set_get_tuple_name(size);
443 if (name && !strcmp(name, data->type)) {
444 data->res = size;
445 return -1;
448 isl_set_free(size);
449 return 0;
452 /* Given a union map { kernel[i] -> *[...] },
453 * return the range in the space called "type" for the kernel with
454 * sequence number "id".
456 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
457 const char *type, int id)
459 isl_space *space;
460 isl_set *dom;
461 isl_union_set *local_sizes;
462 struct ppcg_extract_size_data data = { type, NULL };
464 if (!sizes)
465 return NULL;
467 space = isl_union_map_get_space(sizes);
468 space = isl_space_set_from_params(space);
469 space = isl_space_add_dims(space, isl_dim_set, 1);
470 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
471 dom = isl_set_universe(space);
472 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
474 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
475 isl_union_map_copy(sizes));
476 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
477 isl_union_set_free(local_sizes);
478 return data.res;
481 /* Given a singleton set, extract the first (at most *len) elements
482 * of the single integer tuple into *sizes and update *len if needed.
484 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
486 int i;
487 int dim;
489 if (!set)
490 return;
492 dim = isl_set_dim(set, isl_dim_set);
493 if (dim < *len)
494 *len = dim;
496 for (i = 0; i < *len; ++i) {
497 isl_val *v;
499 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
500 assert(v);
502 sizes[i] = isl_val_get_num_si(v);
503 isl_val_free(v);
506 isl_set_free(set);
509 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
510 * if the option debug->dump_sizes is set.
512 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
513 int *sizes, int len)
515 int i;
516 isl_space *space;
517 isl_map *map;
519 if (!gen->options->debug->dump_sizes)
520 return;
522 space = isl_union_map_get_space(gen->used_sizes);
523 space = isl_space_set_from_params(space);
524 space = isl_space_add_dims(space, isl_dim_set, 1);
525 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
526 space = isl_space_from_domain(space);
527 space = isl_space_add_dims(space, isl_dim_out, len);
528 space = isl_space_set_tuple_name(space, isl_dim_out, type);
530 map = isl_map_universe(space);
531 map = isl_map_fix_si(map, isl_dim_in, 0, id);
532 for (i = 0; i < len; ++i)
533 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
535 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
538 /* Extract user specified "tile" sizes from the "sizes" command line option,
539 * defaulting to option->tile_size in each dimension.
540 * *tile_len contains the maximum number of tile sizes needed.
541 * Update *tile_len to the number of specified tile sizes, if any, and
542 * return a pointer to the tile sizes (or NULL on error).
543 * Add the effectively used sizes to gen->used_sizes.
545 static int *read_tile_sizes(struct gpu_gen *gen, int *tile_len)
547 int n;
548 int *tile_size;
549 isl_set *size;
551 tile_size = isl_alloc_array(gen->ctx, int, *tile_len);
552 if (!tile_size)
553 return NULL;
554 for (n = 0; n < *tile_len; ++n)
555 tile_size[n] = gen->options->tile_size;
557 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
558 read_sizes_from_set(size, tile_size, tile_len);
559 set_used_sizes(gen, "tile", gen->kernel_id, tile_size, *tile_len);
561 return tile_size;
564 /* Extract user specified "block" sizes from the "sizes" command line option,
565 * after filling in some potentially useful defaults.
567 static void read_block_sizes(struct ppcg_kernel *kernel,
568 __isl_keep isl_union_map *sizes)
570 isl_set *size;
572 if (kernel->n_block > 3)
573 kernel->n_block = 3;
574 switch (kernel->n_block) {
575 case 1:
576 kernel->block_dim[0] = 512;
577 break;
578 case 2:
579 kernel->block_dim[0] = 32;
580 kernel->block_dim[1] = 16;
581 break;
582 default:
583 kernel->block_dim[0] = 32;
584 kernel->block_dim[1] = 4;
585 kernel->block_dim[2] = 4;
586 break;
589 size = extract_sizes(sizes, "block", kernel->id);
590 read_sizes_from_set(size, kernel->block_dim, &kernel->n_block);
593 /* Extract user specified "grid" sizes from the "sizes" command line option,
594 * after filling in some potentially useful defaults.
596 static void read_grid_sizes(struct ppcg_kernel *kernel,
597 __isl_keep isl_union_map *sizes)
599 isl_set *size;
601 if (kernel->n_grid > 2)
602 kernel->n_grid = 2;
603 switch (kernel->n_grid) {
604 case 1:
605 kernel->grid_dim[0] = 32768;
606 break;
607 default:
608 kernel->grid_dim[0] = 256;
609 kernel->grid_dim[1] = 256;
610 break;
613 size = extract_sizes(sizes, "grid", kernel->id);
614 read_sizes_from_set(size, kernel->grid_dim, &kernel->n_grid);
617 /* Extract user specified grid and block sizes from the gen->sizes
618 * command line option after filling in some potentially useful defaults.
619 * Store the extracted sizes in "kernel".
620 * Add the effectively used sizes to gen->used_sizes.
622 static void read_grid_and_block_sizes(struct ppcg_kernel *kernel,
623 struct gpu_gen *gen)
625 read_block_sizes(kernel, gen->sizes);
626 read_grid_sizes(kernel, gen->sizes);
627 set_used_sizes(gen, "block", kernel->id,
628 kernel->block_dim, kernel->n_block);
629 set_used_sizes(gen, "grid", kernel->id,
630 kernel->grid_dim, kernel->n_grid);
633 static void *free_stmts(struct gpu_stmt *stmts, int n)
635 int i;
637 if (!stmts)
638 return NULL;
640 for (i = 0; i < n; ++i) {
641 struct gpu_stmt_access *access, *next;
643 for (access = stmts[i].accesses; access; access = next) {
644 next = access->next;
645 isl_id_free(access->ref_id);
646 isl_map_free(access->access);
647 isl_map_free(access->tagged_access);
648 free(access);
651 isl_id_free(stmts[i].id);
653 free(stmts);
655 return NULL;
658 /* Add parameters p[i] with identifiers "ids" to "set",
659 * with bounds to 0 <= p[i] < size[i].
661 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
662 int *size, __isl_keep isl_id_list *ids)
664 int i, len;
665 unsigned nparam;
667 len = isl_id_list_n_id(ids);
668 nparam = isl_set_dim(set, isl_dim_param);
669 set = isl_set_add_dims(set, isl_dim_param, len);
671 for (i = 0; i < len; ++i) {
672 isl_id *id;
674 id = isl_id_list_get_id(ids, i);
675 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
676 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
677 set = isl_set_upper_bound_si(set, isl_dim_param,
678 nparam + i, size[i] - 1);
681 return set;
684 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
685 * with
687 * { : 0 <= p[i] < size[i] }
689 * or an overapproximation.
691 static __isl_give isl_set *add_bounded_parameters_dynamic(
692 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
693 __isl_keep isl_id_list *ids)
695 int i, len;
696 unsigned nparam;
697 isl_space *space;
698 isl_local_space *ls;
700 len = isl_multi_pw_aff_dim(size, isl_dim_out);
701 nparam = isl_set_dim(set, isl_dim_param);
702 set = isl_set_add_dims(set, isl_dim_param, len);
704 for (i = 0; i < len; ++i) {
705 isl_id *id;
707 id = isl_id_list_get_id(ids, i);
708 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
711 space = isl_space_params(isl_set_get_space(set));
712 ls = isl_local_space_from_space(space);
713 for (i = 0; i < len; ++i) {
714 isl_pw_aff *param, *size_i, *zero;
715 isl_set *bound;
717 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
718 isl_dim_param, nparam + i);
720 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
721 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
722 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
723 set = isl_set_intersect_params(set, bound);
725 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
726 bound = isl_pw_aff_ge_set(param, zero);
727 set = isl_set_intersect_params(set, bound);
729 isl_local_space_free(ls);
731 return set;
734 /* Return the union of all tagged access relations in the group.
736 static __isl_give isl_union_map *group_tagged_access_relation(
737 struct gpu_array_ref_group *group)
739 int i;
740 isl_union_map *access;
742 access = isl_union_map_empty(isl_map_get_space(group->access));
743 for (i = 0; i < group->n_ref; ++i) {
744 isl_map *map_i;
746 map_i = isl_map_copy(group->refs[i]->tagged_access);
747 access = isl_union_map_union(access,
748 isl_union_map_from_map(map_i));
751 return access;
754 /* Return the extent of "array", recomputed from the bounds.
755 * The recomputed extent may be simpler than the original extent.
757 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
759 int i;
760 isl_id *id;
761 isl_space *space;
762 isl_local_space *ls;
763 isl_set *extent;
765 id = isl_set_get_tuple_id(array->extent);
766 space = isl_set_get_space(array->extent);
767 extent = isl_set_universe(isl_space_copy(space));
768 ls = isl_local_space_from_space(space);
769 for (i = 0; i < array->n_index; ++i) {
770 isl_pw_aff *bound;
771 isl_aff *aff;
772 isl_pw_aff *index;
773 isl_set *lt;
775 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
777 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
778 isl_dim_set, i);
779 index = isl_pw_aff_from_aff(aff);
780 bound = isl_pw_aff_copy(array->bound[i]);
781 bound = isl_pw_aff_from_range(bound);
782 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
783 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
784 isl_id_copy(id));
785 lt = isl_pw_aff_lt_set(index, bound);
786 extent = isl_set_intersect(extent, lt);
788 isl_local_space_free(ls);
789 isl_id_free(id);
791 return extent;
794 /* Return a map from the first group->depth dimensions of the computed
795 * schedule to the array tile in
796 * global memory that corresponds to the shared memory copy.
798 * In particular, return a map
800 * { D[i] -> A[a] }
802 * with constraints
804 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
806 * and
808 * 0 <= a <= array_size - 1 (2)
810 * Note that if some stride has been detected (i.e., when
811 * group->shared_tile->bound[i].shift is set), then a in (1) refers
812 * to the shifted and scaled down version.
814 * Constraints (1) are obtained by mapping the size constraints on the
815 * shared/private memory tile back to the access relation.
816 * Constraints (2) are obtained from the (recomputed) extent.
818 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
820 int i;
821 int n_index = group->array->n_index;
822 isl_map *tile;
823 isl_space *space;
824 isl_set *local;
825 isl_set *extent;
827 space = isl_multi_aff_get_space(group->shared_tile->tiling);
828 space = isl_space_range(space);
829 local = isl_set_universe(space);
830 for (i = 0; i < n_index; ++i) {
831 isl_val *bound;
833 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
834 bound = isl_val_copy(group->shared_tile->bound[i].size);
835 bound = isl_val_sub_ui(bound, 1);
836 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
838 local = isl_set_preimage_multi_aff(local,
839 isl_multi_aff_copy(group->shared_tile->tiling));
840 tile = isl_set_unwrap(local);
841 extent = array_extent(group->array);
842 tile = isl_map_intersect_range(tile, extent);
844 return tile;
847 /* Given a mapping "iterator_map" from the AST schedule to a domain,
848 * return the corresponding mapping from the AST schedule to
849 * to the outer kernel->shared_schedule_dim dimensions of
850 * the schedule computed by PPCG for this kernel.
852 * Note that kernel->shared_schedule_dim is at least as large as
853 * the largest depth of any array reference group associated to the kernel.
854 * This is needed as the returned schedule is used to extract a mapping
855 * to the outer group->depth dimensions in transform_index.
857 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(
858 struct ppcg_kernel *kernel, __isl_take isl_pw_multi_aff *iterator_map)
860 isl_union_pw_multi_aff *upma;
861 isl_pw_multi_aff *pma;
862 isl_space *space;
864 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
865 space = isl_space_from_domain(space);
866 space = isl_space_add_dims(space, isl_dim_out,
867 kernel->shared_schedule_dim);
869 upma = isl_union_pw_multi_aff_copy(kernel->shared_schedule);
870 pma = isl_union_pw_multi_aff_extract_pw_multi_aff(upma, space);
871 isl_union_pw_multi_aff_free(upma);
873 return isl_pw_multi_aff_pullback_pw_multi_aff(pma, iterator_map);
876 /* If max_shared_memory is not set to infinity (-1), then make
877 * sure that the total amount of shared memory required by the
878 * array reference groups mapped to shared memory by "kernel"
879 * is no larger than this maximum.
881 * We apply a greedy approach and discard (keep in global memory)
882 * those groups that would result in a total memory size that
883 * is larger than the maximum.
885 * This function should be called after any function that may
886 * affect the decision on whether to place a reference group
887 * in private, shared or global memory.
889 static void check_shared_memory_bound(struct ppcg_kernel *kernel)
891 int i, j;
892 isl_val *left, *size;
894 if (kernel->options->max_shared_memory < 0)
895 return;
897 left = isl_val_int_from_si(kernel->ctx,
898 kernel->options->max_shared_memory);
900 for (i = 0; i < kernel->n_array; ++i) {
901 struct gpu_local_array_info *local = &kernel->array[i];
903 for (j = 0; j < local->n_group; ++j) {
904 struct gpu_array_ref_group *group;
906 group = local->groups[j];
907 if (group->private_tile)
908 continue;
909 if (!group->shared_tile)
910 continue;
912 size = gpu_array_tile_size(group->shared_tile);
913 size = isl_val_mul_ui(size, local->array->size);
915 if (isl_val_le(size, left)) {
916 left = isl_val_sub(left, size);
917 continue;
919 isl_val_free(size);
921 group->shared_tile =
922 gpu_array_tile_free(group->shared_tile);
926 isl_val_free(left);
929 /* Compute a tiling for all the array reference groups in "kernel".
931 static void compute_group_tilings(struct ppcg_kernel *kernel)
933 int i, j;
935 for (i = 0; i < kernel->n_array; ++i) {
936 struct gpu_local_array_info *array = &kernel->array[i];
938 for (j = 0; j < array->n_group; ++j)
939 gpu_array_ref_group_compute_tiling(array->groups[j]);
943 /* Compute the size of a bounding box around the origin and "set",
944 * where "set" is assumed to contain only non-negative elements.
945 * In particular, compute the maximal value of "set" in each direction
946 * and add one.
948 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
949 __isl_take isl_set *context)
951 int i, n;
952 isl_multi_pw_aff *mpa;
954 context = isl_set_params(context);
955 n = isl_set_dim(set, isl_dim_set);
956 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
957 for (i = 0; i < n; ++i) {
958 isl_space *space;
959 isl_aff *one;
960 isl_pw_aff *bound;
962 bound = isl_set_dim_max(isl_set_copy(set), i);
963 bound = isl_pw_aff_coalesce(bound);
964 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
966 space = isl_pw_aff_get_domain_space(bound);
967 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
968 one = isl_aff_add_constant_si(one, 1);
969 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
970 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
972 isl_set_free(set);
973 isl_set_free(context);
975 return mpa;
978 /* Compute the effective grid size as a list of the sizes in each dimension.
980 * The grid size specified by the user or set by default
981 * in read_grid_sizes() and applied by the block filter,
982 * may be too large for the given code in the sense that
983 * it may contain blocks that don't need to execute anything.
984 * We therefore don't return this grid size, but instead the
985 * smallest grid size that ensures that all blocks that actually
986 * execute code are included in the grid.
988 * We first extract a description of the grid, i.e., the possible values
989 * of the block ids, from the domain elements in "domain" and
990 * kernel->block_filter.
991 * The block ids are parameters in kernel->block_filter.
992 * We simply need to change them into set dimensions.
994 * Then, for each block dimension, we compute the maximal value of the block id
995 * and add one.
997 static __isl_give isl_multi_pw_aff *extract_grid_size(
998 struct ppcg_kernel *kernel, __isl_take isl_union_set *domain)
1000 int i;
1001 isl_set *grid;
1003 domain = isl_union_set_intersect(domain,
1004 isl_union_set_copy(kernel->block_filter));
1005 grid = isl_union_set_params(domain);
1006 grid = isl_set_from_params(grid);
1007 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1008 for (i = 0; i < kernel->n_grid; ++i) {
1009 int pos;
1010 isl_id *id;
1012 id = isl_id_list_get_id(kernel->block_ids, i);
1013 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1014 isl_id_free(id);
1015 assert(pos >= 0);
1016 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1017 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1020 return extract_size(grid, isl_set_copy(kernel->context));
1023 /* Compute the size of a fixed bounding box around the origin and "set",
1024 * where "set" is assumed to contain only non-negative elements,
1025 * and store the results in "size".
1026 * In particular, compute the maximal value of "set" in each direction
1027 * and add one.
1029 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1031 int i, n;
1032 isl_local_space *ls;
1033 isl_aff *obj;
1035 n = isl_set_dim(set, isl_dim_set);
1036 ls = isl_local_space_from_space(isl_set_get_space(set));
1037 obj = isl_aff_zero_on_domain(ls);
1038 for (i = 0; i < n; ++i) {
1039 isl_val *max;
1041 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1042 max = isl_set_max_val(set, obj);
1043 size[i] = isl_val_get_num_si(max) + 1;
1044 isl_val_free(max);
1045 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1047 isl_aff_free(obj);
1048 isl_set_free(set);
1051 /* Compute the effective block size as a list of the sizes in each dimension
1052 * and store the sizes in kernel->block_dim.
1054 * The block size specified by the user or set by default
1055 * in read_block_sizes() and applied by the thread filter,
1056 * may be too large for the given code in the sense that
1057 * it may contain threads that don't need to execute anything.
1058 * We therefore update this block size in kernel->block_dim
1059 * to the smallest block size that ensures that all threads
1060 * that actually execute code are included in the block.
1062 * The possible values of the thread ids is obtained from
1063 * the domain elements "domain" and kernel->thread_filter.
1064 * The current implementation eliminates all parameters, ensuring
1065 * that the size is a fixed constant in each dimension.
1066 * In principle we could also compute parametric sizes.
1067 * We would have to make sure to project out all b%d and t%d parameters,
1068 * however.
1070 static void extract_block_size(struct ppcg_kernel *kernel,
1071 __isl_take isl_union_set *domain)
1073 int i;
1074 int nparam;
1075 isl_set *block;
1077 domain = isl_union_set_intersect(domain,
1078 isl_union_set_copy(kernel->thread_filter));
1079 block = isl_union_set_params(domain);
1080 block = isl_set_from_params(block);
1081 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1082 for (i = 0; i < kernel->n_block; ++i) {
1083 int pos;
1084 isl_id *id;
1086 id = isl_id_list_get_id(kernel->thread_ids, i);
1087 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1088 isl_id_free(id);
1089 assert(pos >= 0);
1090 block = isl_set_equate(block, isl_dim_param, pos,
1091 isl_dim_set, i);
1093 nparam = isl_set_dim(block, isl_dim_param);
1094 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1096 extract_fixed_size(block, kernel->block_dim);
1099 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1101 int i, j;
1103 if (!kernel)
1104 return NULL;
1106 isl_id_list_free(kernel->block_ids);
1107 isl_id_list_free(kernel->thread_ids);
1108 isl_multi_pw_aff_free(kernel->grid_size);
1109 isl_set_free(kernel->context);
1110 isl_union_set_free(kernel->core);
1111 isl_union_set_free(kernel->arrays);
1112 isl_space_free(kernel->space);
1113 isl_ast_node_free(kernel->tree);
1114 isl_union_set_free(kernel->block_filter);
1115 isl_union_set_free(kernel->thread_filter);
1116 isl_union_pw_multi_aff_free(kernel->shared_schedule);
1118 for (i = 0; i < kernel->n_array; ++i) {
1119 struct gpu_local_array_info *array = &kernel->array[i];
1121 for (j = 0; j < array->n_group; ++j)
1122 gpu_array_ref_group_free(array->groups[j]);
1123 free(array->groups);
1125 isl_pw_aff_list_free(array->bound);
1127 free(kernel->array);
1129 for (i = 0; i < kernel->n_var; ++i) {
1130 free(kernel->var[i].name);
1131 isl_vec_free(kernel->var[i].size);
1133 free(kernel->var);
1134 free(kernel->tile_size);
1136 free(kernel);
1138 return NULL;
1141 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1143 static void ppcg_kernel_free_wrap(void *user)
1145 struct ppcg_kernel *kernel = user;
1147 ppcg_kernel_free(kernel);
1150 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1151 struct ppcg_kernel_var *var)
1153 int j;
1154 struct gpu_array_tile *tile;
1155 isl_printer *p;
1156 char *name;
1158 var->array = group->array;
1160 tile = group->private_tile;
1161 var->type = ppcg_access_private;
1162 if (!tile) {
1163 tile = group->shared_tile;
1164 var->type = ppcg_access_shared;
1167 p = isl_printer_to_str(ctx);
1168 p = gpu_array_ref_group_print_name(group, p);
1169 var->name = isl_printer_get_str(p);
1170 isl_printer_free(p);
1172 var->size = isl_vec_alloc(ctx, group->array->n_index);
1174 for (j = 0; j < group->array->n_index; ++j)
1175 var->size = isl_vec_set_element_val(var->size, j,
1176 isl_val_copy(tile->bound[j].size));
1179 static void create_kernel_vars(struct ppcg_kernel *kernel)
1181 int i, j, n;
1183 n = 0;
1184 for (i = 0; i < kernel->n_array; ++i) {
1185 struct gpu_local_array_info *array = &kernel->array[i];
1187 for (j = 0; j < array->n_group; ++j) {
1188 struct gpu_array_ref_group *group = array->groups[j];
1189 if (group->private_tile || group->shared_tile)
1190 ++n;
1194 kernel->n_var = n;
1195 kernel->var = isl_calloc_array(kernel->ctx, struct ppcg_kernel_var, n);
1196 assert(kernel->var);
1198 n = 0;
1199 for (i = 0; i < kernel->n_array; ++i) {
1200 struct gpu_local_array_info *array = &kernel->array[i];
1202 for (j = 0; j < array->n_group; ++j) {
1203 struct gpu_array_ref_group *group = array->groups[j];
1204 if (!group->private_tile && !group->shared_tile)
1205 continue;
1206 create_kernel_var(kernel->ctx, group, &kernel->var[n]);
1207 ++n;
1212 /* Replace "pa" by the zero function defined over the universe domain
1213 * in the space of "pa".
1215 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1217 isl_space *space;
1218 isl_aff *zero;
1220 space = isl_space_domain(isl_pw_aff_get_space(pa));
1221 isl_pw_aff_free(pa);
1222 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1224 return isl_pw_aff_from_aff(zero);
1227 /* The sizes of the arrays on the host that have been computed by
1228 * extract_array_info may depend on the parameters. Use the extra
1229 * constraints on the parameters that are valid at "host_domain"
1230 * to simplify these expressions and store the results in kernel->array.
1232 * We only need these localized bounds for arrays that are accessed
1233 * by the current kernel. If we have found at least one reference group
1234 * then the array is accessed by the kernel. If the array has compound
1235 * elements then we skipped the construction of array reference groups.
1237 * The resulting sizes may be functions that are nowhere defined
1238 * in case the access function cannot possibly access anything inside
1239 * the kernel for some reason. If so, they are replaced by the zero
1240 * function. Since the access function cannot actually access anything,
1241 * there is no harm in printing the array sizes as zero.
1243 static void localize_bounds(struct ppcg_kernel *kernel,
1244 __isl_keep isl_set *host_domain)
1246 int i, j;
1247 isl_set *context;
1249 context = isl_set_copy(host_domain);
1250 context = isl_set_params(context);
1252 for (i = 0; i < kernel->n_array; ++i) {
1253 struct gpu_local_array_info *local = &kernel->array[i];
1254 isl_pw_aff_list *bound;
1255 int n_index;
1257 if (local->n_group == 0 && !local->array->has_compound_element)
1258 continue;
1260 n_index = local->array->n_index;
1261 bound = isl_pw_aff_list_alloc(kernel->ctx, n_index);
1263 for (j = 0; j < n_index; ++j) {
1264 isl_pw_aff *pwaff;
1265 int empty;
1267 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1268 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1269 empty = isl_pw_aff_is_empty(pwaff);
1270 if (empty < 0)
1271 pwaff = isl_pw_aff_free(pwaff);
1272 else if (empty)
1273 pwaff = set_universally_zero(pwaff);
1274 bound = isl_pw_aff_list_add(bound, pwaff);
1277 local->n_index = n_index;
1278 local->bound = bound;
1280 isl_set_free(context);
1283 /* Create the array of gpu_local_array_info structures "array"
1284 * inside "kernel". The number of elements in this array is
1285 * the same as the number of arrays in "prog".
1286 * Initialize the "array" field of each local array to point
1287 * to the corresponding array in "prog".
1289 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1290 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1292 int i;
1293 isl_ctx *ctx;
1295 ctx = isl_set_get_ctx(prog->context);
1296 kernel->array = isl_calloc_array(ctx,
1297 struct gpu_local_array_info, prog->n_array);
1298 if (!kernel->array)
1299 return ppcg_kernel_free(kernel);
1300 kernel->n_array = prog->n_array;
1302 for (i = 0; i < prog->n_array; ++i)
1303 kernel->array[i].array = &prog->array[i];
1305 return kernel;
1308 /* Find the element in gen->stmt that has the given "id".
1309 * Return NULL if no such gpu_stmt can be found.
1311 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1313 int i;
1315 for (i = 0; i < prog->n_stmts; ++i) {
1316 if (id == prog->stmts[i].id)
1317 break;
1320 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1323 void ppcg_kernel_stmt_free(void *user)
1325 int i;
1326 struct ppcg_kernel_stmt *stmt = user;
1328 if (!stmt)
1329 return;
1331 switch (stmt->type) {
1332 case ppcg_kernel_copy:
1333 isl_ast_expr_free(stmt->u.c.index);
1334 isl_ast_expr_free(stmt->u.c.local_index);
1335 break;
1336 case ppcg_kernel_domain:
1337 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1338 break;
1339 case ppcg_kernel_sync:
1340 break;
1343 free(stmt);
1346 /* Return the gpu_stmt_access in the list "accesses" that corresponds
1347 * to "ref_id".
1349 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
1350 __isl_keep isl_id *ref_id)
1352 struct gpu_stmt_access *access;
1354 for (access = accesses; access; access = access->next)
1355 if (access->ref_id == ref_id)
1356 return access;
1358 return NULL;
1361 /* Return the index of the array called "name" in the list of arrays.
1363 static int find_array_index(struct ppcg_kernel *kernel, const char *name)
1365 int i;
1367 for (i = 0; i < kernel->n_array; ++i)
1368 if (!strcmp(name, kernel->array[i].array->name))
1369 return i;
1371 return -1;
1374 /* Internal data structure for the index and AST expression transformation
1375 * callbacks for pet_stmt_build_ast_exprs.
1377 * "accesses" is the list of gpu_stmt_access in the statement.
1378 * "iterator_map" expresses the statement iterators in terms of
1379 * the AST loop iterators.
1380 * "sched2shared" expresses the outer shared_schedule_dim dimensions of
1381 * the kernel schedule in terms of the AST loop iterators.
1383 * The following fields are set in transform_index and used in transform_expr.
1384 * "array" is the array that is being accessed.
1385 * "global" is set if the global array is accessed (rather than
1386 * shared/private memory).
1387 * "local_array" refers to information on the array specialized
1388 * to the current kernel.
1390 struct ppcg_transform_data {
1391 struct gpu_gen *gen;
1392 struct gpu_stmt_access *accesses;
1393 isl_pw_multi_aff *iterator_map;
1394 isl_pw_multi_aff *sched2shared;
1396 struct gpu_array_info *array;
1397 int global;
1398 struct gpu_local_array_info *local_array;
1401 /* Return the name of the outer array (of structs) accessed by "access".
1403 static const char *get_outer_array_name(__isl_keep isl_map *access)
1405 isl_space *space;
1406 const char *name;
1408 space = isl_space_range(isl_map_get_space(access));
1409 while (space && isl_space_is_wrapping(space))
1410 space = isl_space_domain(isl_space_unwrap(space));
1411 name = isl_space_get_tuple_name(space, isl_dim_set);
1412 isl_space_free(space);
1414 return name;
1417 /* Return a pointer to the gpu_array_ref_group in "local"
1418 * that contains the reference "access".
1419 * Return NULL if no such group can be found.
1421 static struct gpu_array_ref_group *find_ref_group(
1422 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
1424 int i, j;
1426 for (i = 0; i < local->n_group; ++i) {
1427 struct gpu_array_ref_group *group = local->groups[i];
1429 for (j = 0; j < group->n_ref; ++j)
1430 if (group->refs[j] == access)
1431 return group;
1434 return NULL;
1437 /* Index transformation callback for pet_stmt_build_ast_exprs.
1439 * "index" expresses the array indices in terms of statement iterators
1441 * We first reformulate "index" in terms of the AST loop iterators.
1442 * Then we check if we are accessing the global array or
1443 * a shared/private copy. In the former case, we simply return
1444 * the updated index. If "index" is an affine expression rather
1445 * than an array access, then we also return the updated index here.
1447 * If no reference groups have been computed for the array,
1448 * then we can only be accessing the global array.
1450 * Otherwise, we apply the tiling to the index.
1451 * This tiling is of the form
1453 * [D -> A] -> T
1455 * where D corresponds to the outer group->depth dimensions of
1456 * the kernel schedule.
1457 * The index is of the form
1459 * L -> A
1461 * We update the tiling to refer to the AST loop iterators
1463 * [L -> A] -> T
1465 * and modify index to keep track of those iterators
1467 * L -> [L -> A]
1469 * Combining these two yields a tiled index expression in terms
1470 * of the AST loop iterators
1472 * L -> T
1474 static __isl_give isl_multi_pw_aff *transform_index(
1475 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
1476 void *user)
1478 struct ppcg_transform_data *data = user;
1479 struct gpu_stmt_access *access;
1480 struct gpu_array_ref_group *group;
1481 struct gpu_array_tile *tile;
1482 isl_pw_multi_aff *iterator_map;
1483 int i;
1484 int dim;
1485 const char *name;
1486 isl_space *space;
1487 isl_multi_pw_aff *tiling;
1488 isl_pw_multi_aff *pma;
1489 isl_multi_pw_aff *mpa;
1490 isl_pw_multi_aff *sched2depth;
1492 data->array = NULL;
1494 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
1495 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
1497 access = find_access(data->accesses, ref_id);
1498 if (!access)
1499 return index;
1500 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
1501 return index;
1503 name = get_outer_array_name(access->access);
1504 i = find_array_index(data->gen->kernel, name);
1505 if (i < 0)
1506 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
1507 "cannot find array",
1508 return isl_multi_pw_aff_free(index));
1509 data->array = &data->gen->prog->array[i];
1510 data->local_array = &data->gen->kernel->array[i];
1512 group = find_ref_group(data->local_array, access);
1513 if (!group) {
1514 data->global = 1;
1515 return index;
1518 tile = group->private_tile;
1519 if (!tile)
1520 tile = group->shared_tile;
1521 data->global = !tile;
1522 if (!tile)
1523 return index;
1525 space = isl_space_range(isl_multi_pw_aff_get_space(index));
1526 space = isl_space_map_from_set(space);
1527 pma = isl_pw_multi_aff_identity(space);
1528 sched2depth = isl_pw_multi_aff_copy(data->sched2shared);
1529 dim = isl_pw_multi_aff_dim(sched2depth, isl_dim_out);
1530 sched2depth = isl_pw_multi_aff_drop_dims(sched2depth, isl_dim_out,
1531 group->depth, dim - group->depth);
1532 pma = isl_pw_multi_aff_product(sched2depth, pma);
1533 tiling = isl_multi_pw_aff_from_multi_aff(
1534 isl_multi_aff_copy(tile->tiling));
1535 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
1537 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
1538 space = isl_space_map_from_set(space);
1539 mpa = isl_multi_pw_aff_identity(space);
1540 index = isl_multi_pw_aff_range_product(mpa, index);
1541 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
1543 return index;
1546 /* Dereference "expr" by adding an index [0].
1547 * The original "expr" is assumed not to have any indices.
1549 * If "expr" is a member access, then the dereferencing needs
1550 * to be applied to the structure argument of this member access.
1552 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
1554 isl_ctx *ctx;
1555 isl_ast_expr *arg0, *res;
1556 isl_ast_expr_list *list;
1558 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1559 if (!arg0)
1560 return isl_ast_expr_free(expr);
1561 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1562 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1563 isl_ast_expr *arg;
1565 arg = isl_ast_expr_get_op_arg(arg0, 0);
1566 arg = dereference(arg);
1567 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1568 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1570 return expr;
1572 isl_ast_expr_free(arg0);
1574 ctx = isl_ast_expr_get_ctx(expr);
1575 res = isl_ast_expr_from_val(isl_val_zero(ctx));
1576 list = isl_ast_expr_list_from_ast_expr(res);
1577 res = isl_ast_expr_get_op_arg(expr, 0);
1578 res = isl_ast_expr_access(res, list);
1579 isl_ast_expr_free(expr);
1581 return res;
1584 /* Linearize the index expression "expr" based on the array bounds
1585 * of "array".
1587 * That is, transform expression
1589 * A[i_0][i_1]...[i_n]
1591 * to
1593 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
1595 * where b_0, b_1, ..., b_n are the bounds on the array.
1597 * If the base of "expr" is a member access, then the linearization needs
1598 * to be applied to the structure argument of this member access.
1600 * In the base case, if "expr" has no arguments (other than the name of
1601 * the array), then we are passing an entire array to a function.
1602 * In this case, there is nothing to linearize.
1603 * Note that at this point an expression with no arguments can
1604 * only be an entire array because the scalar case and
1605 * the case of single struct are handled by the caller.
1607 * If the number of specified index expressions in "expr"
1608 * is smaller than the dimension of the accessed array,
1609 * then the missing i_j also do not appear in the linearized expression.
1610 * Furthermore, since such an expression does not refer to a single
1611 * element while the default linearized expression would refer to
1612 * a single element, we return the expression
1614 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
1616 * instead. Note that because of the special case handling above,
1617 * we can assume here that here that there is at least one index expression.
1619 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
1620 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
1622 int i, n;
1623 isl_ctx *ctx;
1624 isl_set *context;
1625 isl_ast_expr *arg0;
1626 isl_ast_expr *res;
1627 isl_ast_expr_list *list;
1628 isl_ast_build *build;
1630 arg0 = isl_ast_expr_get_op_arg(expr, 0);
1631 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
1632 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
1633 isl_ast_expr *arg;
1635 arg = isl_ast_expr_get_op_arg(arg0, 0);
1636 arg = gpu_local_array_info_linearize_index(array, arg);
1637 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
1638 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
1640 return expr;
1642 isl_ast_expr_free(arg0);
1644 if (isl_ast_expr_get_op_n_arg(expr) == 1)
1645 return expr;
1647 ctx = isl_ast_expr_get_ctx(expr);
1648 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
1649 build = isl_ast_build_from_context(context);
1651 n = isl_ast_expr_get_op_n_arg(expr);
1652 res = isl_ast_expr_get_op_arg(expr, 1);
1653 for (i = 1; i < array->n_index; ++i) {
1654 isl_pw_aff *bound_i;
1655 isl_ast_expr *expr_i;
1657 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
1658 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
1659 res = isl_ast_expr_mul(res, expr_i);
1661 if (i + 1 >= n)
1662 continue;
1663 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
1664 res = isl_ast_expr_add(res, expr_i);
1667 isl_ast_build_free(build);
1669 if (1 + array->n_index > n) {
1670 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
1671 } else {
1672 list = isl_ast_expr_list_from_ast_expr(res);
1673 res = isl_ast_expr_get_op_arg(expr, 0);
1674 res = isl_ast_expr_access(res, list);
1677 isl_ast_expr_free(expr);
1679 return res;
1682 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
1684 * If the AST expression refers to an array that is not accessed
1685 * at all, then this means the value of the expression is not used,
1686 * so we might as well print zero (NULL pointer) instead.
1688 * If the AST expression refers to a global scalar that is not
1689 * a read-only scalar, then its address was passed to the kernel and
1690 * we need to dereference it.
1692 * If the AST expression refers to an access to a global array,
1693 * then we linearize the access exploiting the bounds in data->local_array.
1695 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
1696 __isl_keep isl_id *id, void *user)
1698 struct ppcg_transform_data *data = user;
1700 if (!data->array)
1701 return expr;
1702 if (!data->array->accessed) {
1703 isl_ctx *ctx;
1705 ctx = isl_ast_expr_get_ctx(expr);
1706 isl_ast_expr_free(expr);
1707 return isl_ast_expr_from_val(isl_val_zero(ctx));
1709 if (gpu_array_is_read_only_scalar(data->array))
1710 return expr;
1711 if (!data->global)
1712 return expr;
1713 if (data->array->n_index == 0)
1714 return dereference(expr);
1715 if (!data->array->linearize)
1716 return expr;
1718 return gpu_local_array_info_linearize_index(data->local_array, expr);
1721 /* This function is called for each instance of a user statement
1722 * in the kernel, identified by "gpu_stmt".
1724 * We attach a struct ppcg_kernel_stmt to the "node", containing
1725 * a computed AST expression for each access.
1726 * These AST expressions are computed from iterator_map,
1727 * which expresses the domain
1728 * elements in terms of the generated loops, and sched2shared,
1729 * which expresses the outer shared_schedule_dim dimensions of
1730 * the kernel schedule computed by PPCG in terms of the generated loops.
1732 static __isl_give isl_ast_node *create_domain_leaf(struct gpu_gen *gen,
1733 __isl_take isl_ast_node *node, __isl_keep isl_ast_build *build,
1734 struct gpu_stmt *gpu_stmt)
1736 struct ppcg_transform_data data;
1737 struct ppcg_kernel_stmt *stmt;
1738 isl_id *id;
1739 isl_pw_multi_aff *sched2shared;
1740 isl_map *map;
1741 isl_pw_multi_aff *iterator_map;
1742 isl_union_map *schedule;
1744 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
1745 if (!stmt)
1746 return isl_ast_node_free(node);
1748 schedule = isl_ast_build_get_schedule(build);
1749 map = isl_map_reverse(isl_map_from_union_map(schedule));
1750 iterator_map = isl_pw_multi_aff_from_map(map);
1751 sched2shared = compute_sched_to_shared(gen->kernel,
1752 isl_pw_multi_aff_copy(iterator_map));
1754 stmt->type = ppcg_kernel_domain;
1755 stmt->u.d.stmt = gpu_stmt;
1757 data.gen = gen;
1758 data.accesses = stmt->u.d.stmt->accesses;
1759 data.iterator_map = iterator_map;
1760 data.sched2shared = sched2shared;
1761 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
1762 build, &transform_index, &data,
1763 &transform_expr, &data);
1765 isl_pw_multi_aff_free(iterator_map);
1766 isl_pw_multi_aff_free(sched2shared);
1768 id = isl_id_alloc(gen->ctx, NULL, stmt);
1769 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1770 return isl_ast_node_set_annotation(node, id);
1773 /* This function is called for each statement node in the AST
1774 * for copying to or from shared/private memory.
1775 * Attach a pointer to a ppcg_kernel_stmt representing the copy
1776 * statement to the node.
1777 * The statement name is "read" or "write", depending on whether we are
1778 * reading from global memory or writing to global memory.
1780 * The schedule is of the form
1782 * type[D -> A] -> L
1784 * where D corresponds to the outer group->depth dimensions of
1785 * the kernel schedule, A to the global array and L to the outer
1786 * generated AST schedule.
1787 * We compute the inverse and strip off the type, resulting in
1789 * L -> [D -> A]
1791 * We combine this mapping with on the one hand the projection
1793 * [D -> A] -> A
1795 * and on the other hand the group tiling
1797 * [D -> A] -> T
1799 * resulting in
1801 * L -> A and L -> T
1803 * and store the corresponding expressions in stmt->index and stmt->local_index,
1804 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
1806 static __isl_give isl_ast_node *create_access_leaf(struct gpu_gen *gen,
1807 struct gpu_array_ref_group *group, __isl_take isl_ast_node *node,
1808 __isl_keep isl_ast_build *build)
1810 struct ppcg_kernel_stmt *stmt;
1811 struct gpu_array_tile *tile;
1812 isl_id *id;
1813 isl_ast_expr *expr;
1814 isl_space *space;
1815 isl_map *access;
1816 isl_pw_multi_aff *pma, *pma2;
1817 const char *type;
1819 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
1820 if (!stmt)
1821 return isl_ast_node_free(node);
1823 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
1824 type = isl_map_get_tuple_name(access, isl_dim_in);
1825 stmt->u.c.read = !strcmp(type, "read");
1826 access = isl_map_reverse(access);
1827 pma = isl_pw_multi_aff_from_map(access);
1828 pma = isl_pw_multi_aff_reset_tuple_id(pma, isl_dim_out);
1830 space = isl_space_range(isl_pw_multi_aff_get_space(pma));
1831 space = isl_space_unwrap(space);
1832 pma2 = isl_pw_multi_aff_range_map(space);
1833 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2,
1834 isl_pw_multi_aff_copy(pma));
1835 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1836 stmt->u.c.index = expr;
1838 tile = gpu_array_ref_group_tile(group);
1839 pma2 = isl_pw_multi_aff_from_multi_aff(
1840 isl_multi_aff_copy(tile->tiling));
1841 pma2 = isl_pw_multi_aff_pullback_pw_multi_aff(pma2, pma);
1842 expr = isl_ast_build_access_from_pw_multi_aff(build, pma2);
1843 stmt->u.c.local_index = expr;
1845 stmt->u.c.array = group->array;
1846 stmt->u.c.local_array = group->local_array;
1847 stmt->type = ppcg_kernel_copy;
1849 id = isl_id_alloc(gen->ctx, NULL, stmt);
1850 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1851 return isl_ast_node_set_annotation(node, id);
1854 /* Create a synchronization ppcg_kernel_stmt and
1855 * attach it to the node "node" representing the synchronization.
1857 static __isl_give isl_ast_node *create_sync_leaf(
1858 struct gpu_gen *gen, __isl_take isl_ast_node *node,
1859 __isl_keep isl_ast_build *build)
1861 struct ppcg_kernel_stmt *stmt;
1862 isl_id *id;
1864 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
1865 if (!stmt)
1866 return isl_ast_node_free(node);
1868 stmt->type = ppcg_kernel_sync;
1869 id = isl_id_alloc(gen->ctx, NULL, stmt);
1870 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
1871 return isl_ast_node_set_annotation(node, id);
1874 /* This function is called for each instance of a user statement
1875 * in the kernel. This may be one of the original user statements
1876 * or a statement introduced by PPCG.
1878 * We assume that the original user statements only have a name
1879 * and no user pointer. The statements introduced by PPCG
1880 * on the other hand all have a user pointer.
1882 * If the user statement is one of the original user statements
1883 * (one with no user pointer), then we call create_domain_leaf. Otherwise,
1884 * we check if it is a copy or synchronization statement and
1885 * call the appropriate functions.
1887 static __isl_give isl_ast_node *at_domain(__isl_take isl_ast_node *node,
1888 __isl_keep isl_ast_build *build, void *user)
1890 struct gpu_gen *gen = (struct gpu_gen *) user;
1891 isl_ast_expr *expr, *arg;
1892 isl_id *id;
1893 int is_sync;
1894 const char *name;
1895 void *p;
1897 expr = isl_ast_node_user_get_expr(node);
1898 arg = isl_ast_expr_get_op_arg(expr, 0);
1899 id = isl_ast_expr_get_id(arg);
1900 name = isl_id_get_name(id);
1901 p = isl_id_get_user(id);
1902 isl_ast_expr_free(expr);
1903 isl_ast_expr_free(arg);
1905 if (!p) {
1906 struct gpu_stmt *gpu_stmt;
1908 gpu_stmt = find_stmt(gen->prog, id);
1909 isl_id_free(id);
1910 if (!gpu_stmt)
1911 isl_die(gen->ctx, isl_error_internal,
1912 "statement not found",
1913 return isl_ast_node_free(node));
1915 return create_domain_leaf(gen, node, build, gpu_stmt);
1918 is_sync = gpu_tree_id_is_sync(id, gen->kernel);
1919 isl_id_free(id);
1920 if (is_sync < 0)
1921 return isl_ast_node_free(node);
1922 if (!strcmp(name, "read") || !strcmp(name, "write")) {
1923 struct gpu_array_ref_group *group = p;
1924 return create_access_leaf(gen, group, node, build);
1926 if (!is_sync)
1927 isl_die(gen->ctx, isl_error_internal,
1928 "unknown statement type",
1929 return isl_ast_node_free(node));
1930 return create_sync_leaf(gen, node, build);
1933 /* Given a set of wrapped references "ref", return the corresponding
1934 * access relations based on the tagged access relations "tagged".
1936 * The elements of "ref" are of the form
1938 * [D -> R]
1940 * with D an iteration domains and R a reference.
1941 * The elements of "tagged" are of the form
1943 * [D -> R] -> A
1945 * with A an array.
1947 * Extend "tagged" to include the iteration domain in the range, i.e.,
1949 * [D -> R] -> [D -> A]
1951 * apply the result to "ref" and then unwrap the resulting set
1952 * to obtain relations of the form
1954 * D -> A
1956 static __isl_give isl_union_map *wrapped_reference_to_access(
1957 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
1959 isl_union_map *tag2access;
1961 tag2access = isl_union_map_copy(tagged);
1962 tag2access = isl_union_map_universe(tag2access);
1963 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
1964 tag2access = isl_union_map_domain_map(tag2access);
1965 tag2access = isl_union_map_range_product(tag2access, tagged);
1967 ref = isl_union_set_coalesce(ref);
1968 ref = isl_union_set_apply(ref, tag2access);
1970 return isl_union_set_unwrap(ref);
1973 /* Given an access relation "access" from "group", remove those reads
1974 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
1975 * communicate data within the same iteration of "sched".
1977 * If the access is a read then it is either an element of
1979 * live_in union (range flow)
1981 * where live_in and flow may be overapproximations, or
1982 * it reads an uninitialized value (that is not live-in because
1983 * there is an intermediate kill) or it reads a value that was
1984 * written within the same (compound) statement instance.
1985 * If the access is a write then it is either an element of
1987 * live_out union (domain flow)
1989 * or it writes a value that is never read (and is not live-out
1990 * because of an intermediate kill) or only
1991 * within the same (compound) statement instance.
1992 * In both cases, the access relation is also a subset of
1993 * the group access relation.
1995 * The cases where an uninitialized value is read or a value is written
1996 * that is never read or where the dataflow occurs within a statement
1997 * instance are also considered local and may also be removed.
1999 * Essentially, we compute the intersection of "access" with either
2001 * live_in union (range non-local-flow)
2003 * or
2005 * live_out union (domain non-local-flow)
2007 * We first construct a relation "local"
2009 * [[D -> R] -> [D' -> R']]
2011 * of pairs of domain iterations accessing the reference group
2012 * and references in the group that are coscheduled by "sched".
2014 * If this relation does not intersect the dataflow dependences,
2015 * then there is nothing we can possibly remove, unless the dataflow
2016 * dependences themselves only relate a subset of the accesses.
2017 * In particular, the accesses may not be involved in any dataflow
2018 * dependences, either because they are uninitialized reads/dead writes
2019 * or because the dataflow occurs inside a statement instance.
2021 * Since the computation below may break up the access relation
2022 * into smaller pieces, we only perform the intersection with
2023 * the non-local dependent accesses if the local pairs
2024 * intersect the dataflow dependences. Otherwise, we intersect
2025 * with the universe of the non-local dependent accesses.
2026 * This should at least remove accesses from statements that
2027 * do not participate in any dependences.
2029 * In particular, we remove the "local" dataflow dependences from
2030 * the set of all dataflow dependences.
2031 * Note that if the potential dataflow dependences are an overapproximation
2032 * of the actual dataflow dependences, then the result remains an
2033 * overapproximation of the non-local dataflow dependences.
2034 * Copying to/from global memory is only needed for the references
2035 * in the domain/range of the result or for accesses that are live out/in
2036 * for the entire scop.
2038 * We therefore map the domain/range of the "external" relation
2039 * to the corresponding access relation and take the union with
2040 * the live out/in relation.
2042 static __isl_give isl_union_map *remove_local_accesses(
2043 struct gpu_prog *prog, struct gpu_array_ref_group *group,
2044 __isl_take isl_union_map *access, __isl_take isl_union_map *sched,
2045 int read)
2047 int empty;
2048 isl_union_pw_multi_aff *tagger;
2049 isl_union_set *domain;
2050 isl_union_map *local, *tagged, *external;
2051 isl_union_set *tag_set;
2053 if (isl_union_map_is_empty(access)) {
2054 isl_union_map_free(sched);
2055 return access;
2058 tagged = group_tagged_access_relation(group);
2060 tagger = isl_union_pw_multi_aff_copy(prog->scop->tagger);
2061 domain = isl_union_map_domain(isl_union_map_copy(tagged));
2062 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
2063 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
2065 local = isl_union_map_apply_range(sched,
2066 isl_union_map_reverse(isl_union_map_copy(sched)));
2067 local = isl_union_map_intersect(local,
2068 isl_union_map_copy(prog->scop->tagged_dep_flow));
2070 empty = isl_union_map_is_empty(local);
2072 external = isl_union_map_copy(prog->scop->tagged_dep_flow);
2073 external = isl_union_map_intersect_params(external,
2074 isl_set_copy(prog->scop->context));
2075 external = isl_union_map_subtract(external, local);
2077 if (read) {
2078 tag_set = isl_union_map_range(external);
2079 external = wrapped_reference_to_access(tag_set, tagged);
2080 external = isl_union_map_union(external,
2081 isl_union_map_copy(prog->scop->live_in));
2082 } else {
2083 tag_set = isl_union_map_domain(external);
2084 external = wrapped_reference_to_access(tag_set, tagged);
2085 external = isl_union_map_union(external,
2086 isl_union_map_copy(prog->scop->live_out));
2089 if (empty < 0)
2090 external = isl_union_map_free(external);
2091 else if (empty)
2092 external = isl_union_map_universe(external);
2094 access = isl_union_map_intersect(access, external);
2096 return access;
2099 /* Given an access relation "access" from "group", remove those reads
2100 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
2101 * communicate data within the same iteration of the schedule at the
2102 * position where the copying of the group is inserted.
2103 * "node" points to this position, i.e., the depth at "node"
2104 * is equal to group->depth.
2106 * We extract a schedule that picks out the iterations of the outer
2107 * group->depth dimensions and call remove_local_accesses.
2109 static __isl_give isl_union_map *remove_local_accesses_group(
2110 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2111 __isl_take isl_union_map *access, __isl_keep isl_schedule_node *node,
2112 int read)
2114 isl_union_map *sched;
2116 if (isl_union_map_is_empty(access))
2117 return access;
2119 sched = isl_schedule_node_get_prefix_schedule_relation(node);
2121 return remove_local_accesses(kernel->prog, group, access, sched, read);
2124 /* This function is called before the AST generator starts traversing
2125 * the schedule subtree of a node with mark "mark".
2127 * If the mark is called "kernel", store the kernel pointer in gen->kernel
2128 * for use in at_domain.
2130 static int before_mark(__isl_keep isl_id *mark,
2131 __isl_keep isl_ast_build *build, void *user)
2133 struct gpu_gen *gen = user;
2135 if (!mark)
2136 return -1;
2137 if (!strcmp(isl_id_get_name(mark), "kernel"))
2138 gen->kernel = isl_id_get_user(mark);
2139 return 0;
2142 /* This function is called after the AST generator has finished traversing
2143 * the schedule subtree of a mark node. "node" points to the corresponding
2144 * mark AST node.
2146 * If the mark is called "kernel", then replace "node" by a user node
2147 * that "calls" the kernel, representing the launch of the kernel.
2148 * The original "node" is stored inside the kernel object so that
2149 * it can be used to print the device code.
2150 * Note that this assumes that a kernel is only launched once.
2151 * Also clear the kernel field of gen.
2153 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
2154 __isl_keep isl_ast_build *build, void *user)
2156 isl_ctx *ctx;
2157 isl_id *id;
2158 isl_ast_expr *expr;
2159 isl_ast_expr_list *list;
2160 struct ppcg_kernel *kernel;
2161 struct gpu_gen *gen = user;
2163 ctx = isl_ast_node_get_ctx(node);
2164 id = isl_ast_node_mark_get_id(node);
2165 if (!id)
2166 return isl_ast_node_free(node);
2167 if (strcmp(isl_id_get_name(id), "kernel") || !gen->kernel) {
2168 isl_id_free(id);
2169 return node;
2171 kernel = gen->kernel;
2172 gen->kernel = NULL;
2173 kernel->space = isl_ast_build_get_schedule_space(build);
2174 kernel->tree = isl_ast_node_mark_get_node(node);
2175 isl_ast_node_free(node);
2177 expr = isl_ast_expr_from_id(isl_id_copy(id));
2178 list = isl_ast_expr_list_alloc(ctx, 0);
2179 expr = isl_ast_expr_call(expr, list);
2180 node = isl_ast_node_alloc_user(expr);
2181 node = isl_ast_node_set_annotation(node, id);
2183 return node;
2186 static int update_depth(__isl_keep isl_schedule_node *node, void *user)
2188 int *depth = user;
2189 int node_depth;
2191 if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf)
2192 return 1;
2193 node_depth = isl_schedule_node_get_schedule_depth(node);
2194 if (node_depth > *depth)
2195 *depth = node_depth;
2197 return 0;
2200 /* Use isl to generate code for both the host and the device
2201 * from gen->schedule.
2202 * The device code is marked by "kernel" mark nodes in the schedule tree,
2203 * containing a pointer to a ppcg_kernel object.
2204 * The returned AST only contains the AST for the host code.
2205 * The ASTs for the device code are embedded in ppcg_kernel objects
2206 * attached to the leaf nodes that call "kernel".
2208 static __isl_give isl_ast_node *generate_code(struct gpu_gen *gen)
2210 isl_ast_build *build;
2211 isl_ast_node *tree;
2212 isl_schedule *schedule;
2213 isl_id_list *iterators;
2214 int depth;
2216 depth = 0;
2217 if (isl_schedule_foreach_schedule_node(gen->schedule, &update_depth,
2218 &depth) < 0)
2219 return NULL;
2220 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
2221 iterators = ppcg_scop_generate_names(gen->prog->scop, depth, "c");
2222 build = isl_ast_build_set_iterators(build, iterators);
2223 build = isl_ast_build_set_at_each_domain(build, &at_domain, gen);
2224 build = isl_ast_build_set_before_each_mark(build, &before_mark, gen);
2225 build = isl_ast_build_set_after_each_mark(build, &after_mark, gen);
2226 schedule = isl_schedule_copy(gen->schedule);
2227 tree = isl_ast_build_node_from_schedule(build, schedule);
2228 isl_ast_build_free(build);
2230 return tree;
2233 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
2235 if (!str)
2236 return NULL;
2237 return isl_union_map_read_from_str(ctx, str);
2240 /* Information about the outermost tilable bands in the forest of bands.
2242 * prefix is the (padded) schedule leading up to the outermost tilable bands.
2244 * tile_first is the number of schedule dimensions in prefix.
2246 * suffix is the schedule of the outermost tilable bands and their descendants.
2248 struct band_info {
2249 struct gpu_gen *gen;
2250 int tile_first;
2251 isl_union_map *prefix;
2252 isl_union_map *suffix;
2255 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
2256 * from the elements in "tile_size".
2258 static __isl_give isl_multi_val *construct_band_tiles_sizes(
2259 __isl_keep isl_schedule_node *node, int *tile_size)
2261 int i, n;
2262 isl_ctx *ctx;
2263 isl_space *space;
2264 isl_multi_val *mv;
2266 if (!node)
2267 return NULL;
2269 ctx = isl_schedule_node_get_ctx(node);
2270 space = isl_schedule_node_band_get_space(node);
2271 n = isl_schedule_node_band_n_member(node);
2272 mv = isl_multi_val_zero(space);
2273 for (i = 0; i < n; ++i) {
2274 isl_val *v;
2276 v = isl_val_int_from_si(ctx, tile_size[i]);
2277 mv = isl_multi_val_set_val(mv, i, v);
2280 return mv;
2283 /* Replace the partial schedule S of the band node "node" by
2285 * floor(S/f)
2287 * or
2289 * f * floor(S/f)
2291 * if scale_tile_loops is set, with f the integers in "factor".
2292 * The list that "factor" points to is assumed to contain at least
2293 * as many elements as the number of members in the band.
2295 static __isl_give isl_schedule_node *snap_band_to_sizes(
2296 __isl_take isl_schedule_node *node, int *factor,
2297 struct ppcg_options *options)
2299 isl_multi_val *mv;
2301 mv = construct_band_tiles_sizes(node, factor);
2302 node = isl_schedule_node_band_scale_down(node, isl_multi_val_copy(mv));
2303 if (options->scale_tile_loops)
2304 node = isl_schedule_node_band_scale(node,
2305 isl_multi_val_copy(mv));
2306 isl_multi_val_free(mv);
2308 return node;
2311 /* Tile "band" with tile size specified by "sizes".
2313 * Since the tile loops will be mapped to block ids, we forcibly
2314 * turn off tile loop scaling. We may want to enable tile loop scaling
2315 * at some later point, but then we would have to support the detection
2316 * of strides during the mapping to block ids.
2317 * Similarly, since the point loops will be mapped to thread ids,
2318 * we forcibly shift the point loops so that they start at zero.
2320 static __isl_give isl_schedule_node *tile_band(
2321 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2323 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
2324 int scale_tile;
2325 int shift_point;
2327 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
2328 isl_options_set_tile_scale_tile_loops(ctx, 0);
2329 shift_point = isl_options_get_tile_shift_point_loops(ctx);
2330 isl_options_set_tile_shift_point_loops(ctx, 1);
2332 node = isl_schedule_node_band_tile(node, sizes);
2334 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
2335 isl_options_set_tile_shift_point_loops(ctx, shift_point);
2337 return node;
2340 /* Extract the set of parameter values and outer schedule dimensions
2341 * for which any statement instance
2342 * in the kernel inserted at "node" needs to be executed.
2343 * Intersect the set of parameter values derived from the host schedule
2344 * relation with the context of "prog".
2346 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
2347 struct gpu_prog *prog)
2349 isl_union_map *schedule;
2350 isl_union_set *schedule_domain;
2351 isl_set *context;
2352 int empty;
2354 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
2355 schedule_domain = isl_union_map_range(schedule);
2356 empty = isl_union_set_is_empty(schedule_domain);
2357 if (empty < 0) {
2358 isl_union_set_free(schedule_domain);
2359 return NULL;
2361 if (empty) {
2362 int depth;
2363 isl_space *space;
2365 space = isl_union_set_get_space(schedule_domain);
2366 isl_union_set_free(schedule_domain);
2367 space = isl_space_set_from_params(space);
2368 depth = isl_schedule_node_get_schedule_depth(node);
2369 space = isl_space_add_dims(space, isl_dim_set, depth);
2370 context = isl_set_empty(space);
2371 } else {
2372 context = isl_set_from_union_set(schedule_domain);
2374 context = isl_set_intersect_params(context,
2375 isl_set_copy(prog->context));
2377 return context;
2380 /* Return the set of outer array elements accessed by
2381 * by the statement instance in "domain" in "prog".
2383 static __isl_give isl_union_set *accessed_by_domain(
2384 __isl_take isl_union_set *domain, struct gpu_prog *prog)
2386 isl_union_map *access;
2387 isl_union_set *arrays;
2389 access = isl_union_map_union(isl_union_map_copy(prog->read),
2390 isl_union_map_copy(prog->may_write));
2391 access = isl_union_map_intersect_domain(access, domain);
2392 arrays = isl_union_map_range(access);
2393 arrays = isl_union_set_apply(arrays,
2394 isl_union_map_copy(prog->to_outer));
2396 return arrays;
2399 /* Return the number of outer band members of the band node "node"
2400 * that are marked coincident.
2402 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
2404 int i, n;
2406 n = isl_schedule_node_band_n_member(node);
2408 for (i = 0; i < n; ++i)
2409 if (!isl_schedule_node_band_member_get_coincident(node, i))
2410 break;
2412 return i;
2415 /* If the band node "node" has more than "n" members, then split off
2416 * the first "n" of them.
2418 static __isl_give isl_schedule_node *split_band(
2419 __isl_take isl_schedule_node *node, int n)
2421 int dim;
2423 dim = isl_schedule_node_band_n_member(node);
2424 if (n < dim)
2425 node = isl_schedule_node_band_split(node, n);
2427 return node;
2430 /* Scale a band node that may have been split by split_band.
2431 * "sizes" are the scaling factors for the original node.
2432 * "node" either points to the original band node, or the outer
2433 * of the two pieces after splitting.
2435 * If the number of elements in "node" is smaller than the number of
2436 * elements in "sizes", then some splitting has occurred and we split
2437 * "sizes" in the same way.
2439 static __isl_give isl_schedule_node *scale_band(
2440 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
2442 int n, dim;
2444 n = isl_multi_val_dim(sizes, isl_dim_set);
2445 dim = isl_schedule_node_band_n_member(node);
2446 if (n > dim) {
2447 isl_multi_val *sizes2;
2449 sizes2 = isl_multi_val_copy(sizes);
2450 sizes = isl_multi_val_drop_dims(sizes,
2451 isl_dim_set, dim, n - dim);
2452 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
2453 node = isl_schedule_node_child(node, 0);
2454 node = isl_schedule_node_band_scale(node, sizes2);
2455 node = isl_schedule_node_parent(node);
2458 return isl_schedule_node_band_scale(node, sizes);
2461 /* Return an isl_multi_aff, with as elements the parameters in "space"
2462 * that have the names specified by the elements in "names".
2463 * If (some of) these parameters do not already appear in "space",
2464 * then they are added first.
2466 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
2467 __isl_keep isl_id_list *names)
2469 int i, n;
2470 isl_local_space *ls;
2471 isl_multi_aff *ma;
2473 if (!names)
2474 space = isl_space_free(space);
2476 n = isl_id_list_n_id(names);
2477 for (i = 0; i < n; ++i) {
2478 int pos;
2479 isl_id *id;
2481 id = isl_id_list_get_id(names, i);
2482 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2483 if (pos >= 0) {
2484 isl_id_free(id);
2485 continue;
2487 pos = isl_space_dim(space, isl_dim_param);
2488 space = isl_space_add_dims(space, isl_dim_param, 1);
2489 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
2491 ma = isl_multi_aff_zero(isl_space_copy(space));
2492 ls = isl_local_space_from_space(isl_space_domain(space));
2493 for (i = 0; i < n; ++i) {
2494 int pos;
2495 isl_id *id;
2496 isl_aff *aff;
2498 id = isl_id_list_get_id(names, i);
2499 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
2500 isl_id_free(id);
2501 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
2502 isl_dim_param, pos);
2503 ma = isl_multi_aff_set_aff(ma, i, aff);
2505 isl_local_space_free(ls);
2507 return ma;
2510 /* Return constraints on the domain elements that equate a sequence of
2511 * parameters called "names", to the partial schedule
2512 * of "node" modulo the integers in "size".
2513 * The number of elements in the array "size" should be equal
2514 * to the number of elements in "names".
2515 * The number of members of the band node "node" should be smaller
2516 * than or equal to this number. If it is smaller, then the first
2517 * elements of "names" are equated to zero.
2519 static __isl_give isl_union_set *set_schedule_modulo(
2520 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
2521 int *size)
2523 int n, n_zero;
2524 isl_space *space;
2525 isl_multi_aff *ma;
2526 isl_multi_union_pw_aff *mupa, *mupa2;
2527 isl_multi_val *mv;
2528 isl_union_set *domain;
2530 if (!node)
2531 return NULL;
2532 n = isl_id_list_n_id(names);
2533 if (n == 0)
2534 return isl_schedule_node_get_universe_domain(node);
2535 n_zero = n - isl_schedule_node_band_n_member(node);
2537 mupa = isl_schedule_node_band_get_partial_schedule(node);
2538 mv = construct_band_tiles_sizes(node, size + n_zero);
2539 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
2541 space = isl_multi_union_pw_aff_get_space(mupa);
2542 space = isl_space_params(space);
2543 space = isl_space_set_from_params(space);
2544 space = isl_space_add_dims(space, isl_dim_set, n_zero);
2545 ma = isl_multi_aff_zero(space);
2547 domain = isl_schedule_node_get_universe_domain(node);
2548 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(
2549 isl_union_set_copy(domain), ma);
2550 mupa = isl_multi_union_pw_aff_range_product(mupa2, mupa);
2552 space = isl_multi_union_pw_aff_get_space(mupa);
2553 ma = parameter_vector(space, names);
2555 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
2556 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
2558 return isl_multi_union_pw_aff_zero_union_set(mupa);
2561 /* Insert a context node at "node" introducing the block and thread
2562 * identifiers along with their bounds, which are stored in kernel->grid_size
2563 * and kernel->block_dim.
2564 * Note that the bounds on the block identifiers may implicitly impose
2565 * constraints on the parameters. A guard needs to be inserted
2566 * in the schedule tree to ensure that those bounds hold at "node".
2567 * This guard is inserted in insert_guard.
2569 static __isl_give isl_schedule_node *insert_context(struct ppcg_kernel *kernel,
2570 __isl_take isl_schedule_node *node)
2572 isl_set *context;
2574 context = isl_set_universe(isl_set_get_space(kernel->context));
2576 context = add_bounded_parameters_dynamic(context,
2577 kernel->grid_size, kernel->block_ids);
2578 context = add_bounded_parameters(context,
2579 kernel->block_dim, kernel->thread_ids);
2581 node = isl_schedule_node_insert_context(node, context);
2583 return node;
2586 /* Insert a guard that eliminates kernel launches where the kernel
2587 * obviously does not have any work to do.
2589 * In particular, eliminate kernel launches where there are obviously
2590 * zero blocks.
2591 * Use the same block size constraints that are used to create the context
2592 * to ensure that all constraints implicit in the constructed context
2593 * are imposed by the guard.
2595 * Additionally, add other constraints that are valid
2596 * for each executed instance ("context"), as long as this does not result
2597 * in a disjunction.
2599 static __isl_give isl_schedule_node *insert_guard(
2600 __isl_take isl_schedule_node *node, __isl_keep isl_set *context,
2601 __isl_keep isl_multi_pw_aff *size, struct ppcg_scop *scop)
2603 unsigned nparam, n;
2604 isl_set *guard;
2605 isl_id_list *ids;
2607 guard = isl_set_copy(context);
2608 guard = isl_set_compute_divs(guard);
2609 guard = isl_set_from_basic_set(isl_set_simple_hull(guard));
2611 nparam = isl_set_dim(guard, isl_dim_param);
2612 n = isl_multi_pw_aff_dim(size, isl_dim_out);
2613 ids = ppcg_scop_generate_names(scop, n, "__ppcg_tmp");
2614 guard = add_bounded_parameters_dynamic(guard, size, ids);
2615 isl_id_list_free(ids);
2616 guard = isl_set_project_out(guard, isl_dim_param, nparam, n);
2618 node = isl_schedule_node_insert_guard(node, guard);
2620 return node;
2623 /* Does any array reference group mapping require the band that is mapped
2624 * to threads to be unrolled?
2626 static int kernel_requires_unroll(struct ppcg_kernel *kernel)
2628 int i, j;
2630 for (i = 0; i < kernel->n_array; ++i) {
2631 struct gpu_local_array_info *array = &kernel->array[i];
2633 for (j = 0; j < array->n_group; ++j) {
2634 struct gpu_array_ref_group *group = array->groups[j];
2635 if (gpu_array_ref_group_requires_unroll(group))
2636 return 1;
2640 return 0;
2643 /* Mark the given band node "node" for unrolling by the AST generator and
2644 * then sink it to the leaves of the schedule tree.
2645 * All dimensions of "node" are assumed to be coincident, such that this
2646 * sinking is a valid operation.
2648 static __isl_give isl_schedule_node *unroll(__isl_take isl_schedule_node *node)
2650 int i, n;
2652 n = isl_schedule_node_band_n_member(node);
2653 for (i = 0; i < n; ++i)
2654 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
2655 isl_ast_loop_unroll);
2657 node = isl_schedule_node_band_sink(node);
2659 return node;
2662 /* Is there any write in "kernel" that writes directly to global memory?
2663 * That is, is there any array reference group that involves a write and
2664 * that is not mapped to private or shared memory?
2666 static int any_global_write(struct ppcg_kernel *kernel)
2668 int i, j;
2670 for (i = 0; i < kernel->n_array; ++i) {
2671 struct gpu_local_array_info *array = &kernel->array[i];
2673 for (j = 0; j < array->n_group; ++j) {
2674 struct gpu_array_ref_group *group = array->groups[j];
2676 if (!group->write)
2677 continue;
2678 if (group->private_tile || group->shared_tile)
2679 continue;
2680 return 1;
2684 return 0;
2687 /* Insert a synchronization node in the schedule tree of "node"
2688 * after the core computation of "kernel" at the level of the band
2689 * that is mapped to threads, except if that level is equal to
2690 * that of the band that is mapped to blocks.
2691 * "node" is assumed to point to the kernel node.
2693 static __isl_give isl_schedule_node *add_sync(struct ppcg_kernel *kernel,
2694 __isl_take isl_schedule_node *node)
2696 int kernel_depth;
2698 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2700 node = gpu_tree_move_down_to_thread(node, kernel->core);
2701 if (kernel_depth == isl_schedule_node_get_schedule_depth(node))
2702 return gpu_tree_move_up_to_kernel(node);
2704 node = gpu_tree_ensure_following_sync(node, kernel);
2706 node = gpu_tree_move_up_to_kernel(node);
2708 return node;
2711 /* Return a read ("read" is 1) or write access relation for "group"
2712 * with those accesses removed that are only needed to communicate data
2713 * within the subtree of the schedule rooted at "node".
2714 * Furthermore, include the prefix schedule at "node".
2715 * That is, return a relation of the form
2717 * S -> [D -> A]
2719 * with D the outer schedule dimensions at "node".
2721 static __isl_give isl_union_map *anchored_non_local_accesses(
2722 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2723 __isl_take isl_schedule_node *node, int read)
2725 isl_union_map *access;
2726 isl_union_map *prefix;
2728 access = gpu_array_ref_group_access_relation(group, read, !read);
2729 access = remove_local_accesses_group(kernel, group, access, node, read);
2730 prefix = isl_schedule_node_get_prefix_schedule_relation(node);
2731 access = isl_union_map_range_product(prefix, access);
2733 return access;
2736 /* Given an array reference group "group", create a mapping
2738 * read[D -> A] -> [D -> A]
2740 * if "read" is set or
2742 * write[D -> A] -> [D -> A]
2744 * if "read" is not set.
2745 * D corresponds to the outer group->depth dimensions of
2746 * the kernel schedule.
2748 static __isl_give isl_multi_aff *create_from_access(isl_ctx *ctx,
2749 struct gpu_array_ref_group *group, int read)
2751 isl_space *space;
2752 isl_id *id;
2754 space = isl_space_copy(group->array->space);
2755 space = isl_space_from_range(space);
2756 space = isl_space_add_dims(space, isl_dim_in, group->depth);
2757 space = isl_space_wrap(space);
2758 space = isl_space_map_from_set(space);
2760 id = isl_id_alloc(ctx, read ? "read" : "write", group);
2761 space = isl_space_set_tuple_id(space, isl_dim_in, id);
2763 return isl_multi_aff_identity(space);
2766 /* Add copy statements to the schedule tree of "node"
2767 * for reading from global memory to private memory (if "read" is set) or
2768 * for writing back from private memory to global memory
2769 * (if "read" is not set) for the array reference group "group" that
2770 * is mapped to private memory.
2771 * On input, "node" points to the kernel node, and it is moved
2772 * back there on output.
2774 * The copies are performed in the order of the array elements.
2775 * The copy statement instances include a reference to the outer
2776 * group->depth dimensions of the kernel schedule for ease of
2777 * combining them with the group tiling.
2779 * That is, the extra schedule is of the form
2781 * type[D -> A] -> A
2783 * where D corresponds to the outer group->depth dimensions of
2784 * the kernel schedule and A to the global array.
2785 * This schedule is unrolled because registers are not addressable.
2787 * The copying is inserted in the schedule tree through an extension
2788 * of the form
2790 * D -> type[D -> A]
2792 * where the extra domain elements type[D -> A] are those accessed
2793 * by the group.
2794 * A filter is inserted on type[D -> A] to ensure that the element
2795 * is read/written by the same thread that needs the element.
2796 * This filter is obtained by applying
2798 * S -> type[D -> A]
2800 * to the thread filter for the core statements.
2802 * The extension is inserted before the core computation in case of a read
2803 * and after the core computation in case of a write.
2804 * In the latter case, we also make sure that there is a synchronization
2805 * node after the write to global memory, unless this write is performed
2806 * at the outer level of the kernel.
2807 * In principle, this synchronization could be inserted higher
2808 * in the schedule tree depending on where the corresponding reads
2809 * from global memory are performed.
2811 static __isl_give isl_schedule_node *add_copies_group_private(
2812 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2813 __isl_take isl_schedule_node *node, int read)
2815 isl_union_map *access;
2816 isl_union_map *prefix;
2817 isl_union_set *domain;
2818 isl_space *space;
2819 isl_multi_aff *from_access;
2820 isl_multi_pw_aff *mpa;
2821 isl_multi_union_pw_aff *mupa;
2822 isl_schedule_node *graft;
2823 isl_union_set *filter;
2824 int kernel_depth;
2825 int empty;
2827 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2828 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
2830 access = anchored_non_local_accesses(kernel, group, node, read);
2831 empty = isl_union_map_is_empty(access);
2832 if (empty < 0 || empty) {
2833 isl_union_map_free(access);
2834 if (empty < 0)
2835 return isl_schedule_node_free(node);
2836 return gpu_tree_move_up_to_kernel(node);
2839 from_access = create_from_access(kernel->ctx, group, read);
2840 space = isl_space_domain(isl_multi_aff_get_space(from_access));
2841 access = isl_union_map_preimage_range_multi_aff(access, from_access);
2843 filter = isl_union_set_copy(kernel->thread_filter);
2844 filter = isl_union_set_apply(filter, isl_union_map_copy(access));
2845 filter = isl_union_set_detect_equalities(filter);
2846 filter = isl_union_set_coalesce(filter);
2848 domain = isl_union_map_range(access);
2849 access = isl_union_set_wrapped_domain_map(domain);
2850 access = isl_union_map_reverse(access);
2851 access = isl_union_map_coalesce(access);
2852 graft = isl_schedule_node_from_extension(access);
2854 space = isl_space_map_from_set(space);
2855 mpa = isl_multi_pw_aff_identity(space);
2856 mpa = isl_multi_pw_aff_range_factor_range(mpa);
2857 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
2859 graft = isl_schedule_node_child(graft, 0);
2860 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
2861 graft = unroll(graft);
2863 graft = isl_schedule_node_insert_filter(graft, filter);
2865 graft = isl_schedule_node_parent(graft);
2867 if (read)
2868 node = isl_schedule_node_graft_before(node, graft);
2869 else {
2870 node = isl_schedule_node_graft_after(node, graft);
2871 if (kernel_depth < group->depth) {
2872 node = isl_schedule_node_parent(node);
2873 node = isl_schedule_node_next_sibling(node);
2874 node = isl_schedule_node_child(node, 0);
2875 node = gpu_tree_ensure_following_sync(node, kernel);
2879 node = gpu_tree_move_up_to_kernel(node);
2881 return node;
2884 /* Add copy statements to the schedule tree of "node"
2885 * for reading from global memory to shared memory (if "read" is set) or
2886 * for writing back from shared memory to global memory
2887 * (if "read" is not set) for the array reference group "group" that
2888 * is mapped to shared memory.
2889 * On input, "node" points to the kernel node, and it is moved
2890 * back there on output.
2892 * The copies are performed in the order of the corresponding shared
2893 * memory tile.
2894 * The copy statement instances include a reference to the outer
2895 * group->depth dimensions of the kernel schedule for ease of
2896 * combining them with the group tiling.
2898 * If we are performing a read from global memory to shared memory and
2899 * if the array involved is not a scalar, then we copy
2900 * the entire tile to shared memory. This may result in some extra
2901 * elements getting copied, but it should lead to simpler code
2902 * (which means that fewer registers may be needed) and less divergence.
2904 * Otherwise, we only copy the elements that will be read or have been written
2905 * in the kernel.
2907 * That is, the extra schedule is of the form
2909 * type[D -> A] -> T
2911 * where D corresponds to the outer group->depth dimensions of
2912 * the kernel schedule, A to the global array and T is the corresponding
2913 * shared memory tile.
2915 * The copying is inserted in the schedule tree through an extension
2916 * of the form
2918 * D -> type[D -> A]
2920 * where the extra domain elements type[D -> A] are those accessed
2921 * by the group. In the case of read from a non-scalar, this set
2922 * is replaced by the entire shared memory tile.
2924 * A filter is inserted on type[D -> A] to map the copy instances
2925 * to the threads. In particular, the thread identifiers are
2926 * equated to the position inside the shared memory tile (T)
2927 * modulo the block size.
2928 * We try to align the innermost tile dimension with the innermost
2929 * thread identifier (x) as a heuristic to improve coalescing.
2930 * In particular, if the dimension of the tile is greater than
2931 * the dimension of the block, then the schedule mapping to the tile
2932 * is broken up into two pieces and the filter is applied to the inner part.
2933 * If, on the other hand, the dimension of the tile is smaller than
2934 * the dimension of the block, then the initial thread identifiers
2935 * are equated to zero and the remaining thread identifiers are
2936 * matched to the memory tile.
2938 * The extension is inserted before the core computation in case of a read
2939 * and after the core computation in case of a write.
2940 * In the case of a read, we first need to make sure there is some
2941 * synchronization before the core computation such that we can put the read
2942 * from global memory to shared memory before that synchronization.
2943 * This ensures that all threads have finished copying into shared memory
2944 * before the shared memory is used.
2945 * We also need to make sure that there is a synchronization node after
2946 * the core computation to ensure that the next load into shared memory
2947 * only happens after all data has been used. There is no need for
2948 * this synchronization if we are at the outer level since then there
2949 * won't be a next load.
2950 * In the case of a write, we need to make sure there is some synchronization
2951 * after the core computation such taht we can put the write from shared
2952 * memory to global memory after that synchronization.
2953 * Unless we are at the outer level, we also need a synchronization node
2954 * after the write to ensure the data is saved to global memory
2955 * before the next iteration write to the same shared memory.
2956 * It also makes sure the data has arrived in global memory before
2957 * it is read in a subsequent iteration.
2959 static __isl_give isl_schedule_node *add_copies_group_shared(
2960 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
2961 __isl_take isl_schedule_node *node, int read)
2963 struct gpu_array_tile *tile;
2964 isl_union_map *access;
2965 isl_union_set *domain;
2966 isl_union_set *sync;
2967 isl_multi_aff *ma;
2968 isl_multi_aff *from_access;
2969 isl_multi_pw_aff *mpa;
2970 isl_multi_union_pw_aff *mupa;
2971 isl_schedule_node *graft;
2972 isl_union_set *filter;
2973 int skip;
2974 int kernel_depth;
2975 int empty;
2977 kernel_depth = isl_schedule_node_get_schedule_depth(node);
2978 node = gpu_tree_move_down_to_depth(node, group->depth, kernel->core);
2980 access = anchored_non_local_accesses(kernel, group, node, read);
2981 empty = isl_union_map_is_empty(access);
2982 if (empty < 0 || empty) {
2983 isl_union_map_free(access);
2984 if (empty < 0)
2985 return isl_schedule_node_free(node);
2986 return gpu_tree_move_up_to_kernel(node);
2989 from_access = create_from_access(kernel->ctx, group, read);
2991 tile = gpu_array_ref_group_tile(group);
2992 ma = isl_multi_aff_copy(tile->tiling);
2993 ma = isl_multi_aff_pullback_multi_aff(ma,
2994 isl_multi_aff_copy(from_access));
2995 mpa = isl_multi_pw_aff_from_multi_aff(ma);
2996 mupa = isl_multi_union_pw_aff_from_multi_pw_aff(mpa);
2998 domain = isl_union_map_range(access);
3000 if (read && !gpu_array_is_scalar(group->array)) {
3001 isl_map *map;
3002 isl_union_set_free(domain);
3003 map = group_tile(group);
3004 domain = isl_union_set_from_set(isl_map_wrap(map));
3007 domain = isl_union_set_preimage_multi_aff(domain, from_access);
3008 access = isl_union_set_wrapped_domain_map(domain);
3009 access = isl_union_map_reverse(access);
3010 access = isl_union_map_coalesce(access);
3011 graft = isl_schedule_node_from_extension(access);
3013 graft = isl_schedule_node_child(graft, 0);
3015 graft = isl_schedule_node_insert_partial_schedule(graft, mupa);
3017 if (tile->n > kernel->n_block && kernel->n_block > 0) {
3018 graft = isl_schedule_node_band_split(graft,
3019 tile->n - kernel->n_block);
3020 graft = isl_schedule_node_child(graft, 0);
3022 if (tile->n < kernel->n_block)
3023 skip = kernel->n_block - tile->n;
3024 else
3025 skip = 0;
3026 filter = set_schedule_modulo(graft, kernel->thread_ids,
3027 kernel->block_dim);
3028 if (!kernel->options->wrap)
3029 graft = snap_band_to_sizes(graft, kernel->block_dim + skip,
3030 kernel->options);
3031 if (tile->n > kernel->n_block && kernel->n_block > 0)
3032 graft = isl_schedule_node_parent(graft);
3033 graft = isl_schedule_node_insert_filter(graft, filter);
3035 while (graft && isl_schedule_node_has_parent(graft))
3036 graft = isl_schedule_node_parent(graft);
3038 if (read) {
3039 if (kernel_depth < group->depth)
3040 node = gpu_tree_ensure_sync_after_core(node, kernel);
3041 node = gpu_tree_move_left_to_sync(node, kernel);
3042 node = isl_schedule_node_graft_before(node, graft);
3043 } else {
3044 node = gpu_tree_move_right_to_sync(node, kernel);
3045 node = isl_schedule_node_graft_after(node, graft);
3046 node = isl_schedule_node_parent(node);
3047 node = isl_schedule_node_next_sibling(node);
3048 node = isl_schedule_node_child(node, 0);
3049 if (kernel_depth < group->depth)
3050 node = gpu_tree_ensure_following_sync(node, kernel);
3053 node = gpu_tree_move_up_to_kernel(node);
3055 return node;
3058 /* Check whether the array reference group "group" is mapped to
3059 * private or shared memory and, if so,
3060 * add copy statements to the schedule tree of "node"
3061 * for reading from global memory to private or shared memory
3062 * (if "read" is set) or for writing back from private or shared memory
3063 * to global memory (if "read" is not set) for this group.
3064 * On input, "node" points to the kernel node, and it is moved
3065 * back there on output.
3067 static __isl_give isl_schedule_node *add_copies_group(
3068 struct ppcg_kernel *kernel, struct gpu_array_ref_group *group,
3069 __isl_take isl_schedule_node *node, int read)
3071 if (group->private_tile)
3072 return add_copies_group_private(kernel, group, node, read);
3073 if (group->shared_tile)
3074 return add_copies_group_shared(kernel, group, node, read);
3075 return node;
3078 /* For each array reference group that is mapped to private or shared memory,
3079 * add copy statements to the schedule tree of "node"
3080 * for reading from global memory to private or shared memory
3081 * and for writing back.
3082 * On input, "node" points to the kernel node, and it is moved
3083 * back there on output.
3085 static __isl_give isl_schedule_node *add_copies(struct ppcg_kernel *kernel,
3086 __isl_take isl_schedule_node *node)
3088 int i, j;
3090 for (i = 0; i < kernel->n_array; ++i) {
3091 struct gpu_local_array_info *array = &kernel->array[i];
3093 for (j = 0; j < array->n_group; ++j) {
3094 struct gpu_array_ref_group *group = array->groups[j];
3096 node = add_copies_group(kernel, group, node, 1);
3097 if (!node)
3098 return NULL;
3099 node = add_copies_group(kernel, group, node, 0);
3100 if (!node)
3101 return NULL;
3105 return node;
3108 /* Mark all dimensions in the current band node atomic.
3110 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3112 int i, n;
3114 n = isl_schedule_node_band_n_member(node);
3115 for (i = 0; i < n; ++i)
3116 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3117 isl_ast_loop_atomic);
3119 return node;
3122 /* Mark "node" atomic, if it is a band node.
3123 * Do the same for all ancestors.
3124 * Return a pointer to "node" (in the updated schedule tree).
3126 static __isl_give isl_schedule_node *atomic_ancestors(
3127 __isl_take isl_schedule_node *node)
3129 int pos;
3131 if (!node)
3132 return NULL;
3133 if (!isl_schedule_node_has_parent(node))
3134 return node;
3136 pos = isl_schedule_node_get_child_position(node);
3137 node = isl_schedule_node_parent(node);
3138 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
3139 node = atomic(node);
3140 node = atomic_ancestors(node);
3141 node = isl_schedule_node_child(node, pos);
3143 return node;
3146 /* Group the domain elements into a single space, named kernelX,
3147 * with X the kernel sequence number "kernel_id".
3149 static __isl_give isl_schedule_node *group_statements(
3150 __isl_take isl_schedule_node *node, int kernel_id)
3152 char buffer[20];
3153 isl_id *id;
3155 if (!node)
3156 return NULL;
3158 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
3159 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
3160 return isl_schedule_node_group(node, id);
3163 /* Create a ppcg_kernel representing the domain instances that reach "node"
3164 * and insert a mark node pointing to the ppcg_kernel before "node".
3165 * The band that "node" points to is the band that needs to be mapped
3166 * to block identifiers. The band that needs to be mapped to thread
3167 * identifiers should be marked by a "thread" mark by the caller.
3168 * This mark is removed by this function.
3169 * If "scale" is set, then the band that "node" points to is scaled
3170 * by "sizes".
3172 * Mark all outer band nodes as atomic to ensure each kernel is only
3173 * scheduled once.
3174 * If the domain elements that reach "node" live in more than one space,
3175 * then group the domain elements into a single space, named kernelX,
3176 * with X the kernel sequence number.
3178 * Insert a guard node governing the kernel node to ensure that
3179 * no kernels with zero blocks are launched.
3181 * Insert a context node describing the block and thread
3182 * identifiers inside the kernel mark.
3183 * The context node needs to be inserted after the effective block size
3184 * has been determined such that the bounds on the thread identifiers
3185 * would reflect the effective block size.
3186 * Insert a filter node inside the context node mapping the statement
3187 * instances to block identifiers. In particular, the block identifiers
3188 * are equated to the partial schedule of band that was marked for mapping
3189 * to blocks modulo the grid size.
3190 * Insert a filter node inside the "thread" mark mapping the statement
3191 * instances to thread identifiers. In particular, the thread identifiers
3192 * are equated to the partial schedule of band that was marked for mapping
3193 * to threads modulo the block size.
3195 * Compute array reference groups for all arrays, set the local
3196 * array bounds based on the set of domain instances that reach
3197 * the kernel node, check the total amount of shared memory used
3198 * and compute all group tilings.
3199 * The array reference groups are computed after the block filter
3200 * has been inserted because it affects the mapping to shared or
3201 * private memory. This computation also requires the thread filter
3202 * (in the ppcg_kernel object), but this thread filter should not
3203 * have been added to the schedule tree yet since the computation
3204 * requires the schedule of the band that needs to be mapped to
3205 * threads before the privatization is applied.
3207 * If any array reference group requires the band mapped to threads
3208 * to be unrolled, then we perform the required unrolling.
3210 * We save a copy of the schedule that may influence the mappings
3211 * to shared or private memory in kernel->shared_schedule.
3213 * Finally, we add synchronization and copy statements to the schedule tree,
3214 * remove the "thread" mark and create representations for the local
3215 * variables in the kernel.
3217 * Store a pointer to the created ppcg_kernel in gen->kernel.
3219 * We keep a copy of the isl_id that points to the kernel to ensure
3220 * that the kernel does not get destroyed if the schedule node
3221 * is freed due to some error condition.
3223 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
3224 __isl_take isl_schedule_node *node, int scale,
3225 __isl_keep isl_multi_val *sizes)
3227 struct ppcg_kernel *kernel;
3228 isl_id *id;
3229 isl_schedule_node *node_thread;
3230 isl_union_map *host_schedule;
3231 isl_set *host_domain;
3232 isl_union_set *domain;
3233 int single_statement;
3235 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
3236 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
3237 if (!kernel)
3238 return isl_schedule_node_free(node);
3240 domain = isl_schedule_node_get_domain(node);
3241 single_statement = isl_union_set_n_set(domain) == 1;
3243 kernel->ctx = gen->ctx;
3244 kernel->prog = gen->prog;
3245 kernel->options = gen->options;
3246 kernel->context = extract_context(node, gen->prog);
3247 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
3248 kernel->arrays = accessed_by_domain(isl_union_set_copy(domain),
3249 gen->prog);
3250 kernel->tile_len = isl_schedule_node_band_n_member(node);
3251 kernel->n_parallel = n_outer_coincidence(node);
3252 kernel->n_grid = kernel->n_parallel;
3253 node_thread = isl_schedule_node_copy(node);
3254 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
3255 node_thread = isl_schedule_node_child(node_thread, 0);
3256 kernel->n_block = n_outer_coincidence(node_thread);
3257 isl_schedule_node_free(node_thread);
3258 kernel->id = gen->kernel_id++;
3259 read_grid_and_block_sizes(kernel, gen);
3261 gen->kernel = kernel;
3263 host_schedule = isl_schedule_node_get_prefix_schedule_union_map(node);
3264 host_domain = isl_set_from_union_set(isl_union_map_range(
3265 host_schedule));
3267 node = atomic_ancestors(node);
3269 id = isl_id_alloc(gen->ctx, "kernel", kernel);
3270 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
3271 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
3273 if (!single_statement)
3274 node = group_statements(node, kernel->id);
3276 node = isl_schedule_node_child(node, 0);
3277 node = split_band(node, kernel->n_grid);
3278 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
3279 kernel->n_grid, "b");
3280 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
3281 kernel->grid_dim);
3282 kernel->grid_size = extract_grid_size(kernel,
3283 isl_union_set_copy(domain));
3284 if (!kernel->options->wrap)
3285 node = snap_band_to_sizes(node, kernel->grid_dim,
3286 kernel->options);
3287 if (scale)
3288 node = scale_band(node, isl_multi_val_copy(sizes));
3289 node = isl_schedule_node_parent(node);
3290 if (!single_statement)
3291 node = isl_schedule_node_parent(node);
3292 node = insert_guard(node, kernel->context, kernel->grid_size,
3293 gen->prog->scop);
3294 node = gpu_tree_move_down_to_thread(node, kernel->core);
3295 node = isl_schedule_node_child(node, 0);
3296 node = split_band(node, kernel->n_block);
3297 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3298 kernel->n_block, "t");
3299 kernel->thread_filter = set_schedule_modulo(node, kernel->thread_ids,
3300 kernel->block_dim);
3301 extract_block_size(kernel, domain);
3303 node = gpu_tree_move_up_to_kernel(node);
3304 node = isl_schedule_node_child(node, 0);
3305 node = insert_context(kernel, node);
3306 node = isl_schedule_node_child(node, 0);
3307 node = isl_schedule_node_insert_filter(node,
3308 isl_union_set_copy(kernel->block_filter));
3310 node = gpu_tree_move_up_to_kernel(node);
3312 if (gpu_group_references(kernel, node) < 0)
3313 node = isl_schedule_node_free(node);
3314 localize_bounds(kernel, host_domain);
3315 isl_set_free(host_domain);
3317 check_shared_memory_bound(kernel);
3318 compute_group_tilings(kernel);
3320 node = gpu_tree_move_down_to_thread(node, kernel->core);
3321 node = isl_schedule_node_child(node, 0);
3322 if (!kernel->options->wrap)
3323 node = snap_band_to_sizes(node, kernel->block_dim,
3324 kernel->options);
3325 node = isl_schedule_node_insert_filter(node,
3326 isl_union_set_copy(kernel->thread_filter));
3327 if (kernel_requires_unroll(kernel)) {
3328 node = isl_schedule_node_child(node, 0);
3329 node = unroll(node);
3332 node = gpu_tree_move_up_to_thread(node);
3333 kernel->shared_schedule_dim =
3334 isl_schedule_node_get_schedule_depth(node);
3335 kernel->shared_schedule =
3336 isl_schedule_node_get_prefix_schedule_union_pw_multi_aff(node);
3338 node = gpu_tree_move_up_to_kernel(node);
3340 if (any_global_write(kernel))
3341 node = add_sync(kernel, node);
3342 node = add_copies(kernel, node);
3344 node = gpu_tree_move_down_to_thread(node, kernel->core);
3345 node = isl_schedule_node_delete(node);
3347 node = gpu_tree_move_up_to_kernel(node);
3349 create_kernel_vars(kernel);
3351 if (!single_statement)
3352 node = isl_schedule_node_parent(node);
3353 node = isl_schedule_node_parent(node);
3355 isl_id_free(id);
3356 return node;
3359 /* Insert a zero-dimensional permutable band at "node".
3361 static __isl_give isl_schedule_node *insert_empty_permutable_band(
3362 __isl_take isl_schedule_node *node)
3364 isl_space *space;
3365 isl_schedule *schedule;
3366 isl_union_set *domain;
3367 isl_multi_union_pw_aff *mupa;
3369 schedule = isl_schedule_node_get_schedule(node);
3370 domain = isl_schedule_get_domain(schedule);
3371 space = isl_union_set_get_space(domain);
3372 isl_union_set_free(domain);
3373 isl_schedule_free(schedule);
3375 space = isl_space_set_from_params(space);
3376 mupa = isl_multi_union_pw_aff_zero(space);
3377 node = isl_schedule_node_insert_partial_schedule(node, mupa);
3378 node = isl_schedule_node_band_set_permutable(node, 1);
3380 return node;
3383 /* Mark "node" as outer permutable.
3385 * If "node" originally points to a leaf, then insert a zero-dimensional
3386 * permutable band such that we can assume that "node" always
3387 * points to a band node.
3389 * Tile "node" using user specified tile sizes, after splitting the band
3390 * if the number of specified tile sizes is smaller than the dimension
3391 * of the band. Mark the point band of this tiling as the band that
3392 * needs to be mapped to threads.
3393 * Create a kernel representing the domain instances that reach "node" and
3394 * insert a mark node pointing to the ppcg_kernel before the band node.
3396 static __isl_give isl_schedule_node *mark_outer_permutable(
3397 struct gpu_gen *gen, __isl_take isl_schedule_node *node)
3399 struct ppcg_kernel *kernel;
3400 int scale;
3401 int tile_len;
3402 int *tile_size;
3403 isl_id *id;
3404 isl_multi_val *sizes;
3406 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
3407 node = insert_empty_permutable_band(node);
3409 tile_len = isl_schedule_node_band_n_member(node);
3410 tile_size = read_tile_sizes(gen, &tile_len);
3411 if (!tile_size)
3412 return isl_schedule_node_free(node);
3413 if (tile_len < isl_schedule_node_band_n_member(node))
3414 node = isl_schedule_node_band_split(node, tile_len);
3415 sizes = construct_band_tiles_sizes(node, tile_size);
3416 node = tile_band(node, isl_multi_val_copy(sizes));
3417 node = isl_schedule_node_child(node, 0);
3418 id = isl_id_alloc(gen->ctx, "thread", NULL);
3419 node = isl_schedule_node_insert_mark(node, id);
3420 node = isl_schedule_node_parent(node);
3422 scale = gen->options->scale_tile_loops;
3423 node = create_kernel(gen, node, scale, sizes);
3424 isl_multi_val_free(sizes);
3425 if (!node)
3426 return NULL;
3427 kernel = gen->kernel;
3428 kernel->tile_len = tile_len;
3429 kernel->tile_size = tile_size;
3431 return node;
3434 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
3435 __isl_take isl_schedule_node *node, int pos, struct band_info *info);
3437 /* Check if this band node is tilable and has any parallel loops. If so,
3438 * take it as the outermost tilable band. If not, continue looking for the
3439 * outermost tilable band in the children of the current band.
3440 * Return a pointer to the same node in a tree where all outermost tilable
3441 * bands in the current subtree have been replaced by mark nodes
3442 * containing a pointer to a ppcg_kernel object.
3444 static __isl_give isl_schedule_node *band_select_outer_band(struct gpu_gen *gen,
3445 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
3447 int n = isl_schedule_node_band_n_member(node);
3448 int n_parallel;
3450 n_parallel = n_outer_coincidence(node);
3452 if (!isl_schedule_node_band_get_permutable(node) || n_parallel == 0) {
3453 node = isl_schedule_node_child(node, 0);
3454 node = select_outer_band(gen, node, pos + n, info);
3455 return isl_schedule_node_parent(node);
3458 gen->any_parallelism = 1;
3459 info->gen = gen;
3460 info->tile_first = pos;
3461 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3462 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
3464 node = mark_outer_permutable(gen, node);
3466 return node;
3469 /* Extend "umap" with coordinates with fixed value "val"
3470 * to a total length of "dst_len", assuming the original dimension is "src_len".
3472 static __isl_give isl_union_map *extend_range(
3473 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
3475 isl_space *dim;
3476 isl_map *map;
3477 int i;
3479 dim = isl_union_map_get_space(umap);
3480 map = isl_map_reverse(projection(dim, dst_len, src_len));
3481 for (i = src_len; i < dst_len; ++i)
3482 map = isl_map_fix_si(map, isl_dim_out, i, val);
3484 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
3486 return umap;
3489 /* Select the outermost bands in the elements of the sequence or set
3490 * node "node", align their prefix schedules and combine the resulting
3491 * prefix and suffix schedules into a single pair of prefix and
3492 * suffix schedules for the entire list.
3493 * Return a pointer to the same node in a tree where all outermost tilable
3494 * bands in the current subtree have been replaced by mark nodes
3495 * containing a pointer to a ppcg_kernel object.
3497 static __isl_give isl_schedule_node *list_select_outer_band(
3498 struct gpu_gen *gen, __isl_take isl_schedule_node *node, int pos,
3499 struct band_info *list_info)
3501 int i;
3502 int n = isl_schedule_node_n_children(node);
3503 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
3504 struct band_info *info;
3505 int max_tile_first;
3506 isl_union_map *prefix;
3507 isl_union_map *suffix;
3509 assert(n >= 1);
3510 info = isl_calloc_array(ctx, struct band_info, n);
3511 assert(info);
3513 max_tile_first = 0;
3514 for (i = 0; i < n; ++i) {
3515 node = isl_schedule_node_child(node, i);
3516 node = select_outer_band(gen, node, pos, &info[i]);
3517 if (info[i].tile_first > max_tile_first)
3518 max_tile_first = info[i].tile_first;
3519 node = isl_schedule_node_parent(node);
3522 for (i = 0; i < n; ++i) {
3523 if (info[i].tile_first == max_tile_first)
3524 continue;
3525 info[i].prefix = extend_range(info[i].prefix,
3526 info[i].tile_first, max_tile_first, 0);
3527 info[i].tile_first = max_tile_first;
3530 prefix = info[0].prefix;
3531 suffix = info[0].suffix;
3533 for (i = 1; i < n; ++i) {
3534 prefix = isl_union_map_union(prefix, info[i].prefix);
3535 suffix = isl_union_map_union(suffix, info[i].suffix);
3538 list_info->tile_first = info[0].tile_first;
3539 list_info->prefix = prefix;
3540 list_info->suffix = suffix;
3542 free(info);
3543 return node;
3546 /* If we reach a leaf node, then we have not found any outer tilable
3547 * band with parallel loops, so consider the leaf node as the outermost
3548 * tilable band.
3549 * Return a pointer to a mark node containing a pointer
3550 * to a ppcg_kernel object inserted at the original leaf node.
3552 static __isl_give isl_schedule_node *leaf_select_outer_band(struct gpu_gen *gen,
3553 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
3555 info->gen = gen;
3556 info->tile_first = pos;
3557 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
3558 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
3560 node = mark_outer_permutable(gen, node);
3562 return node;
3565 /* Select the outermost tilable band in the subtree that "node" points to and
3566 * return a pointer to the same node in a tree where all outermost tilable
3567 * bands in the current subtree have been replaced by mark nodes
3568 * containing a pointer to a ppcg_kernel object.
3570 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
3571 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
3573 enum isl_schedule_node_type type;
3575 type = isl_schedule_node_get_type(node);
3576 switch (type) {
3577 case isl_schedule_node_domain:
3578 case isl_schedule_node_filter:
3579 node = isl_schedule_node_child(node, 0);
3580 node = select_outer_band(gen, node, pos, info);
3581 return isl_schedule_node_parent(node);
3582 case isl_schedule_node_leaf:
3583 return leaf_select_outer_band(gen, node, pos, info);
3584 case isl_schedule_node_band:
3585 return band_select_outer_band(gen, node, pos, info);
3586 case isl_schedule_node_set:
3587 case isl_schedule_node_sequence:
3588 return list_select_outer_band(gen, node, pos, info);
3589 default:
3590 isl_die(isl_schedule_node_get_ctx(node),
3591 isl_error_unsupported, "unhandled schedule node type",
3592 node = node);
3593 case isl_schedule_node_error:
3594 info->prefix = NULL;
3595 info->suffix = NULL;
3596 break;
3599 return isl_schedule_node_free(node);
3602 /* Select the outermost tilable band that (by construction)
3603 * has at least one parallel loop.
3604 * The starting position of the aligned band is stored in the pair
3605 * gen->tile_first.
3606 * The sizes and number of parallel loops may be different in different
3607 * parts of the band forest and are therefore stored in the gpu_stmts.
3609 * Return the complete schedule, with the tilable bands aligned
3610 * at gen->tile_first and padded with zero, if needed.
3611 * Store a schedule tree corresponding to the outer gen->tile_first
3612 * dimensions, with mark nodes containing pointers to ppcg_kernel objects,
3613 * in gen->schedule.
3615 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
3616 __isl_keep isl_schedule *schedule)
3618 isl_schedule_node *node;
3619 struct band_info info;
3621 node = isl_schedule_get_root(schedule);
3622 node = select_outer_band(gen, node, 0, &info);
3623 gen->schedule = isl_schedule_node_get_schedule(node);
3624 isl_schedule_node_free(node);
3626 gen->tile_first = info.tile_first;
3627 info.suffix = align_range(info.suffix);
3629 return isl_union_map_flat_range_product(info.prefix, info.suffix);
3632 /* Set gen->untiled_len to the number of scheduling dimensions
3633 * for the schedule of the first domain.
3634 * We assume here that this number is the same for all domains.
3636 static int set_untiled_len(__isl_take isl_map *map, void *user)
3638 unsigned *untiled_len = user;
3640 *untiled_len = isl_map_dim(map, isl_dim_out);
3642 isl_map_free(map);
3643 return -1;
3646 /* Compute an appropriate schedule based on the accesses in
3647 * gen->read and gen->write.
3649 * We use the dependences in gen->prog->scop to compute
3650 * a schedule that has a parallel loop in each tilable band.
3651 * Finally, we select the outermost tilable band.
3653 * If live range reordering is allowed, then we need to make sure
3654 * that live ranges on arrays are not run in parallel since doing
3655 * so would require array expansion. We therefore add the array
3656 * order dependences to the coincidence dependences. Non-zero array
3657 * order dependences will then prevent a schedule dimension from being
3658 * considered parallel.
3659 * Live ranges derived from scalars are allowed to be run in parallel
3660 * since we force the scalars to be mapped to private memory in
3661 * check_scalar_live_ranges.
3662 * If live range reordering is allowed, then the false dependences
3663 * are not added to the validity constraints as that would prevent
3664 * reordering. Instead, the external false dependences that enforce that reads
3665 * from potentially live-in data precede any later write and
3666 * that writes of potentially live-out data follow any other earlier write
3667 * are added to the validity and the coincidence constraints.
3668 * The false dependences are still added to the proximity constraints
3669 * for consistency with the case where live range reordering is not allowed.
3670 * The coincidence constraints then consist of flow dependences,
3671 * external false dependences and array order dependences.
3672 * The independences can be filtered out from the first two sets.
3673 * They have already been filtered out from the array order dependences
3674 * on a per array basis in collect_order_dependences.
3675 * There is no need for a per array handling of the other two sets
3676 * as there should be no flow or external false dependence on local
3677 * variables that can be filtered out.
3679 static void compute_schedule(struct gpu_gen *gen)
3681 isl_union_set *domain;
3682 isl_union_map *dep_raw, *dep;
3683 isl_union_map *validity, *proximity, *coincidence;
3684 isl_union_map *sched;
3685 isl_schedule_constraints *sc;
3686 isl_schedule *schedule;
3688 domain = isl_union_set_copy(gen->prog->scop->domain);
3689 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
3690 sc = isl_schedule_constraints_set_context(sc,
3691 isl_set_copy(gen->prog->scop->context));
3692 if (gen->options->live_range_reordering) {
3693 sc = isl_schedule_constraints_set_conditional_validity(sc,
3694 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
3695 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
3696 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
3697 validity = isl_union_map_copy(proximity);
3698 validity = isl_union_map_union(validity,
3699 isl_union_map_copy(gen->prog->scop->dep_forced));
3700 proximity = isl_union_map_union(proximity,
3701 isl_union_map_copy(gen->prog->scop->dep_false));
3702 coincidence = isl_union_map_copy(validity);
3703 coincidence = isl_union_map_subtract(coincidence,
3704 isl_union_map_copy(gen->prog->scop->independence));
3705 coincidence = isl_union_map_union(coincidence,
3706 isl_union_map_copy(gen->prog->array_order));
3707 } else {
3708 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
3709 dep = isl_union_map_copy(gen->prog->scop->dep_false);
3710 dep = isl_union_map_union(dep, dep_raw);
3711 dep = isl_union_map_coalesce(dep);
3712 proximity = isl_union_map_copy(dep);
3713 coincidence = isl_union_map_copy(dep);
3714 validity = dep;
3716 sc = isl_schedule_constraints_set_validity(sc, validity);
3717 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
3718 sc = isl_schedule_constraints_set_proximity(sc, proximity);
3720 if (gen->options->debug->dump_schedule_constraints)
3721 isl_schedule_constraints_dump(sc);
3722 schedule = isl_schedule_constraints_compute_schedule(sc);
3723 if (gen->options->debug->dump_schedule)
3724 isl_schedule_dump(schedule);
3726 sched = select_outer_tilable_band(gen, schedule);
3728 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
3729 sched = isl_union_map_intersect_domain(sched, domain);
3730 gen->sched = sched;
3732 isl_schedule_free(schedule);
3735 /* Compute the sets of outer array elements that need to be copied in and out.
3737 * In particular, for each array that is possibly written anywhere in
3738 * gen->prog and that is visible outside the corresponding scop,
3739 * we copy out its entire extent.
3741 * Any array elements that is read without first being written needs
3742 * to be copied in. Furthermore, if there are any array elements that
3743 * are copied out, but that may not be written inside gen->prog, then
3744 * they also need to be copied in to ensure that the value after execution
3745 * is the same as the value before execution, at least for those array
3746 * elements that may have their values preserved by the scop.
3747 * In case the array elements are structures, we need to take into
3748 * account that all members of the structures need to be written
3749 * by gen->prog before we can avoid copying the data structure in.
3751 * While computing the set of array elements that are copied out but
3752 * not necessarily written, we intersect both sets with the context.
3753 * This helps in those cases where the arrays are declared with a fixed size,
3754 * while the accesses are parametric and the context assigns a fixed value
3755 * to the parameters.
3757 * If an element from a local array is read without first being written,
3758 * then there is no point in copying it in since it cannot have been
3759 * written prior to the scop. Warn about the uninitialized read instead.
3761 static void compute_copy_in_and_out(struct gpu_gen *gen)
3763 int i;
3764 isl_union_set *local;
3765 isl_union_set *may_write, *must_write;
3766 isl_union_set *copy_in, *copy_out;
3767 isl_union_set *not_written;
3768 isl_union_map *uninitialized;
3769 isl_union_map *local_uninitialized;
3771 must_write = isl_union_map_range(
3772 isl_union_map_copy(gen->prog->must_write));
3773 must_write = isl_union_set_intersect_params(must_write,
3774 isl_set_copy(gen->prog->context));
3775 may_write = isl_union_map_range(
3776 isl_union_map_copy(gen->prog->may_write));
3777 may_write = isl_union_set_intersect_params(may_write,
3778 isl_set_copy(gen->prog->context));
3779 may_write = isl_union_set_universe(may_write);
3780 may_write = isl_union_set_apply(may_write,
3781 isl_union_map_copy(gen->prog->to_outer));
3782 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
3783 local = isl_union_set_copy(copy_out);
3785 for (i = 0; i < gen->prog->n_array; ++i) {
3786 isl_space *space;
3787 isl_set *write_i;
3788 int empty;
3790 space = isl_space_copy(gen->prog->array[i].space);
3792 if (gen->prog->array[i].local) {
3793 isl_set *set;
3795 set = isl_set_universe(space);
3796 local = isl_union_set_add_set(local, set);
3797 continue;
3800 write_i = isl_union_set_extract_set(may_write, space);
3801 empty = isl_set_plain_is_empty(write_i);
3802 isl_set_free(write_i);
3803 if (empty)
3804 continue;
3806 write_i = isl_set_copy(gen->prog->array[i].extent);
3807 copy_out = isl_union_set_add_set(copy_out, write_i);
3809 isl_union_set_free(may_write);
3811 copy_out = isl_union_set_intersect_params(copy_out,
3812 isl_set_copy(gen->prog->context));
3814 gen->prog->copy_out = isl_union_set_copy(copy_out);
3816 copy_out = isl_union_set_apply(copy_out,
3817 isl_union_map_copy(gen->prog->to_inner));
3818 copy_out = isl_union_set_intersect(copy_out,
3819 isl_union_set_copy(gen->prog->may_persist));
3820 not_written = isl_union_set_subtract(copy_out, must_write);
3822 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
3823 local_uninitialized = isl_union_map_copy(uninitialized);
3825 local = isl_union_set_apply(local,
3826 isl_union_map_copy(gen->prog->to_inner));
3827 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
3828 local);
3829 if (!isl_union_map_is_empty(local_uninitialized)) {
3830 fprintf(stderr,
3831 "possibly uninitialized reads (not copied in):\n");
3832 isl_union_map_dump(local_uninitialized);
3834 uninitialized = isl_union_map_subtract(uninitialized,
3835 local_uninitialized);
3836 copy_in = isl_union_map_range(uninitialized);
3837 copy_in = isl_union_set_union(copy_in, not_written);
3838 copy_in = isl_union_set_apply(copy_in,
3839 isl_union_map_copy(gen->prog->to_outer));
3841 gen->prog->copy_in = copy_in;
3844 /* Internal data structure for extract_access.
3845 * "next_access" points to the end of a linked list that is extended
3846 * by extract_access.
3847 * "single_expression" is set if the access expressions belong to
3848 * an expression statement (i.e., a statement without internal control).
3849 * "any_to_outer" maps all intermediate arrays to their outer arrays.
3851 struct ppcg_extract_access_data {
3852 struct gpu_stmt_access **next_access;
3853 int single_expression;
3854 isl_union_map *any_to_outer;
3857 /* Given a tagged access relation to a single array "tagged", extract it
3858 * as a map, taking into account that the input may be empty.
3859 * If the access relation is empty, then it does not contain
3860 * any space information, so we try to recover it from the index
3861 * expression.
3862 * The space of the index expression is of the form I -> A,
3863 * with I the statement instances and A the array, or [I -> F] -> A,
3864 * with F the filters corresponding to arguments.
3865 * We first drop F, if present, obtaining I -> A.
3866 * Then we construct I -> R, with R the reference tag,
3867 * combine the two into I -> [R -> A] and uncurry to obtain
3868 * the final result [I -> R] -> A.
3869 * Note that the index expression may have a lower dimension
3870 * than that of the array, but this dimension is not used
3871 * if the access relation is empty.
3873 static __isl_give isl_map *extract_single_tagged_access(
3874 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
3876 int empty;
3877 isl_id *id;
3878 isl_space *space, *space2;
3879 isl_multi_pw_aff *index;
3881 empty = isl_union_map_is_empty(tagged);
3882 if (empty < 0)
3883 goto error;
3884 if (!empty)
3885 return isl_map_from_union_map(tagged);
3886 isl_union_map_free(tagged);
3888 index = pet_expr_access_get_index(expr);
3889 space = isl_multi_pw_aff_get_space(index);
3890 isl_multi_pw_aff_free(index);
3891 if (isl_space_domain_is_wrapping(space))
3892 space = isl_space_domain_factor_domain(space);
3893 space2 = isl_space_copy(space);
3894 space2 = isl_space_from_domain(isl_space_domain(space));
3895 id = pet_expr_access_get_ref_id(expr);
3896 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
3897 space = isl_space_range_product(space2, space);
3898 space = isl_space_uncurry(space);
3900 return isl_map_empty(space);
3901 error:
3902 isl_union_map_free(tagged);
3903 return NULL;
3906 /* Extract a gpu_stmt_access from "expr", append it to the list
3907 * that ends in *data->next_access and update the end of the list.
3908 * If the access expression performs a write, then it is considered
3909 * exact only if it appears in a single expression statement and
3910 * if its may access relation is equal to its must access relation.
3912 * The combined set of may accesses may be union if member accesses
3913 * are involved, but the entire set is derived from a single reference and
3914 * therefore from a single index expression. These accesses therefore
3915 * all map to the same outer array.
3917 static int extract_access(__isl_keep pet_expr *expr, void *user)
3919 struct ppcg_extract_access_data *data = user;
3920 isl_union_map *tagged;
3921 struct gpu_stmt_access *access;
3922 isl_ctx *ctx = pet_expr_get_ctx(expr);
3923 isl_multi_pw_aff *index;
3925 access = isl_alloc_type(ctx, struct gpu_stmt_access);
3926 assert(access);
3927 access->next = NULL;
3928 access->read = pet_expr_access_is_read(expr);
3929 access->write = pet_expr_access_is_write(expr);
3930 tagged = pet_expr_access_get_tagged_may_read(expr);
3931 tagged = isl_union_map_union(tagged,
3932 pet_expr_access_get_tagged_may_write(expr));
3933 tagged = isl_union_map_apply_range(tagged,
3934 isl_union_map_copy(data->any_to_outer));
3935 if (!access->write) {
3936 access->exact_write = 1;
3937 } else if (!data->single_expression) {
3938 access->exact_write = 0;
3939 } else {
3940 isl_union_map *must, *may;
3941 may = isl_union_map_copy(tagged);
3942 may = isl_union_map_domain_factor_domain(may);
3943 must = pet_expr_access_get_must_write(expr);
3944 access->exact_write = isl_union_map_is_equal(must, may);
3945 isl_union_map_free(must);
3946 isl_union_map_free(may);
3948 index = pet_expr_access_get_index(expr);
3949 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
3950 isl_multi_pw_aff_free(index);
3951 access->ref_id = pet_expr_access_get_ref_id(expr);
3952 access->tagged_access = extract_single_tagged_access(tagged, expr);
3953 access->access = isl_map_copy(access->tagged_access);
3954 access->access = isl_map_domain_factor_domain(access->access);
3956 *data->next_access = access;
3957 data->next_access = &(*data->next_access)->next;
3959 if (!access->access)
3960 return -1;
3962 return 0;
3965 /* Construct a linked list of gpu_stmt_access objects,
3966 * one for each access expression in the statement body.
3967 * "any_to_outer" maps all intermediate arrays to their outer arrays.
3969 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
3970 __isl_keep isl_union_map *any_to_outer)
3972 struct ppcg_extract_access_data data;
3974 stmt->accesses = NULL;
3975 data.next_access = &stmt->accesses;
3976 data.single_expression =
3977 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
3978 data.any_to_outer = any_to_outer;
3979 return pet_tree_foreach_access_expr(stmt->stmt->body,
3980 &extract_access, &data);
3983 /* Return an array of gpu_stmt representing the statements in "scop".
3985 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
3986 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
3988 int i;
3989 struct gpu_stmt *stmts;
3991 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
3992 if (!stmts)
3993 return NULL;
3995 for (i = 0; i < scop->pet->n_stmt; ++i) {
3996 struct gpu_stmt *s = &stmts[i];
3998 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
3999 s->stmt = scop->pet->stmts[i];
4000 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4001 return free_stmts(stmts, i + 1);
4004 return stmts;
4007 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4009 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4011 struct gpu_gen *gen = user;
4013 return gen->print(p, gen->prog, gen->tree, &gen->types,
4014 gen->print_user);
4017 /* Generate CUDA code for "scop" and print it to "p".
4018 * After generating an AST for the transformed scop as explained below,
4019 * we call "gen->print" to print the AST in the desired output format
4020 * to "p".
4022 * If it turns out that it does not make sense to generate GPU code,
4023 * then we generate CPU code instead.
4025 * The GPU code is generated in a context where at least one
4026 * statement instance is executed. The corresponding guard (if any) is printed
4027 * around the entire generated GPU code, except for the declaration
4028 * of the arrays that are visible outside of the scop and that therefore
4029 * cannot be declared inside the body of any possible guard.
4031 * We first compute a schedule that respects the dependences
4032 * of the original program and select the outermost bands
4033 * of tilable dimensions that have at least one parallel loop.
4035 * Each of these bands B is then tiled according to "tile" sizes, resulting
4036 * in two nested bands, with a kernel marker on top
4044 * We then split off at most 2 parallel dimensions from the T band and
4045 * at most 3 parallel dimension from the P band
4050 * T1
4052 * T2
4054 * P1
4056 * P2
4058 * A filter is introduced in front of T1 that maps the domain instances
4059 * to block identifiers. Similarly, a filter is introduced in front of P1
4060 * that maps the domain instances to thread identifiers.
4062 * For each iteration of the T2 band and for each array, we compute
4063 * the array elements accessed by that iteration, construct a rectangular
4064 * box around it and shift it to the origin. The result is used
4065 * as shared memory for the array.
4067 * Copying and synchronization statements are added to this schedule tree.
4068 * In principle, these are added in front of the P1 band, but some of
4069 * them may get hoisted up to higher levels.
4071 * The entire AST is then generated from the single resulting schedule tree.
4072 * During the generation the subtrees at kernel nodes (K) are saved
4073 * aside and replaced by kernel calls. The result is printed as host code
4074 * while the saved subtrees are printed as device code.
4076 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4077 struct gpu_gen *gen, struct ppcg_scop *scop,
4078 struct ppcg_options *options)
4080 struct gpu_prog *prog;
4081 isl_ctx *ctx;
4082 isl_set *context, *guard;
4084 if (!scop)
4085 return isl_printer_free(p);
4087 ctx = isl_printer_get_ctx(p);
4088 prog = gpu_prog_alloc(ctx, scop);
4089 if (!prog)
4090 return isl_printer_free(p);
4092 context = isl_set_copy(prog->context);
4093 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
4094 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
4096 gen->prog = prog;
4097 gen->any_parallelism = 0;
4098 compute_schedule(gen);
4100 if (!gen->any_parallelism) {
4101 isl_set_free(context);
4102 isl_set_free(guard);
4103 p = print_cpu(p, scop, options);
4104 } else {
4105 compute_copy_in_and_out(gen);
4106 gen->tree = generate_code(gen);
4107 p = ppcg_print_exposed_declarations(p, prog->scop);
4108 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
4109 isl_ast_node_free(gen->tree);
4112 isl_union_map_free(gen->sched);
4113 isl_schedule_free(gen->schedule);
4115 gpu_prog_free(prog);
4117 return p;
4120 /* Wrapper around generate for use as a ppcg_transform callback.
4122 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
4123 struct ppcg_scop *scop, void *user)
4125 struct gpu_gen *gen = user;
4127 return generate(p, gen, scop, gen->options);
4130 /* Transform the code in the file called "input" by replacing
4131 * all scops by corresponding GPU code and write the results to "out".
4133 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4134 struct ppcg_options *options,
4135 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4136 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4137 struct gpu_types *types, void *user), void *user)
4139 struct gpu_gen gen;
4140 int r;
4141 int i;
4143 gen.ctx = ctx;
4144 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4145 gen.options = options;
4146 gen.kernel_id = 0;
4147 gen.print = print;
4148 gen.print_user = user;
4149 gen.types.n = 0;
4150 gen.types.name = NULL;
4152 if (options->debug->dump_sizes) {
4153 isl_space *space = isl_space_params_alloc(ctx, 0);
4154 gen.used_sizes = isl_union_map_empty(space);
4157 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
4159 if (options->debug->dump_sizes) {
4160 isl_union_map_dump(gen.used_sizes);
4161 isl_union_map_free(gen.used_sizes);
4164 isl_union_map_free(gen.sizes);
4165 for (i = 0; i < gen.types.n; ++i)
4166 free(gen.types.name[i]);
4167 free(gen.types.name);
4169 return r;
4172 /* Compute the set of inner array elements that may have their values
4173 * preserved by "prog". In particular, collect the array elements of
4174 * arrays that are not local to "prog" and remove those elements that
4175 * are definitely killed or definitely written by "prog".
4177 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
4179 int i;
4180 isl_union_set *may_persist, *killed;
4181 isl_union_map *must_kill;
4183 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
4184 for (i = 0; i < prog->n_array; ++i) {
4185 isl_set *extent;
4187 if (prog->array[i].local)
4188 continue;
4190 extent = isl_set_copy(prog->array[i].extent);
4191 may_persist = isl_union_set_add_set(may_persist, extent);
4194 may_persist = isl_union_set_intersect_params(may_persist,
4195 isl_set_copy(prog->context));
4196 may_persist = isl_union_set_apply(may_persist,
4197 isl_union_map_copy(prog->to_inner));
4198 must_kill = isl_union_map_copy(prog->tagged_must_kill);
4199 killed = isl_union_map_range(must_kill);
4200 must_kill = isl_union_map_copy(prog->must_write);
4201 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
4203 may_persist = isl_union_set_subtract(may_persist, killed);
4204 return may_persist;
4207 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4209 struct gpu_prog *prog;
4210 isl_space *space;
4211 isl_map *id;
4213 if (!scop)
4214 return NULL;
4216 prog = isl_calloc_type(ctx, struct gpu_prog);
4217 assert(prog);
4219 prog->ctx = ctx;
4220 prog->scop = scop;
4221 prog->context = isl_set_copy(scop->context);
4222 prog->n_stmts = scop->pet->n_stmt;
4223 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
4224 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
4225 space = isl_union_map_get_space(prog->any_to_outer);
4226 space = isl_space_set_from_params(space);
4227 space = isl_space_add_dims(space, isl_dim_set, 1);
4228 space = isl_space_map_from_set(space);
4229 id = isl_map_identity(space);
4230 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
4231 prog->stmts = extract_stmts(ctx, scop,
4232 prog->context, prog->any_to_outer);
4233 prog->read = isl_union_map_copy(scop->reads);
4234 prog->may_write = isl_union_map_copy(scop->may_writes);
4235 prog->must_write = isl_union_map_copy(scop->must_writes);
4236 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
4237 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
4238 prog->to_outer = isl_union_map_copy(prog->to_inner);
4239 prog->to_outer = isl_union_map_reverse(prog->to_outer);
4241 if (!prog->stmts)
4242 return gpu_prog_free(prog);
4244 if (collect_array_info(prog) < 0)
4245 return gpu_prog_free(prog);
4246 prog->may_persist = compute_may_persist(prog);
4248 return prog;
4251 void *gpu_prog_free(struct gpu_prog *prog)
4253 if (!prog)
4254 return NULL;
4255 free_array_info(prog);
4256 free_stmts(prog->stmts, prog->n_stmts);
4257 isl_union_map_free(prog->any_to_outer);
4258 isl_union_map_free(prog->to_outer);
4259 isl_union_map_free(prog->to_inner);
4260 isl_union_set_free(prog->copy_in);
4261 isl_union_set_free(prog->copy_out);
4262 isl_union_map_free(prog->read);
4263 isl_union_map_free(prog->may_write);
4264 isl_union_map_free(prog->must_write);
4265 isl_union_map_free(prog->tagged_must_kill);
4266 isl_union_map_free(prog->array_order);
4267 isl_union_set_free(prog->may_persist);
4268 isl_set_free(prog->context);
4269 free(prog);
4270 return NULL;