ppcg_kernel: store mapping from domain elements to block identifiers
[ppcg.git] / gpu.c
blobdf3fbed7a94e877cc258aa82fb7453b26616c280
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 /* Construct a map from a domain of dimensionality "len"
659 * to a domain of dimensionality "len" + "tile_len" that tiles
660 * the "tile_len" coordinates starting at "first".
661 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
662 * "dim" prescribes the parameters.
664 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
665 int first, int tile_len, int *tile_size)
667 int i;
668 isl_basic_map *bmap;
669 isl_constraint *c;
670 isl_local_space *ls;
672 dim = isl_space_add_dims(dim, isl_dim_in, len);
673 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
674 bmap = isl_basic_map_universe(isl_space_copy(dim));
675 ls = isl_local_space_from_space(dim);
677 for (i = 0; i < len - tile_len; ++i) {
678 int j = i < first ? i : i + tile_len;
679 int k = i < first ? i : i + 2 * tile_len;
681 c = isl_equality_alloc(isl_local_space_copy(ls));
682 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
683 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
684 bmap = isl_basic_map_add_constraint(bmap, c);
687 for (i = 0; i < tile_len; ++i) {
688 c = isl_equality_alloc(isl_local_space_copy(ls));
689 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
690 first + i, -1);
691 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
692 first + i, tile_size[i]);
693 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
694 first + i + tile_len, 1);
695 bmap = isl_basic_map_add_constraint(bmap, c);
697 c = isl_inequality_alloc(isl_local_space_copy(ls));
698 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
699 first + i + tile_len, 1);
700 bmap = isl_basic_map_add_constraint(bmap, c);
702 c = isl_inequality_alloc(isl_local_space_copy(ls));
703 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
704 first + i + tile_len, -1);
705 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
706 bmap = isl_basic_map_add_constraint(bmap, c);
709 isl_local_space_free(ls);
711 return isl_map_from_basic_map(bmap);
714 /* Construct a map from a domain of dimensionality "len"
715 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
716 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
717 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
718 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
719 * that are projected out at the end.
720 * "dim" prescribes the parameters.
722 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
723 int first, int wrap_len, int *wrap_size)
725 int i;
726 isl_basic_map *bmap;
727 isl_constraint *c;
728 isl_local_space *ls;
730 dim = isl_space_add_dims(dim, isl_dim_in, len);
731 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
732 bmap = isl_basic_map_universe(isl_space_copy(dim));
733 ls = isl_local_space_from_space(dim);
735 for (i = 0; i < len; ++i) {
736 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
738 c = isl_equality_alloc(isl_local_space_copy(ls));
739 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
740 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
741 bmap = isl_basic_map_add_constraint(bmap, c);
744 for (i = 0; i < wrap_len; ++i) {
745 c = isl_equality_alloc(isl_local_space_copy(ls));
746 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
747 first + i, -1);
748 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
749 first + wrap_len + i, 1);
750 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
751 first + 2 * wrap_len + i, wrap_size[i]);
752 bmap = isl_basic_map_add_constraint(bmap, c);
754 c = isl_inequality_alloc(isl_local_space_copy(ls));
755 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
756 first + wrap_len + i, 1);
757 bmap = isl_basic_map_add_constraint(bmap, c);
759 c = isl_inequality_alloc(isl_local_space_copy(ls));
760 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
761 first + wrap_len + i, -1);
762 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
763 bmap = isl_basic_map_add_constraint(bmap, c);
766 isl_local_space_free(ls);
768 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
769 first + 2 * wrap_len, wrap_len);
771 return isl_map_from_basic_map(bmap);
774 /* Tile the B loops over the tile sizes and then tile/wrap
775 * the T1 loops over the blocks.
777 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
778 __isl_take isl_union_map *sched)
780 struct ppcg_kernel *kernel = gen->kernel;
781 isl_space *dim;
782 isl_map *tiling, *block_tiling;
784 dim = isl_union_map_get_space(sched);
785 tiling = tile(isl_space_copy(dim), gen->untiled_len,
786 gen->tile_first, kernel->tile_len, kernel->tile_size);
788 if (gen->options->wrap)
789 block_tiling = wrap(dim, gen->untiled_len + kernel->tile_len,
790 gen->tile_first, kernel->n_grid, kernel->grid_dim);
791 else
792 block_tiling = tile(dim, gen->untiled_len + kernel->tile_len,
793 gen->tile_first, kernel->n_grid, kernel->grid_dim);
795 gen->tiled_len = gen->untiled_len + kernel->tile_len + kernel->n_grid;
797 tiling = isl_map_apply_range(tiling, block_tiling);
799 sched = isl_union_map_apply_range(sched,
800 isl_union_map_from_map(tiling));
802 gen->shared_len = gen->tile_first + kernel->tile_len + kernel->n_grid;
804 return sched;
807 /* Equate the "T1P" iterators in the tiled schedule "sched"
808 * to the block dimensions.
810 static __isl_give isl_union_map *parametrize_tiled_schedule(
811 struct gpu_gen *gen, __isl_take isl_union_map *sched)
813 struct ppcg_kernel *kernel = gen->kernel;
814 isl_space *dim;
815 isl_set *par;
817 dim = isl_union_map_get_space(sched);
818 par = parametrization(dim, gen->tiled_len,
819 gen->tile_first + kernel->n_grid, kernel->block_ids);
820 sched = isl_union_map_intersect_range(sched,
821 isl_union_set_from_set(par));
823 return sched;
826 /* Tile/wrap the P1 loops over the threads.
828 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
829 __isl_take isl_union_map *sched)
831 struct ppcg_kernel *kernel = gen->kernel;
832 isl_space *dim;
833 isl_map *tiling;
834 isl_set *par;
836 dim = isl_union_map_get_space(sched);
838 if (gen->options->wrap)
839 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
840 gen->shared_len, kernel->n_block, kernel->block_dim);
841 else
842 tiling = tile(isl_space_copy(dim), gen->tiled_len,
843 gen->shared_len, kernel->n_block, kernel->block_dim);
844 gen->thread_tiled_len = gen->tiled_len + kernel->n_block;
846 sched = isl_union_map_apply_range(sched,
847 isl_union_map_from_map(tiling));
849 par = parametrization(dim, gen->thread_tiled_len,
850 gen->tile_first + kernel->tile_len +
851 kernel->n_grid + kernel->n_block, kernel->thread_ids);
852 sched = isl_union_map_intersect_range(sched,
853 isl_union_set_from_set(par));
855 gen->shared_len = gen->tile_first + kernel->tile_len + kernel->n_grid;
857 return sched;
860 /* If the user asked for it, scale the shared memory tile loops
861 * (T1T and T2) of "sched" by kernel->tile_size[i].
862 * If we are not performing "wrapping", then additionally scale the T1P
863 * loops by kernel->grid_dim[i].
865 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
866 __isl_take isl_union_map *sched)
868 struct ppcg_kernel *kernel = gen->kernel;
869 int i;
870 isl_space *dim;
871 isl_basic_map *scale;
872 isl_constraint *c;
873 isl_local_space *ls;
875 if (!gen->options->scale_tile_loops)
876 return sched;
878 dim = isl_union_map_get_space(sched);
879 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
880 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
881 scale = isl_basic_map_universe(isl_space_copy(dim));
882 ls = isl_local_space_from_space(dim);
884 for (i = 0; i < gen->tiled_len; ++i) {
885 int f = 1;
887 if (i >= gen->tile_first &&
888 i < gen->tile_first + kernel->n_grid) {
889 f = kernel->tile_size[i - gen->tile_first];
890 if (!gen->options->wrap)
891 f *= kernel->grid_dim[i - gen->tile_first];
892 } else if (i >= gen->tile_first + kernel->n_grid &&
893 i < gen->tile_first + kernel->n_grid +
894 kernel->tile_len) {
895 f = kernel->tile_size[i -
896 (gen->tile_first + kernel->n_grid)];
899 c = isl_equality_alloc(isl_local_space_copy(ls));
900 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
901 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
902 scale = isl_basic_map_add_constraint(scale, c);
905 isl_local_space_free(ls);
907 sched = isl_union_map_apply_range(sched,
908 isl_union_map_from_map(isl_map_from_basic_map(scale)));
910 return sched;
913 /* If we are not performing "wrapping" and if the user asked for it,
914 * scale the thread tile loops (P1T) of "sched" by kernel->block_dim[i].
916 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
917 __isl_take isl_union_map *sched)
919 int i;
920 isl_space *dim;
921 isl_basic_map *scale;
922 isl_constraint *c;
923 isl_local_space *ls;
925 if (gen->options->wrap)
926 return sched;
927 if (!gen->options->scale_tile_loops)
928 return sched;
930 dim = isl_union_map_get_space(sched);
931 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
932 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
933 scale = isl_basic_map_universe(isl_space_copy(dim));
934 ls = isl_local_space_from_space(dim);
936 for (i = 0; i < gen->thread_tiled_len; ++i) {
937 int f = 1;
939 if (i >= gen->shared_len &&
940 i < gen->shared_len + gen->kernel->n_block)
941 f = gen->kernel->block_dim[i - gen->shared_len];
943 c = isl_equality_alloc(isl_local_space_copy(ls));
944 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
945 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
946 scale = isl_basic_map_add_constraint(scale, c);
949 isl_local_space_free(ls);
951 sched = isl_union_map_apply_range(sched,
952 isl_union_map_from_map(isl_map_from_basic_map(scale)));
954 return sched;
957 /* If we are not performing "wrapping" and if the user asked for it,
958 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
960 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
961 __isl_take isl_union_map *sched, int len, int first, int n_tile)
963 int i;
964 isl_space *dim;
965 isl_basic_map *scale;
966 isl_constraint *c;
967 isl_local_space *ls;
969 if (gen->options->wrap)
970 return sched;
971 if (!gen->options->scale_tile_loops)
972 return sched;
974 dim = isl_union_map_get_space(sched);
975 dim = isl_space_add_dims(dim, isl_dim_in, len);
976 dim = isl_space_add_dims(dim, isl_dim_out, len);
977 scale = isl_basic_map_universe(isl_space_copy(dim));
978 ls = isl_local_space_from_space(dim);
980 for (i = 0; i < len; ++i) {
981 int f = 1;
983 if (i >= first && i < first + n_tile)
984 f = gen->kernel->block_dim[i - first];
986 c = isl_equality_alloc(isl_local_space_copy(ls));
987 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
988 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
989 scale = isl_basic_map_add_constraint(scale, c);
992 isl_local_space_free(ls);
994 sched = isl_union_map_apply_range(sched,
995 isl_union_map_from_map(isl_map_from_basic_map(scale)));
997 return sched;
1000 /* Add parameters p[i] with identifiers "ids" to "set",
1001 * with bounds to 0 <= p[i] < size[i].
1003 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1004 int *size, __isl_keep isl_id_list *ids)
1006 int i, len;
1007 unsigned nparam;
1009 len = isl_id_list_n_id(ids);
1010 nparam = isl_set_dim(set, isl_dim_param);
1011 set = isl_set_add_dims(set, isl_dim_param, len);
1013 for (i = 0; i < len; ++i) {
1014 isl_id *id;
1016 id = isl_id_list_get_id(ids, i);
1017 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1018 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
1019 set = isl_set_upper_bound_si(set, isl_dim_param,
1020 nparam + i, size[i] - 1);
1023 return set;
1026 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
1027 * with
1029 * { : 0 <= p[i] < size[i] }
1031 * or an overapproximation.
1033 static __isl_give isl_set *add_bounded_parameters_dynamic(
1034 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1035 __isl_keep isl_id_list *ids)
1037 int i, len;
1038 unsigned nparam;
1039 isl_space *space;
1040 isl_local_space *ls;
1042 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1043 nparam = isl_set_dim(set, isl_dim_param);
1044 set = isl_set_add_dims(set, isl_dim_param, len);
1046 for (i = 0; i < len; ++i) {
1047 isl_id *id;
1049 id = isl_id_list_get_id(ids, i);
1050 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1053 space = isl_space_params(isl_set_get_space(set));
1054 ls = isl_local_space_from_space(space);
1055 for (i = 0; i < len; ++i) {
1056 isl_pw_aff *param, *size_i, *zero;
1057 isl_set *bound;
1059 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1060 isl_dim_param, nparam + i);
1062 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1063 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1064 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1065 set = isl_set_intersect_params(set, bound);
1067 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1068 bound = isl_pw_aff_ge_set(param, zero);
1069 set = isl_set_intersect_params(set, bound);
1071 isl_local_space_free(ls);
1073 return set;
1076 /* Construct a map from an access to group->array to the corresponding
1077 * shared/private memory tile.
1078 * The map is of the form
1080 * { [D[i] -> A[a]] -> T[t] }
1082 * where D represents the initial shared_len dimensions
1083 * of the computed schedule.
1085 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1087 struct gpu_array_tile *tile;
1088 isl_multi_aff *tiling;
1090 tile = group->private_tile;
1091 if (!tile)
1092 tile = group->shared_tile;
1094 tiling = isl_multi_aff_copy(tile->tiling);
1096 return isl_map_from_multi_aff(tiling);
1099 /* Given a schedule that iterates over all elements in a piece of an array,
1100 * perform tiling/wrapping over the threads.
1102 * In particular, we tile the final iterators so that the final thread
1103 * dimension runs over the final array dimension.
1104 * However, if those final iterators have only a single iteration,
1105 * we try to tile earlier iterators instead.
1107 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1108 __isl_take isl_map *sched)
1110 isl_space *dim;
1111 isl_union_map *usched;
1112 isl_map *tiling;
1113 isl_set *par;
1114 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1115 int n_tile;
1116 int first;
1118 n_tile = gen->kernel->n_block;
1119 if (n_tile > nvar) {
1120 int i;
1121 sched = isl_map_insert_dims(sched,
1122 isl_dim_out, 0, n_tile - nvar);
1123 for (i = 0; i < n_tile - nvar; ++i)
1124 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1125 nvar = n_tile;
1128 first = nvar - n_tile;
1130 for (; first > 0; first --)
1131 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1132 break;
1134 dim = isl_map_get_space(sched);
1135 dim = isl_space_params(dim);
1136 if (gen->options->wrap)
1137 tiling = wrap(isl_space_copy(dim), nvar, first,
1138 n_tile, gen->kernel->block_dim);
1139 else
1140 tiling = tile(isl_space_copy(dim), nvar, first,
1141 n_tile, gen->kernel->block_dim);
1142 sched = isl_map_apply_range(sched, tiling);
1144 par = parametrization(dim, nvar + n_tile, first + n_tile,
1145 gen->kernel->thread_ids);
1146 sched = isl_map_intersect_range(sched, par);
1148 usched = isl_union_map_from_map(sched);
1149 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1150 first, n_tile);
1151 sched = isl_map_from_union_map(usched);
1153 return sched;
1156 /* Return the union of all tagged access relations in the group.
1158 static __isl_give isl_union_map *group_tagged_access_relation(
1159 struct gpu_array_ref_group *group)
1161 int i;
1162 isl_union_map *access;
1164 access = isl_union_map_empty(isl_map_get_space(group->access));
1165 for (i = 0; i < group->n_ref; ++i) {
1166 isl_map *map_i;
1168 map_i = isl_map_copy(group->refs[i]->tagged_access);
1169 access = isl_union_map_union(access,
1170 isl_union_map_from_map(map_i));
1173 return access;
1176 /* Return the extent of "array", recomputed from the bounds.
1177 * The recomputed extent may be simpler than the original extent.
1179 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1181 int i;
1182 isl_id *id;
1183 isl_space *space;
1184 isl_local_space *ls;
1185 isl_set *extent;
1187 id = isl_set_get_tuple_id(array->extent);
1188 space = isl_set_get_space(array->extent);
1189 extent = isl_set_universe(isl_space_copy(space));
1190 ls = isl_local_space_from_space(space);
1191 for (i = 0; i < array->n_index; ++i) {
1192 isl_pw_aff *bound;
1193 isl_aff *aff;
1194 isl_pw_aff *index;
1195 isl_set *lt;
1197 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1199 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1200 isl_dim_set, i);
1201 index = isl_pw_aff_from_aff(aff);
1202 bound = isl_pw_aff_copy(array->bound[i]);
1203 bound = isl_pw_aff_from_range(bound);
1204 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1205 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1206 isl_id_copy(id));
1207 lt = isl_pw_aff_lt_set(index, bound);
1208 extent = isl_set_intersect(extent, lt);
1210 isl_local_space_free(ls);
1211 isl_id_free(id);
1213 return extent;
1216 /* Return a map from the first shared_len dimensions of the computed
1217 * schedule to the array tile in
1218 * global memory that corresponds to the shared memory copy.
1220 * In particular, return a map
1222 * { D[i] -> A[a] }
1224 * with constraints
1226 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1228 * and
1230 * 0 <= a <= array_size - 1 (2)
1232 * Note that if some stride has been detected (i.e., when
1233 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1234 * to the shifted and scaled down version.
1236 * Constraints (1) are obtained by mapping the size constraints on the
1237 * shared/private memory tile back to the access relation.
1238 * Constraints (2) are obtained from the (recomputed) extent.
1240 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1242 int i;
1243 int n_index = group->array->n_index;
1244 isl_map *tile;
1245 isl_space *space;
1246 isl_set *local;
1247 isl_set *extent;
1249 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1250 space = isl_space_range(space);
1251 local = isl_set_universe(space);
1252 for (i = 0; i < n_index; ++i) {
1253 isl_val *bound;
1255 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1256 bound = isl_val_copy(group->shared_tile->bound[i].size);
1257 bound = isl_val_sub_ui(bound, 1);
1258 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1260 local = isl_set_preimage_multi_aff(local,
1261 isl_multi_aff_copy(group->shared_tile->tiling));
1262 tile = isl_set_unwrap(local);
1263 extent = array_extent(group->array);
1264 tile = isl_map_intersect_range(tile, extent);
1266 return tile;
1269 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1270 * return the corresponding mapping from the AST schedule to
1271 * to the first shared_len dimensions of the schedule computed by PPCG.
1273 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1274 __isl_take isl_pw_multi_aff *iterator_map)
1276 isl_union_map *umap;
1277 isl_space *space;
1278 isl_map *map, *sched;;
1280 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1281 space = isl_space_from_domain(space);
1282 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1284 umap = isl_union_map_copy(gen->shared_sched);
1285 umap = isl_union_map_apply_range(umap,
1286 isl_union_map_copy(gen->shared_proj));
1287 map = isl_union_map_extract_map(umap, space);
1288 isl_union_map_free(umap);
1290 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1291 sched = isl_map_detect_equalities(sched);
1293 return isl_pw_multi_aff_from_map(sched);
1296 /* Set unroll[j] if the input dimension j is involved in
1297 * the index expression represented by ma.
1299 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1300 void *user)
1302 int i, j;
1303 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1304 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1305 int *unroll = user;
1307 for (i = 0; i < n_out; ++i) {
1308 isl_aff *aff;
1310 aff = isl_multi_aff_get_aff(ma, i);
1311 for (j = 0; j < n_in; ++j)
1312 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1313 unroll[j] = 1;
1314 isl_aff_free(aff);
1317 isl_set_free(set);
1318 isl_multi_aff_free(ma);
1319 return 0;
1322 /* Given an array pos mapping input dimensions to the corresponding
1323 * output dimension, construct the corresponding map.
1325 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1326 int *pos, int len)
1328 int i;
1329 isl_constraint *c;
1330 isl_basic_map *bmap;
1331 isl_local_space *ls;
1333 dim = isl_space_add_dims(dim, isl_dim_in, len);
1334 dim = isl_space_add_dims(dim, isl_dim_out, len);
1335 bmap = isl_basic_map_universe(isl_space_copy(dim));
1336 ls = isl_local_space_from_space(dim);
1338 for (i = 0; i < len; ++i) {
1339 c = isl_equality_alloc(isl_local_space_copy(ls));
1340 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1341 -1);
1342 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1344 bmap = isl_basic_map_add_constraint(bmap, c);
1346 isl_local_space_free(ls);
1348 return isl_map_from_basic_map(bmap);
1351 /* Remove the private tiles from all array reference groups,
1352 * except for the groups of arrays that are marked force_private.
1354 static void remove_private_tiles(struct gpu_gen *gen)
1356 int i, j;
1358 for (i = 0; i < gen->kernel->n_array; ++i) {
1359 struct gpu_local_array_info *local = &gen->kernel->array[i];
1361 if (local->force_private)
1362 continue;
1364 for (j = 0; j < local->n_group; ++j) {
1365 struct gpu_array_ref_group *group = local->groups[j];
1367 group->private_tile =
1368 gpu_array_tile_free(group->private_tile);
1373 /* Find all loops involved in any of the index expressions for any of
1374 * the private accesses, move them innermost and then mark them as
1375 * requiring unrolling by setting gen->first_unroll.
1376 * The loops involved should all be parallel because of the checks
1377 * we performed in check_private_group_access. Moving them innermost
1378 * is therefore a valid transformation.
1380 * If any of the arrays are marked force_private, however, then
1381 * those loops may not be parallel with respect to the marked arrays.
1382 * If any of the loops would have to be moved innermost for the
1383 * (non forced) private accesses and if there are any force_private
1384 * arrays, then we revert the decision to map the selected arrays
1385 * to private memory. An alternative solution would be to expand
1386 * the force_private arrays.
1388 * Loops up to gen->shared_len are generated before the mapping to
1389 * threads is applied. They should therefore be ignored.
1391 * We compute the hidden equalities of the schedule first
1392 * since we will need them in our calls to isl_pw_multi_aff_from_map
1393 * and because we want to make sure that the same equalities
1394 * are also available to the code generator.
1396 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1397 __isl_take isl_union_map *sched)
1399 struct ppcg_kernel *kernel = gen->kernel;
1400 int i, j;
1401 int unroll[gen->thread_tiled_len];
1402 int perm[gen->thread_tiled_len];
1403 isl_space *dim;
1404 isl_map *permute;
1405 int len = gen->shared_len + kernel->n_parallel + kernel->n_block;
1407 gen->first_unroll = -1;
1409 sched = isl_union_map_detect_equalities(sched);
1410 for (i = 0; i < gen->thread_tiled_len; ++i)
1411 unroll[i] = 0;
1412 for (i = 0; i < kernel->n_array; ++i) {
1413 struct gpu_local_array_info *array = &kernel->array[i];
1415 for (j = 0; j < array->n_group; ++j) {
1416 isl_union_map *access;
1417 isl_map *acc;
1418 isl_pw_multi_aff *pma;
1420 if (!array->groups[j]->private_tile)
1421 continue;
1423 access = gpu_array_ref_group_access_relation(
1424 array->groups[j], 1, 1);
1425 access = isl_union_map_apply_domain(access,
1426 isl_union_map_copy(sched));
1428 acc = isl_map_from_union_map(access);
1429 pma = isl_pw_multi_aff_from_map(acc);
1430 isl_pw_multi_aff_foreach_piece(pma,
1431 &check_unroll, unroll);
1433 isl_pw_multi_aff_free(pma);
1437 for (i = gen->shared_len; i < len; ++i)
1438 if (unroll[i])
1439 break;
1441 if (i >= len)
1442 return sched;
1444 for (i = len; i < gen->thread_tiled_len; ++i)
1445 if (unroll[i])
1446 return sched;
1448 if (kernel->any_force_private) {
1449 remove_private_tiles(gen);
1450 return sched;
1453 j = 0;
1454 for (i = 0; i < gen->shared_len; ++i)
1455 perm[i] = j++;
1456 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1457 if (!unroll[i])
1458 perm[i] = j++;
1459 gen->first_unroll = j - gen->shared_len;
1460 for (i = gen->shared_len; i < len; ++i)
1461 if (unroll[i])
1462 perm[i] = j++;
1464 dim = isl_union_map_get_space(sched);
1465 permute = permutation(dim, perm, gen->thread_tiled_len);
1466 sched = isl_union_map_apply_range(sched,
1467 isl_union_map_from_map(permute));
1469 return sched;
1472 /* Construct a map with input the shared tile loops and the loops that
1473 * will be wrapped around the threads that relates these later loops
1474 * to the thread indices and then projects them out.
1476 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
1478 struct ppcg_kernel *kernel = gen->kernel;
1479 isl_map *priv;
1480 isl_map *tiling;
1481 isl_map *proj;
1482 isl_set *par;
1483 isl_space *dim;
1485 dim = isl_union_map_get_space(gen->shared_sched);
1487 if (gen->options->wrap)
1488 tiling = wrap(isl_space_copy(dim),
1489 gen->shared_len + kernel->n_block,
1490 gen->shared_len, kernel->n_block, kernel->block_dim);
1491 else
1492 tiling = tile(isl_space_copy(dim),
1493 gen->shared_len + kernel->n_block,
1494 gen->shared_len, kernel->n_block, kernel->block_dim);
1496 priv = tiling;
1498 par = parametrization(dim, gen->shared_len + 2 * kernel->n_block,
1499 gen->tile_first + kernel->tile_len +
1500 kernel->n_grid + kernel->n_block, kernel->thread_ids);
1502 priv = isl_map_align_params(priv, isl_set_get_space(par));
1503 priv = isl_map_intersect_range(priv, par);
1505 dim = isl_map_get_space(priv);
1506 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
1507 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
1508 proj = projection(dim, gen->shared_len + 2 * kernel->n_block,
1509 gen->shared_len);
1511 priv = isl_map_apply_range(priv, proj);
1513 return priv;
1516 /* If max_shared_memory is not set to infinity (-1), then make
1517 * sure that the total amount of shared memory required by the
1518 * array reference groups mapped to shared memory is no larger
1519 * than this maximum.
1521 * We apply a greedy approach and discard (keep in global memory)
1522 * those groups that would result in a total memory size that
1523 * is larger than the maximum.
1525 * This function should be called after any function that may
1526 * affect the decision on whether to place a reference group
1527 * in private, shared or global memory.
1529 static void check_shared_memory_bound(struct gpu_gen *gen)
1531 int i, j;
1532 isl_val *left, *size;
1534 if (gen->options->max_shared_memory < 0)
1535 return;
1537 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
1539 for (i = 0; i < gen->kernel->n_array; ++i) {
1540 struct gpu_local_array_info *local = &gen->kernel->array[i];
1542 for (j = 0; j < local->n_group; ++j) {
1543 struct gpu_array_ref_group *group;
1545 group = local->groups[j];
1546 if (group->private_tile)
1547 continue;
1548 if (!group->shared_tile)
1549 continue;
1551 size = gpu_array_tile_size(group->shared_tile);
1552 size = isl_val_mul_ui(size, local->array->size);
1554 if (isl_val_le(size, left)) {
1555 left = isl_val_sub(left, size);
1556 continue;
1558 isl_val_free(size);
1560 group->shared_tile =
1561 gpu_array_tile_free(group->shared_tile);
1565 isl_val_free(left);
1568 /* Compute a tiling for all the array reference groups.
1570 static void compute_group_tilings(struct gpu_gen *gen)
1572 int i, j;
1574 for (i = 0; i < gen->kernel->n_array; ++i) {
1575 struct gpu_local_array_info *array = &gen->kernel->array[i];
1577 for (j = 0; j < array->n_group; ++j)
1578 gpu_array_ref_group_compute_tiling(array->groups[j]);
1582 /* Take tiled_sched, project it onto the shared tile loops and
1583 * the loops that will be wrapped over the threads and
1584 * store the result in gen->shared_sched.
1585 * Also compute a projection that projects out the loops that will be
1586 * wrapped over the threads and store this projection in gen->shared_proj.
1588 static void compute_shared_sched(struct gpu_gen *gen)
1590 isl_space *dim;
1591 isl_map *proj;
1592 isl_set *par;
1593 isl_union_map *sched;
1595 sched = isl_union_map_copy(gen->tiled_sched);
1597 dim = isl_union_map_get_space(sched);
1598 proj = projection(dim, gen->tiled_len,
1599 gen->shared_len + gen->kernel->n_block);
1600 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
1602 dim = isl_union_map_get_space(sched);
1603 proj = projection(dim, gen->shared_len + gen->kernel->n_block,
1604 gen->shared_len);
1606 gen->shared_sched = sched;
1607 gen->shared_proj = isl_union_map_from_map(proj);
1610 /* Compute the size of a bounding box around the origin and "set",
1611 * where "set" is assumed to contain only non-negative elements.
1612 * In particular, compute the maximal value of "set" in each direction
1613 * and add one.
1615 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
1616 __isl_take isl_set *context)
1618 int i, n;
1619 isl_multi_pw_aff *mpa;
1621 context = isl_set_params(context);
1622 n = isl_set_dim(set, isl_dim_set);
1623 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
1624 for (i = 0; i < n; ++i) {
1625 isl_space *space;
1626 isl_aff *one;
1627 isl_pw_aff *bound;
1629 bound = isl_set_dim_max(isl_set_copy(set), i);
1630 bound = isl_pw_aff_coalesce(bound);
1631 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
1633 space = isl_pw_aff_get_domain_space(bound);
1634 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1635 one = isl_aff_add_constant_si(one, 1);
1636 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
1637 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
1639 isl_set_free(set);
1640 isl_set_free(context);
1642 return mpa;
1645 /* Compute the effective grid size as a list of the sizes in each dimension.
1647 * The grid size specified by the user or set by default
1648 * in read_grid_sizes() and applied in tile_schedule(),
1649 * may be too large for the given code in the sense that
1650 * it may contain blocks that don't need to execute anything.
1651 * We therefore don't return this grid size, but instead the
1652 * smallest grid size that ensures that all blocks that actually
1653 * execute code are included in the grid.
1655 * We first extract a description of the grid, i.e., the possible values
1656 * of the block ids, from gen->tiled_sched.
1657 * The block ids are parameters in gen->tiled_sched.
1658 * We simply need to change them into set dimensions.
1660 * Then, for each block dimension, we compute the maximal value of the block id
1661 * and add one.
1663 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
1664 struct ppcg_kernel *kernel)
1666 int i;
1667 isl_set *grid;
1669 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
1670 grid = isl_set_from_params(grid);
1671 grid = isl_set_add_dims(grid, isl_dim_set, kernel->n_grid);
1672 for (i = 0; i < kernel->n_grid; ++i) {
1673 int pos;
1674 isl_id *id;
1676 id = isl_id_list_get_id(kernel->block_ids, i);
1677 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
1678 isl_id_free(id);
1679 assert(pos >= 0);
1680 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
1681 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
1684 return extract_size(grid, isl_set_copy(kernel->context));
1687 /* Compute the size of a fixed bounding box around the origin and "set",
1688 * where "set" is assumed to contain only non-negative elements,
1689 * and store the results in "size".
1690 * In particular, compute the maximal value of "set" in each direction
1691 * and add one.
1693 static void extract_fixed_size(__isl_take isl_set *set, int *size)
1695 int i, n;
1696 isl_local_space *ls;
1697 isl_aff *obj;
1699 n = isl_set_dim(set, isl_dim_set);
1700 ls = isl_local_space_from_space(isl_set_get_space(set));
1701 obj = isl_aff_zero_on_domain(ls);
1702 for (i = 0; i < n; ++i) {
1703 isl_val *max;
1705 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
1706 max = isl_set_max_val(set, obj);
1707 size[i] = isl_val_get_num_si(max) + 1;
1708 isl_val_free(max);
1709 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
1711 isl_aff_free(obj);
1712 isl_set_free(set);
1715 /* Compute the effective block size as a list of the sizes in each dimension
1716 * and store the sizes in kernel->block_dim.
1718 * The block size specified by the user or set by default
1719 * in read_block_sizes() and applied in thread_tile_schedule(),
1720 * may be too large for the given code in the sense that
1721 * it may contain threads that don't need to execute anything.
1722 * We therefore update this block size in kernel->block_dim
1723 * to the smallest block size that ensures that all threads
1724 * that actually execute code are included in the block.
1726 * The current implementation eliminates all parameters, ensuring
1727 * that the size is a fixed constant in each dimension.
1728 * In principle we could also compute parametric sizes.
1729 * We would have to make sure to project out all b%d and t%d parameters,
1730 * however.
1732 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
1734 int i;
1735 int nparam;
1736 isl_set *block;
1737 isl_multi_pw_aff *mpa;
1739 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
1740 block = isl_set_from_params(block);
1741 block = isl_set_add_dims(block, isl_dim_set, kernel->n_block);
1742 for (i = 0; i < kernel->n_block; ++i) {
1743 int pos;
1744 isl_id *id;
1746 id = isl_id_list_get_id(kernel->thread_ids, i);
1747 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
1748 isl_id_free(id);
1749 assert(pos >= 0);
1750 block = isl_set_equate(block, isl_dim_param, pos,
1751 isl_dim_set, i);
1753 nparam = isl_set_dim(block, isl_dim_param);
1754 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
1756 extract_fixed_size(block, kernel->block_dim);
1759 struct ppcg_kernel *ppcg_kernel_free(struct ppcg_kernel *kernel)
1761 int i, j;
1763 if (!kernel)
1764 return NULL;
1766 isl_id_list_free(kernel->block_ids);
1767 isl_id_list_free(kernel->thread_ids);
1768 isl_multi_pw_aff_free(kernel->grid_size);
1769 isl_set_free(kernel->context);
1770 isl_union_set_free(kernel->core);
1771 isl_union_set_free(kernel->arrays);
1772 isl_space_free(kernel->space);
1773 isl_ast_node_free(kernel->tree);
1774 isl_union_set_free(kernel->block_filter);
1776 for (i = 0; i < kernel->n_array; ++i) {
1777 struct gpu_local_array_info *array = &kernel->array[i];
1779 for (j = 0; j < array->n_group; ++j)
1780 gpu_array_ref_group_free(array->groups[j]);
1781 free(array->groups);
1783 isl_pw_aff_list_free(array->bound);
1785 free(kernel->array);
1787 for (i = 0; i < kernel->n_var; ++i) {
1788 free(kernel->var[i].name);
1789 isl_vec_free(kernel->var[i].size);
1791 free(kernel->var);
1792 free(kernel->tile_size);
1794 free(kernel);
1796 return NULL;
1799 /* Wrapper around ppcg_kernel_free for use as a isl_id_set_free_user callback.
1801 static void ppcg_kernel_free_wrap(void *user)
1803 struct ppcg_kernel *kernel = user;
1805 ppcg_kernel_free(kernel);
1808 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
1809 struct ppcg_kernel_var *var)
1811 int j;
1812 struct gpu_array_tile *tile;
1813 isl_printer *p;
1814 char *name;
1816 var->array = group->array;
1818 tile = group->private_tile;
1819 var->type = ppcg_access_private;
1820 if (!tile) {
1821 tile = group->shared_tile;
1822 var->type = ppcg_access_shared;
1825 p = isl_printer_to_str(ctx);
1826 p = gpu_array_ref_group_print_name(group, p);
1827 var->name = isl_printer_get_str(p);
1828 isl_printer_free(p);
1830 var->size = isl_vec_alloc(ctx, group->array->n_index);
1832 for (j = 0; j < group->array->n_index; ++j)
1833 var->size = isl_vec_set_element_val(var->size, j,
1834 isl_val_copy(tile->bound[j].size));
1837 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
1839 int i, j, n;
1841 n = 0;
1842 for (i = 0; i < kernel->n_array; ++i) {
1843 struct gpu_local_array_info *array = &kernel->array[i];
1845 for (j = 0; j < array->n_group; ++j) {
1846 struct gpu_array_ref_group *group = array->groups[j];
1847 if (group->private_tile || group->shared_tile)
1848 ++n;
1852 kernel->n_var = n;
1853 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
1854 assert(kernel->var);
1856 n = 0;
1857 for (i = 0; i < kernel->n_array; ++i) {
1858 struct gpu_local_array_info *array = &kernel->array[i];
1860 for (j = 0; j < array->n_group; ++j) {
1861 struct gpu_array_ref_group *group = array->groups[j];
1862 if (!group->private_tile && !group->shared_tile)
1863 continue;
1864 create_kernel_var(gen->ctx, group, &kernel->var[n]);
1865 ++n;
1870 /* Replace "pa" by the zero function defined over the universe domain
1871 * in the space of "pa".
1873 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
1875 isl_space *space;
1876 isl_aff *zero;
1878 space = isl_space_domain(isl_pw_aff_get_space(pa));
1879 isl_pw_aff_free(pa);
1880 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1882 return isl_pw_aff_from_aff(zero);
1885 /* The sizes of the arrays on the host that have been computed by
1886 * extract_array_info may depend on the parameters. Use the extra
1887 * constraints on the parameters that are valid at "host_domain"
1888 * to simplify these expressions and store the results in kernel->array.
1890 * We only need these localized bounds for arrays that are accessed
1891 * by the current kernel. If we have found at least one reference group
1892 * then the array is accessed by the kernel. If the array has compound
1893 * elements then we skipped the construction of array reference groups.
1895 * The resulting sizes may be functions that are nowhere defined
1896 * in case the access function cannot possibly access anything inside
1897 * the kernel for some reason. If so, they are replaced by the zero
1898 * function. Since the access function cannot actually access anything,
1899 * there is no harm in printing the array sizes as zero.
1901 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
1902 __isl_keep isl_set *host_domain)
1904 int i, j;
1905 isl_set *context;
1907 context = isl_set_copy(host_domain);
1908 context = isl_set_params(context);
1910 for (i = 0; i < kernel->n_array; ++i) {
1911 struct gpu_local_array_info *local = &kernel->array[i];
1912 isl_pw_aff_list *bound;
1913 int n_index;
1915 if (local->n_group == 0 && !local->array->has_compound_element)
1916 continue;
1918 n_index = local->array->n_index;
1919 bound = isl_pw_aff_list_alloc(gen->ctx, n_index);
1921 for (j = 0; j < n_index; ++j) {
1922 isl_pw_aff *pwaff;
1923 int empty;
1925 pwaff = isl_pw_aff_copy(local->array->bound[j]);
1926 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
1927 empty = isl_pw_aff_is_empty(pwaff);
1928 if (empty < 0)
1929 pwaff = isl_pw_aff_free(pwaff);
1930 else if (empty)
1931 pwaff = set_universally_zero(pwaff);
1932 bound = isl_pw_aff_list_add(bound, pwaff);
1935 local->n_index = n_index;
1936 local->bound = bound;
1938 isl_set_free(context);
1941 /* Create the array of gpu_local_array_info structures "array"
1942 * inside "kernel". The number of elements in this array is
1943 * the same as the number of arrays in "prog".
1944 * Initialize the "array" field of each local array to point
1945 * to the corresponding array in "prog".
1947 static struct ppcg_kernel *ppcg_kernel_create_local_arrays(
1948 struct ppcg_kernel *kernel, struct gpu_prog *prog)
1950 int i;
1951 isl_ctx *ctx;
1953 ctx = isl_set_get_ctx(prog->context);
1954 kernel->array = isl_calloc_array(ctx,
1955 struct gpu_local_array_info, prog->n_array);
1956 if (!kernel->array)
1957 return ppcg_kernel_free(kernel);
1958 kernel->n_array = prog->n_array;
1960 for (i = 0; i < prog->n_array; ++i)
1961 kernel->array[i].array = &prog->array[i];
1963 return kernel;
1966 /* Find the element in gen->stmt that has the given "id".
1967 * Return NULL if no such gpu_stmt can be found.
1969 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
1971 int i;
1973 for (i = 0; i < prog->n_stmts; ++i) {
1974 if (id == prog->stmts[i].id)
1975 break;
1978 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
1981 void ppcg_kernel_stmt_free(void *user)
1983 int i;
1984 struct ppcg_kernel_stmt *stmt = user;
1986 if (!stmt)
1987 return;
1989 switch (stmt->type) {
1990 case ppcg_kernel_copy:
1991 isl_ast_expr_free(stmt->u.c.index);
1992 isl_ast_expr_free(stmt->u.c.local_index);
1993 break;
1994 case ppcg_kernel_domain:
1995 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
1996 break;
1997 case ppcg_kernel_sync:
1998 break;
2001 free(stmt);
2004 /* Set the options of "context" to
2006 * { space -> [x] : x >= first }
2008 static __isl_give isl_ast_build *set_unroll(
2009 __isl_take isl_ast_build *build, __isl_take isl_space *space,
2010 int first)
2012 isl_ctx *ctx;
2013 isl_map *unroll;
2014 isl_union_map *opt;
2016 ctx = isl_ast_build_get_ctx(build);
2018 space = isl_space_from_domain(space);
2019 space = isl_space_add_dims(space, isl_dim_out, 1);
2020 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
2021 unroll = isl_map_universe(space);
2022 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
2023 opt = isl_union_map_from_map(unroll);
2025 build = isl_ast_build_set_options(build, opt);
2027 return build;
2030 /* Extend the schedule "schedule" with the part of "extension"
2031 * starting at "first" up to "len".
2033 static __isl_give isl_union_map *extend_schedule(
2034 __isl_take isl_union_map *schedule,
2035 __isl_take isl_union_map *extension, int first, int len)
2037 isl_space *space;
2038 isl_map *proj;
2039 isl_union_map *umap;
2040 isl_set *set;
2042 space = isl_union_map_get_space(schedule);
2043 space = isl_space_set_from_params(space);
2044 space = isl_space_add_dims(space, isl_dim_set, len);
2045 proj = isl_set_identity(isl_set_universe(space));
2046 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
2047 extension = isl_union_map_apply_range(extension,
2048 isl_union_map_from_map(proj));
2050 schedule = isl_union_map_range_product(schedule, extension);
2052 return schedule;
2055 /* Return the gpu_stmt_access in the list "accesses" that corresponds
2056 * to "ref_id".
2058 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
2059 __isl_keep isl_id *ref_id)
2061 struct gpu_stmt_access *access;
2063 for (access = accesses; access; access = access->next)
2064 if (access->ref_id == ref_id)
2065 return access;
2067 return NULL;
2070 /* Return the index of the array called "name" in the list of arrays.
2072 static int find_array_index(struct gpu_gen *gen, const char *name)
2074 int i;
2076 for (i = 0; i < gen->prog->n_array; ++i)
2077 if (!strcmp(name, gen->prog->array[i].name))
2078 return i;
2080 return -1;
2083 /* Internal data structure for the index and AST expression transformation
2084 * callbacks for pet_stmt_build_ast_exprs.
2086 * "accesses" is the list of gpu_stmt_access in the statement.
2087 * "iterator_map" expresses the statement iterators in terms of
2088 * the AST loop iterators.
2089 * "sched2shared" expresses the first shared_len dimensions of
2090 * the computed schedule in terms of the AST loop iterators.
2092 * The following fields are set in transform_index and used in transform_expr.
2093 * "array" is the array that is being accessed.
2094 * "global" is set if the global array is accessed (rather than
2095 * shared/private memory).
2096 * "local_array" refers to information on the array specialized
2097 * to the current kernel.
2099 struct ppcg_transform_data {
2100 struct gpu_gen *gen;
2101 struct gpu_stmt_access *accesses;
2102 isl_pw_multi_aff *iterator_map;
2103 isl_pw_multi_aff *sched2shared;
2105 struct gpu_array_info *array;
2106 int global;
2107 struct gpu_local_array_info *local_array;
2110 /* Return the name of the outer array (of structs) accessed by "access".
2112 static const char *get_outer_array_name(__isl_keep isl_map *access)
2114 isl_space *space;
2115 const char *name;
2117 space = isl_space_range(isl_map_get_space(access));
2118 while (space && isl_space_is_wrapping(space))
2119 space = isl_space_domain(isl_space_unwrap(space));
2120 name = isl_space_get_tuple_name(space, isl_dim_set);
2121 isl_space_free(space);
2123 return name;
2126 /* Return a pointer to the gpu_array_ref_group in "local"
2127 * that contains the reference "access".
2128 * Return NULL if no such group can be found.
2130 static struct gpu_array_ref_group *find_ref_group(
2131 struct gpu_local_array_info *local, struct gpu_stmt_access *access)
2133 int i, j;
2135 for (i = 0; i < local->n_group; ++i) {
2136 struct gpu_array_ref_group *group = local->groups[i];
2138 for (j = 0; j < group->n_ref; ++j)
2139 if (group->refs[j] == access)
2140 return group;
2143 return NULL;
2146 /* Index transformation callback for pet_stmt_build_ast_exprs.
2148 * "index" expresses the array indices in terms of statement iterators
2150 * We first reformulate "index" in terms of the AST loop iterators.
2151 * Then we check if we are accessing the global array or
2152 * a shared/private copy. In the former case, we simply return
2153 * the updated index. If "index" is an affine expression rather
2154 * than an array access, then we also return the updated index here.
2156 * If no reference groups have been computed for the array,
2157 * then we can only be accessing the global array.
2159 * Otherwise, we apply the tiling to the index.
2160 * This tiling is of the form
2162 * [D -> A] -> T
2164 * The index is of the form
2166 * L -> A
2168 * We update the tiling to refer to the AST loop iterators
2170 * [L -> A] -> T
2172 * and modify index to keep track of those iterators
2174 * L -> [L -> A]
2176 * Combining these two yields a tiled index expression in terms
2177 * of the AST loop iterators
2179 * L -> T
2181 static __isl_give isl_multi_pw_aff *transform_index(
2182 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
2183 void *user)
2185 struct ppcg_transform_data *data = user;
2186 struct gpu_stmt_access *access;
2187 struct gpu_array_ref_group *group;
2188 struct gpu_array_tile *tile;
2189 isl_pw_multi_aff *iterator_map;
2190 int i;
2191 const char *name;
2192 isl_space *space;
2193 isl_multi_pw_aff *tiling;
2194 isl_pw_multi_aff *pma;
2195 isl_multi_pw_aff *mpa;
2197 data->array = NULL;
2199 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
2200 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
2202 access = find_access(data->accesses, ref_id);
2203 if (!access)
2204 return index;
2205 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
2206 return index;
2208 name = get_outer_array_name(access->access);
2209 i = find_array_index(data->gen, name);
2210 if (i < 0)
2211 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
2212 "cannot find array",
2213 return isl_multi_pw_aff_free(index));
2214 data->array = &data->gen->prog->array[i];
2215 data->local_array = &data->gen->kernel->array[i];
2217 group = find_ref_group(data->local_array, access);
2218 if (!group) {
2219 data->global = 1;
2220 return index;
2223 tile = group->private_tile;
2224 if (!tile)
2225 tile = group->shared_tile;
2226 data->global = !tile;
2227 if (!tile)
2228 return index;
2230 space = isl_space_range(isl_multi_pw_aff_get_space(index));
2231 space = isl_space_map_from_set(space);
2232 pma = isl_pw_multi_aff_identity(space);
2233 pma = isl_pw_multi_aff_product(
2234 isl_pw_multi_aff_copy(data->sched2shared), pma);
2235 tiling = isl_multi_pw_aff_from_multi_aff(
2236 isl_multi_aff_copy(tile->tiling));
2237 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
2239 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
2240 space = isl_space_map_from_set(space);
2241 mpa = isl_multi_pw_aff_identity(space);
2242 index = isl_multi_pw_aff_range_product(mpa, index);
2243 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
2245 return index;
2248 /* Dereference "expr" by adding an index [0].
2249 * The original "expr" is assumed not to have any indices.
2251 * If "expr" is a member access, then the dereferencing needs
2252 * to be applied to the structure argument of this member access.
2254 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
2256 isl_ctx *ctx;
2257 isl_ast_expr *arg0, *res;
2258 isl_ast_expr_list *list;
2260 arg0 = isl_ast_expr_get_op_arg(expr, 0);
2261 if (!arg0)
2262 return isl_ast_expr_free(expr);
2263 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
2264 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
2265 isl_ast_expr *arg;
2267 arg = isl_ast_expr_get_op_arg(arg0, 0);
2268 arg = dereference(arg);
2269 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
2270 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
2272 return expr;
2274 isl_ast_expr_free(arg0);
2276 ctx = isl_ast_expr_get_ctx(expr);
2277 res = isl_ast_expr_from_val(isl_val_zero(ctx));
2278 list = isl_ast_expr_list_from_ast_expr(res);
2279 res = isl_ast_expr_get_op_arg(expr, 0);
2280 res = isl_ast_expr_access(res, list);
2281 isl_ast_expr_free(expr);
2283 return res;
2286 /* Linearize the index expression "expr" based on the array bounds
2287 * of "array".
2289 * That is, transform expression
2291 * A[i_0][i_1]...[i_n]
2293 * to
2295 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
2297 * where b_0, b_1, ..., b_n are the bounds on the array.
2299 * If the base of "expr" is a member access, then the linearization needs
2300 * to be applied to the structure argument of this member access.
2302 * In the base case, if "expr" has no arguments (other than the name of
2303 * the array), then we are passing an entire array to a function.
2304 * In this case, there is nothing to linearize.
2305 * Note that at this point an expression with no arguments can
2306 * only be an entire array because the scalar case and
2307 * the case of single struct are handled by the caller.
2309 * If the number of specified index expressions in "expr"
2310 * is smaller than the dimension of the accessed array,
2311 * then the missing i_j also do not appear in the linearized expression.
2312 * Furthermore, since such an expression does not refer to a single
2313 * element while the default linearized expression would refer to
2314 * a single element, we return the expression
2316 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
2318 * instead. Note that because of the special case handling above,
2319 * we can assume here that here that there is at least one index expression.
2321 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
2322 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
2324 int i, n;
2325 isl_ctx *ctx;
2326 isl_set *context;
2327 isl_ast_expr *arg0;
2328 isl_ast_expr *res;
2329 isl_ast_expr_list *list;
2330 isl_ast_build *build;
2332 arg0 = isl_ast_expr_get_op_arg(expr, 0);
2333 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
2334 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
2335 isl_ast_expr *arg;
2337 arg = isl_ast_expr_get_op_arg(arg0, 0);
2338 arg = gpu_local_array_info_linearize_index(array, arg);
2339 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
2340 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
2342 return expr;
2344 isl_ast_expr_free(arg0);
2346 if (isl_ast_expr_get_op_n_arg(expr) == 1)
2347 return expr;
2349 ctx = isl_ast_expr_get_ctx(expr);
2350 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
2351 build = isl_ast_build_from_context(context);
2353 n = isl_ast_expr_get_op_n_arg(expr);
2354 res = isl_ast_expr_get_op_arg(expr, 1);
2355 for (i = 1; i < array->n_index; ++i) {
2356 isl_pw_aff *bound_i;
2357 isl_ast_expr *expr_i;
2359 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
2360 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
2361 res = isl_ast_expr_mul(res, expr_i);
2363 if (i + 1 >= n)
2364 continue;
2365 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
2366 res = isl_ast_expr_add(res, expr_i);
2369 isl_ast_build_free(build);
2371 if (1 + array->n_index > n) {
2372 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
2373 } else {
2374 list = isl_ast_expr_list_from_ast_expr(res);
2375 res = isl_ast_expr_get_op_arg(expr, 0);
2376 res = isl_ast_expr_access(res, list);
2379 isl_ast_expr_free(expr);
2381 return res;
2384 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
2386 * If the AST expression refers to an array that is not accessed
2387 * at all, then this means the value of the expression is not used,
2388 * so we might as well print zero (NULL pointer) instead.
2390 * If the AST expression refers to a global scalar that is not
2391 * a read-only scalar, then its address was passed to the kernel and
2392 * we need to dereference it.
2394 * If the AST expression refers to an access to a global array,
2395 * then we linearize the access exploiting the bounds in data->local_array.
2397 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
2398 __isl_keep isl_id *id, void *user)
2400 struct ppcg_transform_data *data = user;
2402 if (!data->array)
2403 return expr;
2404 if (!data->array->accessed) {
2405 isl_ctx *ctx;
2407 ctx = isl_ast_expr_get_ctx(expr);
2408 isl_ast_expr_free(expr);
2409 return isl_ast_expr_from_val(isl_val_zero(ctx));
2411 if (gpu_array_is_read_only_scalar(data->array))
2412 return expr;
2413 if (!data->global)
2414 return expr;
2415 if (data->array->n_index == 0)
2416 return dereference(expr);
2417 if (!data->array->linearize)
2418 return expr;
2420 return gpu_local_array_info_linearize_index(data->local_array, expr);
2423 /* This function is called for each instance of a user statement
2424 * in the kernel.
2426 * We attach a struct ppcg_kernel_stmt to the "node", containing
2427 * a computed AST expression for each access.
2428 * These AST expressions are computed from iterator_map,
2429 * which expresses the domain
2430 * elements in terms of the generated loops, and sched2shared,
2431 * which expresses the first shared_len dimensions of the schedule
2432 * computed by PPCG in terms of the generated loops.
2434 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
2435 __isl_keep isl_ast_build *build, void *user)
2437 struct ppcg_transform_data data;
2438 struct gpu_gen *gen = (struct gpu_gen *) user;
2439 struct ppcg_kernel_stmt *stmt;
2440 isl_id *id;
2441 isl_pw_multi_aff *sched2shared;
2442 isl_map *map;
2443 isl_pw_multi_aff *iterator_map;
2444 isl_ast_expr *expr, *arg;
2445 isl_union_map *schedule;
2447 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2448 if (!stmt)
2449 return isl_ast_node_free(node);
2451 expr = isl_ast_node_user_get_expr(node);
2452 arg = isl_ast_expr_get_op_arg(expr, 0);
2453 id = isl_ast_expr_get_id(arg);
2455 schedule = isl_ast_build_get_schedule(build);
2456 map = isl_map_reverse(isl_map_from_union_map(schedule));
2457 iterator_map = isl_pw_multi_aff_from_map(map);
2458 sched2shared = compute_sched_to_shared(gen,
2459 isl_pw_multi_aff_copy(iterator_map));
2461 stmt->type = ppcg_kernel_domain;
2462 stmt->u.d.stmt = find_stmt(gen->prog, id);
2463 if (!stmt->u.d.stmt)
2464 isl_die(gen->ctx, isl_error_internal,
2465 "statement not found", goto error);
2467 data.gen = gen;
2468 data.accesses = stmt->u.d.stmt->accesses;
2469 data.iterator_map = iterator_map;
2470 data.sched2shared = sched2shared;
2471 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
2472 build, &transform_index, &data,
2473 &transform_expr, &data);
2475 isl_id_free(id);
2476 isl_pw_multi_aff_free(iterator_map);
2477 isl_pw_multi_aff_free(sched2shared);
2478 isl_ast_expr_free(arg);
2479 isl_ast_expr_free(expr);
2481 id = isl_id_alloc(gen->ctx, NULL, stmt);
2482 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2483 return isl_ast_node_set_annotation(node, id);
2484 error:
2485 isl_id_free(id);
2486 isl_pw_multi_aff_free(iterator_map);
2487 ppcg_kernel_stmt_free(stmt);
2488 isl_pw_multi_aff_free(sched2shared);
2489 return isl_ast_node_free(node);
2492 /* This function is called when code has been generated for the shared
2493 * tile loops. The "schedule" refers only to the original statements.
2495 * We extend the schedule with that part of gen->local_sched that hasn't
2496 * been taken into account yet. This introduces parameters referring
2497 * to thread ids in the schedule, so we add them (with the appropriate
2498 * bounds to the context as well).
2499 * Finally, we set the appropriate unrolling options
2500 * if gen->first_unroll is set.
2502 static __isl_give isl_ast_node *create_domain_leaf(
2503 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
2504 void *user)
2506 struct gpu_gen *gen = (struct gpu_gen *) user;
2507 isl_space *space;
2508 isl_union_map *sched;
2509 isl_ast_node *tree;
2510 isl_set *set;
2511 isl_id_list *iterators;
2512 int n;
2514 schedule = extend_schedule(schedule,
2515 isl_union_map_copy(gen->local_sched),
2516 gen->shared_len, gen->thread_tiled_len);
2518 space = isl_ast_build_get_schedule_space(build);
2519 set = isl_set_universe(space);
2520 set = add_bounded_parameters(set, gen->kernel->block_dim,
2521 gen->kernel->thread_ids);
2522 build = isl_ast_build_restrict(build, set);
2524 n = gen->thread_tiled_len - gen->shared_len;
2526 if (gen->first_unroll >= 0) {
2527 space = isl_space_set_alloc(gen->ctx, 0, n);
2528 build = set_unroll(build, space, gen->first_unroll);
2530 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
2531 build = isl_ast_build_set_iterators(build, iterators);
2532 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
2533 tree = isl_ast_build_node_from_schedule_map(build, schedule);
2534 isl_ast_build_free(build);
2536 return tree;
2539 /* This function is called for each statement node in the AST of the code
2540 * for copying to or from shared/private memory.
2541 * Attach a pointer to a ppcg_kernel_stmt representing the copy
2542 * statement to the node.
2543 * The statement name is "read" or "write", depending on whether we are
2544 * reading from global memory or writing to global memory.
2545 * The name of the T space is {shared,private}_<array>.
2547 * The schedule is of the form
2549 * type[A -> T] -> L
2551 * where A refers to a piece of an array and T to the corresponding
2552 * shifted tile. We split this schedule into mappings L -> A and L -> T
2553 * and store the corresponding expressions in stmt->index and stmt->local_index,
2554 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
2556 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
2557 __isl_keep isl_ast_build *build, void *user)
2559 struct gpu_gen *gen = (struct gpu_gen *) user;
2560 struct ppcg_kernel_stmt *stmt;
2561 isl_id *id;
2562 isl_ast_expr *expr;
2563 isl_space *space;
2564 isl_map *access, *local_access, *map;
2565 isl_pw_multi_aff *pma;
2566 const char *type;
2567 int array_index;
2569 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2570 if (!stmt)
2571 return isl_ast_node_free(node);
2573 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
2574 type = isl_map_get_tuple_name(access, isl_dim_in);
2575 stmt->u.c.read = !strcmp(type, "read");
2576 access = isl_map_reverse(access);
2577 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
2578 local_access = isl_map_copy(access);
2580 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
2581 id = isl_map_get_tuple_id(access, isl_dim_out);
2582 map = isl_map_set_tuple_id(map, isl_dim_in, id);
2583 access = isl_map_apply_range(access, map);
2584 pma = isl_pw_multi_aff_from_map(access);
2585 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
2586 stmt->u.c.index = expr;
2588 map = isl_map_range_map(isl_map_universe(space));
2589 id = isl_map_get_tuple_id(local_access, isl_dim_out);
2590 map = isl_map_set_tuple_id(map, isl_dim_in, id);
2591 local_access = isl_map_apply_range(local_access, map);
2592 pma = isl_pw_multi_aff_from_map(local_access);
2593 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
2594 stmt->u.c.local_index = expr;
2596 stmt->u.c.array = gen->copy_group->array;
2597 array_index = stmt->u.c.array - gen->prog->array;
2598 stmt->u.c.local_array = &gen->kernel->array[array_index];
2599 stmt->type = ppcg_kernel_copy;
2601 id = isl_id_alloc(gen->ctx, NULL, stmt);
2602 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2603 return isl_ast_node_set_annotation(node, id);
2606 /* Given a schedule of the form
2608 * [S -> A] -> L
2610 * (with S the first shared_len dimensions of the computed schedule,
2611 * A the array and L the schedule correponding to the generated loops),
2612 * indicating where to copy the array elements that need to be copied,
2613 * construct code for performing the copying.
2615 * "group" is the array reference group that is being copied
2616 * "type" is either "read" or "write"
2617 * private is set if copying needs to be performed to/from registers
2619 * We first construct a mapping to a shifted tile of the array,
2621 * [S -> A] -> T(S,A) (1)
2623 * If private is set, then we also use this mapping as a schedule
2624 * (which is already thread-specific and will be completely unrolled).
2625 * Otherwise, we wrap/tile the range over the threads.
2626 * The result is
2628 * [S -> A] -> T'(S,A)
2630 * Combined with the given schedule, we have
2632 * [S -> A] -> [L -> T'(S,A)] (2)
2634 * From the shifted tile mapping, we construct a mapping
2636 * [S -> A] -> [A -> T(S,A)]
2638 * and apply it to the schedule (2), obtaining
2640 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
2642 * Note that we can project out S because it is uniquely defined by L.
2644 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
2645 __isl_take isl_map *sched,
2646 const char *type, struct gpu_array_ref_group *group,
2647 __isl_take isl_ast_build *build, int private)
2649 isl_space *space;
2650 isl_ast_node *tree;
2651 isl_map *schedule, *shift, *map;
2652 isl_set *set;
2653 isl_id_list *iterators;
2654 int n;
2656 shift = shift_access(group);
2658 schedule = isl_map_copy(shift);
2659 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
2660 if (!private)
2661 schedule = tile_access_schedule(gen, schedule);
2663 n = isl_map_dim(schedule, isl_dim_out);
2664 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
2665 set = add_bounded_parameters(set, gen->kernel->block_dim,
2666 gen->kernel->thread_ids);
2668 schedule = isl_map_range_product(sched, schedule);
2670 space = isl_space_domain(isl_map_get_space(shift));
2671 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
2672 map = isl_map_range_product(map, shift);
2674 schedule = isl_map_apply_domain(schedule, map);
2676 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
2678 build = isl_ast_build_restrict(build, set);
2680 gen->copy_group = group;
2682 if (private) {
2683 space = isl_space_range(isl_map_get_space(schedule));
2684 space = isl_space_range(isl_space_unwrap(space));
2685 build = set_unroll(build, space, 0);
2687 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
2688 build = isl_ast_build_set_iterators(build, iterators);
2689 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
2690 tree = isl_ast_build_node_from_schedule_map(build,
2691 isl_union_map_from_map(schedule));
2692 isl_ast_build_free(build);
2694 return tree;
2697 /* Return code for reading into or writing from shared memory
2698 * the given array reference group.
2700 * If we are performing a read from global memory to shared memory and
2701 * if the array involved is not a scalar, then we copy
2702 * the entire tile to shared memory. This may result in some extra
2703 * elements getting copied, but it should lead to simpler code
2704 * (which means that fewer registers may be needed) and less divergence.
2706 * Otherwise, we only copy the elements that will be read or have been written
2707 * in the kernel.
2710 * The input "sched" is of the form.
2712 * type[S -> A] -> L
2714 * with S the first shared_len dimensions of the computed schedule,
2715 * A the array and L the schedule correponding to the generated loops.
2717 * We first drop "type",
2719 * [S -> A] -> L
2721 * If the above conditions are satisfied, we project out A,
2722 * resulting in
2724 * S -> L
2726 * and then introduce the group tile [S -> T], resulting in
2728 * [S -> T] -> L
2730 static __isl_give isl_ast_node *copy_group_shared_accesses(
2731 struct gpu_gen *gen, struct gpu_array_ref_group *group,
2732 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
2734 const char *type;
2735 int read;
2736 isl_union_map *access;
2738 type = isl_map_get_tuple_name(sched, isl_dim_in);
2739 read = !strcmp(type, "read");
2741 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
2743 if (read && !gpu_array_is_scalar(group->array)) {
2744 isl_space *space;
2745 isl_map *map;
2747 space = isl_space_domain(isl_map_get_space(sched));
2748 space = isl_space_unwrap(space);
2749 map = isl_map_domain_map(isl_map_universe(space));
2750 sched = isl_map_apply_domain(sched, map);
2752 map = group_tile(group);
2753 map = isl_map_reverse(isl_map_domain_map(map));
2754 sched = isl_map_apply_domain(sched, map);
2757 return copy_access(gen, sched, type, group, build, 0);
2760 /* Return code for reading into or writing from private memory
2761 * the given array reference group.
2763 * Let S be the first shared_len dimensions of the computed schedule,
2764 * D the iteration domains, A the array and L the schedule correponding
2765 * to the generated loops.
2766 * "sched" is of the form
2768 * type[S -> A] -> L
2770 * where type is either "read" or "write".
2771 * We apply the privatization D -> S(t), with t the thread ids,
2772 * to the access relation D -> A to obtain the privatized access relation
2774 * S(t) -> A
2776 * We drop the type from "sched" and intersect with the privatized access
2777 * relation to obtain
2779 * [S(t) -> A] -> L
2781 static __isl_give isl_ast_node *copy_group_private_accesses(
2782 struct gpu_gen *gen, struct gpu_array_ref_group *group,
2783 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
2785 const char *type;
2786 int read;
2787 isl_union_map *priv;
2788 isl_union_map *access;
2789 isl_map *access_map;
2791 type = isl_map_get_tuple_name(sched, isl_dim_in);
2792 read = !strcmp(type, "read");
2794 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2795 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2796 priv);
2798 access = gpu_array_ref_group_access_relation(group, read, !read);
2799 access = isl_union_map_apply_domain(access, priv);
2800 access_map = isl_map_from_union_map(access);
2802 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
2803 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
2805 return copy_access(gen, sched, type, group, build, 1);
2808 /* Return code for reading into or writing from shared or private memory.
2810 * "schedule" is of the form
2812 * type[S -> A] -> L
2814 * with S be the first shared_len dimensions of the computed schedule,
2815 * A the array and L the schedule correponding to the generated loops.
2816 * The array reference group is attached to "type".
2818 static __isl_give isl_ast_node *create_access_leaf(
2819 struct gpu_gen *gen, __isl_take isl_map *schedule,
2820 __isl_take isl_ast_build *build)
2822 struct gpu_array_ref_group *group;
2823 isl_id *id;
2825 id = isl_map_get_tuple_id(schedule, isl_dim_in);
2826 group = isl_id_get_user(id);
2827 isl_id_free(id);
2829 if (group->private_tile)
2830 return copy_group_private_accesses(gen, group, schedule,
2831 build);
2832 else
2833 return copy_group_shared_accesses(gen, group, schedule,
2834 build);
2837 /* Create a domain node representing a synchronization.
2839 static __isl_give isl_ast_node *create_sync_leaf(
2840 struct gpu_gen *gen, __isl_take isl_map *schedule,
2841 __isl_take isl_ast_build *build)
2843 struct ppcg_kernel_stmt *stmt;
2844 isl_id *id;
2845 isl_space *space;
2846 isl_ast_node *node;
2847 isl_ast_expr *expr;
2849 isl_map_free(schedule);
2851 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
2852 if (!stmt)
2853 return NULL;
2855 stmt->type = ppcg_kernel_sync;
2857 space = isl_ast_build_get_schedule_space(build);
2858 space = isl_space_from_domain(space);
2859 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
2860 expr = isl_ast_build_call_from_pw_multi_aff(build,
2861 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
2862 node = isl_ast_node_alloc_user(expr);
2863 isl_ast_build_free(build);
2865 id = isl_id_alloc(gen->ctx, NULL, stmt);
2866 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
2867 return isl_ast_node_set_annotation(node, id);
2870 /* This function is called during the code generation at the point
2871 * where the schedule domain element is completely determined by
2872 * the generated code. The input schedule contains the original
2873 * statements as well as synchronization and copy "statements".
2874 * The latter are scheduled at different points than any of the original
2875 * statements, so they will only arrive here in isolation.
2877 * If the current schedule only refers to a single statement,
2878 * we check if it is a copy or synchronization statement and
2879 * call the appropriate functions.
2880 * Otherwise, we assume we are dealing with the original statements
2881 * and we call create_domain_leaf.
2883 static __isl_give isl_ast_node *create_kernel_leaf(
2884 __isl_take isl_ast_build *build, void *user)
2886 struct gpu_gen *gen = (struct gpu_gen *) user;
2887 isl_map *map;
2888 isl_union_map *schedule;
2889 const char *name;
2891 schedule = isl_ast_build_get_schedule(build);
2893 if (isl_union_map_n_map(schedule) != 1)
2894 return create_domain_leaf(schedule, build, user);
2896 map = isl_map_from_union_map(schedule);
2897 name = isl_map_get_tuple_name(map, isl_dim_in);
2898 if (!strcmp(name, "read") || !strcmp(name, "write"))
2899 return create_access_leaf(gen, map, build);
2900 if (!strcmp(name, "sync"))
2901 return create_sync_leaf(gen, map, build);
2903 return create_domain_leaf(isl_union_map_from_map(map), build, user);
2906 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
2907 * have value 0) and all even schedule dimensions as "unroll".
2909 * That is, the options look as follows
2911 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
2912 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
2914 * The even positions are used to be able to schedule copying blocks
2915 * and synchronization before or after each level of the shared memory
2916 * tile loops and we want to make sure that code for these is generated
2917 * separately (within each level).
2919 static __isl_give isl_ast_build *set_atomic_and_unroll(
2920 __isl_take isl_ast_build *build,
2921 __isl_take isl_space *space, int sched_len)
2923 isl_ctx *ctx;
2924 isl_map *map;
2925 isl_constraint *c;
2926 isl_union_map *opt;
2927 isl_local_space *ls;
2928 int i, n;
2930 ctx = isl_ast_build_get_ctx(build);
2932 space = isl_space_params(space);
2933 space = isl_space_add_dims(space, isl_dim_set, sched_len);
2934 space = isl_space_from_domain(space);
2935 space = isl_space_add_dims(space, isl_dim_out, 2);
2936 map = isl_map_universe(isl_space_copy(space));
2937 for (i = 0; i < sched_len; i += 2)
2938 map = isl_map_fix_si(map, isl_dim_in, i, 0);
2939 ls = isl_local_space_from_space(isl_map_get_space(map));
2940 c = isl_equality_alloc(ls);
2941 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
2942 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
2943 c = isl_constraint_set_constant_si(c, 1);
2944 map = isl_map_add_constraint(map, c);
2945 map = isl_map_project_out(map, isl_dim_out, 1, 1);
2946 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
2947 opt = isl_union_map_from_map(map);
2949 map = isl_map_universe(space);
2950 ls = isl_local_space_from_space(isl_map_get_space(map));
2951 c = isl_equality_alloc(ls);
2952 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
2953 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
2954 map = isl_map_add_constraint(map, c);
2955 map = isl_map_project_out(map, isl_dim_out, 1, 1);
2956 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
2957 opt = isl_union_map_add_map(opt, map);
2959 build = isl_ast_build_set_options(build, opt);
2961 return build;
2964 /* Return a map that maps a space of dimension gen->shared_len
2965 * to its last dimensions starting at gen->tile_first.
2966 * The range is of dimension
2968 * 2 * (gen->shared_len - gen->tile_first) + 1
2970 * The input dimensions are mapped to the odd dimensions in the output,
2971 * while the even dimensions (except 2*pos) are fixed to 0.
2972 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
2973 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
2974 * are mapped to the output. The remaining input dimensions are projected
2975 * out and the corresponding output dimensions are fixed to 0.
2977 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
2978 __isl_take isl_space *space, int pos, int val)
2980 int i, n;
2981 isl_map *proj;
2983 space = isl_space_set_from_params(space);
2984 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
2985 space = isl_space_map_from_set(space);
2986 proj = isl_map_identity(space);
2987 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
2988 n = gen->shared_len - gen->tile_first;
2989 for (i = 0; i <= n; ++i) {
2990 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
2991 if (i == pos)
2992 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
2993 else
2994 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
2997 if (pos < 0)
2998 return proj;
3000 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
3001 gen->shared_len - (gen->tile_first + pos));
3002 for (i = pos; i < n; ++i)
3003 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
3005 return proj;
3008 /* Given the AST context schedule "schedule" and the mapping from
3009 * domains to the shared tile loops "shared_sched", add a schedule
3010 * for a synchronization operation at position "val" of loop level "pos".
3012 * schedule is of the form
3014 * D -> L
3016 * (with D the iteration domains and L the already generated loops),
3017 * while shared_sched is of the form
3019 * D -> S
3021 * We combine them into
3023 * L -> S
3025 * apply a mapping
3027 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3029 * and use the result as a schedule for "sync".
3031 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
3032 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3033 __isl_keep isl_union_map *shared_sched, int pos, int val)
3035 isl_space *space;
3036 isl_map *proj, *map;
3038 shared_sched = isl_union_map_copy(shared_sched);
3039 schedule = isl_union_map_copy(schedule);
3041 space = isl_union_map_get_space(shared_sched);
3042 schedule = isl_union_map_apply_domain(shared_sched, schedule);
3043 map = isl_map_from_union_map(schedule);
3045 proj = insert_even(gen, space, pos, val);
3046 map = isl_map_apply_range(map, proj);
3047 map = isl_map_from_range(isl_map_wrap(map));
3048 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
3050 res = isl_union_map_add_map(res, map);
3052 return res;
3055 /* Given a set of wrapped references "ref", return the corresponding
3056 * access relations based on the tagged access relations "tagged".
3058 * The elements of "ref" are of the form
3060 * [D -> R]
3062 * with D an iteration domains and R a reference.
3063 * The elements of "tagged" are of the form
3065 * [D -> R] -> A
3067 * with A an array.
3069 * Extend "tagged" to include the iteration domain in the range, i.e.,
3071 * [D -> R] -> [D -> A]
3073 * apply the result to "ref" and then unwrap the resulting set
3074 * to obtain relations of the form
3076 * D -> A
3078 static __isl_give isl_union_map *wrapped_reference_to_access(
3079 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
3081 isl_union_map *tag2access;
3083 tag2access = isl_union_map_copy(tagged);
3084 tag2access = isl_union_map_universe(tag2access);
3085 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
3086 tag2access = isl_union_map_domain_map(tag2access);
3087 tag2access = isl_union_map_range_product(tag2access, tagged);
3089 ref = isl_union_set_coalesce(ref);
3090 ref = isl_union_set_apply(ref, tag2access);
3092 return isl_union_set_unwrap(ref);
3095 /* Given an access relation "access" from "group", remove those reads
3096 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
3097 * communicate data within the same iteration of the last_shared dimension
3098 * of the group.
3100 * If the access is a read then it is either an element of
3102 * live_in union (range flow)
3104 * where live_in and flow may be overapproximations, or
3105 * it reads an uninitialized value (that is not live-in because
3106 * there is an intermediate kill) or it reads a value that was
3107 * written within the same (compound) statement instance.
3108 * If the access is a write then it is either an element of
3110 * live_out union (domain flow)
3112 * or it writes a value that is never read (and is not live-out
3113 * because of an intermediate kill) or only
3114 * within the same (compound) statement instance.
3115 * In both cases, the access relation is also a subset of
3116 * the group access relation.
3118 * The cases where an uninitialized value is read or a value is written
3119 * that is never read or where the dataflow occurs within a statement
3120 * instance are also considered local and may also be removed.
3122 * Essentially, we compute the intersection of "access" with either
3124 * live_in union (range non-local-flow)
3126 * or
3128 * live_out union (domain non-local-flow)
3130 * We first construct a relation "local"
3132 * [[D -> R] -> [D' -> R']]
3134 * of pairs of domain iterations accessing the reference group
3135 * and references in the group that are scheduled to the same iteration
3136 * of the last_shared dimension.
3138 * If this relation does not intersect the dataflow dependences,
3139 * then there is nothing we can possibly remove, unless the dataflow
3140 * dependences themselves only relate a subset of the accesses.
3141 * In particular, the accesses may not be involved in any dataflow
3142 * dependences, either because they are uninitialized reads/dead writes
3143 * or because the dataflow occurs inside a statement instance.
3145 * Since the computation below may break up the access relation
3146 * into smaller pieces, we only perform the intersection with
3147 * the non-local dependent accesses if the local pairs
3148 * intersect the dataflow dependences. Otherwise, we intersect
3149 * with the universe of the non-local dependent accesses.
3150 * This should at least remove accesses from statements that
3151 * do not participate in any dependences.
3153 * In particular, we remove the "local" dataflow dependences from
3154 * the set of all dataflow dependences.
3155 * Note that if the potential dataflow dependences are an overapproximation
3156 * of the actual dataflow dependences, then the result remains an
3157 * overapproximation of the non-local dataflow dependences.
3158 * Copying to/from global memory is only needed for the references
3159 * in the domain/range of the result or for accesses that are live out/in
3160 * for the entire scop.
3162 * We therefore map the domain/range of the "external" relation
3163 * to the corresponding access relation and take the union with
3164 * the live out/in relation.
3166 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
3167 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
3168 int read)
3170 int empty;
3171 isl_union_pw_multi_aff *tagger;
3172 isl_union_set *domain;
3173 isl_space *space;
3174 isl_union_map *sched, *local, *tagged, *external;
3175 isl_union_set *tag_set;
3176 isl_map *proj;
3178 if (isl_union_map_is_empty(access))
3179 return access;
3181 tagged = group_tagged_access_relation(group);
3183 sched = isl_union_map_copy(gen->sched);
3185 space = isl_union_map_get_space(sched);
3186 proj = projection(space, gen->untiled_len, group->last_shared + 1);
3187 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3189 tagger = isl_union_pw_multi_aff_copy(gen->prog->scop->tagger);
3190 domain = isl_union_map_domain(isl_union_map_copy(tagged));
3191 tagger = isl_union_pw_multi_aff_intersect_domain(tagger, domain);
3192 sched = isl_union_map_preimage_domain_union_pw_multi_aff(sched, tagger);
3194 local = isl_union_map_apply_range(sched,
3195 isl_union_map_reverse(isl_union_map_copy(sched)));
3196 local = isl_union_map_intersect(local,
3197 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
3199 empty = isl_union_map_is_empty(local);
3201 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
3202 external = isl_union_map_intersect_params(external,
3203 isl_set_copy(gen->prog->scop->context));
3204 external = isl_union_map_subtract(external, local);
3206 if (read) {
3207 tag_set = isl_union_map_range(external);
3208 external = wrapped_reference_to_access(tag_set, tagged);
3209 external = isl_union_map_union(external,
3210 isl_union_map_copy(gen->prog->scop->live_in));
3211 } else {
3212 tag_set = isl_union_map_domain(external);
3213 external = wrapped_reference_to_access(tag_set, tagged);
3214 external = isl_union_map_union(external,
3215 isl_union_map_copy(gen->prog->scop->live_out));
3218 if (empty < 0)
3219 external = isl_union_map_free(external);
3220 else if (empty)
3221 external = isl_union_map_universe(external);
3223 access = isl_union_map_intersect(access, external);
3225 return access;
3228 /* Given the AST context schedule "schedule" and the mapping from
3229 * domains to the shared tile loops "shared_sched", add a schedule
3230 * for copying an array reference group to/from shared/private memory.
3231 * "read" is set if data should be copied from global memory
3232 * to shared/private memory.
3233 * "k" represents the current group
3234 * "s" is the total number of groups
3236 * We schedule an operation before or after the innermost loop
3237 * of "shared_sched" that affects the tile of the array reference group.
3239 * schedule is of the form
3241 * D -> L
3243 * (with D the iteration domains and L the already generated loops),
3244 * while shared_sched is of the form
3246 * D -> S
3248 * We first compute the access relation for the reference group
3250 * D -> A
3252 * and remove from this access relation those reads or writes
3253 * that only needed to communicate data within the same iteration
3254 * of the last_shared dimension of the group.
3255 * We then combine what is left with shared_sched into
3257 * D -> [S -> A]
3259 * If this results in an empty relation, no copying needs to be performed
3260 * at this point.
3261 * Otherwise, we invert the relation and combine it with "schedule" into
3263 * [S -> A] -> L
3265 * The actual additional piece of the schedule is obtained from combining
3267 * [S -> A] -> S
3269 * with a mapping
3271 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3273 * The position of "val" corresponds to the innermost loop that affects
3274 * the tile and the value indicates where the copying is scheduled
3275 * with respect to the actual kernel code (at value 0).
3276 * Reads are schedule before the code, writes to global memory from
3277 * private memory are scheduled at values 1 to s, writes to global
3278 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
3280 * If we are scheduling a read from global memory to shared memory,
3281 * we insert a synchronization before the kernel code (at the innermost
3282 * level).
3283 * If we are scheduling a write to global memory, then we add
3284 * a synchronization after all writes (at value 2 *s + 2).
3285 * However, there is no need for a synchronization after the outermost loop.
3286 * A write to global memory from private memory at the innermost level
3287 * does not require a synchronization, because it is covered by
3288 * the synchronization after the kernel inserted by body_schedule.
3290 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
3291 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3292 __isl_keep isl_union_map *shared_sched,
3293 struct gpu_array_ref_group *group, int read, int k, int s)
3295 int n;
3296 int pos, val;
3297 isl_space *space;
3298 isl_union_map *access;
3299 isl_map *map, *proj, *access_map;
3300 isl_id *id;
3302 access = gpu_array_ref_group_access_relation(group, read, !read);
3303 access = remove_local_accesses(gen, group, access, read);
3304 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
3305 access);
3307 if (isl_union_map_is_empty(access)) {
3308 isl_union_map_free(access);
3309 return res;
3312 access = isl_union_map_reverse(access);
3313 access = isl_union_map_apply_range(access,
3314 isl_union_map_copy(schedule));
3315 access_map = isl_map_from_union_map(access);
3317 space = isl_space_copy(group->array->space);
3318 space = isl_space_from_range(space);
3319 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
3320 map = isl_map_domain_map(isl_map_universe(space));
3322 space = isl_union_map_get_space(schedule);
3323 pos = group->last_shared + 1 - gen->tile_first;
3324 assert(pos >= 0);
3325 if (read)
3326 val = -2 - k;
3327 else if (group->private_tile)
3328 val = 1 + k;
3329 else
3330 val = 1 + s + 1 + k;
3331 proj = insert_even(gen, space, pos, val);
3332 map = isl_map_apply_range(map, proj);
3334 access_map = isl_map_range_product(access_map, map);
3336 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
3337 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
3339 res = isl_union_map_add_map(res, access_map);
3341 n = gen->shared_len - gen->tile_first;
3342 if (read) {
3343 if (!group->private_tile)
3344 res = add_sync_schedule(gen, res, schedule,
3345 shared_sched, n, -1);
3346 } else {
3347 if (pos == 0)
3348 return res;
3349 if (pos == n && group->private_tile)
3350 return res;
3351 res = add_sync_schedule(gen, res, schedule, shared_sched,
3352 pos, 2 * s + 2);
3355 return res;
3358 /* Return a schedule for the shared tile loops based on the current
3359 * AST context schedule.
3361 * We create a "shared_sched" that maps the domains to the first
3362 * shared_len dimensions of the computed schedule, project out the
3363 * first tile_first dimensions (as these are already covered by
3364 * the host code) and insert "statement-level" dimensions at even
3365 * positions so that we can schedule copy blocks and synchronization
3366 * before/after each level.
3368 * In particular, copy blocks are inserted inside the innermost
3369 * level that affect the tile. For the copying to global memory,
3370 * those from private memory are scheduled before those from shared
3371 * memory such that synchronization can be inserted between the two
3372 * at the innermost level.
3373 * Synchronization is inserted at the innermost level before the
3374 * actual kernel code if there is any copying from global memory
3375 * to shared memory. It is inserted unconditionally at the innermost
3376 * level after the actual kernel code and the copying to global memory
3377 * from private memory (if any). Finally, it is inserted after
3378 * any copying to global memory, except at the outermost level
3379 * and at the innermost level if there is no copying from shared
3380 * memory. The copying from private memory is covered by the unconditional
3381 * synchronization at the innermost level.
3383 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
3384 __isl_take isl_union_map *schedule)
3386 isl_space *space;
3387 isl_union_map *res;
3388 isl_union_map *shared_sched;
3389 isl_union_map *sched;
3390 isl_map *proj, *map;
3391 int i, j, k, s;
3393 shared_sched = isl_union_map_copy(gen->tiled_sched);
3394 proj = projection(isl_union_map_get_space(shared_sched),
3395 gen->tiled_len, gen->shared_len);
3396 shared_sched = isl_union_map_apply_range(shared_sched,
3397 isl_union_map_from_map(proj));
3398 space = isl_union_map_get_space(shared_sched);
3399 proj = insert_even(gen, space, -1, 0);
3400 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
3401 isl_union_map_from_map(proj));
3403 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
3405 s = 0;
3406 for (i = 0; i < gen->kernel->n_array; ++i)
3407 s += gen->kernel->array[i].n_group;
3409 k = 0;
3410 for (i = 0; i < gen->kernel->n_array; ++i) {
3411 struct gpu_local_array_info *array = &gen->kernel->array[i];
3413 for (j = 0; j < array->n_group; ++j) {
3414 struct gpu_array_ref_group *group;
3416 group = array->groups[j];
3417 if (!group->private_tile && !group->shared_tile)
3418 continue;
3419 res = add_group_schedule(gen, res, schedule,
3420 shared_sched, group, 0, k, s);
3421 res = add_group_schedule(gen, res, schedule,
3422 shared_sched, group, 1, k, s);
3423 ++k;
3427 res = add_sync_schedule(gen, res, schedule, shared_sched,
3428 gen->shared_len - gen->tile_first, 1 + s);
3430 isl_union_map_free(shared_sched);
3431 isl_union_map_free(schedule);
3433 return res;
3436 /* Generate code for "kernel" in the given "context".
3438 * We first generate code for the shared tile loops (T1T, T1P and T2)
3439 * in a context that includes the block ids.
3440 * Within each iteration of these loops an additional code generation
3441 * is performed (within create_kernel_leaf) for the rest of the schedule
3442 * in a context that includes the thread ids.
3444 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
3445 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
3446 __isl_keep isl_multi_pw_aff *grid_size)
3448 isl_space *space;
3449 isl_set *set;
3450 isl_id_list *iterators;
3451 isl_union_map *schedule;
3452 isl_ast_node *tree;
3453 int sched_len;
3455 schedule = isl_ast_build_get_schedule(build);
3457 build = isl_ast_build_copy(build);
3458 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
3459 space = isl_ast_build_get_schedule_space(build);
3460 set = isl_set_universe(isl_space_copy(space));
3461 set = add_bounded_parameters_dynamic(set, grid_size,
3462 gen->kernel->block_ids);
3463 build = isl_ast_build_restrict(build, set);
3465 schedule = body_schedule(gen, schedule);
3467 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
3469 build = set_atomic_and_unroll(build, space, sched_len);
3470 iterators = ppcg_scop_generate_names(gen->prog->scop, sched_len, "g");
3471 build = isl_ast_build_set_iterators(build, iterators);
3472 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
3473 tree = isl_ast_build_node_from_schedule_map(build, schedule);
3474 isl_ast_build_free(build);
3476 return tree;
3479 /* Attach "id" to the given node.
3481 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
3482 __isl_keep isl_ast_build *build, void *user)
3484 isl_id *id = user;
3486 node = isl_ast_node_set_annotation(node, id);
3488 return node;
3491 /* Construct an AST node for performing a kernel launch and attach
3492 * the information about the kernel to that node.
3493 * "kernel_id" has name "kernel" and contains a pointer
3494 * to the ppcg_kernel structure.
3496 * The kernel AST has been constructed in the context of the range
3497 * of "schedule". In particular, the grid size has been computed
3498 * in the context. We therefore still need to make sure that these
3499 * constraints are expressed in the code. We do this by creating a schedule
3501 * kernel[] -> [S -> []]
3503 * where S is the schedule domain, i.e., the range of "schedule".
3504 * The AST generation will then create a single call surrounded by
3505 * all the condition in "S" that have not been expressed yet.
3507 * The kernel information is attached to this node in attach_id.
3509 static __isl_give isl_ast_node *construct_launch(
3510 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
3511 __isl_take isl_id *kernel_id)
3513 isl_ctx *ctx;
3514 isl_union_set *domain;
3515 isl_set *set;
3516 isl_map *map;
3517 isl_ast_node *node;
3519 ctx = isl_ast_build_get_ctx(build);
3521 domain = isl_union_map_range(schedule);
3522 set = isl_set_from_union_set(domain);
3523 map = isl_map_from_domain(set);
3524 map = isl_map_from_range(isl_map_wrap(map));
3525 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
3526 schedule = isl_union_map_from_map(map);
3528 build = isl_ast_build_set_at_each_domain(build, &attach_id, kernel_id);
3529 node = isl_ast_build_node_from_schedule_map(build, schedule);
3530 isl_ast_build_free(build);
3532 return node;
3535 /* This function is called for each leaf in the AST of the host code.
3536 * We first specialize the schedule to the site of the leaf, compute
3537 * the size of shared memory and then construct the body of the host code
3538 * and the associated kernel.
3540 * The necessary information for printing the kernel launch is
3541 * stored in the struct ppcg_kernel that was created in create_kernel and
3542 * attached to an outer mark node in the schedule tree.
3543 * Note that this assumes that a kernel is only launched once.
3544 * The kernel pointer itself is stored in gen->kernel by before_mark,
3545 * while the isl_id containing this pointer is stored in gen->kernel_mark.
3546 * The latter is attached to the leaf AST node created to represent the launch.
3548 static __isl_give isl_ast_node *create_host_leaf(
3549 __isl_take isl_ast_build *build, void *user)
3551 struct gpu_gen *gen = (struct gpu_gen *) user;
3552 isl_id *id;
3553 isl_ast_node *node;
3554 struct ppcg_kernel *kernel;
3555 isl_set *host_domain;
3556 isl_union_map *schedule;
3557 isl_union_map *local_sched;
3558 isl_union_set *domain;
3559 int i;
3561 schedule = isl_ast_build_get_schedule(build);
3563 kernel = gen->kernel;
3564 if (!kernel)
3565 goto error;
3567 domain = isl_union_map_domain(isl_union_map_copy(schedule));
3569 local_sched = isl_union_map_copy(gen->sched);
3570 local_sched = isl_union_map_intersect_domain(local_sched, domain);
3572 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
3573 kernel->n_block, "t");
3575 gen->tiled_sched = tile_schedule(gen, local_sched);
3576 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
3577 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
3579 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
3580 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
3581 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
3583 kernel->grid_size = extract_grid_size(gen, kernel);
3584 extract_block_size(gen, kernel);
3585 kernel->space = isl_ast_build_get_schedule_space(build);
3587 compute_shared_sched(gen);
3588 gen->privatization = compute_privatization(gen);
3589 if (gpu_group_references(gen) < 0)
3590 schedule = isl_union_map_free(schedule);
3591 host_domain = isl_set_from_union_set(isl_union_map_range(
3592 isl_union_map_copy(schedule)));
3593 localize_bounds(gen, kernel, host_domain);
3595 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
3596 check_shared_memory_bound(gen);
3597 compute_group_tilings(gen);
3599 kernel->tree = generate_kernel(gen, build, host_domain,
3600 kernel->grid_size);
3601 create_kernel_vars(gen, kernel);
3603 isl_map_free(gen->privatization);
3604 isl_union_map_free(gen->local_sched);
3605 isl_union_map_free(gen->tiled_sched);
3606 isl_union_map_free(gen->shared_sched);
3607 isl_union_map_free(gen->shared_proj);
3608 isl_set_free(host_domain);
3610 node = construct_launch(build, schedule, isl_id_copy(gen->kernel_mark));
3612 return node;
3613 error:
3614 isl_union_map_free(schedule);
3615 return NULL;
3618 /* This function is called before the AST generator starts traversing
3619 * the schedule subtree of a node with mark "mark".
3621 * If the mark is called "kernel", store the mark itself in gen->kernel_mark
3622 * and the kernel pointer in gen->kernel for use in create_host_leaf.
3624 static int before_mark(__isl_keep isl_id *mark,
3625 __isl_keep isl_ast_build *build, void *user)
3627 struct gpu_gen *gen = user;
3629 if (!mark)
3630 return -1;
3631 if (!strcmp(isl_id_get_name(mark), "kernel")) {
3632 gen->kernel_mark = isl_id_copy(mark);
3633 gen->kernel = isl_id_get_user(mark);
3635 return 0;
3638 /* This function is called after the AST generator has finished traversing
3639 * the schedule subtree of a mark node. "node" points to the corresponding
3640 * mark AST node.
3642 * If the mark is called "kernel", then clear kernel and gen->kernel_mark.
3644 static __isl_give isl_ast_node *after_mark(__isl_take isl_ast_node *node,
3645 __isl_keep isl_ast_build *build, void *user)
3647 struct gpu_gen *gen = user;
3648 isl_id *id;
3650 id = isl_ast_node_mark_get_id(node);
3651 if (!id)
3652 return isl_ast_node_free(node);
3653 if (!strcmp(isl_id_get_name(id), "kernel") && gen->kernel) {
3654 gen->kernel_mark = isl_id_free(gen->kernel_mark);
3655 gen->kernel = NULL;
3658 isl_id_free(id);
3659 return node;
3662 /* Use isl to generate host code from gen->host_schedule, which corresponds to
3663 * the outer gen->tile_first loops of the global schedule in gen->sched.
3664 * Within each iteration of this partial schedule, i.e., for each kernel
3665 * launch, create_host_leaf takes care of generating the kernel code.
3666 * The ppcg_kernel objects are stored in mark nodes in the schedule
3667 * tree and are extracted in before_mark.
3669 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
3671 isl_ast_build *build;
3672 isl_ast_node *tree;
3673 isl_schedule *schedule;
3674 isl_id_list *iterators;
3676 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
3677 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
3678 iterators = ppcg_scop_generate_names(gen->prog->scop,
3679 gen->tile_first, "h");
3680 build = isl_ast_build_set_iterators(build, iterators);
3681 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
3682 build = isl_ast_build_set_before_each_mark(build, &before_mark, gen);
3683 build = isl_ast_build_set_after_each_mark(build, &after_mark, gen);
3684 schedule = isl_schedule_copy(gen->host_schedule);
3685 tree = isl_ast_build_node_from_schedule(build, schedule);
3686 isl_ast_build_free(build);
3688 return tree;
3691 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
3693 if (!str)
3694 return NULL;
3695 return isl_union_map_read_from_str(ctx, str);
3698 /* Information about the outermost tilable bands in the forest of bands.
3700 * prefix is the (padded) schedule leading up to the outermost tilable bands.
3702 * tile_first is the number of schedule dimensions in prefix.
3704 * suffix is the schedule of the outermost tilable bands and their descendants.
3706 struct band_info {
3707 struct gpu_gen *gen;
3708 int tile_first;
3709 isl_union_map *prefix;
3710 isl_union_map *suffix;
3713 /* Construct an isl_multi_val for use as tile sizes for tiling "node"
3714 * from the elements in "tile_size".
3716 static __isl_give isl_multi_val *construct_band_tiles_sizes(
3717 __isl_keep isl_schedule_node *node, int *tile_size)
3719 int i, n;
3720 isl_ctx *ctx;
3721 isl_space *space;
3722 isl_multi_val *mv;
3724 if (!node)
3725 return NULL;
3727 ctx = isl_schedule_node_get_ctx(node);
3728 space = isl_schedule_node_band_get_space(node);
3729 n = isl_schedule_node_band_n_member(node);
3730 mv = isl_multi_val_zero(space);
3731 for (i = 0; i < n; ++i) {
3732 isl_val *v;
3734 v = isl_val_int_from_si(ctx, tile_size[i]);
3735 mv = isl_multi_val_set_val(mv, i, v);
3738 return mv;
3741 /* Tile "band" with tile size specified by "sizes".
3743 * Since the tile loops will be mapped to block ids, we forcibly
3744 * turn off tile loop scaling. We may want to enable tile loop scaling
3745 * at some later point, but then we would have to support the detection
3746 * of strides during the mapping to block ids.
3747 * Similarly, since the point loops will be mapped to thread ids,
3748 * we forcibly shift the point loops so that they start at zero.
3750 static __isl_give isl_schedule_node *tile_band(
3751 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
3753 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
3754 int scale_tile;
3755 int shift_point;
3757 scale_tile = isl_options_get_tile_scale_tile_loops(ctx);
3758 isl_options_set_tile_scale_tile_loops(ctx, 0);
3759 shift_point = isl_options_get_tile_shift_point_loops(ctx);
3760 isl_options_set_tile_shift_point_loops(ctx, 1);
3762 node = isl_schedule_node_band_tile(node, sizes);
3764 isl_options_set_tile_scale_tile_loops(ctx, scale_tile);
3765 isl_options_set_tile_shift_point_loops(ctx, shift_point);
3767 return node;
3770 /* Extract the set of parameter values and outer schedule dimensions
3771 * for which any statement instance
3772 * in the kernel inserted at "node" needs to be executed.
3773 * Intersect the set of parameter values derived from the host schedule
3774 * relation with the context of "prog".
3776 static __isl_give isl_set *extract_context(__isl_keep isl_schedule_node *node,
3777 struct gpu_prog *prog)
3779 isl_union_map *schedule;
3780 isl_union_set *schedule_domain;
3781 isl_set *context;
3782 int empty;
3784 schedule = isl_schedule_node_get_prefix_schedule_relation(node);
3785 schedule_domain = isl_union_map_range(schedule);
3786 empty = isl_union_set_is_empty(schedule_domain);
3787 if (empty < 0) {
3788 isl_union_set_free(schedule_domain);
3789 return NULL;
3791 if (empty) {
3792 int depth;
3793 isl_space *space;
3795 space = isl_union_set_get_space(schedule_domain);
3796 isl_union_set_free(schedule_domain);
3797 space = isl_space_set_from_params(space);
3798 depth = isl_schedule_node_get_schedule_depth(node);
3799 space = isl_space_add_dims(space, isl_dim_set, depth);
3800 context = isl_set_empty(space);
3801 } else {
3802 context = isl_set_from_union_set(schedule_domain);
3804 context = isl_set_intersect_params(context,
3805 isl_set_copy(prog->context));
3807 return context;
3810 /* Return the set of outer array elements accessed by
3811 * by the statement instance in "domain" in "prog".
3813 static __isl_give isl_union_set *accessed_by_domain(
3814 __isl_take isl_union_set *domain, struct gpu_prog *prog)
3816 isl_union_map *access;
3817 isl_union_set *arrays;
3819 access = isl_union_map_union(isl_union_map_copy(prog->read),
3820 isl_union_map_copy(prog->may_write));
3821 access = isl_union_map_intersect_domain(access, domain);
3822 arrays = isl_union_map_range(access);
3823 arrays = isl_union_set_apply(arrays,
3824 isl_union_map_copy(prog->to_outer));
3826 return arrays;
3829 /* Return the number of outer band members of the band node "node"
3830 * that are marked coincident.
3832 static int n_outer_coincidence(__isl_keep isl_schedule_node *node)
3834 int i, n;
3836 n = isl_schedule_node_band_n_member(node);
3838 for (i = 0; i < n; ++i)
3839 if (!isl_schedule_node_band_member_get_coincident(node, i))
3840 break;
3842 return i;
3845 /* If the band node "node" has more than "n" members, then split off
3846 * the first "n" of them.
3848 static __isl_give isl_schedule_node *split_band(
3849 __isl_take isl_schedule_node *node, int n)
3851 int dim;
3853 dim = isl_schedule_node_band_n_member(node);
3854 if (n < dim)
3855 node = isl_schedule_node_band_split(node, n);
3857 return node;
3860 /* Scale a band node that may have been split by split_band.
3861 * "sizes" are the scaling factors for the original node.
3862 * "node" either points to the original band node, or the outer
3863 * of the two pieces after splitting.
3865 * If the number of elements in "node" is smaller than the number of
3866 * elements in "sizes", then some splitting has occurred and we split
3867 * "sizes" in the same way.
3869 static __isl_give isl_schedule_node *scale_band(
3870 __isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes)
3872 int n, dim;
3874 n = isl_multi_val_dim(sizes, isl_dim_set);
3875 dim = isl_schedule_node_band_n_member(node);
3876 if (n > dim) {
3877 isl_multi_val *sizes2;
3879 sizes2 = isl_multi_val_copy(sizes);
3880 sizes = isl_multi_val_drop_dims(sizes,
3881 isl_dim_set, dim, n - dim);
3882 sizes2 = isl_multi_val_drop_dims(sizes2, isl_dim_set, 0, dim);
3883 node = isl_schedule_node_child(node, 0);
3884 node = isl_schedule_node_band_scale(node, sizes2);
3885 node = isl_schedule_node_parent(node);
3888 return isl_schedule_node_band_scale(node, sizes);
3891 /* Return an isl_multi_aff, with as elements the parameters in "space"
3892 * that have the names specified by the elements in "names".
3893 * If (some of) these parameters do not already appear in "space",
3894 * then they are added first.
3896 static __isl_give isl_multi_aff *parameter_vector(__isl_take isl_space *space,
3897 __isl_keep isl_id_list *names)
3899 int i, n;
3900 isl_local_space *ls;
3901 isl_multi_aff *ma;
3903 if (!names)
3904 space = isl_space_free(space);
3906 n = isl_id_list_n_id(names);
3907 for (i = 0; i < n; ++i) {
3908 int pos;
3909 isl_id *id;
3911 id = isl_id_list_get_id(names, i);
3912 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
3913 if (pos >= 0) {
3914 isl_id_free(id);
3915 continue;
3917 pos = isl_space_dim(space, isl_dim_param);
3918 space = isl_space_add_dims(space, isl_dim_param, 1);
3919 space = isl_space_set_dim_id(space, isl_dim_param, pos, id);
3921 ma = isl_multi_aff_zero(isl_space_copy(space));
3922 ls = isl_local_space_from_space(isl_space_domain(space));
3923 for (i = 0; i < n; ++i) {
3924 int pos;
3925 isl_id *id;
3926 isl_aff *aff;
3928 id = isl_id_list_get_id(names, i);
3929 pos = isl_space_find_dim_by_id(space, isl_dim_param, id);
3930 isl_id_free(id);
3931 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
3932 isl_dim_param, pos);
3933 ma = isl_multi_aff_set_aff(ma, i, aff);
3935 isl_local_space_free(ls);
3937 return ma;
3940 /* Return constraints on the domain elements that equate a sequence of
3941 * parameters called "names", to the partial schedule
3942 * of "node" modulo the integers in "size".
3943 * The number of elements in the array "size" should be equal
3944 * to the number of members of the band node "node" and
3945 * to the number of elements in "names".
3947 static __isl_give isl_union_set *set_schedule_modulo(
3948 __isl_keep isl_schedule_node *node, __isl_keep isl_id_list *names,
3949 int *size)
3951 isl_space *space;
3952 isl_multi_aff *ma;
3953 isl_multi_union_pw_aff *mupa, *mupa2;
3954 isl_multi_val *mv;
3955 isl_union_set *domain;
3957 if (!node)
3958 return NULL;
3959 if (isl_schedule_node_band_n_member(node) == 0)
3960 return isl_schedule_node_get_universe_domain(node);
3962 mupa = isl_schedule_node_band_get_partial_schedule(node);
3963 mv = construct_band_tiles_sizes(node, size);
3964 mupa = isl_multi_union_pw_aff_mod_multi_val(mupa, mv);
3966 space = isl_multi_union_pw_aff_get_space(mupa);
3967 ma = parameter_vector(space, names);
3969 domain = isl_schedule_node_get_universe_domain(node);
3971 mupa2 = isl_multi_union_pw_aff_multi_aff_on_domain(domain, ma);
3972 mupa = isl_multi_union_pw_aff_sub(mupa, mupa2);
3974 return isl_multi_union_pw_aff_zero_union_set(mupa);
3977 /* Mark all dimensions in the current band node atomic.
3979 static __isl_give isl_schedule_node *atomic(__isl_take isl_schedule_node *node)
3981 int i, n;
3983 n = isl_schedule_node_band_n_member(node);
3984 for (i = 0; i < n; ++i)
3985 node = isl_schedule_node_band_member_set_ast_loop_type(node, i,
3986 isl_ast_loop_atomic);
3988 return node;
3991 /* Mark "node" atomic, if it is a band node.
3992 * Do the same for all ancestors.
3993 * Return a pointer to "node" (in the updated schedule tree).
3995 static __isl_give isl_schedule_node *atomic_ancestors(
3996 __isl_take isl_schedule_node *node)
3998 int pos;
4000 if (!node)
4001 return NULL;
4002 if (!isl_schedule_node_has_parent(node))
4003 return node;
4005 pos = isl_schedule_node_get_child_position(node);
4006 node = isl_schedule_node_parent(node);
4007 if (isl_schedule_node_get_type(node) == isl_schedule_node_band)
4008 node = atomic(node);
4009 node = atomic_ancestors(node);
4010 node = isl_schedule_node_child(node, pos);
4012 return node;
4015 /* Group the domain elements into a single space, named kernelX,
4016 * with X the kernel sequence number "kernel_id".
4018 static __isl_give isl_schedule_node *group_statements(
4019 __isl_take isl_schedule_node *node, int kernel_id)
4021 char buffer[20];
4022 isl_id *id;
4024 if (!node)
4025 return NULL;
4027 snprintf(buffer, sizeof(buffer), "kernel%d", kernel_id);
4028 id = isl_id_alloc(isl_schedule_node_get_ctx(node), buffer, NULL);
4029 return isl_schedule_node_group(node, id);
4032 /* Create a ppcg_kernel representing the domain instances that reach "node"
4033 * and replace the subtree at "node" by a mark node pointing
4034 * to the ppcg_kernel.
4035 * The band that "node" points to is the band that needs to be mapped
4036 * to block identifiers. The band that needs to be mapped to thread
4037 * identifiers should be marked by a "thread" mark by the caller.
4038 * If "scale" is set, then the band that "node" points to is scaled
4039 * by "sizes".
4041 * Mark all outer band nodes as atomic to ensure each kernel is only
4042 * scheduled once.
4043 * If the domain elements that reach "node" live in more than one space,
4044 * then group the domain elements into a single space, named kernelX,
4045 * with X the kernel sequence number.
4047 * Store a pointer to the created ppcg_kernel in gen->kernel.
4049 * We keep a copy of the isl_id that points to the kernel to ensure
4050 * that the kernel does not get destroyed if the schedule node
4051 * is freed due to some error condition.
4053 static __isl_give isl_schedule_node *create_kernel(struct gpu_gen *gen,
4054 __isl_take isl_schedule_node *node, int scale,
4055 __isl_keep isl_multi_val *sizes)
4057 struct ppcg_kernel *kernel;
4058 isl_id *id;
4059 isl_schedule_node *node_thread;
4060 isl_union_set *domain;
4061 int single_statement;
4063 kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4064 kernel = ppcg_kernel_create_local_arrays(kernel, gen->prog);
4065 if (!kernel)
4066 return isl_schedule_node_free(node);
4068 domain = isl_schedule_node_get_domain(node);
4069 single_statement = isl_union_set_n_set(domain) == 1;
4071 kernel->ctx = gen->ctx;
4072 kernel->options = gen->options;
4073 kernel->context = extract_context(node, gen->prog);
4074 kernel->core = isl_union_set_universe(isl_union_set_copy(domain));
4075 kernel->arrays = accessed_by_domain(domain, gen->prog);
4076 kernel->tile_len = isl_schedule_node_band_n_member(node);
4077 kernel->n_parallel = n_outer_coincidence(node);
4078 kernel->n_grid = kernel->n_parallel;
4079 node_thread = isl_schedule_node_copy(node);
4080 node_thread = gpu_tree_move_down_to_thread(node_thread, kernel->core);
4081 node_thread = isl_schedule_node_child(node_thread, 0);
4082 kernel->n_block = n_outer_coincidence(node_thread);
4083 isl_schedule_node_free(node_thread);
4084 kernel->id = gen->kernel_id++;
4085 read_grid_and_block_sizes(kernel, gen);
4087 gen->kernel = kernel;
4089 node = atomic_ancestors(node);
4091 id = isl_id_alloc(gen->ctx, "kernel", kernel);
4092 id = isl_id_set_free_user(id, &ppcg_kernel_free_wrap);
4093 node = isl_schedule_node_insert_mark(node, isl_id_copy(id));
4095 if (!single_statement)
4096 node = group_statements(node, kernel->id);
4098 node = isl_schedule_node_child(node, 0);
4099 node = split_band(node, kernel->n_grid);
4100 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
4101 kernel->n_grid, "b");
4102 kernel->block_filter = set_schedule_modulo(node, kernel->block_ids,
4103 kernel->grid_dim);
4104 if (scale)
4105 node = scale_band(node, isl_multi_val_copy(sizes));
4107 node = isl_schedule_node_cut(node);
4108 node = isl_schedule_node_parent(node);
4110 if (!single_statement)
4111 node = isl_schedule_node_parent(node);
4113 isl_id_free(id);
4114 return node;
4117 /* Insert a zero-dimensional permutable band at "node".
4119 static __isl_give isl_schedule_node *insert_empty_permutable_band(
4120 __isl_take isl_schedule_node *node)
4122 isl_space *space;
4123 isl_schedule *schedule;
4124 isl_union_set *domain;
4125 isl_multi_union_pw_aff *mupa;
4127 schedule = isl_schedule_node_get_schedule(node);
4128 domain = isl_schedule_get_domain(schedule);
4129 space = isl_union_set_get_space(domain);
4130 isl_union_set_free(domain);
4131 isl_schedule_free(schedule);
4133 space = isl_space_set_from_params(space);
4134 mupa = isl_multi_union_pw_aff_zero(space);
4135 node = isl_schedule_node_insert_partial_schedule(node, mupa);
4136 node = isl_schedule_node_band_set_permutable(node, 1);
4138 return node;
4141 /* Mark "node" as outer permutable.
4143 * If "node" originally points to a leaf, then insert a zero-dimensional
4144 * permutable band such that we can assume that "node" always
4145 * points to a band node.
4147 * Tile "node" using user specified tile sizes, after splitting the band
4148 * if the number of specified tile sizes is smaller than the dimension
4149 * of the band. Mark the point band of this tiling as the band that
4150 * needs to be mapped to threads.
4151 * Create a kernel representing the domain instances that reach "node" and
4152 * replace the band node with a mark node pointing to the kernel.
4154 static __isl_give isl_schedule_node *mark_outer_permutable(
4155 struct gpu_gen *gen, __isl_take isl_schedule_node *node)
4157 struct ppcg_kernel *kernel;
4158 int scale;
4159 int tile_len;
4160 int *tile_size;
4161 isl_id *id;
4162 isl_multi_val *sizes;
4164 if (isl_schedule_node_get_type(node) == isl_schedule_node_leaf)
4165 node = insert_empty_permutable_band(node);
4167 tile_len = isl_schedule_node_band_n_member(node);
4168 tile_size = read_tile_sizes(gen, &tile_len);
4169 if (!tile_size)
4170 return isl_schedule_node_free(node);
4171 if (tile_len < isl_schedule_node_band_n_member(node))
4172 node = isl_schedule_node_band_split(node, tile_len);
4173 sizes = construct_band_tiles_sizes(node, tile_size);
4174 node = tile_band(node, isl_multi_val_copy(sizes));
4175 node = isl_schedule_node_child(node, 0);
4176 id = isl_id_alloc(gen->ctx, "thread", NULL);
4177 node = isl_schedule_node_insert_mark(node, id);
4178 node = isl_schedule_node_parent(node);
4180 scale = gen->options->scale_tile_loops;
4181 node = create_kernel(gen, node, scale, sizes);
4182 isl_multi_val_free(sizes);
4183 if (!node)
4184 return NULL;
4185 kernel = gen->kernel;
4186 kernel->tile_len = tile_len;
4187 kernel->tile_size = tile_size;
4189 return node;
4192 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
4193 __isl_take isl_schedule_node *node, int pos, struct band_info *info);
4195 /* Check if this band node is tilable and has any parallel loops. If so,
4196 * take it as the outermost tilable band. If not, continue looking for the
4197 * outermost tilable band in the children of the current band.
4198 * Return a pointer to the same node in a tree where all outermost tilable
4199 * bands in the current subtree have been replaced by mark nodes
4200 * containing a pointer to a ppcg_kernel object.
4202 static __isl_give isl_schedule_node *band_select_outer_band(struct gpu_gen *gen,
4203 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
4205 int n = isl_schedule_node_band_n_member(node);
4206 int n_parallel;
4208 n_parallel = n_outer_coincidence(node);
4210 if (!isl_schedule_node_band_get_permutable(node) || n_parallel == 0) {
4211 node = isl_schedule_node_child(node, 0);
4212 node = select_outer_band(gen, node, pos + n, info);
4213 return isl_schedule_node_parent(node);
4216 gen->any_parallelism = 1;
4217 info->gen = gen;
4218 info->tile_first = pos;
4219 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4220 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
4222 node = mark_outer_permutable(gen, node);
4224 return node;
4227 /* Extend "umap" with coordinates with fixed value "val"
4228 * to a total length of "dst_len", assuming the original dimension is "src_len".
4230 static __isl_give isl_union_map *extend_range(
4231 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4233 isl_space *dim;
4234 isl_map *map;
4235 int i;
4237 dim = isl_union_map_get_space(umap);
4238 map = isl_map_reverse(projection(dim, dst_len, src_len));
4239 for (i = src_len; i < dst_len; ++i)
4240 map = isl_map_fix_si(map, isl_dim_out, i, val);
4242 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4244 return umap;
4247 /* Select the outermost bands in the elements of the sequence or set
4248 * node "node", align their prefix schedules and combine the resulting
4249 * prefix and suffix schedules into a single pair of prefix and
4250 * suffix schedules for the entire list.
4251 * Return a pointer to the same node in a tree where all outermost tilable
4252 * bands in the current subtree have been replaced by mark nodes
4253 * containing a pointer to a ppcg_kernel object.
4255 static __isl_give isl_schedule_node *list_select_outer_band(
4256 struct gpu_gen *gen, __isl_take isl_schedule_node *node, int pos,
4257 struct band_info *list_info)
4259 int i;
4260 int n = isl_schedule_node_n_children(node);
4261 isl_ctx *ctx = isl_schedule_node_get_ctx(node);
4262 struct band_info *info;
4263 int max_tile_first;
4264 isl_union_map *prefix;
4265 isl_union_map *suffix;
4267 assert(n >= 1);
4268 info = isl_calloc_array(ctx, struct band_info, n);
4269 assert(info);
4271 max_tile_first = 0;
4272 for (i = 0; i < n; ++i) {
4273 node = isl_schedule_node_child(node, i);
4274 node = select_outer_band(gen, node, pos, &info[i]);
4275 if (info[i].tile_first > max_tile_first)
4276 max_tile_first = info[i].tile_first;
4277 node = isl_schedule_node_parent(node);
4280 for (i = 0; i < n; ++i) {
4281 if (info[i].tile_first == max_tile_first)
4282 continue;
4283 info[i].prefix = extend_range(info[i].prefix,
4284 info[i].tile_first, max_tile_first, 0);
4285 info[i].tile_first = max_tile_first;
4288 prefix = info[0].prefix;
4289 suffix = info[0].suffix;
4291 for (i = 1; i < n; ++i) {
4292 prefix = isl_union_map_union(prefix, info[i].prefix);
4293 suffix = isl_union_map_union(suffix, info[i].suffix);
4296 list_info->tile_first = info[0].tile_first;
4297 list_info->prefix = prefix;
4298 list_info->suffix = suffix;
4300 free(info);
4301 return node;
4304 /* If we reach a leaf node, then we have not found any outer tilable
4305 * band with parallel loops, so consider the leaf node as the outermost
4306 * tilable band.
4307 * Return a pointer to a mark node containing a pointer
4308 * to a ppcg_kernel object inserted at the original leaf node.
4310 static __isl_give isl_schedule_node *leaf_select_outer_band(struct gpu_gen *gen,
4311 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
4313 info->gen = gen;
4314 info->tile_first = pos;
4315 info->prefix = isl_schedule_node_get_prefix_schedule_union_map(node);
4316 info->suffix = isl_schedule_node_get_subtree_schedule_union_map(node);
4318 node = mark_outer_permutable(gen, node);
4320 return node;
4323 /* Select the outermost tilable band in the subtree that "node" points to and
4324 * return a pointer to the same node in a tree where all outermost tilable
4325 * bands in the current subtree have been replaced by mark nodes
4326 * containing a pointer to a ppcg_kernel object.
4328 static __isl_give isl_schedule_node *select_outer_band(struct gpu_gen *gen,
4329 __isl_take isl_schedule_node *node, int pos, struct band_info *info)
4331 enum isl_schedule_node_type type;
4333 type = isl_schedule_node_get_type(node);
4334 switch (type) {
4335 case isl_schedule_node_domain:
4336 case isl_schedule_node_filter:
4337 node = isl_schedule_node_child(node, 0);
4338 node = select_outer_band(gen, node, pos, info);
4339 return isl_schedule_node_parent(node);
4340 case isl_schedule_node_leaf:
4341 return leaf_select_outer_band(gen, node, pos, info);
4342 case isl_schedule_node_band:
4343 return band_select_outer_band(gen, node, pos, info);
4344 case isl_schedule_node_set:
4345 case isl_schedule_node_sequence:
4346 return list_select_outer_band(gen, node, pos, info);
4347 default:
4348 isl_die(isl_schedule_node_get_ctx(node),
4349 isl_error_unsupported, "unhandled schedule node type",
4350 node = node);
4351 case isl_schedule_node_error:
4352 info->prefix = NULL;
4353 info->suffix = NULL;
4354 break;
4357 return isl_schedule_node_free(node);
4360 /* Select the outermost tilable band that (by construction)
4361 * has at least one parallel loop.
4362 * The starting position of the aligned band is stored in the pair
4363 * gen->tile_first.
4364 * The sizes and number of parallel loops may be different in different
4365 * parts of the band forest and are therefore stored in the gpu_stmts.
4367 * Return the complete schedule, with the tilable bands aligned
4368 * at gen->tile_first and padded with zero, if needed.
4369 * Store a schedule tree corresponding to the outer gen->tile_first
4370 * dimensions, with mark nodes containing pointers to ppcg_kernel objects,
4371 * in gen->host_schedule.
4373 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4374 __isl_keep isl_schedule *schedule)
4376 isl_schedule_node *node;
4377 struct band_info info;
4379 node = isl_schedule_get_root(schedule);
4380 node = select_outer_band(gen, node, 0, &info);
4381 gen->host_schedule = isl_schedule_node_get_schedule(node);
4382 isl_schedule_node_free(node);
4384 gen->tile_first = info.tile_first;
4385 info.suffix = align_range(info.suffix);
4387 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4390 /* Set gen->untiled_len to the number of scheduling dimensions
4391 * for the schedule of the first domain.
4392 * We assume here that this number is the same for all domains.
4394 static int set_untiled_len(__isl_take isl_map *map, void *user)
4396 unsigned *untiled_len = user;
4398 *untiled_len = isl_map_dim(map, isl_dim_out);
4400 isl_map_free(map);
4401 return -1;
4404 /* Compute an appropriate schedule based on the accesses in
4405 * gen->read and gen->write.
4407 * We use the dependences in gen->prog->scop to compute
4408 * a schedule that has a parallel loop in each tilable band.
4409 * Finally, we select the outermost tilable band.
4411 * If live range reordering is allowed, then we need to make sure
4412 * that live ranges on arrays are not run in parallel since doing
4413 * so would require array expansion. We therefore add the array
4414 * order dependences to the coincidence dependences. Non-zero array
4415 * order dependences will then prevent a schedule dimension from being
4416 * considered parallel.
4417 * Live ranges derived from scalars are allowed to be run in parallel
4418 * since we force the scalars to be mapped to private memory in
4419 * check_scalar_live_ranges.
4420 * If live range reordering is allowed, then the false dependences
4421 * are not added to the validity constraints as that would prevent
4422 * reordering. Instead, the external false dependences that enforce that reads
4423 * from potentially live-in data precede any later write and
4424 * that writes of potentially live-out data follow any other earlier write
4425 * are added to the validity and the coincidence constraints.
4426 * The false dependences are still added to the proximity constraints
4427 * for consistency with the case where live range reordering is not allowed.
4428 * The coincidence constraints then consist of flow dependences,
4429 * external false dependences and array order dependences.
4430 * The independences can be filtered out from the first two sets.
4431 * They have already been filtered out from the array order dependences
4432 * on a per array basis in collect_order_dependences.
4433 * There is no need for a per array handling of the other two sets
4434 * as there should be no flow or external false dependence on local
4435 * variables that can be filtered out.
4437 static void compute_schedule(struct gpu_gen *gen)
4439 isl_union_set *domain;
4440 isl_union_map *dep_raw, *dep;
4441 isl_union_map *validity, *proximity, *coincidence;
4442 isl_union_map *sched;
4443 isl_schedule_constraints *sc;
4444 isl_schedule *schedule;
4446 domain = isl_union_set_copy(gen->prog->scop->domain);
4447 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
4448 sc = isl_schedule_constraints_set_context(sc,
4449 isl_set_copy(gen->prog->scop->context));
4450 if (gen->options->live_range_reordering) {
4451 sc = isl_schedule_constraints_set_conditional_validity(sc,
4452 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
4453 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
4454 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
4455 validity = isl_union_map_copy(proximity);
4456 validity = isl_union_map_union(validity,
4457 isl_union_map_copy(gen->prog->scop->dep_forced));
4458 proximity = isl_union_map_union(proximity,
4459 isl_union_map_copy(gen->prog->scop->dep_false));
4460 coincidence = isl_union_map_copy(validity);
4461 coincidence = isl_union_map_subtract(coincidence,
4462 isl_union_map_copy(gen->prog->scop->independence));
4463 coincidence = isl_union_map_union(coincidence,
4464 isl_union_map_copy(gen->prog->array_order));
4465 } else {
4466 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4467 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4468 dep = isl_union_map_union(dep, dep_raw);
4469 dep = isl_union_map_coalesce(dep);
4470 proximity = isl_union_map_copy(dep);
4471 coincidence = isl_union_map_copy(dep);
4472 validity = dep;
4474 sc = isl_schedule_constraints_set_validity(sc, validity);
4475 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
4476 sc = isl_schedule_constraints_set_proximity(sc, proximity);
4478 if (gen->options->debug->dump_schedule_constraints)
4479 isl_schedule_constraints_dump(sc);
4480 schedule = isl_schedule_constraints_compute_schedule(sc);
4481 if (gen->options->debug->dump_schedule)
4482 isl_schedule_dump(schedule);
4484 sched = select_outer_tilable_band(gen, schedule);
4486 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4487 sched = isl_union_map_intersect_domain(sched, domain);
4488 gen->sched = sched;
4490 isl_schedule_free(schedule);
4493 /* Compute the sets of outer array elements that need to be copied in and out.
4495 * In particular, for each array that is possibly written anywhere in
4496 * gen->prog and that is visible outside the corresponding scop,
4497 * we copy out its entire extent.
4499 * Any array elements that is read without first being written needs
4500 * to be copied in. Furthermore, if there are any array elements that
4501 * are copied out, but that may not be written inside gen->prog, then
4502 * they also need to be copied in to ensure that the value after execution
4503 * is the same as the value before execution, at least for those array
4504 * elements that may have their values preserved by the scop.
4505 * In case the array elements are structures, we need to take into
4506 * account that all members of the structures need to be written
4507 * by gen->prog before we can avoid copying the data structure in.
4509 * While computing the set of array elements that are copied out but
4510 * not necessarily written, we intersect both sets with the context.
4511 * This helps in those cases where the arrays are declared with a fixed size,
4512 * while the accesses are parametric and the context assigns a fixed value
4513 * to the parameters.
4515 * If an element from a local array is read without first being written,
4516 * then there is no point in copying it in since it cannot have been
4517 * written prior to the scop. Warn about the uninitialized read instead.
4519 static void compute_copy_in_and_out(struct gpu_gen *gen)
4521 int i;
4522 isl_union_set *local;
4523 isl_union_set *may_write, *must_write;
4524 isl_union_set *copy_in, *copy_out;
4525 isl_union_set *not_written;
4526 isl_union_map *uninitialized;
4527 isl_union_map *local_uninitialized;
4529 must_write = isl_union_map_range(
4530 isl_union_map_copy(gen->prog->must_write));
4531 must_write = isl_union_set_intersect_params(must_write,
4532 isl_set_copy(gen->prog->context));
4533 may_write = isl_union_map_range(
4534 isl_union_map_copy(gen->prog->may_write));
4535 may_write = isl_union_set_intersect_params(may_write,
4536 isl_set_copy(gen->prog->context));
4537 may_write = isl_union_set_universe(may_write);
4538 may_write = isl_union_set_apply(may_write,
4539 isl_union_map_copy(gen->prog->to_outer));
4540 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
4541 local = isl_union_set_copy(copy_out);
4543 for (i = 0; i < gen->prog->n_array; ++i) {
4544 isl_space *space;
4545 isl_set *write_i;
4546 int empty;
4548 space = isl_space_copy(gen->prog->array[i].space);
4550 if (gen->prog->array[i].local) {
4551 isl_set *set;
4553 set = isl_set_universe(space);
4554 local = isl_union_set_add_set(local, set);
4555 continue;
4558 write_i = isl_union_set_extract_set(may_write, space);
4559 empty = isl_set_plain_is_empty(write_i);
4560 isl_set_free(write_i);
4561 if (empty)
4562 continue;
4564 write_i = isl_set_copy(gen->prog->array[i].extent);
4565 copy_out = isl_union_set_add_set(copy_out, write_i);
4567 isl_union_set_free(may_write);
4569 copy_out = isl_union_set_intersect_params(copy_out,
4570 isl_set_copy(gen->prog->context));
4572 gen->prog->copy_out = isl_union_set_copy(copy_out);
4574 copy_out = isl_union_set_apply(copy_out,
4575 isl_union_map_copy(gen->prog->to_inner));
4576 copy_out = isl_union_set_intersect(copy_out,
4577 isl_union_set_copy(gen->prog->may_persist));
4578 not_written = isl_union_set_subtract(copy_out, must_write);
4580 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4581 local_uninitialized = isl_union_map_copy(uninitialized);
4583 local = isl_union_set_apply(local,
4584 isl_union_map_copy(gen->prog->to_inner));
4585 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
4586 local);
4587 if (!isl_union_map_is_empty(local_uninitialized)) {
4588 fprintf(stderr,
4589 "possibly uninitialized reads (not copied in):\n");
4590 isl_union_map_dump(local_uninitialized);
4592 uninitialized = isl_union_map_subtract(uninitialized,
4593 local_uninitialized);
4594 copy_in = isl_union_map_range(uninitialized);
4595 copy_in = isl_union_set_union(copy_in, not_written);
4596 copy_in = isl_union_set_apply(copy_in,
4597 isl_union_map_copy(gen->prog->to_outer));
4599 gen->prog->copy_in = copy_in;
4602 /* Internal data structure for extract_access.
4603 * "next_access" points to the end of a linked list that is extended
4604 * by extract_access.
4605 * "single_expression" is set if the access expressions belong to
4606 * an expression statement (i.e., a statement without internal control).
4607 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4609 struct ppcg_extract_access_data {
4610 struct gpu_stmt_access **next_access;
4611 int single_expression;
4612 isl_union_map *any_to_outer;
4615 /* Given a tagged access relation to a single array "tagged", extract it
4616 * as a map, taking into account that the input may be empty.
4617 * If the access relation is empty, then it does not contain
4618 * any space information, so we try to recover it from the index
4619 * expression.
4620 * The space of the index expression is of the form I -> A,
4621 * with I the statement instances and A the array, or [I -> F] -> A,
4622 * with F the filters corresponding to arguments.
4623 * We first drop F, if present, obtaining I -> A.
4624 * Then we construct I -> R, with R the reference tag,
4625 * combine the two into I -> [R -> A] and uncurry to obtain
4626 * the final result [I -> R] -> A.
4627 * Note that the index expression may have a lower dimension
4628 * than that of the array, but this dimension is not used
4629 * if the access relation is empty.
4631 static __isl_give isl_map *extract_single_tagged_access(
4632 __isl_take isl_union_map *tagged, __isl_keep pet_expr *expr)
4634 int empty;
4635 isl_id *id;
4636 isl_space *space, *space2;
4637 isl_multi_pw_aff *index;
4639 empty = isl_union_map_is_empty(tagged);
4640 if (empty < 0)
4641 goto error;
4642 if (!empty)
4643 return isl_map_from_union_map(tagged);
4644 isl_union_map_free(tagged);
4646 index = pet_expr_access_get_index(expr);
4647 space = isl_multi_pw_aff_get_space(index);
4648 isl_multi_pw_aff_free(index);
4649 if (isl_space_domain_is_wrapping(space))
4650 space = isl_space_domain_factor_domain(space);
4651 space2 = isl_space_copy(space);
4652 space2 = isl_space_from_domain(isl_space_domain(space));
4653 id = pet_expr_access_get_ref_id(expr);
4654 space2 = isl_space_set_tuple_id(space2, isl_dim_out, id);
4655 space = isl_space_range_product(space2, space);
4656 space = isl_space_uncurry(space);
4658 return isl_map_empty(space);
4659 error:
4660 isl_union_map_free(tagged);
4661 return NULL;
4664 /* Extract a gpu_stmt_access from "expr", append it to the list
4665 * that ends in *data->next_access and update the end of the list.
4666 * If the access expression performs a write, then it is considered
4667 * exact only if it appears in a single expression statement and
4668 * if its may access relation is equal to its must access relation.
4670 * The combined set of may accesses may be union if member accesses
4671 * are involved, but the entire set is derived from a single reference and
4672 * therefore from a single index expression. These accesses therefore
4673 * all map to the same outer array.
4675 static int extract_access(__isl_keep pet_expr *expr, void *user)
4677 struct ppcg_extract_access_data *data = user;
4678 isl_union_map *tagged;
4679 struct gpu_stmt_access *access;
4680 isl_ctx *ctx = pet_expr_get_ctx(expr);
4681 isl_multi_pw_aff *index;
4683 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4684 assert(access);
4685 access->next = NULL;
4686 access->read = pet_expr_access_is_read(expr);
4687 access->write = pet_expr_access_is_write(expr);
4688 tagged = pet_expr_access_get_tagged_may_read(expr);
4689 tagged = isl_union_map_union(tagged,
4690 pet_expr_access_get_tagged_may_write(expr));
4691 tagged = isl_union_map_apply_range(tagged,
4692 isl_union_map_copy(data->any_to_outer));
4693 if (!access->write) {
4694 access->exact_write = 1;
4695 } else if (!data->single_expression) {
4696 access->exact_write = 0;
4697 } else {
4698 isl_union_map *must, *may;
4699 may = isl_union_map_copy(tagged);
4700 may = isl_union_map_domain_factor_domain(may);
4701 must = pet_expr_access_get_must_write(expr);
4702 access->exact_write = isl_union_map_is_equal(must, may);
4703 isl_union_map_free(must);
4704 isl_union_map_free(may);
4706 index = pet_expr_access_get_index(expr);
4707 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
4708 isl_multi_pw_aff_free(index);
4709 access->ref_id = pet_expr_access_get_ref_id(expr);
4710 access->tagged_access = extract_single_tagged_access(tagged, expr);
4711 access->access = isl_map_copy(access->tagged_access);
4712 access->access = isl_map_domain_factor_domain(access->access);
4714 *data->next_access = access;
4715 data->next_access = &(*data->next_access)->next;
4717 if (!access->access)
4718 return -1;
4720 return 0;
4723 /* Construct a linked list of gpu_stmt_access objects,
4724 * one for each access expression in the statement body.
4725 * "any_to_outer" maps all intermediate arrays to their outer arrays.
4727 static int pet_stmt_extract_accesses(struct gpu_stmt *stmt,
4728 __isl_keep isl_union_map *any_to_outer)
4730 struct ppcg_extract_access_data data;
4732 stmt->accesses = NULL;
4733 data.next_access = &stmt->accesses;
4734 data.single_expression =
4735 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
4736 data.any_to_outer = any_to_outer;
4737 return pet_tree_foreach_access_expr(stmt->stmt->body,
4738 &extract_access, &data);
4741 /* Return an array of gpu_stmt representing the statements in "scop".
4743 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4744 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
4746 int i;
4747 struct gpu_stmt *stmts;
4749 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
4750 if (!stmts)
4751 return NULL;
4753 for (i = 0; i < scop->pet->n_stmt; ++i) {
4754 struct gpu_stmt *s = &stmts[i];
4756 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
4757 s->stmt = scop->pet->stmts[i];
4758 if (pet_stmt_extract_accesses(s, any_to_outer) < 0)
4759 return free_stmts(stmts, i + 1);
4762 return stmts;
4765 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
4767 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
4769 struct gpu_gen *gen = user;
4771 return gen->print(p, gen->prog, gen->tree, &gen->types,
4772 gen->print_user);
4775 /* Generate CUDA code for "scop" and print it to "p".
4776 * After generating an AST for the transformed scop as explained below,
4777 * we call "gen->print" to print the AST in the desired output format
4778 * to "p".
4780 * If it turns out that it does not make sense to generate GPU code,
4781 * then we generate CPU code instead.
4783 * The GPU code is generated in a context where at least one
4784 * statement instance is executed. The corresponding guard (if any) is printed
4785 * around the entire generated GPU code, except for the declaration
4786 * of the arrays that are visible outside of the scop and that therefore
4787 * cannot be declared inside the body of any possible guard.
4789 * We first compute a schedule that respects the dependences
4790 * of the original program and select the outermost band
4791 * of tilable dimensions that has at least one parallel loop.
4792 * We then have three blocks of dimensions
4794 * H B G
4796 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4797 * in
4799 * H T P G
4801 * For each iteration of the T loop and for each array, we compute
4802 * the array elements accessed by that iteration, construct a rectangular
4803 * box around it and shift it to the origin. The result is used
4804 * as shared memory for the array.
4806 * We then split off at most 2 parallel loops from the T loops and
4807 * at most 3 parallel loops from the P loops
4809 * H T1 T2 P1 P2 G
4811 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4812 * according to "grid"/"block" sizes.
4814 * H T1T T1P T2 P1T P1P P2 G
4816 * Finally, the T1P and P1P iterators are equated to the block and
4817 * thread dimensions respectively and so are effectively removed.
4818 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4819 * are run on the GPU.
4821 * Code is generated in three stages. We first generate code for the
4822 * host (the H loops), with iterators h%d. Then, for each leaf node
4823 * of the resulting AST, we generate code for the shared loops (up to
4824 * and including T2), with iterators g%d and after equating the H loops
4825 * to h%d parameters and the T1P loops to the block dimensions.
4826 * Finally, we generate code for the remaining loops in a similar fashion.
4828 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
4829 struct gpu_gen *gen, struct ppcg_scop *scop,
4830 struct ppcg_options *options)
4832 struct gpu_prog *prog;
4833 isl_ctx *ctx;
4834 isl_set *context, *guard;
4836 if (!scop)
4837 return isl_printer_free(p);
4839 ctx = isl_printer_get_ctx(p);
4840 prog = gpu_prog_alloc(ctx, scop);
4841 if (!prog)
4842 return isl_printer_free(p);
4844 context = isl_set_copy(prog->context);
4845 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
4846 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
4848 gen->prog = prog;
4849 gen->any_parallelism = 0;
4850 compute_schedule(gen);
4852 if (!gen->any_parallelism) {
4853 isl_set_free(context);
4854 isl_set_free(guard);
4855 p = print_cpu(p, scop, options);
4856 } else {
4857 compute_copy_in_and_out(gen);
4858 gen->tree = generate_host_code(gen);
4859 p = ppcg_print_exposed_declarations(p, prog->scop);
4860 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
4861 isl_ast_node_free(gen->tree);
4864 isl_union_map_free(gen->sched);
4865 isl_schedule_free(gen->host_schedule);
4867 gpu_prog_free(prog);
4869 return p;
4872 /* Wrapper around generate for use as a ppcg_transform callback.
4874 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
4875 struct ppcg_scop *scop, void *user)
4877 struct gpu_gen *gen = user;
4879 return generate(p, gen, scop, gen->options);
4882 /* Transform the code in the file called "input" by replacing
4883 * all scops by corresponding GPU code and write the results to "out".
4885 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4886 struct ppcg_options *options,
4887 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4888 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4889 struct gpu_types *types, void *user), void *user)
4891 struct gpu_gen gen;
4892 int r;
4893 int i;
4895 gen.ctx = ctx;
4896 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4897 gen.options = options;
4898 gen.kernel_id = 0;
4899 gen.print = print;
4900 gen.print_user = user;
4901 gen.types.n = 0;
4902 gen.types.name = NULL;
4904 if (options->debug->dump_sizes) {
4905 isl_space *space = isl_space_params_alloc(ctx, 0);
4906 gen.used_sizes = isl_union_map_empty(space);
4909 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
4911 if (options->debug->dump_sizes) {
4912 isl_union_map_dump(gen.used_sizes);
4913 isl_union_map_free(gen.used_sizes);
4916 isl_union_map_free(gen.sizes);
4917 for (i = 0; i < gen.types.n; ++i)
4918 free(gen.types.name[i]);
4919 free(gen.types.name);
4921 return r;
4924 /* Compute the set of inner array elements that may have their values
4925 * preserved by "prog". In particular, collect the array elements of
4926 * arrays that are not local to "prog" and remove those elements that
4927 * are definitely killed or definitely written by "prog".
4929 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
4931 int i;
4932 isl_union_set *may_persist, *killed;
4933 isl_union_map *must_kill;
4935 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
4936 for (i = 0; i < prog->n_array; ++i) {
4937 isl_set *extent;
4939 if (prog->array[i].local)
4940 continue;
4942 extent = isl_set_copy(prog->array[i].extent);
4943 may_persist = isl_union_set_add_set(may_persist, extent);
4946 may_persist = isl_union_set_intersect_params(may_persist,
4947 isl_set_copy(prog->context));
4948 may_persist = isl_union_set_apply(may_persist,
4949 isl_union_map_copy(prog->to_inner));
4950 must_kill = isl_union_map_copy(prog->tagged_must_kill);
4951 killed = isl_union_map_range(must_kill);
4952 must_kill = isl_union_map_copy(prog->must_write);
4953 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
4955 may_persist = isl_union_set_subtract(may_persist, killed);
4956 return may_persist;
4959 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4961 struct gpu_prog *prog;
4962 isl_space *space;
4963 isl_map *id;
4965 if (!scop)
4966 return NULL;
4968 prog = isl_calloc_type(ctx, struct gpu_prog);
4969 assert(prog);
4971 prog->ctx = ctx;
4972 prog->scop = scop;
4973 prog->context = isl_set_copy(scop->context);
4974 prog->n_stmts = scop->pet->n_stmt;
4975 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
4976 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
4977 space = isl_union_map_get_space(prog->any_to_outer);
4978 space = isl_space_set_from_params(space);
4979 space = isl_space_add_dims(space, isl_dim_set, 1);
4980 space = isl_space_map_from_set(space);
4981 id = isl_map_identity(space);
4982 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
4983 prog->stmts = extract_stmts(ctx, scop,
4984 prog->context, prog->any_to_outer);
4985 prog->read = isl_union_map_copy(scop->reads);
4986 prog->may_write = isl_union_map_copy(scop->may_writes);
4987 prog->must_write = isl_union_map_copy(scop->must_writes);
4988 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
4989 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
4990 prog->to_outer = isl_union_map_copy(prog->to_inner);
4991 prog->to_outer = isl_union_map_reverse(prog->to_outer);
4993 if (!prog->stmts)
4994 return gpu_prog_free(prog);
4996 if (collect_array_info(prog) < 0)
4997 return gpu_prog_free(prog);
4998 prog->may_persist = compute_may_persist(prog);
5000 return prog;
5003 void *gpu_prog_free(struct gpu_prog *prog)
5005 if (!prog)
5006 return NULL;
5007 free_array_info(prog);
5008 free_stmts(prog->stmts, prog->n_stmts);
5009 isl_union_map_free(prog->any_to_outer);
5010 isl_union_map_free(prog->to_outer);
5011 isl_union_map_free(prog->to_inner);
5012 isl_union_set_free(prog->copy_in);
5013 isl_union_set_free(prog->copy_out);
5014 isl_union_map_free(prog->read);
5015 isl_union_map_free(prog->may_write);
5016 isl_union_map_free(prog->must_write);
5017 isl_union_map_free(prog->tagged_must_kill);
5018 isl_union_map_free(prog->array_order);
5019 isl_union_set_free(prog->may_persist);
5020 isl_set_free(prog->context);
5021 free(prog);
5022 return NULL;