gpu_array_info: keep track of whether the array is accessed at all
[ppcg.git] / gpu.c
blobe6c3dffc992ab111b626b7e8790605a0b4d57757
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/band.h>
23 #include <isl/schedule.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "cpu.h"
28 #include "gpu.h"
29 #include "schedule.h"
30 #include "ppcg_options.h"
31 #include "print.h"
33 /* The fields stride and shift only contain valid information
34 * if shift != NULL.
35 * If so, they express that current index is such that if you add shift,
36 * then the result is always a multiple of stride.
37 * Let D represent the initial shared_len dimensions of the computed schedule.
38 * The spaces of "lb" and "shift" are of the form
40 * D -> [b]
42 struct gpu_array_bound {
43 isl_val *size;
44 isl_aff *lb;
46 isl_val *stride;
47 isl_aff *shift;
50 /* A tile of an array.
52 * n is the dimension of the array.
53 * bound is an array of size "n" representing the lower bound
54 * and size for each index.
56 * tiling maps a tile in the global array to the corresponding
57 * shared/private memory tile and is of the form
59 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
61 * where D represents the initial shared_len dimensions
62 * of the computed schedule.
64 struct gpu_array_tile {
65 int n;
66 struct gpu_array_bound *bound;
67 isl_multi_aff *tiling;
70 struct gpu_array_info;
72 /* A group of array references in a kernel that should be handled together.
73 * If private_tile is not NULL, then it is mapped to registers.
74 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
75 * Otherwise, it is accessed from global memory.
77 struct gpu_array_ref_group {
78 /* The references in this group access this array. */
79 struct gpu_array_info *array;
80 /* Position of this group in the list of reference groups of array. */
81 int nr;
83 /* The following fields are use during the construction of the groups.
84 * access is the combined access relation relative to the shared
85 * memory tiling. In particular, the domain of the map corresponds
86 * to the first shared_len dimensions of the computed schedule.
87 * write is set if any access in the group is a write.
88 * exact_write is set if all writes are definite writes.
89 * slice is set if there is at least one access in the group
90 * that refers to more than one element
92 isl_map *access;
93 int write;
94 int exact_write;
95 int slice;
97 /* The shared memory tile, NULL if none. */
98 struct gpu_array_tile *shared_tile;
100 /* The private memory tile, NULL if none. */
101 struct gpu_array_tile *private_tile;
103 /* References in this group; point to elements of a linked list. */
104 int n_ref;
105 struct gpu_stmt_access **refs;
107 /* Last shared memory tile dimension that affects tile of this group. */
108 int last_shared;
111 struct gpu_gen {
112 isl_ctx *ctx;
113 struct ppcg_options *options;
115 /* Callback for printing of AST in appropriate format. */
116 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
117 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
118 struct gpu_types *types, void *user);
119 void *print_user;
121 struct gpu_prog *prog;
122 /* The generated AST. */
123 isl_ast_node *tree;
125 /* The sequence of types for which a definition has been printed. */
126 struct gpu_types types;
128 /* User specified tile, grid and block sizes for each kernel */
129 isl_union_map *sizes;
131 /* Effectively used tile, grid and block sizes for each kernel */
132 isl_union_map *used_sizes;
134 /* Identifier of current kernel. */
135 int kernel_id;
136 /* Pointer to the current kernel. */
137 struct ppcg_kernel *kernel;
138 /* Does the computed schedule exhibit any parallelism? */
139 int any_parallelism;
141 /* First tile dimension. */
142 int tile_first;
143 /* Number of tile dimensions. */
144 int tile_len;
145 /* Number of initial parallel loops among tile dimensions. */
146 int n_parallel;
148 /* Number of dimensions determining shared memory. */
149 int shared_len;
151 /* Number of rows in the untiled schedule. */
152 int untiled_len;
153 /* Number of rows in the tiled schedule. */
154 int tiled_len;
155 /* Number of rows in schedule after tiling/wrapping over threads. */
156 int thread_tiled_len;
158 /* Global untiled schedule. */
159 isl_union_map *sched;
160 /* Local (per kernel launch) tiled schedule. */
161 isl_union_map *tiled_sched;
162 /* Local schedule per shared memory tile loop iteration. */
163 isl_union_map *local_sched;
165 /* Local tiled schedule projected onto the shared tile loops and
166 * the loops that will be wrapped over the threads,
167 * with all shared tile loops parametrized.
169 isl_union_map *shared_sched;
170 /* Projects out the loops that will be wrapped over the threads
171 * from shared_sched.
173 isl_union_map *shared_proj;
175 /* A map that takes the range of shared_sched as input,
176 * wraps the appropriate loops over the threads and then projects
177 * out these loops.
179 isl_map *privatization;
181 /* The array reference group corresponding to copy_sched. */
182 struct gpu_array_ref_group *copy_group;
184 /* Is any array in the current kernel marked force_private? */
185 int any_force_private;
187 /* First loop to unroll (or -1 if none) in the current part of the
188 * schedule.
190 int first_unroll;
192 int n_grid;
193 int n_block;
194 /* Note: in the input file, the sizes of the grid and the blocks
195 * are specified in the order x, y, z, but internally, the sizes
196 * are stored in reverse order, so that the last element always
197 * refers to the x dimension.
199 int grid_dim[2];
200 int block_dim[3];
201 int *tile_size;
204 /* Print the name of the local copy of a given group of array references.
206 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
207 struct gpu_array_ref_group *group)
209 int global = 0;
211 if (group->private_tile)
212 p = isl_printer_print_str(p, "private_");
213 else if (group->shared_tile)
214 p = isl_printer_print_str(p, "shared_");
215 else
216 global = 1;
217 p = isl_printer_print_str(p, group->array->name);
218 if (!global && group->array->n_group > 1) {
219 p = isl_printer_print_str(p, "_");
220 p = isl_printer_print_int(p, group->nr);
223 return p;
226 /* Collect all references to the given array and store pointers to them
227 * in array->refs.
229 * If the array contains structures, then there is no need to collect
230 * the references since we will not be computing any reference groups.
232 static void collect_references(struct gpu_prog *prog,
233 struct gpu_array_info *array)
235 int i;
236 int n;
238 if (array->has_compound_element)
239 return;
241 n = 0;
242 for (i = 0; i < prog->n_stmts; ++i) {
243 struct gpu_stmt *stmt = &prog->stmts[i];
244 struct gpu_stmt_access *access;
246 for (access = stmt->accesses; access; access = access->next) {
247 const char *name;
248 name = isl_map_get_tuple_name(access->access,
249 isl_dim_out);
250 if (name && !strcmp(array->name, name))
251 n++;
255 array->n_ref = n;
256 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
257 assert(array->refs);
259 n = 0;
260 for (i = 0; i < prog->n_stmts; ++i) {
261 struct gpu_stmt *stmt = &prog->stmts[i];
262 struct gpu_stmt_access *access;
264 for (access = stmt->accesses; access; access = access->next) {
265 const char *name;
266 name = isl_map_get_tuple_name(access->access,
267 isl_dim_out);
268 if (!name || strcmp(array->name, name))
269 continue;
271 array->refs[n++] = access;
276 /* Create a gpu_array_tile for an array of dimension "n_index".
278 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
280 int i;
281 struct gpu_array_tile *tile;
283 tile = isl_calloc_type(ctx, struct gpu_array_tile);
284 assert(tile);
286 tile->n = n_index;
288 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
289 assert(tile->bound);
291 for (i = 0; i < n_index; ++i) {
292 tile->bound[i].size = NULL;
293 tile->bound[i].lb = NULL;
294 tile->bound[i].stride = NULL;
295 tile->bound[i].shift = NULL;
298 return tile;
301 static void *free_tile(struct gpu_array_tile *tile)
303 int j;
305 if (!tile)
306 return NULL;
308 for (j = 0; j < tile->n; ++j) {
309 isl_val_free(tile->bound[j].size);
310 isl_val_free(tile->bound[j].stride);
311 isl_aff_free(tile->bound[j].lb);
312 isl_aff_free(tile->bound[j].shift);
314 free(tile->bound);
315 isl_multi_aff_free(tile->tiling);
316 free(tile);
318 return NULL;
321 static struct pet_array *find_array(struct ppcg_scop *scop,
322 __isl_keep isl_set *accessed)
324 int i;
325 isl_id *id;
327 id = isl_set_get_tuple_id(accessed);
329 for (i = 0; i < scop->pet->n_array; ++i) {
330 isl_id *id_i;
332 id_i = isl_set_get_tuple_id(scop->pet->arrays[i]->extent);
333 isl_id_free(id_i);
334 if (id == id_i)
335 break;
337 isl_id_free(id);
339 return i < scop->pet->n_array ? scop->pet->arrays[i] : NULL;
342 /* Compute and return the extent of "array", taking into account the set of
343 * accessed elements.
345 * In particular, the extent in the outer dimension is taken
346 * from "accessed", while the extents in the remaining dimensions
347 * are taken from array->extent.
349 * The extent in the outer dimension cannot be taken from array->extent
350 * because that may be unbounded. Furthermore, even if it is bounded,
351 * it may be larger than the piece of the array that is being accessed.
353 static __isl_give isl_set *compute_extent(struct pet_array *array,
354 __isl_keep isl_set *accessed)
356 int n_index;
357 isl_id *id;
358 isl_set *outer;
359 isl_set *extent;
361 extent = isl_set_copy(array->extent);
363 n_index = isl_set_dim(accessed, isl_dim_set);
364 if (n_index == 0)
365 return extent;
367 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
368 outer = isl_set_copy(accessed);
369 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
370 extent = isl_set_flat_product(outer, extent);
371 id = isl_set_get_tuple_id(accessed);
372 extent = isl_set_set_tuple_id(extent, id);
374 return extent;
377 /* Is the array "array" being extracted a read-only scalar?
379 * That is, is "array" a scalar that is never possibly written to.
380 * An array containing structures is never considered to be a scalar.
382 static int is_read_only_scalar(struct gpu_array_info *array,
383 struct gpu_prog *prog)
385 isl_set *space;
386 isl_union_map *write;
387 int empty;
389 if (array->has_compound_element)
390 return 0;
391 if (array->n_index != 0)
392 return 0;
394 write = isl_union_map_copy(prog->may_write);
395 space = isl_set_universe(isl_space_copy(array->space));
396 write = isl_union_map_intersect_range(write,
397 isl_union_set_from_set(space));
398 empty = isl_union_map_is_empty(write);
399 isl_union_map_free(write);
401 return empty;
404 /* Compute bounds on the host arrays based on the accessed elements
405 * and collect all references to the array.
407 * If the array is zero-dimensional and does not contain structures,
408 * i.e., if the array is a scalar, we check whether it is read-only.
409 * We also check whether the array is accessed at all.
411 static int extract_array_info(__isl_take isl_set *array, void *user)
413 int i, empty;
414 struct gpu_prog *prog = (struct gpu_prog *)user;
415 const char *name;
416 int n_index;
417 isl_pw_aff **bounds;
418 struct pet_array *pa;
419 struct gpu_array_info *info;
420 isl_set *extent;
422 info = &prog->array[prog->n_array];
423 prog->n_array++;
425 n_index = isl_set_dim(array, isl_dim_set);
426 name = isl_set_get_tuple_name(array);
427 bounds = isl_alloc_array(isl_set_get_ctx(array),
428 isl_pw_aff *, n_index);
429 if (!bounds)
430 goto error;
432 info->space = isl_set_get_space(array);
433 info->name = strdup(name);
434 info->n_index = n_index;
435 info->bound = bounds;
436 info->linearize = prog->scop->options->linearize_device_arrays;
438 pa = find_array(prog->scop, array);
439 if (!pa)
440 isl_die(isl_set_get_ctx(array), isl_error_internal,
441 "unable to find array in scop", goto error);
443 info->type = strdup(pa->element_type);
444 info->size = pa->element_size;
445 info->local = pa->declared && !pa->exposed;
446 info->has_compound_element = pa->element_is_record;
447 info->read_only_scalar = is_read_only_scalar(info, prog);
449 empty = isl_set_is_empty(array);
450 extent = compute_extent(pa, array);
451 info->extent = extent;
452 if (empty < 0)
453 return -1;
454 info->accessed = !empty;
455 for (i = 0; i < n_index; ++i) {
456 isl_set *dom;
457 isl_local_space *ls;
458 isl_aff *one;
459 isl_pw_aff *bound;
461 dom = isl_set_copy(extent);
462 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
463 n_index - (i + 1));
464 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
465 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
466 fprintf(stderr, "unable to determine extent of '%s' "
467 "in dimension %d\n", info->name, i);
468 dom = isl_set_free(dom);
470 bound = isl_set_dim_max(dom, 0);
471 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
472 ls = isl_local_space_from_space(isl_set_get_space(dom));
473 one = isl_aff_zero_on_domain(ls);
474 one = isl_aff_add_constant_si(one, 1);
475 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
476 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
478 bounds[i] = bound;
479 if (!isl_pw_aff_is_cst(bound))
480 info->linearize = 1;
483 collect_references(prog, info);
485 isl_set_free(array);
486 return 0;
487 error:
488 isl_set_free(array);
489 return -1;
492 /* Remove independence from the order constraints "order" on array "array".
493 * Since the pairs of iterations in the filter relation of an independence
494 * are guaranteed to be completely independent by the user, there is
495 * no need to ensure that live ranges are ordered along thong pairs.
496 * We make an exception for local variables, though, as the independence
497 * guarantee does not apply to those.
499 * The order constraints are used in two places.
500 * Those on scalars are used in check_scalar_live_ranges to check if
501 * we need to force the scalar to be private. Any non-local scalar
502 * should not be forced scalar if it only appears in independent loops.
503 * Those on non-scalars are added to the coincidence constraints
504 * in compute_schedule because we do not support any array expansion.
505 * Accesses to non-local arrays should not prevent a loop from being
506 * considered coincident so we should indeed remove those constraints
507 * from the order constraints.
509 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
510 struct gpu_array_info *array, __isl_take isl_union_map *order)
512 int i;
514 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
515 struct pet_independence *pi = prog->scop->pet->independences[i];
516 if (isl_union_set_contains(pi->local, array->space))
517 continue;
519 order = isl_union_map_subtract(order,
520 isl_union_map_copy(pi->filter));
523 return order;
526 /* For each array in "prog", store the (untagged) order dependences
527 * derived from the array in array->dep_order.
528 * In particular, consider all references that access the given array
529 * and take the order dependences that have one of these references
530 * as source. (Since an order dependence relates two references to
531 * the same array, the target of these order dependences will also
532 * be one of these references.)
533 * Additionally, store the union of these array->dep_order relations
534 * for all non-scalar arrays in prog->array_order.
536 void collect_order_dependences(struct gpu_prog *prog)
538 int i;
539 isl_space *space;
540 isl_union_map *accesses;
542 space = isl_union_map_get_space(prog->read);
543 prog->array_order = isl_union_map_empty(space);
545 accesses = isl_union_map_copy(prog->scop->tagged_reads);
546 accesses = isl_union_map_union(accesses,
547 isl_union_map_copy(prog->scop->tagged_may_writes));
548 accesses = isl_union_map_universe(accesses);
549 accesses = isl_union_map_apply_range(accesses,
550 isl_union_map_copy(prog->to_outer));
552 for (i = 0; i < prog->n_array; ++i) {
553 struct gpu_array_info *array = &prog->array[i];
554 isl_set *set;
555 isl_union_set *uset;
556 isl_union_map *order;
558 set = isl_set_universe(isl_space_copy(array->space));
559 uset = isl_union_set_from_set(set);
560 uset = isl_union_map_domain(
561 isl_union_map_intersect_range(isl_union_map_copy(accesses),
562 uset));
563 order = isl_union_map_copy(prog->scop->tagged_dep_order);
564 order = isl_union_map_intersect_domain(order, uset);
565 order = isl_union_map_zip(order);
566 order = isl_union_set_unwrap(isl_union_map_domain(order));
567 order = remove_independences(prog, array, order);
568 array->dep_order = order;
570 if (gpu_array_is_scalar(array) && !array->has_compound_element)
571 continue;
573 prog->array_order = isl_union_map_union(prog->array_order,
574 isl_union_map_copy(array->dep_order));
577 isl_union_map_free(accesses);
580 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
581 * collect them in prog->array.
583 * If there are any member accesses involved, then they are first mapped
584 * to the outer arrays of structs.
586 * If we are allowing live range reordering, then also set
587 * the dep_order field. Otherwise leave it NULL.
589 static int collect_array_info(struct gpu_prog *prog)
591 int r;
592 isl_union_set *arrays;
594 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
595 arrays = isl_union_set_union(arrays,
596 isl_union_map_range(isl_union_map_copy(prog->may_write)));
598 arrays = isl_union_set_apply(arrays,
599 isl_union_map_copy(prog->to_outer));
601 arrays = isl_union_set_coalesce(arrays);
603 prog->n_array = isl_union_set_n_set(arrays);
604 prog->array = isl_calloc_array(prog->ctx,
605 struct gpu_array_info, prog->n_array);
606 assert(prog->array);
607 prog->n_array = 0;
608 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
609 isl_union_set_free(arrays);
611 if (prog->scop->options->live_range_reordering)
612 collect_order_dependences(prog);
614 return r;
617 static void free_array_info(struct gpu_prog *prog)
619 int i, j;
621 for (i = 0; i < prog->n_array; ++i) {
622 int n_index = prog->array[i].n_index;
623 free(prog->array[i].type);
624 free(prog->array[i].name);
625 for (j = 0; j < n_index; ++j)
626 isl_pw_aff_free(prog->array[i].bound[j]);
627 isl_space_free(prog->array[i].space);
628 isl_set_free(prog->array[i].extent);
629 free(prog->array[i].bound);
630 free(prog->array[i].refs);
631 isl_union_map_free(prog->array[i].dep_order);
633 free(prog->array);
636 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
637 * as an array or through a pointer reference, but as a single data element.
638 * At the moment, scalars are represented as zero-dimensional arrays.
639 * Note that the single data element may be an entire structure.
641 int gpu_array_is_scalar(struct gpu_array_info *array)
643 return array->n_index == 0;
646 /* Is "array" a read-only scalar?
648 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
650 return array->read_only_scalar;
653 /* Return the set of parameter values for which the array has a positive
654 * size in all dimensions.
655 * If the sizes are only valid for some parameter values, then those
656 * constraints are also taken into account.
658 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
660 int i;
661 isl_space *space;
662 isl_set *guard;
664 space = isl_space_params(isl_space_copy(array->space));
665 guard = isl_set_universe(space);
667 for (i = 0; i < array->n_index; ++i) {
668 isl_pw_aff *bound;
669 isl_set *guard_i, *zero;
671 bound = isl_pw_aff_copy(array->bound[i]);
672 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
673 zero = isl_pw_aff_zero_set(bound);
674 guard_i = isl_set_subtract(guard_i, zero);
675 guard = isl_set_intersect(guard, guard_i);
678 return guard;
681 /* Internal data structure for extract_size_of_type.
682 * "type" specifies the name of the space that we want to extract.
683 * "res" is used to store the subset of that space.
685 struct ppcg_extract_size_data {
686 const char *type;
687 isl_set *res;
690 /* This function is called for each set in a union_set.
691 * If the name of the set matches data->type, we store the
692 * set in data->res.
694 static int extract_size_of_type(__isl_take isl_set *size, void *user)
696 struct ppcg_extract_size_data *data = user;
697 const char *name;
699 name = isl_set_get_tuple_name(size);
700 if (name && !strcmp(name, data->type)) {
701 data->res = size;
702 return -1;
705 isl_set_free(size);
706 return 0;
709 /* Given a union map { kernel[i] -> *[...] },
710 * return the range in the space called "type" for the kernel with
711 * sequence number "id".
713 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
714 const char *type, int id)
716 isl_space *space;
717 isl_set *dom;
718 isl_union_set *local_sizes;
719 struct ppcg_extract_size_data data = { type, NULL };
721 if (!sizes)
722 return NULL;
724 space = isl_union_map_get_space(sizes);
725 space = isl_space_set_from_params(space);
726 space = isl_space_add_dims(space, isl_dim_set, 1);
727 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
728 dom = isl_set_universe(space);
729 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
731 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
732 isl_union_map_copy(sizes));
733 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
734 isl_union_set_free(local_sizes);
735 return data.res;
738 /* Given a singleton set, extract the first (at most *len) elements
739 * of the single integer tuple into *sizes and update *len if needed.
741 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
743 int i;
744 int dim;
746 if (!set)
747 return;
749 dim = isl_set_dim(set, isl_dim_set);
750 if (dim < *len)
751 *len = dim;
753 for (i = 0; i < *len; ++i) {
754 isl_val *v;
756 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
757 assert(v);
759 sizes[i] = isl_val_get_num_si(v);
760 isl_val_free(v);
763 isl_set_free(set);
766 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
767 * if the option debug->dump_sizes is set.
769 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
770 int *sizes, int len)
772 int i;
773 isl_space *space;
774 isl_map *map;
776 if (!gen->options->debug->dump_sizes)
777 return;
779 space = isl_union_map_get_space(gen->used_sizes);
780 space = isl_space_set_from_params(space);
781 space = isl_space_add_dims(space, isl_dim_set, 1);
782 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
783 space = isl_space_from_domain(space);
784 space = isl_space_add_dims(space, isl_dim_out, len);
785 space = isl_space_set_tuple_name(space, isl_dim_out, type);
787 map = isl_map_universe(space);
788 map = isl_map_fix_si(map, isl_dim_in, 0, id);
789 for (i = 0; i < len; ++i)
790 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
792 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
795 /* Extract user specified "tile" sizes from the "sizes" command line option,
796 * defaulting to option->tile_size in each dimension.
797 * Add the effectively used sizes to gen->used_sizes.
799 static void read_tile_sizes(struct gpu_gen *gen)
801 int n;
802 isl_set *size;
804 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
805 assert(gen->tile_size);
806 for (n = 0; n < gen->tile_len; ++n)
807 gen->tile_size[n] = gen->options->tile_size;
809 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
810 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
811 set_used_sizes(gen, "tile", gen->kernel_id,
812 gen->tile_size, gen->tile_len);
814 if (gen->n_parallel > gen->tile_len)
815 gen->n_parallel = gen->tile_len;
818 /* Extract user specified "block" sizes from the "sizes" command line option,
819 * after filling in some potentially useful defaults.
820 * Add the effectively used sizes to gen->used_sizes.
822 static void read_block_sizes(struct gpu_gen *gen)
824 int n;
825 isl_set *size;
827 n = gen->n_parallel;
828 gen->n_block = (n <= 3) ? n : 3;
829 switch (gen->n_block) {
830 case 1:
831 gen->block_dim[0] = 512;
832 break;
833 case 2:
834 gen->block_dim[0] = 32;
835 gen->block_dim[1] = 16;
836 break;
837 default:
838 gen->block_dim[0] = 32;
839 gen->block_dim[1] = 4;
840 gen->block_dim[2] = 4;
841 break;
844 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
845 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
846 set_used_sizes(gen, "block", gen->kernel_id,
847 gen->block_dim, gen->n_block);
850 /* Extract user specified "grid" sizes from the "sizes" command line option,
851 * after filling in some potentially useful defaults.
852 * Add the effectively used sizes to gen->used_sizes.
854 static void read_grid_sizes(struct gpu_gen *gen)
856 int n = gen->n_parallel;
857 isl_set *size;
859 gen->n_grid = (n <= 2) ? n : 2;
860 switch (gen->n_grid) {
861 case 1:
862 gen->grid_dim[0] = 32768;
863 break;
864 default:
865 gen->grid_dim[0] = 256;
866 gen->grid_dim[1] = 256;
867 break;
870 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
871 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
872 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
875 /* Extract user specified sizes from the "sizes" command line option
876 * after filling in some potentially useful defaults.
878 static void read_sizes(struct gpu_gen *gen)
880 read_tile_sizes(gen);
881 read_block_sizes(gen);
882 read_grid_sizes(gen);
885 static void *free_stmts(struct gpu_stmt *stmts, int n)
887 int i;
889 if (!stmts)
890 return NULL;
892 for (i = 0; i < n; ++i) {
893 struct gpu_stmt_access *access, *next;
895 for (access = stmts[i].accesses; access; access = next) {
896 next = access->next;
897 isl_id_free(access->ref_id);
898 isl_map_free(access->access);
899 isl_map_free(access->tagged_access);
900 free(access);
903 isl_id_free(stmts[i].id);
905 free(stmts);
907 return NULL;
910 /* Construct a map from a domain of dimensionality "len"
911 * to a domain of dimensionality "len" + "tile_len" that tiles
912 * the "tile_len" coordinates starting at "first".
913 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
914 * "dim" prescribes the parameters.
916 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
917 int first, int tile_len, int *tile_size)
919 int i;
920 isl_basic_map *bmap;
921 isl_constraint *c;
922 isl_local_space *ls;
924 dim = isl_space_add_dims(dim, isl_dim_in, len);
925 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
926 bmap = isl_basic_map_universe(isl_space_copy(dim));
927 ls = isl_local_space_from_space(dim);
929 for (i = 0; i < len - tile_len; ++i) {
930 int j = i < first ? i : i + tile_len;
931 int k = i < first ? i : i + 2 * tile_len;
933 c = isl_equality_alloc(isl_local_space_copy(ls));
934 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
935 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
936 bmap = isl_basic_map_add_constraint(bmap, c);
939 for (i = 0; i < tile_len; ++i) {
940 c = isl_equality_alloc(isl_local_space_copy(ls));
941 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
942 first + i, -1);
943 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
944 first + i, tile_size[i]);
945 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
946 first + i + tile_len, 1);
947 bmap = isl_basic_map_add_constraint(bmap, c);
949 c = isl_inequality_alloc(isl_local_space_copy(ls));
950 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
951 first + i + tile_len, 1);
952 bmap = isl_basic_map_add_constraint(bmap, c);
954 c = isl_inequality_alloc(isl_local_space_copy(ls));
955 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
956 first + i + tile_len, -1);
957 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
958 bmap = isl_basic_map_add_constraint(bmap, c);
961 isl_local_space_free(ls);
963 return isl_map_from_basic_map(bmap);
966 /* Construct a map from a domain of dimensionality "len"
967 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
968 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
969 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
970 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
971 * that are projected out at the end.
972 * "dim" prescribes the parameters.
974 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
975 int first, int wrap_len, int *wrap_size)
977 int i;
978 isl_basic_map *bmap;
979 isl_constraint *c;
980 isl_local_space *ls;
982 dim = isl_space_add_dims(dim, isl_dim_in, len);
983 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
984 bmap = isl_basic_map_universe(isl_space_copy(dim));
985 ls = isl_local_space_from_space(dim);
987 for (i = 0; i < len; ++i) {
988 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
990 c = isl_equality_alloc(isl_local_space_copy(ls));
991 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
992 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
993 bmap = isl_basic_map_add_constraint(bmap, c);
996 for (i = 0; i < wrap_len; ++i) {
997 c = isl_equality_alloc(isl_local_space_copy(ls));
998 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
999 first + i, -1);
1000 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1001 first + wrap_len + i, 1);
1002 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1003 first + 2 * wrap_len + i, wrap_size[i]);
1004 bmap = isl_basic_map_add_constraint(bmap, c);
1006 c = isl_inequality_alloc(isl_local_space_copy(ls));
1007 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1008 first + wrap_len + i, 1);
1009 bmap = isl_basic_map_add_constraint(bmap, c);
1011 c = isl_inequality_alloc(isl_local_space_copy(ls));
1012 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1013 first + wrap_len + i, -1);
1014 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1015 bmap = isl_basic_map_add_constraint(bmap, c);
1018 isl_local_space_free(ls);
1020 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1021 first + 2 * wrap_len, wrap_len);
1023 return isl_map_from_basic_map(bmap);
1026 /* Add parameters with identifiers "ids" to "set".
1028 static __isl_give isl_set *add_params(__isl_take isl_set *set,
1029 __isl_keep isl_id_list *ids)
1031 int i, n;
1032 unsigned nparam;
1034 n = isl_id_list_n_id(ids);
1036 nparam = isl_set_dim(set, isl_dim_param);
1037 set = isl_set_add_dims(set, isl_dim_param, n);
1039 for (i = 0; i < n; ++i) {
1040 isl_id *id;
1042 id = isl_id_list_get_id(ids, i);
1043 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1046 return set;
1049 /* Equate the dimensions of "set" starting at "first" to
1050 * freshly created parameters with identifiers "ids".
1051 * The number of equated dimensions is equal to the number of elements in "ids".
1053 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1054 int first, __isl_keep isl_id_list *ids)
1056 int i, n;
1057 unsigned nparam;
1059 nparam = isl_set_dim(set, isl_dim_param);
1061 set = add_params(set, ids);
1063 n = isl_id_list_n_id(ids);
1064 for (i = 0; i < n; ++i)
1065 set = isl_set_equate(set, isl_dim_param, nparam + i,
1066 isl_dim_set, first + i);
1068 return set;
1071 /* Given a parameter space "space", create a set of dimension "len"
1072 * of which the dimensions starting at "first" are equated to
1073 * freshly created parameters with identifiers "ids".
1075 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1076 int len, int first, __isl_keep isl_id_list *ids)
1078 isl_set *set;
1080 space = isl_space_set_from_params(space);
1081 space = isl_space_add_dims(space, isl_dim_set, len);
1082 set = isl_set_universe(space);
1084 return parametrize(set, first, ids);
1087 /* Tile the B loops over the tile sizes and then tile/wrap
1088 * the T1 loops over the blocks.
1090 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1091 __isl_take isl_union_map *sched)
1093 isl_space *dim;
1094 isl_map *tiling, *block_tiling;
1096 dim = isl_union_map_get_space(sched);
1097 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1098 gen->tile_first, gen->tile_len, gen->tile_size);
1100 if (gen->options->wrap)
1101 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1102 gen->tile_first, gen->n_grid, gen->grid_dim);
1103 else
1104 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1105 gen->tile_first, gen->n_grid, gen->grid_dim);
1107 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1109 tiling = isl_map_apply_range(tiling, block_tiling);
1111 sched = isl_union_map_apply_range(sched,
1112 isl_union_map_from_map(tiling));
1114 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1116 return sched;
1119 /* Equate the "T1P" iterators in the tiled schedule "sched"
1120 * to the block dimensions.
1122 static __isl_give isl_union_map *parametrize_tiled_schedule(
1123 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1125 isl_space *dim;
1126 isl_set *par;
1128 dim = isl_union_map_get_space(sched);
1129 par = parametrization(dim, gen->tiled_len,
1130 gen->tile_first + gen->n_grid, gen->kernel->block_ids);
1131 sched = isl_union_map_intersect_range(sched,
1132 isl_union_set_from_set(par));
1134 return sched;
1137 /* Tile/wrap the P1 loops over the threads.
1139 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1140 __isl_take isl_union_map *sched)
1142 isl_space *dim;
1143 isl_map *tiling;
1144 isl_set *par;
1146 dim = isl_union_map_get_space(sched);
1148 if (gen->options->wrap)
1149 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1150 gen->shared_len, gen->n_block, gen->block_dim);
1151 else
1152 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1153 gen->shared_len, gen->n_block, gen->block_dim);
1154 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1156 sched = isl_union_map_apply_range(sched,
1157 isl_union_map_from_map(tiling));
1159 par = parametrization(dim, gen->thread_tiled_len,
1160 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1161 gen->kernel->thread_ids);
1162 sched = isl_union_map_intersect_range(sched,
1163 isl_union_set_from_set(par));
1165 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1167 return sched;
1170 /* If the user asked for it, scale the shared memory tile loops
1171 * (T1T and T2) of "sched" by gen->tile_size[i].
1172 * If we are not performing "wrapping", then additionally scale the T1P
1173 * loops by gen->grid_dim[i].
1175 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1176 __isl_take isl_union_map *sched)
1178 int i;
1179 isl_space *dim;
1180 isl_basic_map *scale;
1181 isl_constraint *c;
1182 isl_local_space *ls;
1184 if (!gen->options->scale_tile_loops)
1185 return sched;
1187 dim = isl_union_map_get_space(sched);
1188 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1189 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1190 scale = isl_basic_map_universe(isl_space_copy(dim));
1191 ls = isl_local_space_from_space(dim);
1193 for (i = 0; i < gen->tiled_len; ++i) {
1194 int f = 1;
1196 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1197 f = gen->tile_size[i - gen->tile_first];
1198 if (!gen->options->wrap)
1199 f *= gen->grid_dim[i - gen->tile_first];
1200 } else if (i >= gen->tile_first + gen->n_grid &&
1201 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1202 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1205 c = isl_equality_alloc(isl_local_space_copy(ls));
1206 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1207 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1208 scale = isl_basic_map_add_constraint(scale, c);
1211 isl_local_space_free(ls);
1213 sched = isl_union_map_apply_range(sched,
1214 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1216 return sched;
1219 /* If we are not performing "wrapping" and if the user asked for it,
1220 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1222 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1223 __isl_take isl_union_map *sched)
1225 int i;
1226 isl_space *dim;
1227 isl_basic_map *scale;
1228 isl_constraint *c;
1229 isl_local_space *ls;
1231 if (gen->options->wrap)
1232 return sched;
1233 if (!gen->options->scale_tile_loops)
1234 return sched;
1236 dim = isl_union_map_get_space(sched);
1237 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1238 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1239 scale = isl_basic_map_universe(isl_space_copy(dim));
1240 ls = isl_local_space_from_space(dim);
1242 for (i = 0; i < gen->thread_tiled_len; ++i) {
1243 int f = 1;
1245 if (i >= gen->shared_len &&
1246 i < gen->shared_len + gen->n_block)
1247 f = gen->block_dim[i - gen->shared_len];
1249 c = isl_equality_alloc(isl_local_space_copy(ls));
1250 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1251 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1252 scale = isl_basic_map_add_constraint(scale, c);
1255 isl_local_space_free(ls);
1257 sched = isl_union_map_apply_range(sched,
1258 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1260 return sched;
1263 /* If we are not performing "wrapping" and if the user asked for it,
1264 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1266 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1267 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1269 int i;
1270 isl_space *dim;
1271 isl_basic_map *scale;
1272 isl_constraint *c;
1273 isl_local_space *ls;
1275 if (gen->options->wrap)
1276 return sched;
1277 if (!gen->options->scale_tile_loops)
1278 return sched;
1280 dim = isl_union_map_get_space(sched);
1281 dim = isl_space_add_dims(dim, isl_dim_in, len);
1282 dim = isl_space_add_dims(dim, isl_dim_out, len);
1283 scale = isl_basic_map_universe(isl_space_copy(dim));
1284 ls = isl_local_space_from_space(dim);
1286 for (i = 0; i < len; ++i) {
1287 int f = 1;
1289 if (i >= first && i < first + n_tile)
1290 f = gen->kernel->block_dim[i - first];
1292 c = isl_equality_alloc(isl_local_space_copy(ls));
1293 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1294 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1295 scale = isl_basic_map_add_constraint(scale, c);
1298 isl_local_space_free(ls);
1300 sched = isl_union_map_apply_range(sched,
1301 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1303 return sched;
1306 /* Add parameters p[i] with identifiers "ids" to "set",
1307 * with bounds to 0 <= p[i] < size[i].
1309 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1310 int *size, __isl_keep isl_id_list *ids)
1312 int i, len;
1313 unsigned nparam;
1315 len = isl_id_list_n_id(ids);
1316 nparam = isl_set_dim(set, isl_dim_param);
1317 set = isl_set_add_dims(set, isl_dim_param, len);
1319 for (i = 0; i < len; ++i) {
1320 isl_id *id;
1322 id = isl_id_list_get_id(ids, i);
1323 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1324 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
1325 set = isl_set_upper_bound_si(set, isl_dim_param,
1326 nparam + i, size[i] - 1);
1329 return set;
1332 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
1333 * with
1335 * { : 0 <= p[i] < size[i] }
1337 * or an overapproximation.
1339 static __isl_give isl_set *add_bounded_parameters_dynamic(
1340 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1341 __isl_keep isl_id_list *ids)
1343 int i, len;
1344 unsigned nparam;
1345 isl_space *space;
1346 isl_local_space *ls;
1348 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1349 nparam = isl_set_dim(set, isl_dim_param);
1350 set = isl_set_add_dims(set, isl_dim_param, len);
1352 for (i = 0; i < len; ++i) {
1353 isl_id *id;
1355 id = isl_id_list_get_id(ids, i);
1356 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1359 space = isl_space_params(isl_set_get_space(set));
1360 ls = isl_local_space_from_space(space);
1361 for (i = 0; i < len; ++i) {
1362 isl_pw_aff *param, *size_i, *zero;
1363 isl_set *bound;
1365 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1366 isl_dim_param, nparam + i);
1368 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1369 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1370 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1371 set = isl_set_intersect_params(set, bound);
1373 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1374 bound = isl_pw_aff_ge_set(param, zero);
1375 set = isl_set_intersect_params(set, bound);
1377 isl_local_space_free(ls);
1379 return set;
1382 /* Construct a map from an access to group->array to the corresponding
1383 * shared/private memory tile.
1384 * The map is of the form
1386 * { [D[i] -> A[a]] -> T[t] }
1388 * where D represents the initial shared_len dimensions
1389 * of the computed schedule.
1391 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1393 struct gpu_array_tile *tile;
1394 isl_multi_aff *tiling;
1396 tile = group->private_tile;
1397 if (!tile)
1398 tile = group->shared_tile;
1400 tiling = isl_multi_aff_copy(tile->tiling);
1402 return isl_map_from_multi_aff(tiling);
1405 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1407 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1408 unsigned pos)
1410 isl_val *v;
1411 int fixed;
1413 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1414 if (!v)
1415 return -1;
1416 fixed = isl_val_is_int(v);
1417 isl_val_free(v);
1419 return fixed;
1422 /* Given a schedule that iterates over all elements in a piece of an array,
1423 * perform tiling/wrapping over the threads.
1425 * In particular, we tile the final iterators so that the final thread
1426 * dimension runs over the final array dimension.
1427 * However, if those final iterators have only a single iteration,
1428 * we try to tile earlier iterators instead.
1430 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1431 __isl_take isl_map *sched)
1433 isl_space *dim;
1434 isl_union_map *usched;
1435 isl_map *tiling;
1436 isl_set *par;
1437 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1438 int n_tile;
1439 int first;
1441 n_tile = gen->kernel->n_block;
1442 if (n_tile > nvar) {
1443 int i;
1444 sched = isl_map_insert_dims(sched,
1445 isl_dim_out, 0, n_tile - nvar);
1446 for (i = 0; i < n_tile - nvar; ++i)
1447 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1448 nvar = n_tile;
1451 first = nvar - n_tile;
1453 for (; first > 0; first --)
1454 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1455 break;
1457 dim = isl_map_get_space(sched);
1458 dim = isl_space_params(dim);
1459 if (gen->options->wrap)
1460 tiling = wrap(isl_space_copy(dim), nvar, first,
1461 n_tile, gen->kernel->block_dim);
1462 else
1463 tiling = tile(isl_space_copy(dim), nvar, first,
1464 n_tile, gen->kernel->block_dim);
1465 sched = isl_map_apply_range(sched, tiling);
1467 par = parametrization(dim, nvar + n_tile, first + n_tile,
1468 gen->kernel->thread_ids);
1469 sched = isl_map_intersect_range(sched, par);
1471 usched = isl_union_map_from_map(sched);
1472 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1473 first, n_tile);
1474 sched = isl_map_from_union_map(usched);
1476 return sched;
1479 /* Return the union of all read (read = 1) and/or write (write = 1)
1480 * access relations in the group.
1482 static __isl_give isl_union_map *group_access_relation(
1483 struct gpu_array_ref_group *group, int read, int write)
1485 int i;
1486 isl_union_map *access;
1488 access = isl_union_map_empty(isl_map_get_space(group->access));
1489 for (i = 0; i < group->n_ref; ++i) {
1490 isl_map *map_i;
1492 if (!((read && group->refs[i]->read) ||
1493 (write && group->refs[i]->write)))
1494 continue;
1495 map_i = isl_map_copy(group->refs[i]->access);
1496 access = isl_union_map_union(access,
1497 isl_union_map_from_map(map_i));
1500 return access;
1503 /* Return the union of all tagged access relations in the group.
1505 static __isl_give isl_union_map *group_tagged_access_relation(
1506 struct gpu_array_ref_group *group)
1508 int i;
1509 isl_union_map *access;
1511 access = isl_union_map_empty(isl_map_get_space(group->access));
1512 for (i = 0; i < group->n_ref; ++i) {
1513 isl_map *map_i;
1515 map_i = isl_map_copy(group->refs[i]->tagged_access);
1516 access = isl_union_map_union(access,
1517 isl_union_map_from_map(map_i));
1520 return access;
1523 /* Return the extent of "array", recomputed from the bounds.
1524 * The recomputed extent may be simpler than the original extent.
1526 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1528 int i;
1529 isl_id *id;
1530 isl_space *space;
1531 isl_local_space *ls;
1532 isl_set *extent;
1534 id = isl_set_get_tuple_id(array->extent);
1535 space = isl_set_get_space(array->extent);
1536 extent = isl_set_universe(isl_space_copy(space));
1537 ls = isl_local_space_from_space(space);
1538 for (i = 0; i < array->n_index; ++i) {
1539 isl_pw_aff *bound;
1540 isl_aff *aff;
1541 isl_pw_aff *index;
1542 isl_set *lt;
1544 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1546 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1547 isl_dim_set, i);
1548 index = isl_pw_aff_from_aff(aff);
1549 bound = isl_pw_aff_copy(array->bound[i]);
1550 bound = isl_pw_aff_from_range(bound);
1551 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1552 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1553 isl_id_copy(id));
1554 lt = isl_pw_aff_lt_set(index, bound);
1555 extent = isl_set_intersect(extent, lt);
1557 isl_local_space_free(ls);
1558 isl_id_free(id);
1560 return extent;
1563 /* Return a map from the first shared_len dimensions of the computed
1564 * schedule to the array tile in
1565 * global memory that corresponds to the shared memory copy.
1567 * In particular, return a map
1569 * { D[i] -> A[a] }
1571 * with constraints
1573 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1575 * and
1577 * 0 <= a <= array_size - 1 (2)
1579 * Note that if some stride has been detected (i.e., when
1580 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1581 * to the shifted and scaled down version.
1583 * Constraints (1) are obtained by mapping the size constraints on the
1584 * shared/private memory tile back to the access relation.
1585 * Constraints (2) are obtained from the (recomputed) extent.
1587 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1589 int i;
1590 int n_index = group->array->n_index;
1591 isl_map *tile;
1592 isl_space *space;
1593 isl_set *local;
1594 isl_set *extent;
1596 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1597 space = isl_space_range(space);
1598 local = isl_set_universe(space);
1599 for (i = 0; i < n_index; ++i) {
1600 isl_val *bound;
1602 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1603 bound = isl_val_copy(group->shared_tile->bound[i].size);
1604 bound = isl_val_sub_ui(bound, 1);
1605 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1607 local = isl_set_preimage_multi_aff(local,
1608 isl_multi_aff_copy(group->shared_tile->tiling));
1609 tile = isl_set_unwrap(local);
1610 extent = array_extent(group->array);
1611 tile = isl_map_intersect_range(tile, extent);
1613 return tile;
1616 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1617 * return the corresponding mapping from the AST schedule to
1618 * to the first shared_len dimensions of the schedule computed by PPCG.
1620 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1621 __isl_take isl_pw_multi_aff *iterator_map)
1623 isl_union_map *umap;
1624 isl_space *space;
1625 isl_map *map, *sched;;
1627 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1628 space = isl_space_from_domain(space);
1629 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1631 umap = isl_union_map_copy(gen->shared_sched);
1632 umap = isl_union_map_apply_range(umap,
1633 isl_union_map_copy(gen->shared_proj));
1634 map = isl_union_map_extract_map(umap, space);
1635 isl_union_map_free(umap);
1637 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1638 sched = isl_map_detect_equalities(sched);
1640 return isl_pw_multi_aff_from_map(sched);
1643 /* Set unroll[j] if the input dimension j is involved in
1644 * the index expression represented by ma.
1646 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1647 void *user)
1649 int i, j;
1650 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1651 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1652 int *unroll = user;
1654 for (i = 0; i < n_out; ++i) {
1655 isl_aff *aff;
1657 aff = isl_multi_aff_get_aff(ma, i);
1658 for (j = 0; j < n_in; ++j)
1659 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1660 unroll[j] = 1;
1661 isl_aff_free(aff);
1664 isl_set_free(set);
1665 isl_multi_aff_free(ma);
1666 return 0;
1669 /* Given an array pos mapping input dimensions to the corresponding
1670 * output dimension, construct the corresponding map.
1672 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1673 int *pos, int len)
1675 int i;
1676 isl_constraint *c;
1677 isl_basic_map *bmap;
1678 isl_local_space *ls;
1680 dim = isl_space_add_dims(dim, isl_dim_in, len);
1681 dim = isl_space_add_dims(dim, isl_dim_out, len);
1682 bmap = isl_basic_map_universe(isl_space_copy(dim));
1683 ls = isl_local_space_from_space(dim);
1685 for (i = 0; i < len; ++i) {
1686 c = isl_equality_alloc(isl_local_space_copy(ls));
1687 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1688 -1);
1689 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1691 bmap = isl_basic_map_add_constraint(bmap, c);
1693 isl_local_space_free(ls);
1695 return isl_map_from_basic_map(bmap);
1698 /* Remove the private tiles from all array reference groups,
1699 * except for the groups of arrays that are marked force_private.
1701 static void remove_private_tiles(struct gpu_gen *gen)
1703 int i, j;
1705 for (i = 0; i < gen->prog->n_array; ++i) {
1706 struct gpu_array_info *array = &gen->prog->array[i];
1708 if (array->force_private)
1709 continue;
1711 for (j = 0; j < array->n_group; ++j) {
1712 struct gpu_array_ref_group *group = array->groups[j];
1714 group->private_tile = free_tile(group->private_tile);
1719 /* Find all loops involved in any of the index expressions for any of
1720 * the private accesses, move them innermost and then mark them as
1721 * requiring unrolling by setting gen->first_unroll.
1722 * The loops involved should all be parallel because of the checks
1723 * we performed in check_private_group_access. Moving them innermost
1724 * is therefore a valid transformation.
1726 * If any of the arrays are marked force_private, however, then
1727 * those loops may not be parallel with respect to the marked arrays.
1728 * If any of the loops would have to be moved innermost for the
1729 * (non forced) private accesses and if there are any force_private
1730 * arrays, then we revert the decision to map the selected arrays
1731 * to private memory. An alternative solution would be to expand
1732 * the force_private arrays.
1734 * Loops up to gen->shared_len are generated before the mapping to
1735 * threads is applied. They should therefore be ignored.
1737 * We compute the hidden equalities of the schedule first
1738 * since we will need them in our calls to isl_pw_multi_aff_from_map
1739 * and because we want to make sure that the same equalities
1740 * are also available to the code generator.
1742 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1743 __isl_take isl_union_map *sched)
1745 int i, j;
1746 int unroll[gen->thread_tiled_len];
1747 int perm[gen->thread_tiled_len];
1748 isl_space *dim;
1749 isl_map *permute;
1750 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1752 gen->first_unroll = -1;
1754 sched = isl_union_map_detect_equalities(sched);
1755 for (i = 0; i < gen->thread_tiled_len; ++i)
1756 unroll[i] = 0;
1757 for (i = 0; i < gen->prog->n_array; ++i) {
1758 struct gpu_array_info *array = &gen->prog->array[i];
1760 for (j = 0; j < array->n_group; ++j) {
1761 isl_union_map *access;
1762 isl_map *acc;
1763 isl_pw_multi_aff *pma;
1765 if (!array->groups[j]->private_tile)
1766 continue;
1768 access = group_access_relation(array->groups[j], 1, 1);
1769 access = isl_union_map_apply_domain(access,
1770 isl_union_map_copy(sched));
1772 acc = isl_map_from_union_map(access);
1773 pma = isl_pw_multi_aff_from_map(acc);
1774 isl_pw_multi_aff_foreach_piece(pma,
1775 &check_unroll, unroll);
1777 isl_pw_multi_aff_free(pma);
1781 for (i = gen->shared_len; i < len; ++i)
1782 if (unroll[i])
1783 break;
1785 if (i >= len)
1786 return sched;
1788 for (i = len; i < gen->thread_tiled_len; ++i)
1789 if (unroll[i])
1790 return sched;
1792 if (gen->any_force_private) {
1793 remove_private_tiles(gen);
1794 return sched;
1797 j = 0;
1798 for (i = 0; i < gen->shared_len; ++i)
1799 perm[i] = j++;
1800 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1801 if (!unroll[i])
1802 perm[i] = j++;
1803 gen->first_unroll = j - gen->shared_len;
1804 for (i = gen->shared_len; i < len; ++i)
1805 if (unroll[i])
1806 perm[i] = j++;
1808 dim = isl_union_map_get_space(sched);
1809 permute = permutation(dim, perm, gen->thread_tiled_len);
1810 sched = isl_union_map_apply_range(sched,
1811 isl_union_map_from_map(permute));
1813 return sched;
1816 /* Given a constraint
1818 * a(p,i) + j = g f(e)
1820 * or -a(p,i) - j = g f(e) if sign < 0,
1821 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1822 * a(p,i) is assumed to be an expression in only the parameters
1823 * and the input dimensions.
1825 static void extract_stride(__isl_keep isl_constraint *c,
1826 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1828 int i;
1829 isl_val *v;
1830 isl_space *space;
1831 unsigned nparam;
1832 unsigned nvar;
1833 isl_aff *aff;
1835 isl_val_free(bound->stride);
1836 bound->stride = isl_val_copy(stride);
1838 space = isl_constraint_get_space(c);
1839 space = isl_space_domain(space);
1841 nparam = isl_space_dim(space, isl_dim_param);
1842 nvar = isl_space_dim(space, isl_dim_set);
1844 v = isl_constraint_get_constant_val(c);
1845 if (sign < 0)
1846 v = isl_val_neg(v);
1847 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1848 aff = isl_aff_set_constant_val(aff, v);
1850 for (i = 0; i < nparam; ++i) {
1851 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1852 continue;
1853 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1854 if (sign < 0)
1855 v = isl_val_neg(v);
1856 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1859 for (i = 0; i < nvar; ++i) {
1860 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1861 continue;
1862 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1863 if (sign < 0)
1864 v = isl_val_neg(v);
1865 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1868 bound->shift = aff;
1871 /* Given an equality constraint of a map with a single output dimension j,
1872 * check if the constraint is of the form
1874 * a(p,i) + j = g f(e)
1876 * with a(p,i) an expression in the parameters and input dimensions
1877 * and f(e) an expression in the existentially quantified variables.
1878 * If so, and if g is larger than any such g from a previously considered
1879 * constraint, then call extract_stride to record the stride information
1880 * in bound.
1882 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1884 int i;
1885 isl_ctx *ctx;
1886 isl_val *v;
1887 unsigned n_div;
1888 struct gpu_array_bound *bound = user;
1890 ctx = isl_constraint_get_ctx(c);
1891 n_div = isl_constraint_dim(c, isl_dim_div);
1892 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1894 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1895 int s = isl_val_sgn(v);
1896 isl_val *stride = isl_val_zero(ctx);
1898 isl_val_free(v);
1899 for (i = 0; i < n_div; ++i) {
1900 v = isl_constraint_get_coefficient_val(c,
1901 isl_dim_div, i);
1902 stride = isl_val_gcd(stride, v);
1904 if (!isl_val_is_zero(stride) &&
1905 isl_val_gt(stride, bound->stride))
1906 extract_stride(c, bound, stride, s);
1908 isl_val_free(stride);
1909 } else
1910 isl_val_free(v);
1912 isl_constraint_free(c);
1913 return 0;
1916 /* Given contraints on an array index i, check if we can find
1917 * a shift a(p) and a stride g such that
1919 * a(p) + i = 0 mod g
1921 * If so, record the information in bound and apply the mapping
1922 * i -> (i + a(p))/g to the array index in bounds and return
1923 * the new constraints.
1924 * If not, simply return the original constraints.
1926 * If bounds is a subset of the space
1928 * D -> i
1930 * then the bound recorded in bound->shift is of the form
1932 * D -> s(D)
1934 * with s(D) equal to a(p) above.
1935 * Next, we construct a mapping of the form
1937 * [D -> i] -> [D -> (i + S(D))/g]
1939 * This mapping is computed as follows.
1940 * We first introduce "i" in the domain through precomposition
1941 * with [D -> i] -> D obtaining
1943 * [D -> i] -> s(D)
1945 * Adding [D -> i] -> i produces
1947 * [D -> i] -> i + s(D)
1949 * and the domain product with [D -> i] -> D yields
1951 * [D -> i] -> [D -> i + s(D)]
1953 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1955 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1956 __isl_take isl_basic_map *bounds)
1958 isl_space *space;
1959 isl_basic_map *hull;
1960 isl_basic_map *shift, *id, *bmap, *scale;
1961 isl_basic_set *bset;
1962 isl_aff *aff;
1964 bound->stride = NULL;
1966 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1968 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1970 isl_basic_map_free(hull);
1972 if (!bound->stride)
1973 return bounds;
1975 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1976 space = isl_basic_map_get_space(bounds);
1977 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1978 shift = isl_basic_map_apply_range(bmap, shift);
1979 space = isl_basic_map_get_space(bounds);
1980 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1981 shift = isl_basic_map_sum(id, shift);
1982 space = isl_basic_map_get_space(bounds);
1983 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1984 shift = isl_basic_map_range_product(id, shift);
1986 space = isl_space_domain(isl_basic_map_get_space(bounds));
1987 id = isl_basic_map_identity(isl_space_map_from_set(space));
1988 space = isl_space_range(isl_basic_map_get_space(bounds));
1989 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1990 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1991 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1992 scale = isl_basic_map_from_aff(aff);
1993 scale = isl_basic_map_product(id, scale);
1995 bmap = isl_basic_map_apply_range(shift, scale);
1996 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1997 bounds = isl_basic_set_unwrap(bset);
1999 return bounds;
2002 /* Data used in compute_array_dim_size and compute_size_in_direction.
2004 * pos is the position of the variable representing the array index,
2005 * i.e., the variable for which want to compute the size. This variable
2006 * is also the last variable in the set.
2008 struct gpu_size_info {
2009 isl_basic_set *bset;
2010 struct gpu_array_bound *bound;
2011 int pos;
2014 /* Given a constraint from the basic set describing the bounds on
2015 * an array index, check if it is a lower bound, say m i >= b(x), and,
2016 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2017 * upper bound. If so, and if this bound is smaller than any bound
2018 * derived from earlier constraints, set the size to this bound on
2019 * the expression and the lower bound to ceil(b(x)/m).
2021 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2023 struct gpu_size_info *size = user;
2024 unsigned nparam;
2025 unsigned n_div;
2026 isl_val *v;
2027 isl_aff *aff;
2028 isl_aff *lb;
2030 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2031 n_div = isl_constraint_dim(c, isl_dim_div);
2033 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2034 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2035 isl_constraint_free(c);
2036 return 0;
2039 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2040 aff = isl_aff_ceil(aff);
2042 lb = isl_aff_copy(aff);
2044 aff = isl_aff_neg(aff);
2045 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2047 v = isl_basic_set_max_val(size->bset, aff);
2048 isl_aff_free(aff);
2050 if (isl_val_is_int(v)) {
2051 v = isl_val_add_ui(v, 1);
2052 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2053 isl_val_free(size->bound->size);
2054 size->bound->size = isl_val_copy(v);
2055 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2056 isl_aff_free(size->bound->lb);
2057 size->bound->lb = isl_aff_copy(lb);
2060 isl_val_free(v);
2061 isl_aff_free(lb);
2063 isl_constraint_free(c);
2065 return 0;
2068 /* Given a basic map "bounds" that maps parameters and input dimensions
2069 * to a single output dimension, look for an expression in the parameters
2070 * and input dimensions such that the range of the output dimension shifted
2071 * by this expression is a constant.
2073 * In particular, we currently only consider lower bounds on the output
2074 * dimension as candidate expressions.
2076 static int compute_array_dim_size(struct gpu_array_bound *bound,
2077 __isl_take isl_basic_map *bounds)
2079 struct gpu_size_info size;
2081 bounds = isl_basic_map_detect_equalities(bounds);
2082 bounds = check_stride(bound, bounds);
2084 bound->size = NULL;
2085 bound->lb = NULL;
2087 size.bound = bound;
2088 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2089 size.bset = isl_basic_map_wrap(bounds);
2090 size.bset = isl_basic_set_flatten(size.bset);
2091 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2092 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2093 &size);
2094 isl_basic_set_free(size.bset);
2096 return bound->size ? 0 : -1;
2099 /* Check if we can find a memory tile for the given array
2100 * based on the given accesses, and if so, put the results in "tile".
2102 * We project the accesses on each index in turn and look for a parametric
2103 * offset such that the size is constant.
2105 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2107 int i;
2109 for (i = 0; i < tile->n; ++i) {
2110 isl_map *access_i;
2111 isl_basic_map *hull;
2113 access_i = isl_map_copy(access);
2114 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2115 access_i = isl_map_project_out(access_i, isl_dim_out,
2116 1, tile->n - (i + 1));
2117 access_i = isl_map_compute_divs(access_i);
2118 hull = isl_map_simple_hull(access_i);
2119 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2120 return 0;
2123 return 1;
2126 /* Construct a map with input the shared tile loops and the loops that
2127 * will be wrapped around the threads that relates these later loops
2128 * to the thread indices and then projects them out.
2130 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2132 isl_map *priv;
2133 isl_map *tiling;
2134 isl_map *proj;
2135 isl_set *par;
2136 isl_space *dim;
2138 dim = isl_union_map_get_space(gen->shared_sched);
2140 if (gen->options->wrap)
2141 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2142 gen->shared_len, gen->n_block, gen->block_dim);
2143 else
2144 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2145 gen->shared_len, gen->n_block, gen->block_dim);
2147 priv = tiling;
2149 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2150 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2151 gen->kernel->thread_ids);
2153 priv = isl_map_align_params(priv, isl_set_get_space(par));
2154 priv = isl_map_intersect_range(priv, par);
2156 dim = isl_map_get_space(priv);
2157 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2158 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2159 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2160 gen->shared_len);
2162 priv = isl_map_apply_range(priv, proj);
2164 return priv;
2167 /* Construct a map from domain_dim to domain_dim that increments
2168 * the dimension at position "pos" and leaves all other dimensions
2169 * constant.
2171 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2173 int i;
2174 int len = isl_space_dim(domain_dim, isl_dim_set);
2175 isl_space *dim;
2176 isl_basic_map *next;
2177 isl_local_space *ls;
2179 dim = isl_space_map_from_set(domain_dim);
2180 next = isl_basic_map_universe(isl_space_copy(dim));
2181 ls = isl_local_space_from_space(dim);
2183 for (i = 0; i < len; ++i) {
2184 isl_constraint *c;
2186 c = isl_equality_alloc(isl_local_space_copy(ls));
2187 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2188 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2189 if (i == pos)
2190 c = isl_constraint_set_constant_si(c, 1);
2191 next = isl_basic_map_add_constraint(next, c);
2194 isl_local_space_free(ls);
2196 return isl_map_from_basic_map(next);
2199 /* Check if the given access is coalesced.
2200 * That is, check whether incrementing the dimension that will get
2201 * wrapped over the last thread index results in incrementing
2202 * the last array index.
2204 * This function is only called for access relations without reuse and
2205 * kernels with at least one block dimension.
2207 static int access_is_coalesced(struct gpu_gen *gen,
2208 __isl_keep isl_union_map *access)
2210 isl_space *dim;
2211 isl_map *access_map;
2212 isl_map *next_thread_x;
2213 isl_map *next_element;
2214 isl_map *map;
2215 int coalesced;
2217 access = isl_union_map_copy(access);
2218 access = isl_union_map_apply_domain(access,
2219 isl_union_map_copy(gen->tiled_sched));
2220 access_map = isl_map_from_union_map(access);
2222 dim = isl_map_get_space(access_map);
2223 dim = isl_space_domain(dim);
2224 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2226 dim = isl_map_get_space(access_map);
2227 dim = isl_space_range(dim);
2228 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2230 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2231 map = isl_map_apply_range(map, access_map);
2233 coalesced = isl_map_is_subset(map, next_element);
2235 isl_map_free(next_element);
2236 isl_map_free(map);
2238 return coalesced;
2241 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2242 * dimensions of the computed schedule, check if it is bijective for
2243 * fixed values of the first gen->shared_len dimensions.
2244 * We perform this check by equating these dimensions to parameters.
2246 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2248 int res;
2249 isl_set *par;
2250 isl_space *space;
2251 isl_id_list *ids;
2253 access = isl_map_copy(access);
2254 space = isl_space_params(isl_map_get_space(access));
2255 ids = ppcg_scop_generate_names(gen->prog->scop, gen->shared_len, "s");
2256 par = parametrization(space, gen->shared_len + gen->n_block, 0, ids);
2257 isl_id_list_free(ids);
2258 access = isl_map_intersect_domain(access, par);
2259 res = isl_map_is_bijective(access);
2260 isl_map_free(access);
2262 return res;
2265 /* Look for the last shared tile loop that affects the offset of "tile"
2266 * and return the result.
2267 * If there is no such loop, then return the index of the loop
2268 * before the first shared tile loop, in particular gen->tile_first - 1.
2270 static int compute_tile_last_shared(struct gpu_gen *gen,
2271 struct gpu_array_tile *tile)
2273 int i, j;
2275 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2276 for (i = 0; i < tile->n; ++i) {
2277 isl_aff *lb;
2278 isl_aff *shift;
2280 lb = tile->bound[i].lb;
2281 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2282 break;
2284 shift = tile->bound[i].shift;
2285 if (!shift)
2286 continue;
2287 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2288 break;
2290 if (i < tile->n)
2291 break;
2294 return j;
2297 /* Look for the last shared tile loop that affects the offset of the
2298 * shared or private tile and store the result in group->last_shared.
2299 * If there is no such loop, then group->last_shared is set to a value
2300 * before the first shared tile loop, in particular gen->tile_first - 1.
2301 * If there is no tile defined on the array reference group,
2302 * then set group->last_shared to gen->shared_len - 1.
2304 static void set_last_shared(struct gpu_gen *gen,
2305 struct gpu_array_ref_group *group)
2307 struct gpu_array_tile *tile;
2309 group->last_shared = gen->shared_len - 1;
2311 tile = group->private_tile;
2312 if (!tile)
2313 tile = group->shared_tile;
2314 if (!tile)
2315 return;
2317 group->last_shared = compute_tile_last_shared(gen, tile);
2320 /* Compute the size of the tile specified by "tile"
2321 * in number of elements and return the result.
2323 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2325 int i;
2326 isl_val *size;
2328 size = isl_val_one(ctx);
2330 for (i = 0; i < tile->n; ++i)
2331 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2333 return size;
2336 /* If max_shared_memory is not set to infinity (-1), then make
2337 * sure that the total amount of shared memory required by the
2338 * array reference groups mapped to shared memory is no larger
2339 * than this maximum.
2341 * We apply a greedy approach and discard (keep in global memory)
2342 * those groups that would result in a total memory size that
2343 * is larger than the maximum.
2345 * This function should be called after any function that may
2346 * affect the decision on whether to place a reference group
2347 * in private, shared or global memory.
2349 static void check_shared_memory_bound(struct gpu_gen *gen)
2351 int i, j;
2352 isl_val *left, *size;
2354 if (gen->options->max_shared_memory < 0)
2355 return;
2357 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2359 for (i = 0; i < gen->prog->n_array; ++i) {
2360 struct gpu_array_info *array = &gen->prog->array[i];
2362 for (j = 0; j < array->n_group; ++j) {
2363 struct gpu_array_ref_group *group;
2365 group = array->groups[j];
2366 if (group->private_tile)
2367 continue;
2368 if (!group->shared_tile)
2369 continue;
2371 size = tile_size(gen->ctx, group->shared_tile);
2372 size = isl_val_mul_ui(size, array->size);
2374 if (isl_val_le(size, left)) {
2375 left = isl_val_sub(left, size);
2376 continue;
2378 isl_val_free(size);
2380 group->shared_tile = free_tile(group->shared_tile);
2384 isl_val_free(left);
2387 /* Given a description of an array tile "tile" and the "space"
2389 * { D -> A }
2391 * where D represents the first shared_len schedule dimensions
2392 * and A represents the array, construct an isl_multi_aff
2394 * { [D[i] -> A[a]] -> A'[a'] }
2396 * with A' a scaled down copy of A according to the shifts and strides
2397 * in "tile". In particular,
2399 * a' = (a + shift(i))/stride
2401 * "insert_array" represents
2403 * { [D -> A] -> D }
2405 * and is used to insert A into the domain of functions that only
2406 * reference D.
2408 static __isl_give isl_multi_aff *strided_tile(
2409 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2410 __isl_keep isl_multi_aff *insert_array)
2412 int i;
2413 isl_ctx *ctx;
2414 isl_multi_aff *shift;
2415 isl_multi_val *stride;
2416 isl_space *space2;
2417 isl_local_space *ls;
2418 isl_multi_aff *tiling;
2420 ctx = isl_space_get_ctx(space);
2421 space2 = isl_space_domain(isl_space_copy(space));
2422 ls = isl_local_space_from_space(space2);
2423 space2 = isl_space_range(isl_space_copy(space));
2424 stride = isl_multi_val_zero(space2);
2425 shift = isl_multi_aff_zero(isl_space_copy(space));
2427 for (i = 0; i < tile->n; ++i) {
2428 struct gpu_array_bound *bound = &tile->bound[i];
2429 isl_val *stride_i;
2430 isl_aff *shift_i;
2432 if (tile->bound[i].shift) {
2433 stride_i = isl_val_copy(bound->stride);
2434 shift_i = isl_aff_copy(bound->shift);
2435 } else {
2436 stride_i = isl_val_one(ctx);
2437 shift_i = isl_aff_zero_on_domain(
2438 isl_local_space_copy(ls));
2441 stride = isl_multi_val_set_val(stride, i, stride_i);
2442 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2444 isl_local_space_free(ls);
2446 shift = isl_multi_aff_pullback_multi_aff(shift,
2447 isl_multi_aff_copy(insert_array));
2449 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2450 tiling = isl_multi_aff_add(tiling, shift);
2451 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2453 return tiling;
2456 /* Compute a tiling for the array reference group "group".
2458 * The tiling is of the form
2460 * { [D[i] -> A[a]] -> T[t] }
2462 * where D represents the first shared_len schedule dimensions,
2463 * A represents the global array and T represents the shared or
2464 * private memory tile. The name of T is the name of the local
2465 * array.
2467 * If there is any stride in the accesses, then the mapping is
2469 * t = (a + shift(i))/stride - lb(i)
2471 * otherwise, it is simply
2473 * t = a - lb(i)
2475 static void compute_group_tiling(struct gpu_array_ref_group *group)
2477 int i;
2478 struct gpu_array_tile *tile;
2479 struct gpu_array_info *array = group->array;
2480 isl_space *space;
2481 isl_multi_aff *tiling, *lb, *insert_array;
2482 isl_printer *p;
2483 char *local_name;
2485 tile = group->private_tile;
2486 if (!tile)
2487 tile = group->shared_tile;
2488 if (!tile)
2489 return;
2491 space = isl_map_get_space(group->access);
2492 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2494 for (i = 0; i < tile->n; ++i)
2495 if (tile->bound[i].shift)
2496 break;
2498 if (i < tile->n)
2499 tiling = strided_tile(tile, space, insert_array);
2500 else
2501 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2503 lb = isl_multi_aff_zero(space);
2504 for (i = 0; i < tile->n; ++i) {
2505 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2506 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2508 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2510 tiling = isl_multi_aff_sub(tiling, lb);
2512 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2513 p = print_array_name(p, group);
2514 local_name = isl_printer_get_str(p);
2515 isl_printer_free(p);
2516 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2517 free(local_name);
2519 tile->tiling = tiling;
2522 /* Compute a tiling for all the array reference groups.
2524 static void compute_group_tilings(struct gpu_gen *gen)
2526 int i, j;
2528 for (i = 0; i < gen->prog->n_array; ++i) {
2529 struct gpu_array_info *array = &gen->prog->array[i];
2531 for (j = 0; j < array->n_group; ++j)
2532 compute_group_tiling(array->groups[j]);
2536 /* Fill up the groups array with singleton groups, i.e., one group
2537 * per reference, initializing the array, access, write, n_ref and refs fields.
2538 * In particular the access field is initialized to the scheduled
2539 * access relation of the array reference.
2541 * Return the number of elements initialized, i.e., the number of
2542 * active references in the current kernel.
2544 static int populate_array_references(struct gpu_array_info *array,
2545 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2547 int i;
2548 int n;
2549 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2551 n = 0;
2552 for (i = 0; i < array->n_ref; ++i) {
2553 isl_union_map *umap;
2554 isl_map *map;
2555 struct gpu_array_ref_group *group;
2556 struct gpu_stmt_access *access = array->refs[i];
2558 map = isl_map_copy(access->access);
2559 umap = isl_union_map_from_map(map);
2560 umap = isl_union_map_apply_domain(umap,
2561 isl_union_map_copy(sched));
2563 if (isl_union_map_is_empty(umap)) {
2564 isl_union_map_free(umap);
2565 continue;
2568 map = isl_map_from_union_map(umap);
2569 map = isl_map_detect_equalities(map);
2571 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2572 assert(group);
2573 group->array = array;
2574 group->access = map;
2575 group->write = access->write;
2576 group->exact_write = access->exact_write;
2577 group->slice = access->n_index < array->n_index;
2578 group->refs = &array->refs[i];
2579 group->n_ref = 1;
2581 groups[n++] = group;
2584 return n;
2587 /* If group->n_ref == 1, then group->refs was set by
2588 * populate_array_references to point directly into
2589 * group->array->refs and should not be freed.
2590 * If group->n_ref > 1, then group->refs was set by join_groups
2591 * to point to a newly allocated array.
2593 static void free_array_ref_group(struct gpu_array_ref_group *group)
2595 if (!group)
2596 return;
2597 free_tile(group->shared_tile);
2598 free_tile(group->private_tile);
2599 isl_map_free(group->access);
2600 if (group->n_ref > 1)
2601 free(group->refs);
2602 free(group);
2605 /* Given a map where the input dimensions represent the tile loops,
2606 * eliminate the innermost of those that have a fixed value
2607 * until we reach one that does not (obviously) have a fixed value.
2609 static __isl_give isl_map *eliminate_fixed_inner_loops(
2610 __isl_take isl_map *access)
2612 int i, n;
2614 n = isl_map_dim(access, isl_dim_in);
2616 for (i = n - 1; i >= 0; --i) {
2617 if (!map_plain_is_fixed(access, isl_dim_in, i))
2618 break;
2619 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2621 return access;
2624 /* Check if the access relations of group1 and group2 overlap within
2625 * the innermost loop. In particular, ignore any inner dimension
2626 * with a fixed value.
2627 * The copying to and from shared memory will be performed within
2628 * the innermost actual loop so we are only allowed to consider
2629 * the dimensions up to that innermost loop while checking whether
2630 * two access relations overlap.
2632 static int accesses_overlap(struct gpu_array_ref_group *group1,
2633 struct gpu_array_ref_group *group2)
2635 int empty;
2636 isl_map *access1, *access2;
2638 access1 = isl_map_copy(group1->access);
2639 access1 = eliminate_fixed_inner_loops(access1);
2640 access2 = isl_map_copy(group2->access);
2641 access2 = eliminate_fixed_inner_loops(access2);
2642 access1 = isl_map_intersect(access1, access2);
2643 empty = isl_map_is_empty(access1);
2644 isl_map_free(access1);
2646 return !empty;
2649 /* Combine the given two groups into a single group, containing
2650 * the references of both groups.
2652 static struct gpu_array_ref_group *join_groups(
2653 struct gpu_array_ref_group *group1,
2654 struct gpu_array_ref_group *group2)
2656 int i;
2657 isl_ctx *ctx;
2658 struct gpu_array_ref_group *group;
2660 ctx = isl_map_get_ctx(group1->access);
2661 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2662 assert(group);
2663 group->array = group1->array;
2664 group->access = isl_map_union(isl_map_copy(group1->access),
2665 isl_map_copy(group2->access));
2666 group->write = group1->write || group2->write;
2667 group->exact_write = group1->exact_write && group2->exact_write;
2668 group->slice = group1->slice || group2->slice;
2669 group->n_ref = group1->n_ref + group2->n_ref;
2670 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2671 group->n_ref);
2672 assert(group->refs);
2673 for (i = 0; i < group1->n_ref; ++i)
2674 group->refs[i] = group1->refs[i];
2675 for (i = 0; i < group2->n_ref; ++i)
2676 group->refs[group1->n_ref + i] = group2->refs[i];
2678 return group;
2681 /* Combine the given two groups into a single group and free
2682 * the original two groups.
2684 static struct gpu_array_ref_group *join_groups_and_free(
2685 struct gpu_array_ref_group *group1,
2686 struct gpu_array_ref_group *group2)
2688 struct gpu_array_ref_group *group;
2690 group = join_groups(group1, group2);
2691 free_array_ref_group(group1);
2692 free_array_ref_group(group2);
2693 return group;
2696 /* Report that the array reference group with the given access relation
2697 * is not mapped to shared memory in the given kernel because
2698 * it does not exhibit any reuse and is considered to be coalesced.
2700 static void report_no_reuse_and_coalesced(struct ppcg_kernel *kernel,
2701 __isl_keep isl_union_map *access)
2703 isl_ctx *ctx;
2704 isl_printer *p;
2706 ctx = isl_union_map_get_ctx(access);
2707 p = isl_printer_to_file(ctx, stdout);
2708 p = isl_printer_print_str(p, "Array reference group ");
2709 p = isl_printer_print_union_map(p, access);
2710 p = isl_printer_print_str(p,
2711 " not considered for mapping to shared memory in kernel");
2712 p = isl_printer_print_int(p, kernel->id);
2713 p = isl_printer_print_str(p,
2714 " because it exhibits no reuse and is considered to be coalesced");
2715 p = isl_printer_end_line(p);
2716 isl_printer_free(p);
2719 /* Compute the private and/or shared memory tiles for the array
2720 * reference group "group" of array "array".
2721 * Return 0 on success and -1 on error.
2723 * If the array is a read-only scalar or if the user requested
2724 * not to use shared or private memory, then we do not need to do anything.
2726 * If any reference in the reference group accesses more than one element,
2727 * then we would have to make sure that the layout in shared memory
2728 * is the same as that in global memory. Since we do not handle this yet
2729 * (and it may not even be possible), we refuse to map to private or
2730 * shared memory in such cases.
2732 * If the array group involves any may writes (that are not must writes),
2733 * then we would have to make sure that we load the data into shared/private
2734 * memory first in case the data is not written by the kernel
2735 * (but still written back out to global memory).
2736 * Since we don't have any such mechanism at the moment, we don't
2737 * compute shared/private tiles for groups involving may writes.
2739 * We only try to compute a shared memory tile if there is any reuse
2740 * or if the access is not coalesced.
2742 * For computing a private memory tile, we also require that there is
2743 * some reuse. Moreover, we require that the access is private
2744 * to the thread. That is, we check that any given array element
2745 * is only accessed by a single thread.
2746 * We compute an access relation that maps the shared tile loop iterators
2747 * and the shared point loop iterators that will be wrapped over the
2748 * threads to the array elements.
2749 * We actually check that those iterators that will be wrapped
2750 * partition the array space. This check is stricter than necessary
2751 * since several iterations may be mapped onto the same thread
2752 * and then they could be allowed to access the same memory elements,
2753 * but our check does not allow this situation.
2755 * We also check that the index expression only depends on parallel
2756 * loops. That way, we can move those loops innermost and unroll them.
2757 * Again, we use a test that is stricter than necessary.
2758 * We actually check whether the index expression only depends
2759 * on the iterators that are wrapped over the threads.
2760 * These are necessarily parallel, but there may be more parallel loops.
2762 * Combining the injectivity of the first test with the single-valuedness
2763 * of the second test, we simply test for bijectivity.
2765 * If the array is marked force_private, then we bypass all checks
2766 * and assume we can (and should) use registers.
2768 * If it turns out we can (or have to) use registers, we compute
2769 * the private memory tile size using can_tile, after introducing a dependence
2770 * on the thread indices.
2772 static int compute_group_bounds_core(struct gpu_gen *gen,
2773 struct gpu_array_ref_group *group)
2775 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2776 isl_union_map *access;
2777 int n_index = group->array->n_index;
2778 int no_reuse, coalesced;
2779 isl_map *acc;
2780 int force_private = group->array->force_private;
2781 int use_shared = gen->options->use_shared_memory && gen->n_block > 0;
2782 int use_private = force_private || gen->options->use_private_memory;
2784 if (!use_shared && !use_private)
2785 return 0;
2786 if (gpu_array_is_read_only_scalar(group->array))
2787 return 0;
2788 if (!force_private && !group->exact_write)
2789 return 0;
2790 if (group->slice)
2791 return 0;
2793 access = group_access_relation(group, 1, 1);
2794 no_reuse = isl_union_map_is_injective(access);
2795 if (use_shared && no_reuse)
2796 coalesced = access_is_coalesced(gen, access);
2798 if (gen->options->debug->verbose && use_shared && no_reuse && coalesced)
2799 report_no_reuse_and_coalesced(gen->kernel, access);
2801 if (use_shared && (!no_reuse || !coalesced)) {
2802 group->shared_tile = create_tile(ctx, group->array->n_index);
2803 if (!can_tile(group->access, group->shared_tile))
2804 group->shared_tile = free_tile(group->shared_tile);
2807 if (!force_private && (!use_private || no_reuse)) {
2808 isl_union_map_free(access);
2809 return 0;
2812 access = isl_union_map_apply_domain(access,
2813 isl_union_map_copy(gen->shared_sched));
2815 acc = isl_map_from_union_map(access);
2817 if (!force_private && !access_is_bijective(gen, acc)) {
2818 isl_map_free(acc);
2819 return 0;
2822 group->private_tile = create_tile(gen->ctx, n_index);
2823 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2824 if (!can_tile(acc, group->private_tile))
2825 group->private_tile = free_tile(group->private_tile);
2827 isl_map_free(acc);
2829 if (force_private && !group->private_tile)
2830 isl_die(ctx, isl_error_internal,
2831 "unable to map array reference group to registers",
2832 return -1);
2834 return 0;
2837 /* Compute the private and/or shared memory tiles for the array
2838 * reference group "group" of array "array" and set last_shared.
2839 * Return 0 on success and -1 on error.
2841 static int compute_group_bounds(struct gpu_gen *gen,
2842 struct gpu_array_ref_group *group)
2844 if (compute_group_bounds_core(gen, group) < 0)
2845 return -1;
2846 set_last_shared(gen, group);
2848 return 0;
2851 /* If two groups have overlapping access relations (as determined by
2852 * the "overlap" function) and if one of them involves a write,
2853 * then merge the two groups into one.
2854 * If "compute_bounds" is set, then call compute_group_bounds
2855 * on the merged groups.
2857 * Return the updated number of groups.
2858 * Return -1 on error.
2860 static int group_writes(struct gpu_gen *gen,
2861 int n, struct gpu_array_ref_group **groups,
2862 int (*overlap)(struct gpu_array_ref_group *group1,
2863 struct gpu_array_ref_group *group2), int compute_bounds)
2865 int i, j;
2867 for (i = 0; i < n; ++i) {
2868 for (j = n - 1; j > i; --j) {
2869 if (!groups[i]->write && !groups[j]->write)
2870 continue;
2872 if (!overlap(groups[i], groups[j]))
2873 continue;
2875 groups[i] = join_groups_and_free(groups[i], groups[j]);
2876 if (j != n - 1)
2877 groups[j] = groups[n - 1];
2878 groups[n - 1] = NULL;
2879 n--;
2881 if (compute_bounds &&
2882 compute_group_bounds(gen, groups[i]) < 0)
2883 return -1;
2887 return n;
2890 /* If two groups have overlapping access relations (within the innermost
2891 * loop) and if one of them involves a write, then merge the two groups
2892 * into one.
2894 * Return the updated number of groups.
2896 static int group_overlapping_writes(struct gpu_gen *gen,
2897 int n, struct gpu_array_ref_group **groups)
2899 return group_writes(gen, n, groups, &accesses_overlap, 0);
2902 /* Check if the access relations of group1 and group2 overlap within
2903 * the outermost min(group1->last_shared, group2->last_shared) loops.
2905 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2906 struct gpu_array_ref_group *group2)
2908 int last_shared;
2909 int dim;
2910 int empty;
2911 isl_map *map_i, *map_j, *map;
2913 last_shared = group1->last_shared;
2914 if (group2->last_shared < last_shared)
2915 last_shared = group2->last_shared;
2916 map_i = isl_map_copy(group1->access);
2917 dim = isl_map_dim(map_i, isl_dim_in);
2918 map_i = isl_map_eliminate(map_i, isl_dim_in,
2919 last_shared + 1, dim - (last_shared + 1));
2920 map_j = isl_map_copy(group2->access);
2921 map_j = isl_map_eliminate(map_j, isl_dim_in,
2922 last_shared + 1, dim - (last_shared + 1));
2923 map = isl_map_intersect(map_i, map_j);
2924 empty = isl_map_is_empty(map);
2925 isl_map_free(map);
2927 return !empty;
2930 /* If two groups have overlapping access relations (within the outer
2931 * last_shared loops) and if one of them involves a write,
2932 * then merge the two groups into one.
2934 * Return the updated number of groups.
2936 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2937 struct gpu_array_ref_group **groups)
2939 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2942 /* Is the size of the tile specified by "tile" smaller than the sum of
2943 * the sizes of the tiles specified by "tile1" and "tile2"?
2945 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2946 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2948 int smaller;
2949 isl_val *size, *size1, *size2;
2951 size = tile_size(ctx, tile);
2952 size1 = tile_size(ctx, tile1);
2953 size2 = tile_size(ctx, tile2);
2955 size = isl_val_sub(size, size1);
2956 size = isl_val_sub(size, size2);
2957 smaller = isl_val_is_neg(size);
2959 isl_val_free(size);
2961 return smaller;
2964 /* Given an initial grouping of array references and shared memory tiles
2965 * for each group that allows for a shared memory tile, merge two groups
2966 * if both have a shared memory tile, the merged group also has
2967 * a shared memory tile and the size of the tile for the merge group
2968 * is smaller than the sum of the tile sizes of the individual groups.
2970 * If merging two groups decreases the "last_shared" dimension of
2971 * one or both of the two groups, then we need to check for overlapping
2972 * writes again.
2974 * Return the number of groups after merging.
2975 * Return -1 on error.
2977 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2978 struct gpu_array_info *array, int n,
2979 struct gpu_array_ref_group **groups)
2981 int i, j;
2982 int recompute_overlap = 0;
2983 isl_ctx *ctx = isl_space_get_ctx(array->space);
2985 for (i = 0; i < n; ++i) {
2986 if (!groups[i]->shared_tile)
2987 continue;
2988 for (j = n - 1; j > i; --j) {
2989 isl_map *map;
2990 int empty;
2991 struct gpu_array_ref_group *group;
2993 if (!groups[j]->shared_tile)
2994 continue;
2996 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2997 isl_map_copy(groups[j]->access));
2998 empty = isl_map_is_empty(map);
2999 isl_map_free(map);
3001 if (empty)
3002 continue;
3004 group = join_groups(groups[i], groups[j]);
3005 if (compute_group_bounds(gen, group) < 0) {
3006 free_array_ref_group(group);
3007 return -1;
3009 if (!group->shared_tile ||
3010 !smaller_tile(ctx, group->shared_tile,
3011 groups[i]->shared_tile,
3012 groups[j]->shared_tile)) {
3013 free_array_ref_group(group);
3014 continue;
3017 if (group->last_shared < groups[i]->last_shared ||
3018 group->last_shared < groups[j]->last_shared)
3019 recompute_overlap = 1;
3020 free_array_ref_group(groups[i]);
3021 free_array_ref_group(groups[j]);
3022 groups[i] = group;
3023 if (j != n - 1)
3024 groups[j] = groups[n - 1];
3025 n--;
3029 if (recompute_overlap)
3030 n = group_last_shared_overlapping_writes(gen, n, groups);
3031 return n;
3034 /* Set array->n_group and array->groups to n and groups.
3036 * Additionally, set the "nr" field of each group
3037 * and the "group" field of each reference in each group.
3039 static void set_array_groups(struct gpu_array_info *array,
3040 int n, struct gpu_array_ref_group **groups)
3042 int i, j;
3044 array->n_group = n;
3045 array->groups = groups;
3047 for (i = 0; i < n; ++i) {
3048 groups[i]->nr = i;
3050 for (j = 0; j < groups[i]->n_ref; ++j)
3051 groups[i]->refs[j]->group = i;
3055 /* Group array references that should be considered together when
3056 * deciding whether to access them from private, shared or global memory.
3057 * Return -1 on error.
3059 * In particular, if two array references overlap and if one of them
3060 * is a write, then the two references are grouped together.
3061 * We first perform an initial grouping based only on the access relation.
3062 * After computing shared and private memory tiles, we check for
3063 * overlapping writes again, but this time taking into account
3064 * the "last_shared" property.
3066 * Furthermore, if two groups admit a shared memory tile and if the
3067 * combination of the two also admits a shared memory tile, we merge
3068 * the two groups.
3070 * If the array contains structures, then there is no need to compute
3071 * reference groups since we do not map such arrays to private or shared
3072 * memory.
3074 static int group_array_references(struct gpu_gen *gen,
3075 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3077 int i;
3078 int n;
3079 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3080 struct gpu_array_ref_group **groups;
3082 if (array->has_compound_element)
3083 return 0;
3085 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3086 array->n_ref);
3087 if (!groups)
3088 return -1;
3090 n = populate_array_references(array, sched, groups);
3092 n = group_overlapping_writes(gen, n, groups);
3094 for (i = 0; i < n; ++i)
3095 if (compute_group_bounds(gen, groups[i]) < 0)
3096 n = -1;
3098 n = group_last_shared_overlapping_writes(gen, n, groups);
3100 n = group_common_shared_memory_tile(gen, array, n, groups);
3102 set_array_groups(array, n, groups);
3104 if (n >= 0)
3105 return 0;
3107 for (i = 0; i < array->n_ref; ++i)
3108 free_array_ref_group(groups[i]);
3109 return -1;
3112 /* Take tiled_sched, project it onto the shared tile loops and
3113 * the loops that will be wrapped over the threads and
3114 * store the result in gen->shared_sched.
3115 * Also compute a projection that projects out the loops that will be
3116 * wrapped over the threads and store this projection in gen->shared_proj.
3118 static void compute_shared_sched(struct gpu_gen *gen)
3120 isl_space *dim;
3121 isl_map *proj;
3122 isl_set *par;
3123 isl_union_map *sched;
3125 sched = isl_union_map_copy(gen->tiled_sched);
3127 dim = isl_union_map_get_space(sched);
3128 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3129 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3131 dim = isl_union_map_get_space(sched);
3132 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3134 gen->shared_sched = sched;
3135 gen->shared_proj = isl_union_map_from_map(proj);
3138 /* For each scalar in the input program, check if there are any
3139 * order dependences active inside the current kernel, within
3140 * the same iteration of the host schedule.
3141 * If so, mark the scalar as force_private so that it will be
3142 * mapped to a register.
3144 static void check_scalar_live_ranges(struct gpu_gen *gen)
3146 int i;
3147 isl_map *proj;
3148 isl_union_map *sched;
3149 isl_union_set *domain;
3150 isl_union_map *same_host_iteration;
3152 gen->any_force_private = 0;
3154 if (!gen->options->live_range_reordering)
3155 return;
3157 sched = gen->shared_sched;
3158 sched = isl_union_map_universe(isl_union_map_copy(sched));
3159 domain = isl_union_map_domain(sched);
3161 sched = isl_union_map_copy(gen->sched);
3162 proj = projection(isl_union_map_get_space(sched),
3163 gen->untiled_len, gen->tile_first);
3164 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3165 same_host_iteration = isl_union_map_apply_range(sched,
3166 isl_union_map_reverse(isl_union_map_copy(sched)));
3168 for (i = 0; i < gen->prog->n_array; ++i) {
3169 struct gpu_array_info *array = &gen->prog->array[i];
3170 isl_union_map *order;
3172 array->force_private = 0;
3173 if (array->n_index != 0)
3174 continue;
3175 order = isl_union_map_copy(array->dep_order);
3176 order = isl_union_map_intersect_domain(order,
3177 isl_union_set_copy(domain));
3178 order = isl_union_map_intersect_range(order,
3179 isl_union_set_copy(domain));
3180 order = isl_union_map_intersect(order,
3181 isl_union_map_copy(same_host_iteration));
3182 if (!isl_union_map_is_empty(order)) {
3183 array->force_private = 1;
3184 gen->any_force_private = 1;
3186 isl_union_map_free(order);
3189 isl_union_map_free(same_host_iteration);
3190 isl_union_set_free(domain);
3193 /* Group references of all arrays in the program.
3195 static int group_references(struct gpu_gen *gen)
3197 int i;
3198 int r = 0;
3199 isl_union_map *sched;
3201 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3202 isl_union_map_copy(gen->shared_proj));
3204 for (i = 0; i < gen->prog->n_array; ++i) {
3205 r = group_array_references(gen, &gen->prog->array[i], sched);
3206 if (r < 0)
3207 break;
3210 isl_union_map_free(sched);
3212 return r;
3215 /* Free all array information that is local to the current kernel.
3217 static void free_local_array_info(struct gpu_gen *gen)
3219 int i, j;
3221 for (i = 0; i < gen->prog->n_array; ++i) {
3222 struct gpu_array_info *array = &gen->prog->array[i];
3224 for (j = 0; j < array->n_group; ++j)
3225 free_array_ref_group(array->groups[j]);
3226 free(array->groups);
3230 /* Compute the size of a bounding box around the origin and "set",
3231 * where "set" is assumed to contain only non-negative elements.
3232 * In particular, compute the maximal value of "set" in each direction
3233 * and add one.
3235 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3236 __isl_keep isl_set *context)
3238 int i, n;
3239 isl_multi_pw_aff *mpa;
3241 n = isl_set_dim(set, isl_dim_set);
3242 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3243 for (i = 0; i < n; ++i) {
3244 isl_space *space;
3245 isl_aff *one;
3246 isl_pw_aff *bound;
3248 bound = isl_set_dim_max(isl_set_copy(set), i);
3249 bound = isl_pw_aff_coalesce(bound);
3250 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3252 space = isl_pw_aff_get_domain_space(bound);
3253 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3254 one = isl_aff_add_constant_si(one, 1);
3255 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3256 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3258 isl_set_free(set);
3260 return mpa;
3263 /* Compute the effective grid size as a list of the sizes in each dimension.
3265 * The grid size specified by the user or set by default
3266 * in read_grid_sizes() and applied in tile_schedule(),
3267 * may be too large for the given code in the sense that
3268 * it may contain blocks that don't need to execute anything.
3269 * We therefore don't return this grid size, but instead the
3270 * smallest grid size that ensures that all blocks that actually
3271 * execute code are included in the grid.
3273 * We first extract a description of the grid, i.e., the possible values
3274 * of the block ids, from gen->tiled_sched.
3275 * The block ids are parameters in gen->tiled_sched.
3276 * We simply need to change them into set dimensions.
3278 * Then, for each block dimension, we compute the maximal value of the block id
3279 * and add one.
3281 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3282 struct ppcg_kernel *kernel)
3284 int i;
3285 isl_set *grid;
3287 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3288 grid = isl_set_from_params(grid);
3289 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3290 for (i = 0; i < gen->n_grid; ++i) {
3291 int pos;
3292 isl_id *id;
3294 id = isl_id_list_get_id(kernel->block_ids, i);
3295 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
3296 isl_id_free(id);
3297 assert(pos >= 0);
3298 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3299 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3302 return extract_size(grid, kernel->context);
3305 /* Compute the size of a fixed bounding box around the origin and "set",
3306 * where "set" is assumed to contain only non-negative elements,
3307 * and store the results in "size".
3308 * In particular, compute the maximal value of "set" in each direction
3309 * and add one.
3311 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3313 int i, n;
3314 isl_local_space *ls;
3315 isl_aff *obj;
3317 n = isl_set_dim(set, isl_dim_set);
3318 ls = isl_local_space_from_space(isl_set_get_space(set));
3319 obj = isl_aff_zero_on_domain(ls);
3320 for (i = 0; i < n; ++i) {
3321 isl_val *max;
3323 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3324 max = isl_set_max_val(set, obj);
3325 size[i] = isl_val_get_num_si(max) + 1;
3326 isl_val_free(max);
3327 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3329 isl_aff_free(obj);
3330 isl_set_free(set);
3333 /* Compute the effective block size as a list of the sizes in each dimension
3334 * and store the sizes in kernel->block_dim.
3336 * The block size specified by the user or set by default
3337 * in read_block_sizes() and applied in thread_tile_schedule(),
3338 * may be too large for the given code in the sense that
3339 * it may contain threads that don't need to execute anything.
3340 * We therefore don't store this block size in kernel->block_dim,
3341 * but instead the smallest block size that ensures that all threads
3342 * that actually execute code are included in the block.
3344 * The current implementation eliminates all parameters, ensuring
3345 * that the size is a fixed constant in each dimension.
3346 * In principle we could also compute parametric sizes.
3347 * We would have to make sure to project out all b%d and t%d parameters,
3348 * however.
3350 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3352 int i;
3353 int nparam;
3354 isl_set *block;
3355 isl_multi_pw_aff *mpa;
3357 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3358 block = isl_set_from_params(block);
3359 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3360 kernel->n_block = gen->n_block;
3361 for (i = 0; i < gen->n_block; ++i) {
3362 int pos;
3363 isl_id *id;
3365 id = isl_id_list_get_id(kernel->thread_ids, i);
3366 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
3367 isl_id_free(id);
3368 assert(pos >= 0);
3369 block = isl_set_equate(block, isl_dim_param, pos,
3370 isl_dim_set, i);
3372 nparam = isl_set_dim(block, isl_dim_param);
3373 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3375 extract_fixed_size(block, kernel->block_dim);
3378 void ppcg_kernel_free(void *user)
3380 struct ppcg_kernel *kernel = user;
3381 int i;
3383 if (!kernel)
3384 return;
3386 isl_id_list_free(kernel->block_ids);
3387 isl_id_list_free(kernel->thread_ids);
3388 isl_multi_pw_aff_free(kernel->grid_size);
3389 isl_set_free(kernel->context);
3390 isl_union_set_free(kernel->arrays);
3391 isl_space_free(kernel->space);
3392 isl_ast_node_free(kernel->tree);
3394 for (i = 0; i < kernel->n_array; ++i)
3395 isl_pw_aff_list_free(kernel->array[i].bound);
3396 free(kernel->array);
3398 for (i = 0; i < kernel->n_var; ++i) {
3399 free(kernel->var[i].name);
3400 isl_vec_free(kernel->var[i].size);
3402 free(kernel->var);
3404 free(kernel);
3407 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3408 struct ppcg_kernel_var *var)
3410 int j;
3411 struct gpu_array_tile *tile;
3412 isl_printer *p;
3413 char *name;
3415 var->array = group->array;
3417 tile = group->private_tile;
3418 var->type = ppcg_access_private;
3419 if (!tile) {
3420 tile = group->shared_tile;
3421 var->type = ppcg_access_shared;
3424 p = isl_printer_to_str(ctx);
3425 p = print_array_name(p, group);
3426 var->name = isl_printer_get_str(p);
3427 isl_printer_free(p);
3429 var->size = isl_vec_alloc(ctx, group->array->n_index);
3431 for (j = 0; j < group->array->n_index; ++j)
3432 var->size = isl_vec_set_element_val(var->size, j,
3433 isl_val_copy(tile->bound[j].size));
3436 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3438 int i, j, n;
3440 n = 0;
3441 for (i = 0; i < gen->prog->n_array; ++i) {
3442 struct gpu_array_info *array = &gen->prog->array[i];
3444 for (j = 0; j < array->n_group; ++j) {
3445 struct gpu_array_ref_group *group = array->groups[j];
3446 if (group->private_tile || group->shared_tile)
3447 ++n;
3451 kernel->n_var = n;
3452 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3453 assert(kernel->var);
3455 n = 0;
3456 for (i = 0; i < gen->prog->n_array; ++i) {
3457 struct gpu_array_info *array = &gen->prog->array[i];
3459 for (j = 0; j < array->n_group; ++j) {
3460 struct gpu_array_ref_group *group = array->groups[j];
3461 if (!group->private_tile && !group->shared_tile)
3462 continue;
3463 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3464 ++n;
3469 /* Replace "pa" by the zero function defined over the universe domain
3470 * in the space of "pa".
3472 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
3474 isl_space *space;
3475 isl_aff *zero;
3477 space = isl_space_domain(isl_pw_aff_get_space(pa));
3478 isl_pw_aff_free(pa);
3479 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3481 return isl_pw_aff_from_aff(zero);
3484 /* The sizes of the arrays on the host that have been computed by
3485 * extract_array_info may depend on the parameters. Use the extra
3486 * constraints on the parameters that are valid at "host_domain"
3487 * to simplify these expressions and store the results in kernel->array.
3489 * We only need these localized bounds for arrays that are accessed
3490 * by the current kernel. If we have found at least one reference group
3491 * then the array is accessed by the kernel. If the array has compound
3492 * elements then we skipped the construction of array reference groups.
3494 * The resulting sizes may be functions that are nowhere defined
3495 * in case the access function cannot possibly access anything inside
3496 * the kernel for some reason. If so, they are replaced by the zero
3497 * function. Since the access function cannot actually access anything,
3498 * there is no harm in printing the array sizes as zero.
3500 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3501 __isl_keep isl_set *host_domain)
3503 int i, j;
3504 isl_set *context;
3506 kernel->array = isl_calloc_array(gen->ctx,
3507 struct gpu_local_array_info, gen->prog->n_array);
3508 assert(kernel->array);
3509 kernel->n_array = gen->prog->n_array;
3511 context = isl_set_copy(host_domain);
3512 context = isl_set_params(context);
3514 for (i = 0; i < gen->prog->n_array; ++i) {
3515 struct gpu_array_info *array = &gen->prog->array[i];
3516 isl_pw_aff_list *local;
3518 if (array->n_group == 0 && !array->has_compound_element)
3519 continue;
3521 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3523 for (j = 0; j < array->n_index; ++j) {
3524 isl_pw_aff *pwaff;
3525 int empty;
3527 pwaff = isl_pw_aff_copy(array->bound[j]);
3528 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3529 empty = isl_pw_aff_is_empty(pwaff);
3530 if (empty < 0)
3531 pwaff = isl_pw_aff_free(pwaff);
3532 else if (empty)
3533 pwaff = set_universally_zero(pwaff);
3534 local = isl_pw_aff_list_add(local, pwaff);
3537 kernel->array[i].n_index = array->n_index;
3538 kernel->array[i].bound = local;
3540 isl_set_free(context);
3543 /* Find the element in gen->stmt that has the given "id".
3544 * Return NULL if no such gpu_stmt can be found.
3546 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3548 int i;
3550 for (i = 0; i < prog->n_stmts; ++i) {
3551 if (id == prog->stmts[i].id)
3552 break;
3555 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3558 /* Set gen->tile_len and gen->n_parallel to those of the statement
3559 * affected by the first map (part of the schedule)
3560 * on which this function is called.
3561 * Because of the way the schedule is constructed, the other statements
3562 * in the list, if any, should have the same values for these properties.
3564 static int extract_tile_len(__isl_take isl_map *map, void *user)
3566 struct gpu_gen *gen = (struct gpu_gen *) user;
3567 isl_id *id;
3568 struct gpu_stmt *stmt;
3570 id = isl_map_get_tuple_id(map, isl_dim_in);
3571 stmt = find_stmt(gen->prog, id);
3572 isl_id_free(id);
3574 isl_map_free(map);
3576 if (!stmt)
3577 isl_die(gen->ctx, isl_error_unknown,
3578 "statement not found", return -1);
3580 gen->tile_len = stmt->tile_len;
3581 gen->n_parallel = stmt->n_parallel;
3583 return -1;
3586 void ppcg_kernel_stmt_free(void *user)
3588 int i;
3589 struct ppcg_kernel_stmt *stmt = user;
3591 if (!stmt)
3592 return;
3594 switch (stmt->type) {
3595 case ppcg_kernel_copy:
3596 isl_ast_expr_free(stmt->u.c.index);
3597 isl_ast_expr_free(stmt->u.c.local_index);
3598 break;
3599 case ppcg_kernel_domain:
3600 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3601 break;
3602 case ppcg_kernel_sync:
3603 break;
3606 free(stmt);
3609 /* Set the options of "context" to
3611 * { space -> [x] : x >= first }
3613 static __isl_give isl_ast_build *set_unroll(
3614 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3615 int first)
3617 isl_ctx *ctx;
3618 isl_map *unroll;
3619 isl_union_map *opt;
3621 ctx = isl_ast_build_get_ctx(build);
3623 space = isl_space_from_domain(space);
3624 space = isl_space_add_dims(space, isl_dim_out, 1);
3625 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3626 unroll = isl_map_universe(space);
3627 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3628 opt = isl_union_map_from_map(unroll);
3630 build = isl_ast_build_set_options(build, opt);
3632 return build;
3635 /* Extend the schedule "schedule" with the part of "extension"
3636 * starting at "first" up to "len".
3638 static __isl_give isl_union_map *extend_schedule(
3639 __isl_take isl_union_map *schedule,
3640 __isl_take isl_union_map *extension, int first, int len)
3642 isl_space *space;
3643 isl_map *proj;
3644 isl_union_map *umap;
3645 isl_set *set;
3647 space = isl_union_map_get_space(schedule);
3648 space = isl_space_set_from_params(space);
3649 space = isl_space_add_dims(space, isl_dim_set, len);
3650 proj = isl_set_identity(isl_set_universe(space));
3651 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3652 extension = isl_union_map_apply_range(extension,
3653 isl_union_map_from_map(proj));
3655 schedule = isl_union_map_range_product(schedule, extension);
3657 return schedule;
3660 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3661 * to "ref_id".
3663 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3664 __isl_keep isl_id *ref_id)
3666 struct gpu_stmt_access *access;
3668 for (access = accesses; access; access = access->next)
3669 if (access->ref_id == ref_id)
3670 return access;
3672 return NULL;
3675 /* Return the index of the array called "name" in the list of arrays.
3677 static int find_array_index(struct gpu_gen *gen, const char *name)
3679 int i;
3681 for (i = 0; i < gen->prog->n_array; ++i)
3682 if (!strcmp(name, gen->prog->array[i].name))
3683 return i;
3685 return -1;
3688 /* Internal data structure for the index and AST expression transformation
3689 * callbacks for pet_stmt_build_ast_exprs.
3691 * "accesses" is the list of gpu_stmt_access in the statement.
3692 * "iterator_map" expresses the statement iterators in terms of
3693 * the AST loop iterators.
3694 * "sched2shared" expresses the first shared_len dimensions of
3695 * the computed schedule in terms of the AST loop iterators.
3697 * The following fields are set in transform_index and used in transform_expr.
3698 * "array" is the array that is being accessed.
3699 * "global" is set if the global array is accessed (rather than
3700 * shared/private memory).
3701 * "local_array" refers to information on the array specialized
3702 * to the current kernel.
3704 struct ppcg_transform_data {
3705 struct gpu_gen *gen;
3706 struct gpu_stmt_access *accesses;
3707 isl_pw_multi_aff *iterator_map;
3708 isl_pw_multi_aff *sched2shared;
3710 struct gpu_array_info *array;
3711 int global;
3712 struct gpu_local_array_info *local_array;
3715 /* Return the name of the outer array (of structs) accessed by "access".
3717 static const char *get_outer_array_name(__isl_keep isl_map *access)
3719 isl_space *space;
3720 const char *name;
3722 space = isl_space_range(isl_map_get_space(access));
3723 while (space && isl_space_is_wrapping(space))
3724 space = isl_space_domain(isl_space_unwrap(space));
3725 name = isl_space_get_tuple_name(space, isl_dim_set);
3726 isl_space_free(space);
3728 return name;
3731 /* Index transformation callback for pet_stmt_build_ast_exprs.
3733 * "index" expresses the array indices in terms of statement iterators
3735 * We first reformulate "index" in terms of the AST loop iterators.
3736 * Then we check if we are accessing the global array or
3737 * a shared/private copy. In the former case, we simply return
3738 * the updated index. If "index" is an affine expression rather
3739 * than an array access, then we also return the updated index here.
3741 * If no reference groups have been computed for the array,
3742 * then we can only be accessing the global array.
3744 * Otherwise, we apply the tiling to the index.
3745 * This tiling is of the form
3747 * [D -> A] -> T
3749 * The index is of the form
3751 * L -> A
3753 * We update the tiling to refer to the AST loop iterators
3755 * [L -> A] -> T
3757 * and modify index to keep track of those iterators
3759 * L -> [L -> A]
3761 * Combining these two yields a tiled index expression in terms
3762 * of the AST loop iterators
3764 * L -> T
3766 static __isl_give isl_multi_pw_aff *transform_index(
3767 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3768 void *user)
3770 struct ppcg_transform_data *data = user;
3771 struct gpu_stmt_access *access;
3772 struct gpu_array_ref_group *group;
3773 struct gpu_array_tile *tile;
3774 isl_pw_multi_aff *iterator_map;
3775 int i;
3776 const char *name;
3777 isl_space *space;
3778 isl_multi_pw_aff *tiling;
3779 isl_pw_multi_aff *pma;
3780 isl_multi_pw_aff *mpa;
3782 data->array = NULL;
3784 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3785 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3787 access = find_access(data->accesses, ref_id);
3788 if (!access)
3789 return index;
3790 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3791 return index;
3793 name = get_outer_array_name(access->access);
3794 i = find_array_index(data->gen, name);
3795 if (i < 0)
3796 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3797 "cannot find array",
3798 return isl_multi_pw_aff_free(index));
3799 data->array = &data->gen->prog->array[i];
3800 data->local_array = &data->gen->kernel->array[i];
3802 if (access->group < 0) {
3803 data->global = 1;
3804 return index;
3807 group = data->array->groups[access->group];
3808 tile = group->private_tile;
3809 if (!tile)
3810 tile = group->shared_tile;
3811 data->global = !tile;
3812 if (!tile)
3813 return index;
3815 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3816 space = isl_space_map_from_set(space);
3817 pma = isl_pw_multi_aff_identity(space);
3818 pma = isl_pw_multi_aff_product(
3819 isl_pw_multi_aff_copy(data->sched2shared), pma);
3820 tiling = isl_multi_pw_aff_from_multi_aff(
3821 isl_multi_aff_copy(tile->tiling));
3822 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3824 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3825 space = isl_space_map_from_set(space);
3826 mpa = isl_multi_pw_aff_identity(space);
3827 index = isl_multi_pw_aff_range_product(mpa, index);
3828 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3830 return index;
3833 /* Dereference "expr" by adding an index [0].
3834 * The original "expr" is assumed not to have any indices.
3836 * If "expr" is a member access, then the dereferencing needs
3837 * to be applied to the structure argument of this member access.
3839 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3841 isl_ctx *ctx;
3842 isl_ast_expr *arg0, *res;
3843 isl_ast_expr_list *list;
3845 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3846 if (!arg0)
3847 return isl_ast_expr_free(expr);
3848 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3849 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3850 isl_ast_expr *arg;
3852 arg = isl_ast_expr_get_op_arg(arg0, 0);
3853 arg = dereference(arg);
3854 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3855 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3857 return expr;
3859 isl_ast_expr_free(arg0);
3861 ctx = isl_ast_expr_get_ctx(expr);
3862 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3863 list = isl_ast_expr_list_from_ast_expr(res);
3864 res = isl_ast_expr_get_op_arg(expr, 0);
3865 res = isl_ast_expr_access(res, list);
3866 isl_ast_expr_free(expr);
3868 return res;
3871 /* Linearize the index expression "expr" based on the array bounds
3872 * of "array".
3874 * That is, transform expression
3876 * A[i_0][i_1]...[i_n]
3878 * to
3880 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3882 * where b_0, b_1, ..., b_n are the bounds on the array.
3884 * If the base of "expr" is a member access, then the linearization needs
3885 * to be applied to the structure argument of this member access.
3887 * In the base case, if "expr" has no arguments (other than the name of
3888 * the array), then we are passing an entire array to a function.
3889 * In this case, there is nothing to linearize.
3890 * Note that at this point an expression with no arguments can
3891 * only be an entire array because the scalar case and
3892 * the case of single struct are handled by the caller.
3894 * If the number of specified index expressions in "expr"
3895 * is smaller than the dimension of the accessed array,
3896 * then the missing i_j also do not appear in the linearized expression.
3897 * Furthermore, since such an expression does not refer to a single
3898 * element while the default linearized expression would refer to
3899 * a single element, we return the expression
3901 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
3903 * instead. Note that because of the special case handling above,
3904 * we can assume here that here that there is at least one index expression.
3906 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3907 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3909 int i, n;
3910 isl_ctx *ctx;
3911 isl_set *context;
3912 isl_ast_expr *arg0;
3913 isl_ast_expr *res;
3914 isl_ast_expr_list *list;
3915 isl_ast_build *build;
3917 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3918 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3919 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3920 isl_ast_expr *arg;
3922 arg = isl_ast_expr_get_op_arg(arg0, 0);
3923 arg = gpu_local_array_info_linearize_index(array, arg);
3924 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3925 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3927 return expr;
3929 isl_ast_expr_free(arg0);
3931 if (isl_ast_expr_get_op_n_arg(expr) == 1)
3932 return expr;
3934 ctx = isl_ast_expr_get_ctx(expr);
3935 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3936 build = isl_ast_build_from_context(context);
3938 n = isl_ast_expr_get_op_n_arg(expr);
3939 res = isl_ast_expr_get_op_arg(expr, 1);
3940 for (i = 1; i < array->n_index; ++i) {
3941 isl_pw_aff *bound_i;
3942 isl_ast_expr *expr_i;
3944 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
3945 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3946 res = isl_ast_expr_mul(res, expr_i);
3948 if (i + 1 >= n)
3949 continue;
3950 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
3951 res = isl_ast_expr_add(res, expr_i);
3954 isl_ast_build_free(build);
3956 if (1 + array->n_index > n) {
3957 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
3958 } else {
3959 list = isl_ast_expr_list_from_ast_expr(res);
3960 res = isl_ast_expr_get_op_arg(expr, 0);
3961 res = isl_ast_expr_access(res, list);
3964 isl_ast_expr_free(expr);
3966 return res;
3969 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3971 * If the AST expression refers to a global scalar that is not
3972 * a read-only scalar, then its address was passed to the kernel and
3973 * we need to dereference it.
3975 * If the AST expression refers to an access to a global array,
3976 * then we linearize the access exploiting the bounds in data->local_array.
3978 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3979 __isl_keep isl_id *id, void *user)
3981 struct ppcg_transform_data *data = user;
3983 if (!data->array)
3984 return expr;
3985 if (gpu_array_is_read_only_scalar(data->array))
3986 return expr;
3987 if (!data->global)
3988 return expr;
3989 if (data->array->n_index == 0)
3990 return dereference(expr);
3991 if (!data->array->linearize)
3992 return expr;
3994 return gpu_local_array_info_linearize_index(data->local_array, expr);
3997 /* This function is called for each instance of a user statement
3998 * in the kernel.
4000 * We attach a struct ppcg_kernel_stmt to the "node", containing
4001 * a computed AST expression for each access.
4002 * These AST expressions are computed from iterator_map,
4003 * which expresses the domain
4004 * elements in terms of the generated loops, and sched2shared,
4005 * which expresses the first shared_len dimensions of the schedule
4006 * computed by PPCG in terms of the generated loops.
4008 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
4009 __isl_keep isl_ast_build *build, void *user)
4011 struct ppcg_transform_data data;
4012 struct gpu_gen *gen = (struct gpu_gen *) user;
4013 struct ppcg_kernel_stmt *stmt;
4014 isl_id *id;
4015 isl_pw_multi_aff *sched2shared;
4016 isl_map *map;
4017 isl_pw_multi_aff *iterator_map;
4018 isl_ast_expr *expr, *arg;
4019 isl_union_map *schedule;
4021 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4022 if (!stmt)
4023 return isl_ast_node_free(node);
4025 expr = isl_ast_node_user_get_expr(node);
4026 arg = isl_ast_expr_get_op_arg(expr, 0);
4027 id = isl_ast_expr_get_id(arg);
4029 schedule = isl_ast_build_get_schedule(build);
4030 map = isl_map_reverse(isl_map_from_union_map(schedule));
4031 iterator_map = isl_pw_multi_aff_from_map(map);
4032 sched2shared = compute_sched_to_shared(gen,
4033 isl_pw_multi_aff_copy(iterator_map));
4035 stmt->type = ppcg_kernel_domain;
4036 stmt->u.d.stmt = find_stmt(gen->prog, id);
4037 if (!stmt->u.d.stmt)
4038 isl_die(gen->ctx, isl_error_internal,
4039 "statement not found", goto error);
4041 data.gen = gen;
4042 data.accesses = stmt->u.d.stmt->accesses;
4043 data.iterator_map = iterator_map;
4044 data.sched2shared = sched2shared;
4045 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4046 build, &transform_index, &data,
4047 &transform_expr, &data);
4049 isl_id_free(id);
4050 isl_pw_multi_aff_free(iterator_map);
4051 isl_pw_multi_aff_free(sched2shared);
4052 isl_ast_expr_free(arg);
4053 isl_ast_expr_free(expr);
4055 id = isl_id_alloc(gen->ctx, NULL, stmt);
4056 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4057 return isl_ast_node_set_annotation(node, id);
4058 error:
4059 isl_id_free(id);
4060 isl_pw_multi_aff_free(iterator_map);
4061 ppcg_kernel_stmt_free(stmt);
4062 isl_pw_multi_aff_free(sched2shared);
4063 return isl_ast_node_free(node);
4066 /* This function is called when code has been generated for the shared
4067 * tile loops. The "schedule" refers only to the original statements.
4069 * We extend the schedule with that part of gen->local_sched that hasn't
4070 * been taken into account yet. This introduces parameters referring
4071 * to thread ids in the schedule, so we add them (with the appropriate
4072 * bounds to the context as well).
4073 * Finally, we set the appropriate unrolling options
4074 * if gen->first_unroll is set.
4076 static __isl_give isl_ast_node *create_domain_leaf(
4077 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4078 void *user)
4080 struct gpu_gen *gen = (struct gpu_gen *) user;
4081 isl_space *space;
4082 isl_union_map *sched;
4083 isl_ast_node *tree;
4084 isl_set *set;
4085 isl_id_list *iterators;
4086 int n;
4088 schedule = extend_schedule(schedule,
4089 isl_union_map_copy(gen->local_sched),
4090 gen->shared_len, gen->thread_tiled_len);
4092 space = isl_ast_build_get_schedule_space(build);
4093 set = isl_set_universe(space);
4094 set = add_bounded_parameters(set, gen->kernel->block_dim,
4095 gen->kernel->thread_ids);
4096 build = isl_ast_build_restrict(build, set);
4098 n = gen->thread_tiled_len - gen->shared_len;
4100 if (gen->first_unroll >= 0) {
4101 space = isl_space_set_alloc(gen->ctx, 0, n);
4102 build = set_unroll(build, space, gen->first_unroll);
4104 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
4105 build = isl_ast_build_set_iterators(build, iterators);
4106 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4107 tree = isl_ast_build_ast_from_schedule(build, schedule);
4108 isl_ast_build_free(build);
4110 return tree;
4113 /* This function is called for each statement node in the AST of the code
4114 * for copying to or from shared/private memory.
4115 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4116 * statement to the node.
4117 * The statement name is "read" or "write", depending on whether we are
4118 * reading from global memory or writing to global memory.
4119 * The name of the T space is {shared,private}_<array>.
4121 * The schedule is of the form
4123 * type[A -> T] -> L
4125 * where A refers to a piece of an array and T to the corresponding
4126 * shifted tile. We split this schedule into mappings L -> A and L -> T
4127 * and store the corresponding expressions in stmt->index and stmt->local_index,
4128 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4130 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4131 __isl_keep isl_ast_build *build, void *user)
4133 struct gpu_gen *gen = (struct gpu_gen *) user;
4134 struct ppcg_kernel_stmt *stmt;
4135 isl_id *id;
4136 isl_ast_expr *expr;
4137 isl_space *space;
4138 isl_map *access, *local_access, *map;
4139 isl_pw_multi_aff *pma;
4140 const char *type;
4141 int array_index;
4143 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4144 if (!stmt)
4145 return isl_ast_node_free(node);
4147 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4148 type = isl_map_get_tuple_name(access, isl_dim_in);
4149 stmt->u.c.read = !strcmp(type, "read");
4150 access = isl_map_reverse(access);
4151 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4152 local_access = isl_map_copy(access);
4154 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4155 id = isl_map_get_tuple_id(access, isl_dim_out);
4156 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4157 access = isl_map_apply_range(access, map);
4158 pma = isl_pw_multi_aff_from_map(access);
4159 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4160 stmt->u.c.index = expr;
4162 map = isl_map_range_map(isl_map_universe(space));
4163 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4164 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4165 local_access = isl_map_apply_range(local_access, map);
4166 pma = isl_pw_multi_aff_from_map(local_access);
4167 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4168 stmt->u.c.local_index = expr;
4170 stmt->u.c.array = gen->copy_group->array;
4171 array_index = stmt->u.c.array - gen->prog->array;
4172 stmt->u.c.local_array = &gen->kernel->array[array_index];
4173 stmt->type = ppcg_kernel_copy;
4175 id = isl_id_alloc(gen->ctx, NULL, stmt);
4176 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4177 return isl_ast_node_set_annotation(node, id);
4180 /* Given a schedule of the form
4182 * [S -> A] -> L
4184 * (with S the first shared_len dimensions of the computed schedule,
4185 * A the array and L the schedule correponding to the generated loops),
4186 * indicating where to copy the array elements that need to be copied,
4187 * construct code for performing the copying.
4189 * "group" is the array reference group that is being copied
4190 * "type" is either "read" or "write"
4191 * private is set if copying needs to be performed to/from registers
4193 * We first construct a mapping to a shifted tile of the array,
4195 * [S -> A] -> T(S,A) (1)
4197 * If private is set, then we also use this mapping as a schedule
4198 * (which is already thread-specific and will be completely unrolled).
4199 * Otherwise, we wrap/tile the range over the threads.
4200 * The result is
4202 * [S -> A] -> T'(S,A)
4204 * Combined with the given schedule, we have
4206 * [S -> A] -> [L -> T'(S,A)] (2)
4208 * From the shifted tile mapping, we construct a mapping
4210 * [S -> A] -> [A -> T(S,A)]
4212 * and apply it to the schedule (2), obtaining
4214 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4216 * Note that we can project out S because it is uniquely defined by L.
4218 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4219 __isl_take isl_map *sched,
4220 const char *type, struct gpu_array_ref_group *group,
4221 __isl_take isl_ast_build *build, int private)
4223 isl_space *space;
4224 isl_ast_node *tree;
4225 isl_map *schedule, *shift, *map;
4226 isl_set *set;
4227 isl_id_list *iterators;
4228 int n;
4230 shift = shift_access(group);
4232 schedule = isl_map_copy(shift);
4233 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4234 if (!private)
4235 schedule = tile_access_schedule(gen, schedule);
4237 n = isl_map_dim(schedule, isl_dim_out);
4238 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4239 set = add_bounded_parameters(set, gen->kernel->block_dim,
4240 gen->kernel->thread_ids);
4242 schedule = isl_map_range_product(sched, schedule);
4244 space = isl_space_domain(isl_map_get_space(shift));
4245 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4246 map = isl_map_range_product(map, shift);
4248 schedule = isl_map_apply_domain(schedule, map);
4250 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4252 build = isl_ast_build_restrict(build, set);
4254 gen->copy_group = group;
4256 if (private) {
4257 space = isl_space_range(isl_map_get_space(schedule));
4258 space = isl_space_range(isl_space_unwrap(space));
4259 build = set_unroll(build, space, 0);
4261 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
4262 build = isl_ast_build_set_iterators(build, iterators);
4263 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4264 tree = isl_ast_build_ast_from_schedule(build,
4265 isl_union_map_from_map(schedule));
4266 isl_ast_build_free(build);
4268 return tree;
4271 /* Return code for reading into or writing from shared memory
4272 * the given array reference group.
4274 * If we are performing a read from global memory to shared memory and
4275 * if the array involved is not a scalar, then we copy
4276 * the entire tile to shared memory. This may result in some extra
4277 * elements getting copied, but it should lead to simpler code
4278 * (which means that fewer registers may be needed) and less divergence.
4280 * Otherwise, we only copy the elements that will be read or have been written
4281 * in the kernel.
4284 * The input "sched" is of the form.
4286 * type[S -> A] -> L
4288 * with S the first shared_len dimensions of the computed schedule,
4289 * A the array and L the schedule correponding to the generated loops.
4291 * We first drop "type",
4293 * [S -> A] -> L
4295 * If the above conditions are satisfied, we project out A,
4296 * resulting in
4298 * S -> L
4300 * and then introduce the group tile [S -> T], resulting in
4302 * [S -> T] -> L
4304 static __isl_give isl_ast_node *copy_group_shared_accesses(
4305 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4306 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4308 const char *type;
4309 int read;
4310 isl_union_map *access;
4312 type = isl_map_get_tuple_name(sched, isl_dim_in);
4313 read = !strcmp(type, "read");
4315 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4317 if (read && !gpu_array_is_scalar(group->array)) {
4318 isl_space *space;
4319 isl_map *map;
4321 space = isl_space_domain(isl_map_get_space(sched));
4322 space = isl_space_unwrap(space);
4323 map = isl_map_domain_map(isl_map_universe(space));
4324 sched = isl_map_apply_domain(sched, map);
4326 map = group_tile(group);
4327 map = isl_map_reverse(isl_map_domain_map(map));
4328 sched = isl_map_apply_domain(sched, map);
4331 return copy_access(gen, sched, type, group, build, 0);
4334 /* Return code for reading into or writing from private memory
4335 * the given array reference group.
4337 * Let S be the first shared_len dimensions of the computed schedule,
4338 * D the iteration domains, A the array and L the schedule correponding
4339 * to the generated loops.
4340 * "sched" is of the form
4342 * type[S -> A] -> L
4344 * where type is either "read" or "write".
4345 * We apply the privatization D -> S(t), with t the thread ids,
4346 * to the access relation D -> A to obtain the privatized access relation
4348 * S(t) -> A
4350 * We drop the type from "sched" and intersect with the privatized access
4351 * relation to obtain
4353 * [S(t) -> A] -> L
4355 static __isl_give isl_ast_node *copy_group_private_accesses(
4356 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4357 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4359 const char *type;
4360 int read;
4361 isl_union_map *priv;
4362 isl_union_map *access;
4363 isl_map *access_map;
4365 type = isl_map_get_tuple_name(sched, isl_dim_in);
4366 read = !strcmp(type, "read");
4368 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4369 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4370 priv);
4372 access = group_access_relation(group, read, !read);
4373 access = isl_union_map_apply_domain(access, priv);
4374 access_map = isl_map_from_union_map(access);
4376 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4377 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4379 return copy_access(gen, sched, type, group, build, 1);
4382 /* Return code for reading into or writing from shared or private memory.
4384 * "schedule" is of the form
4386 * type[S -> A] -> L
4388 * with S be the first shared_len dimensions of the computed schedule,
4389 * A the array and L the schedule correponding to the generated loops.
4390 * The array reference group is attached to "type".
4392 static __isl_give isl_ast_node *create_access_leaf(
4393 struct gpu_gen *gen, __isl_take isl_map *schedule,
4394 __isl_take isl_ast_build *build)
4396 struct gpu_array_ref_group *group;
4397 isl_id *id;
4399 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4400 group = isl_id_get_user(id);
4401 isl_id_free(id);
4403 if (group->private_tile)
4404 return copy_group_private_accesses(gen, group, schedule,
4405 build);
4406 else
4407 return copy_group_shared_accesses(gen, group, schedule,
4408 build);
4411 /* Create a domain node representing a synchronization.
4413 static __isl_give isl_ast_node *create_sync_leaf(
4414 struct gpu_gen *gen, __isl_take isl_map *schedule,
4415 __isl_take isl_ast_build *build)
4417 struct ppcg_kernel_stmt *stmt;
4418 isl_id *id;
4419 isl_space *space;
4420 isl_ast_node *node;
4421 isl_ast_expr *expr;
4423 isl_map_free(schedule);
4425 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4426 if (!stmt)
4427 return NULL;
4429 stmt->type = ppcg_kernel_sync;
4431 space = isl_ast_build_get_schedule_space(build);
4432 space = isl_space_from_domain(space);
4433 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4434 expr = isl_ast_build_call_from_pw_multi_aff(build,
4435 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4436 node = isl_ast_node_alloc_user(expr);
4437 isl_ast_build_free(build);
4439 id = isl_id_alloc(gen->ctx, NULL, stmt);
4440 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4441 return isl_ast_node_set_annotation(node, id);
4444 /* This function is called during the code generation at the point
4445 * where the schedule domain element is completely determined by
4446 * the generated code. The input schedule contains the original
4447 * statements as well as synchronization and copy "statements".
4448 * The latter are scheduled at different points than any of the original
4449 * statements, so they will only arrive here in isolation.
4451 * If the current schedule only refers to a single statement,
4452 * we check if it is a copy or synchronization statement and
4453 * call the appropriate functions.
4454 * Otherwise, we assume we are dealing with the original statements
4455 * and we call create_domain_leaf.
4457 static __isl_give isl_ast_node *create_kernel_leaf(
4458 __isl_take isl_ast_build *build, void *user)
4460 struct gpu_gen *gen = (struct gpu_gen *) user;
4461 isl_map *map;
4462 isl_union_map *schedule;
4463 const char *name;
4465 schedule = isl_ast_build_get_schedule(build);
4467 if (isl_union_map_n_map(schedule) != 1)
4468 return create_domain_leaf(schedule, build, user);
4470 map = isl_map_from_union_map(schedule);
4471 name = isl_map_get_tuple_name(map, isl_dim_in);
4472 if (!strcmp(name, "read") || !strcmp(name, "write"))
4473 return create_access_leaf(gen, map, build);
4474 if (!strcmp(name, "sync"))
4475 return create_sync_leaf(gen, map, build);
4477 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4480 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4481 * have value 0) and all even schedule dimensions as "unroll".
4483 * That is, the options look as follows
4485 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4486 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4488 * The even positions are used to be able to schedule copying blocks
4489 * and synchronization before or after each level of the shared memory
4490 * tile loops and we want to make sure that code for these is generated
4491 * separately (within each level).
4493 static __isl_give isl_ast_build *set_atomic_and_unroll(
4494 __isl_take isl_ast_build *build,
4495 __isl_take isl_space *space, int sched_len)
4497 isl_ctx *ctx;
4498 isl_map *map;
4499 isl_constraint *c;
4500 isl_union_map *opt;
4501 isl_local_space *ls;
4502 int i, n;
4504 ctx = isl_ast_build_get_ctx(build);
4506 space = isl_space_params(space);
4507 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4508 space = isl_space_from_domain(space);
4509 space = isl_space_add_dims(space, isl_dim_out, 2);
4510 map = isl_map_universe(isl_space_copy(space));
4511 for (i = 0; i < sched_len; i += 2)
4512 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4513 ls = isl_local_space_from_space(isl_map_get_space(map));
4514 c = isl_equality_alloc(ls);
4515 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4516 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4517 c = isl_constraint_set_constant_si(c, 1);
4518 map = isl_map_add_constraint(map, c);
4519 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4520 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4521 opt = isl_union_map_from_map(map);
4523 map = isl_map_universe(space);
4524 ls = isl_local_space_from_space(isl_map_get_space(map));
4525 c = isl_equality_alloc(ls);
4526 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4527 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4528 map = isl_map_add_constraint(map, c);
4529 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4530 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4531 opt = isl_union_map_add_map(opt, map);
4533 build = isl_ast_build_set_options(build, opt);
4535 return build;
4538 /* Return a map that maps a space of dimension gen->shared_len
4539 * to its last dimensions starting at gen->tile_first.
4540 * The range is of dimension
4542 * 2 * (gen->shared_len - gen->tile_first) + 1
4544 * The input dimensions are mapped to the odd dimensions in the output,
4545 * while the even dimensions (except 2*pos) are fixed to 0.
4546 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4547 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4548 * are mapped to the output. The remaining input dimensions are projected
4549 * out and the corresponding output dimensions are fixed to 0.
4551 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4552 __isl_take isl_space *space, int pos, int val)
4554 int i, n;
4555 isl_map *proj;
4557 space = isl_space_set_from_params(space);
4558 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4559 space = isl_space_map_from_set(space);
4560 proj = isl_map_identity(space);
4561 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4562 n = gen->shared_len - gen->tile_first;
4563 for (i = 0; i <= n; ++i) {
4564 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4565 if (i == pos)
4566 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4567 else
4568 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4571 if (pos < 0)
4572 return proj;
4574 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4575 gen->shared_len - (gen->tile_first + pos));
4576 for (i = pos; i < n; ++i)
4577 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4579 return proj;
4582 /* Given the AST context schedule "schedule" and the mapping from
4583 * domains to the shared tile loops "shared_sched", add a schedule
4584 * for a synchronization operation at position "val" of loop level "pos".
4586 * schedule is of the form
4588 * D -> L
4590 * (with D the iteration domains and L the already generated loops),
4591 * while shared_sched is of the form
4593 * D -> S
4595 * We combine them into
4597 * L -> S
4599 * apply a mapping
4601 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4603 * and use the result as a schedule for "sync".
4605 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4606 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4607 __isl_keep isl_union_map *shared_sched, int pos, int val)
4609 isl_space *space;
4610 isl_map *proj, *map;
4612 shared_sched = isl_union_map_copy(shared_sched);
4613 schedule = isl_union_map_copy(schedule);
4615 space = isl_union_map_get_space(shared_sched);
4616 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4617 map = isl_map_from_union_map(schedule);
4619 proj = insert_even(gen, space, pos, val);
4620 map = isl_map_apply_range(map, proj);
4621 map = isl_map_from_range(isl_map_wrap(map));
4622 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4624 res = isl_union_map_add_map(res, map);
4626 return res;
4629 /* Given a set of wrapped references "ref", return the corresponding
4630 * access relations based on the tagged access relations "tagged".
4632 * The elements of "ref" are of the form
4634 * [D -> R]
4636 * with D an iteration domains and R a reference.
4637 * The elements of "tagged" are of the form
4639 * [D -> R] -> A
4641 * with A an array.
4643 * Extend "tagged" to include the iteration domain in the range, i.e.,
4645 * [D -> R] -> [D -> A]
4647 * apply the result to "ref" and then unwrap the resulting set
4648 * to obtain relations of the form
4650 * D -> A
4652 static __isl_give isl_union_map *wrapped_reference_to_access(
4653 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4655 isl_union_map *tag2access;
4657 tag2access = isl_union_map_copy(tagged);
4658 tag2access = isl_union_map_universe(tag2access);
4659 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4660 tag2access = isl_union_map_domain_map(tag2access);
4661 tag2access = isl_union_map_range_product(tag2access, tagged);
4663 ref = isl_union_set_coalesce(ref);
4664 ref = isl_union_set_apply(ref, tag2access);
4666 return isl_union_set_unwrap(ref);
4669 /* Given an access relation "access" from "group", remove those reads
4670 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4671 * communicate data within the same iteration of the last_shared dimension
4672 * of the group.
4674 * If the access is a read then it is either an element of
4676 * live_in union (range flow)
4678 * where live_in and flow may be overapproximations, or
4679 * it reads an uninitialized value (that is not live-in because
4680 * there is an intermediate kill) or it reads a value that was
4681 * written within the same (compound) statement instance.
4682 * If the access is a write then it is either an element of
4684 * live_out union (domain flow)
4686 * or it writes a value that is never read (and is not live-out
4687 * because of an intermediate kill) or only
4688 * within the same (compound) statement instance.
4689 * In both cases, the access relation is also a subset of
4690 * the group access relation.
4692 * The cases where an uninitialized value is read or a value is written
4693 * that is never read or where the dataflow occurs within a statement
4694 * instance are also considered local and may also be removed.
4696 * Essentially, we compute the intersection of "access" with either
4698 * live_in union (range non-local-flow)
4700 * or
4702 * live_out union (domain non-local-flow)
4704 * We first construct a relation "local"
4706 * [[D -> R] -> [D' -> R']]
4708 * of pairs of domain iterations accessing the reference group
4709 * and references in the group that are scheduled to the same iteration
4710 * of the last_shared dimension.
4712 * If this relation does not intersect the dataflow dependences,
4713 * then there is nothing we can possibly remove, unless the dataflow
4714 * dependences themselves only relate a subset of the accesses.
4715 * In particular, the accesses may not be involved in any dataflow
4716 * dependences, either because they are uninitialized reads/dead writes
4717 * or because the dataflow occurs inside a statement instance.
4719 * Since the computation below may break up the access relation
4720 * into smaller pieces, we only perform the intersection with
4721 * the non-local dependent accesses if the local pairs
4722 * intersect the dataflow dependences. Otherwise, we intersect
4723 * with the universe of the non-local dependent accesses.
4724 * This should at least remove accesses from statements that
4725 * do not participate in any dependences.
4727 * In particular, we remove the "local" dataflow dependences from
4728 * the set of all dataflow dependences.
4729 * Note that if the potential dataflow dependences are an overapproximation
4730 * of the actual dataflow dependences, then the result remains an
4731 * overapproximation of the non-local dataflow dependences.
4732 * Copying to/from global memory is only needed for the references
4733 * in the domain/range of the result or for accesses that are live out/in
4734 * for the entire scop.
4736 * We therefore map the domain/range of the "external" relation
4737 * to the corresponding access relation and take the union with
4738 * the live out/in relation.
4740 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4741 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4742 int read)
4744 int empty;
4745 isl_union_map *tagger;
4746 isl_union_set *domain;
4747 isl_space *space;
4748 isl_union_map *sched, *local, *tagged, *external;
4749 isl_union_set *tag_set;
4750 isl_map *proj;
4752 if (isl_union_map_is_empty(access))
4753 return access;
4755 tagged = group_tagged_access_relation(group);
4757 sched = isl_union_map_copy(gen->sched);
4759 space = isl_union_map_get_space(sched);
4760 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4761 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4763 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4764 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4765 tagger = isl_union_map_intersect_range(tagger, domain);
4766 sched = isl_union_map_apply_domain(sched, tagger);
4768 local = isl_union_map_apply_range(sched,
4769 isl_union_map_reverse(isl_union_map_copy(sched)));
4770 local = isl_union_map_intersect(local,
4771 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4773 empty = isl_union_map_is_empty(local);
4775 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4776 external = isl_union_map_intersect_params(external,
4777 isl_set_copy(gen->prog->scop->context));
4778 external = isl_union_map_subtract(external, local);
4780 if (read) {
4781 tag_set = isl_union_map_range(external);
4782 external = wrapped_reference_to_access(tag_set, tagged);
4783 external = isl_union_map_union(external,
4784 isl_union_map_copy(gen->prog->scop->live_in));
4785 } else {
4786 tag_set = isl_union_map_domain(external);
4787 external = wrapped_reference_to_access(tag_set, tagged);
4788 external = isl_union_map_union(external,
4789 isl_union_map_copy(gen->prog->scop->live_out));
4792 if (empty < 0)
4793 external = isl_union_map_free(external);
4794 else if (empty)
4795 external = isl_union_map_universe(external);
4797 access = isl_union_map_intersect(access, external);
4799 return access;
4802 /* Given the AST context schedule "schedule" and the mapping from
4803 * domains to the shared tile loops "shared_sched", add a schedule
4804 * for copying an array reference group to/from shared/private memory.
4805 * "read" is set if data should be copied from global memory
4806 * to shared/private memory.
4807 * "k" represents the current group
4808 * "s" is the total number of groups
4810 * We schedule an operation before or after the innermost loop
4811 * of "shared_sched" that affects the tile of the array reference group.
4813 * schedule is of the form
4815 * D -> L
4817 * (with D the iteration domains and L the already generated loops),
4818 * while shared_sched is of the form
4820 * D -> S
4822 * We first compute the access relation for the reference group
4824 * D -> A
4826 * and remove from this access relation those reads or writes
4827 * that only needed to communicate data within the same iteration
4828 * of the last_shared dimension of the group.
4829 * We then combine what is left with shared_sched into
4831 * D -> [S -> A]
4833 * If this results in an empty relation, no copying needs to be performed
4834 * at this point.
4835 * Otherwise, we invert the relation and combine it with "schedule" into
4837 * [S -> A] -> L
4839 * The actual additional piece of the schedule is obtained from combining
4841 * [S -> A] -> S
4843 * with a mapping
4845 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4847 * The position of "val" corresponds to the innermost loop that affects
4848 * the tile and the value indicates where the copying is scheduled
4849 * with respect to the actual kernel code (at value 0).
4850 * Reads are schedule before the code, writes to global memory from
4851 * private memory are scheduled at values 1 to s, writes to global
4852 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4854 * If we are scheduling a read from global memory to shared memory,
4855 * we insert a synchronization before the kernel code (at the innermost
4856 * level).
4857 * If we are scheduling a write to global memory, then we add
4858 * a synchronization after all writes (at value 2 *s + 2).
4859 * However, there is no need for a synchronization after the outermost loop.
4860 * A write to global memory from private memory at the innermost level
4861 * does not require a synchronization, because it is covered by
4862 * the synchronization after the kernel inserted by body_schedule.
4864 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4865 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4866 __isl_keep isl_union_map *shared_sched,
4867 struct gpu_array_ref_group *group, int read, int k, int s)
4869 int n;
4870 int pos, val;
4871 isl_space *space;
4872 isl_union_map *access;
4873 isl_map *map, *proj, *access_map;
4874 isl_id *id;
4876 access = group_access_relation(group, read, !read);
4877 access = remove_local_accesses(gen, group, access, read);
4878 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4879 access);
4881 if (isl_union_map_is_empty(access)) {
4882 isl_union_map_free(access);
4883 return res;
4886 access = isl_union_map_reverse(access);
4887 access = isl_union_map_apply_range(access,
4888 isl_union_map_copy(schedule));
4889 access_map = isl_map_from_union_map(access);
4891 space = isl_space_copy(group->array->space);
4892 space = isl_space_from_range(space);
4893 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4894 map = isl_map_domain_map(isl_map_universe(space));
4896 space = isl_union_map_get_space(schedule);
4897 pos = group->last_shared + 1 - gen->tile_first;
4898 assert(pos >= 0);
4899 if (read)
4900 val = -2 - k;
4901 else if (group->private_tile)
4902 val = 1 + k;
4903 else
4904 val = 1 + s + 1 + k;
4905 proj = insert_even(gen, space, pos, val);
4906 map = isl_map_apply_range(map, proj);
4908 access_map = isl_map_range_product(access_map, map);
4910 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4911 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4913 res = isl_union_map_add_map(res, access_map);
4915 n = gen->shared_len - gen->tile_first;
4916 if (read) {
4917 if (!group->private_tile)
4918 res = add_sync_schedule(gen, res, schedule,
4919 shared_sched, n, -1);
4920 } else {
4921 if (pos == 0)
4922 return res;
4923 if (pos == n && group->private_tile)
4924 return res;
4925 res = add_sync_schedule(gen, res, schedule, shared_sched,
4926 pos, 2 * s + 2);
4929 return res;
4932 /* Return a schedule for the shared tile loops based on the current
4933 * AST context schedule.
4935 * We create a "shared_sched" that maps the domains to the first
4936 * shared_len dimensions of the computed schedule, project out the
4937 * first tile_first dimensions (as these are already covered by
4938 * the host code) and insert "statement-level" dimensions at even
4939 * positions so that we can schedule copy blocks and synchronization
4940 * before/after each level.
4942 * In particular, copy blocks are inserted inside the innermost
4943 * level that affect the tile. For the copying to global memory,
4944 * those from private memory are scheduled before those from shared
4945 * memory such that synchronization can be inserted between the two
4946 * at the innermost level.
4947 * Synchronization is inserted at the innermost level before the
4948 * actual kernel code if there is any copying from global memory
4949 * to shared memory. It is inserted unconditionally at the innermost
4950 * level after the actual kernel code and the copying to global memory
4951 * from private memory (if any). Finally, it is inserted after
4952 * any copying to global memory, except at the outermost level
4953 * and at the innermost level if there is no copying from shared
4954 * memory. The copying from private memory is covered by the unconditional
4955 * synchronization at the innermost level.
4957 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4958 __isl_take isl_union_map *schedule)
4960 isl_space *space;
4961 isl_union_map *res;
4962 isl_union_map *shared_sched;
4963 isl_union_map *sched;
4964 isl_map *proj, *map;
4965 int i, j, k, s;
4967 shared_sched = isl_union_map_copy(gen->tiled_sched);
4968 proj = projection(isl_union_map_get_space(shared_sched),
4969 gen->tiled_len, gen->shared_len);
4970 shared_sched = isl_union_map_apply_range(shared_sched,
4971 isl_union_map_from_map(proj));
4972 space = isl_union_map_get_space(shared_sched);
4973 proj = insert_even(gen, space, -1, 0);
4974 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4975 isl_union_map_from_map(proj));
4977 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4979 s = 0;
4980 for (i = 0; i < gen->prog->n_array; ++i)
4981 s += gen->prog->array[i].n_group;
4983 k = 0;
4984 for (i = 0; i < gen->prog->n_array; ++i) {
4985 struct gpu_array_info *array = &gen->prog->array[i];
4987 for (j = 0; j < array->n_group; ++j) {
4988 struct gpu_array_ref_group *group;
4990 group = array->groups[j];
4991 if (!group->private_tile && !group->shared_tile)
4992 continue;
4993 res = add_group_schedule(gen, res, schedule,
4994 shared_sched, group, 0, k, s);
4995 res = add_group_schedule(gen, res, schedule,
4996 shared_sched, group, 1, k, s);
4997 ++k;
5001 res = add_sync_schedule(gen, res, schedule, shared_sched,
5002 gen->shared_len - gen->tile_first, 1 + s);
5004 isl_union_map_free(shared_sched);
5005 isl_union_map_free(schedule);
5007 return res;
5010 /* Generate code for "kernel" in the given "context".
5012 * We first generate code for the shared tile loops (T1T, T1P and T2)
5013 * in a context that includes the block ids.
5014 * Within each iteration of these loops an additional code generation
5015 * is performed (within create_kernel_leaf) for the rest of the schedule
5016 * in a context that includes the thread ids.
5018 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
5019 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
5020 __isl_keep isl_multi_pw_aff *grid_size)
5022 isl_space *space;
5023 isl_set *set;
5024 isl_id_list *iterators;
5025 isl_union_map *schedule;
5026 isl_ast_node *tree;
5027 int sched_len;
5029 schedule = isl_ast_build_get_schedule(build);
5031 build = isl_ast_build_copy(build);
5032 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5033 space = isl_ast_build_get_schedule_space(build);
5034 set = isl_set_universe(isl_space_copy(space));
5035 set = add_bounded_parameters_dynamic(set, grid_size,
5036 gen->kernel->block_ids);
5037 build = isl_ast_build_restrict(build, set);
5039 schedule = body_schedule(gen, schedule);
5041 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5043 build = set_atomic_and_unroll(build, space, sched_len);
5044 iterators = ppcg_scop_generate_names(gen->prog->scop, sched_len, "g");
5045 build = isl_ast_build_set_iterators(build, iterators);
5046 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5047 tree = isl_ast_build_ast_from_schedule(build, schedule);
5048 isl_ast_build_free(build);
5050 return tree;
5053 /* Attach "id" to the given node.
5055 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5056 __isl_keep isl_ast_build *build, void *user)
5058 isl_id *id = user;
5060 node = isl_ast_node_set_annotation(node, id);
5062 return node;
5065 /* Construct an AST node for performing a kernel launch and attach
5066 * the information about the kernel to that node.
5068 * The kernel AST has been constructed in the context of the range
5069 * of "schedule". In particular, the grid size has been computed
5070 * in the context. We therefore still need to make sure that these
5071 * constraints are expressed in the code. We do this by creating a schedule
5073 * kernel[] -> [S -> []]
5075 * where S is the schedule domain, i.e., the range of "schedule".
5076 * The AST generation will then create a single call surrounded by
5077 * all the condition in "S" that have not been expressed yet.
5079 * The kernel information is attached to this node in attach_id.
5081 static __isl_give isl_ast_node *construct_launch(
5082 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5083 __isl_take struct ppcg_kernel *kernel)
5085 isl_id *id;
5086 isl_ctx *ctx;
5087 isl_union_set *domain;
5088 isl_set *set;
5089 isl_map *map;
5090 isl_ast_node *node;
5092 ctx = isl_ast_build_get_ctx(build);
5094 id = isl_id_alloc(ctx, NULL, kernel);
5095 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5097 domain = isl_union_map_range(schedule);
5098 set = isl_set_from_union_set(domain);
5099 map = isl_map_from_domain(set);
5100 map = isl_map_from_range(isl_map_wrap(map));
5101 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5102 schedule = isl_union_map_from_map(map);
5104 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5105 node = isl_ast_build_ast_from_schedule(build, schedule);
5106 isl_ast_build_free(build);
5108 return node;
5111 /* This function is called for each leaf in the AST of the host code.
5112 * We first specialize the schedule to the site of the leaf, compute
5113 * the size of shared memory and then construct the body of the host code
5114 * and the associated kernel.
5116 * The necessary information for printing the kernel launch is
5117 * stored in a struct ppcg_kernel and attached to the leaf node
5118 * created to represent the launch.
5120 static __isl_give isl_ast_node *create_host_leaf(
5121 __isl_take isl_ast_build *build, void *user)
5123 struct gpu_gen *gen = (struct gpu_gen *) user;
5124 isl_id *id;
5125 isl_ast_node *node;
5126 struct ppcg_kernel *kernel;
5127 isl_set *host_domain;
5128 isl_union_map *schedule;
5129 isl_union_map *local_sched;
5130 isl_union_map *access;
5131 isl_union_set *domain;
5132 int i;
5134 schedule = isl_ast_build_get_schedule(build);
5136 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5137 read_sizes(gen);
5139 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5141 local_sched = isl_union_map_copy(gen->sched);
5142 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5143 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5144 isl_union_map_copy(gen->prog->may_write));
5145 access = isl_union_map_apply_domain(access,
5146 isl_union_map_copy(local_sched));
5148 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5149 if (!kernel)
5150 goto error;
5151 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
5152 gen->n_grid, "b");
5153 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
5154 gen->n_block, "t");
5156 gen->tiled_sched = tile_schedule(gen, local_sched);
5157 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5158 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5160 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5161 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5162 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5164 kernel->id = gen->kernel_id++;
5165 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5166 kernel->grid_size = extract_grid_size(gen, kernel);
5167 extract_block_size(gen, kernel);
5168 kernel->arrays = isl_union_map_range(access);
5169 kernel->arrays = isl_union_set_apply(kernel->arrays,
5170 isl_union_map_copy(gen->prog->to_outer));
5171 kernel->space = isl_ast_build_get_schedule_space(build);
5173 compute_shared_sched(gen);
5174 gen->privatization = compute_privatization(gen);
5175 check_scalar_live_ranges(gen);
5176 if (group_references(gen) < 0)
5177 schedule = isl_union_map_free(schedule);
5178 host_domain = isl_set_from_union_set(isl_union_map_range(
5179 isl_union_map_copy(schedule)));
5180 localize_bounds(gen, kernel, host_domain);
5182 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5183 check_shared_memory_bound(gen);
5184 compute_group_tilings(gen);
5186 kernel->tree = generate_kernel(gen, build, host_domain,
5187 kernel->grid_size);
5188 create_kernel_vars(gen, kernel);
5190 free_local_array_info(gen);
5191 isl_map_free(gen->privatization);
5192 isl_union_map_free(gen->local_sched);
5193 isl_union_map_free(gen->tiled_sched);
5194 isl_union_map_free(gen->shared_sched);
5195 isl_union_map_free(gen->shared_proj);
5196 isl_set_free(host_domain);
5197 free(gen->tile_size);
5199 node = construct_launch(build, schedule, kernel);
5201 return node;
5202 error:
5203 isl_union_map_free(schedule);
5204 return NULL;
5207 /* Use isl to generate code for the outer gen->tile_first loops
5208 * of the global schedule in gen->sched, resulting in the host code.
5209 * Within each iteration of this partial schedule, i.e., for each kernel
5210 * launch, create_host_leaf takes care of generating the kernel code.
5212 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5214 isl_ast_build *build;
5215 isl_ast_node *tree;
5216 isl_union_map *sched;
5217 isl_map *proj;
5218 isl_id_list *iterators;
5220 sched = isl_union_map_copy(gen->sched);
5221 proj = projection(isl_union_map_get_space(sched),
5222 gen->untiled_len, gen->tile_first);
5223 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5225 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5226 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5227 iterators = ppcg_scop_generate_names(gen->prog->scop,
5228 gen->tile_first, "h");
5229 build = isl_ast_build_set_iterators(build, iterators);
5230 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5231 tree = isl_ast_build_ast_from_schedule(build, sched);
5232 isl_ast_build_free(build);
5234 return tree;
5237 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5239 if (!str)
5240 return NULL;
5241 return isl_union_map_read_from_str(ctx, str);
5244 /* Information about the outermost tilable bands in the forest of bands.
5246 * tile_len and n_parallel are only sets on band_info structures
5247 * that correspond to outermost bands. For other bands (in particular,
5248 * ancestors of the outermost bands), n_parallal is set to 0.
5250 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5252 * tile_first is the number of schedule dimensions in prefix.
5254 * suffix is the schedule of the outermost tilable bands and their descendants.
5256 struct band_info {
5257 struct gpu_gen *gen;
5258 int tile_first;
5259 int tile_len;
5260 int n_parallel;
5261 isl_union_map *prefix;
5262 isl_union_map *suffix;
5265 /* Set tile_len and n_parallel of the statement to that of
5266 * their outermost band, recorded in the band_info.
5268 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5270 struct band_info *info = user;
5271 struct gpu_stmt *stmt;
5272 isl_id *id;
5274 id = isl_map_get_tuple_id(map, isl_dim_in);
5275 stmt = find_stmt(info->gen->prog, id);
5276 isl_id_free(id);
5278 stmt->tile_len = info->tile_len;
5279 stmt->n_parallel = info->n_parallel;
5281 isl_map_free(map);
5283 return 0;
5286 static void list_select_outer_band(struct gpu_gen *gen,
5287 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5289 /* Check if this band has any parallel loops. If so, take it as
5290 * the outermost tilable band. If not, continue looking for the
5291 * outermost tilable band in the children of the current band.
5293 static void band_select_outer_band(struct gpu_gen *gen,
5294 __isl_take isl_band *band, int pos, struct band_info *info)
5296 int n = isl_band_n_member(band);
5297 int n_parallel;
5299 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5300 if (!isl_band_member_is_coincident(band, n_parallel))
5301 break;
5303 info->n_parallel = n_parallel;
5304 if (n_parallel) {
5305 gen->any_parallelism = 1;
5306 info->gen = gen;
5307 info->tile_first = pos;
5308 info->tile_len = n;
5309 info->prefix = isl_band_get_prefix_schedule(band);
5310 info->suffix = isl_union_map_flat_range_product(
5311 isl_band_get_partial_schedule(band),
5312 isl_band_get_suffix_schedule(band));
5313 isl_union_map_foreach_map(info->prefix,
5314 &set_stmt_tile_len, info);
5315 } else if (isl_band_has_children(band)) {
5316 isl_band_list *children;
5317 children = isl_band_get_children(band);
5318 list_select_outer_band(gen, children, pos + n, info);
5319 } else {
5320 info->gen = gen;
5321 info->tile_first = pos + n;
5322 info->tile_len = 0;
5323 info->prefix = isl_union_map_flat_range_product(
5324 isl_band_get_prefix_schedule(band),
5325 isl_band_get_partial_schedule(band));
5326 info->suffix = isl_band_get_suffix_schedule(band);
5327 isl_union_map_foreach_map(info->prefix,
5328 &set_stmt_tile_len, info);
5331 isl_band_free(band);
5334 /* Comparison function that returns a non-zero value for band_infos
5335 * with different tile_len fields or different n_parallel fields.
5337 static int cmp_band(const void *p1, const void *p2)
5339 const struct band_info *info1 = p1;
5340 const struct band_info *info2 = p2;
5342 if (info1->tile_len != info2->tile_len)
5343 return info1->tile_len - info2->tile_len;
5345 return info1->n_parallel - info2->n_parallel;
5348 /* Extend "umap" with coordinates with fixed value "val"
5349 * to a total length of "dst_len", assuming the original dimension is "src_len".
5351 static __isl_give isl_union_map *extend_range(
5352 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5354 isl_space *dim;
5355 isl_map *map;
5356 int i;
5358 dim = isl_union_map_get_space(umap);
5359 map = isl_map_reverse(projection(dim, dst_len, src_len));
5360 for (i = src_len; i < dst_len; ++i)
5361 map = isl_map_fix_si(map, isl_dim_out, i, val);
5363 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5365 return umap;
5368 /* Group bands with the same values for tile_len and n_parallel.
5369 * The prefix schedule is then extended with a fixed coordinate that
5370 * is different for each such group.
5371 * Note that the actual values for this coordinate are not important.
5372 * The bands have already been effectively separated at a higher level
5373 * or they are independent and may be executed in parallel.
5374 * The list of band_info has been sorted before this functions is called.
5376 static void separate_bands(struct band_info *info, int n)
5378 int i;
5379 int j = 0;
5381 for (i = 0; i < n; ++i) {
5382 int l = info[i].tile_first;
5384 if (i &&
5385 (info[i].tile_len != info[i - 1].tile_len ||
5386 info[i].n_parallel != info[i - 1].n_parallel))
5387 j++;
5389 info[i].prefix = extend_range(info[i].prefix,
5390 l, l + 1, j);
5391 info[i].tile_first = l + 1;
5395 /* Select the outermost bands in the elements of the list, align
5396 * their prefix schedules, separate bands with different values
5397 * for tile_len and/or n_parallel and then combine the resulting
5398 * prefix and suffix schedules into a single pair of prefix and
5399 * suffix schedules for the entire list.
5401 static void list_select_outer_band(struct gpu_gen *gen,
5402 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5404 isl_band *band;
5405 int i;
5406 int n = isl_band_list_n_band(list);
5407 isl_ctx *ctx = isl_band_list_get_ctx(list);
5408 struct band_info *info;
5409 int max_tile_first;
5410 isl_union_map *prefix;
5411 isl_union_map *suffix;
5413 assert(n >= 1);
5414 info = isl_calloc_array(ctx, struct band_info, n);
5415 assert(info);
5417 max_tile_first = 0;
5418 for (i = 0; i < n; ++i) {
5419 band = isl_band_list_get_band(list, i);
5420 band_select_outer_band(gen, band, pos, &info[i]);
5421 if (info[i].tile_first > max_tile_first)
5422 max_tile_first = info[i].tile_first;
5425 for (i = 0; i < n; ++i) {
5426 if (info[i].tile_first == max_tile_first)
5427 continue;
5428 info[i].prefix = extend_range(info[i].prefix,
5429 info[i].tile_first, max_tile_first, 0);
5430 info[i].tile_first = max_tile_first;
5433 qsort(info, n, sizeof(struct band_info), &cmp_band);
5435 for (i = 0; i < n - 1; ++i)
5436 if (info[i].tile_len != info[i + 1].tile_len ||
5437 info[i].n_parallel != info[i + 1].n_parallel)
5438 break;
5440 if (i < n -1)
5441 separate_bands(info, n);
5443 prefix = info[0].prefix;
5444 suffix = info[0].suffix;
5446 for (i = 1; i < n; ++i) {
5447 prefix = isl_union_map_union(prefix, info[i].prefix);
5448 suffix = isl_union_map_union(suffix, info[i].suffix);
5451 list_info->tile_first = info[0].tile_first;
5452 list_info->tile_len = -1;
5453 list_info->prefix = prefix;
5454 list_info->suffix = suffix;
5456 isl_band_list_free(list);
5457 free(info);
5460 /* Select the outermost tilable band that (by construction)
5461 * has at least one parallel loop.
5462 * The starting position of the aligned band is stored in the pair
5463 * gen->tile_first.
5464 * The sizes and number of parallel loops may be different in different
5465 * parts of the band forest and are therefore stored in the gpu_stmts.
5467 * Return the complete schedule, with the tilable bands aligned
5468 * at gen->tile_first and padded with zero, if needed.
5470 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5471 __isl_keep isl_schedule *schedule)
5473 isl_band_list *list;
5474 struct band_info info;
5476 gen->n_parallel = 0;
5477 gen->tile_len = -1;
5479 list = isl_schedule_get_band_forest(schedule);
5481 if (isl_band_list_n_band(list) == 0) {
5482 isl_band_list_free(list);
5483 return isl_schedule_get_map(schedule);
5486 list_select_outer_band(gen, list, 0, &info);
5488 gen->tile_first = info.tile_first;
5489 info.suffix = align_range(info.suffix);
5491 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5494 /* Set gen->untiled_len to the number of scheduling dimensions
5495 * for the schedule of the first domain.
5496 * We assume here that this number is the same for all domains.
5498 static int set_untiled_len(__isl_take isl_map *map, void *user)
5500 unsigned *untiled_len = user;
5502 *untiled_len = isl_map_dim(map, isl_dim_out);
5504 isl_map_free(map);
5505 return -1;
5508 /* Compute an appropriate schedule based on the accesses in
5509 * gen->read and gen->write.
5511 * We use the dependences in gen->prog->scop to compute
5512 * a schedule that has a parallel loop in each tilable band.
5513 * Finally, we select the outermost tilable band.
5515 * If live range reordering is allowed, then we need to make sure
5516 * that live ranges on arrays are not run in parallel since doing
5517 * so would require array expansion. We therefore add the array
5518 * order dependences to the coincidence dependences. Non-zero array
5519 * order dependences will then prevent a schedule dimension from being
5520 * considered parallel.
5521 * Live ranges derived from scalars are allowed to be run in parallel
5522 * since we force the scalars to be mapped to private memory in
5523 * check_scalar_live_ranges.
5524 * If live range reordering is allowed, then the false dependences
5525 * are not added to the validity constraints as that would prevent
5526 * reordering. Instead, the external false dependences that enforce that reads
5527 * from potentially live-in data precede any later write and
5528 * that writes of potentially live-out data follow any other earlier write
5529 * are added to the validity and the coincidence constraints.
5530 * The false dependences are still added to the proximity constraints
5531 * for consistency with the case where live range reordering is not allowed.
5532 * The coincidence constraints then consist of flow dependences,
5533 * external false dependences and array order dependences.
5534 * The independences can be filtered out from the first two sets.
5535 * They have already been filtered out from the array order dependences
5536 * on a per array basis in collect_order_dependences.
5537 * There is no need for a per array handling of the other two sets
5538 * as there should be no flow or external false dependence on local
5539 * variables that can be filtered out.
5541 static void compute_schedule(struct gpu_gen *gen)
5543 isl_union_set *domain;
5544 isl_union_map *dep_raw, *dep;
5545 isl_union_map *validity, *proximity, *coincidence;
5546 isl_union_map *sched;
5547 isl_schedule_constraints *sc;
5548 isl_schedule *schedule;
5550 domain = isl_union_set_copy(gen->prog->scop->domain);
5551 domain = isl_union_set_intersect_params(domain,
5552 isl_set_copy(gen->prog->scop->context));
5553 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5554 if (gen->options->live_range_reordering) {
5555 sc = isl_schedule_constraints_set_conditional_validity(sc,
5556 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5557 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5558 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5559 validity = isl_union_map_copy(proximity);
5560 validity = isl_union_map_union(validity,
5561 isl_union_map_copy(gen->prog->scop->dep_external));
5562 proximity = isl_union_map_union(proximity,
5563 isl_union_map_copy(gen->prog->scop->dep_false));
5564 coincidence = isl_union_map_copy(validity);
5565 coincidence = isl_union_map_subtract(coincidence,
5566 isl_union_map_copy(gen->prog->scop->independence));
5567 coincidence = isl_union_map_union(coincidence,
5568 isl_union_map_copy(gen->prog->array_order));
5569 } else {
5570 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5571 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5572 dep = isl_union_map_union(dep, dep_raw);
5573 dep = isl_union_map_coalesce(dep);
5574 proximity = isl_union_map_copy(dep);
5575 coincidence = isl_union_map_copy(dep);
5576 validity = dep;
5578 sc = isl_schedule_constraints_set_validity(sc, validity);
5579 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5580 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5582 if (gen->options->debug->dump_schedule_constraints)
5583 isl_schedule_constraints_dump(sc);
5584 schedule = isl_schedule_constraints_compute_schedule(sc);
5585 if (gen->options->debug->dump_schedule)
5586 isl_schedule_dump(schedule);
5588 sched = select_outer_tilable_band(gen, schedule);
5590 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5591 sched = isl_union_map_intersect_domain(sched, domain);
5592 gen->sched = sched;
5594 isl_schedule_free(schedule);
5597 /* Compute the sets of outer array elements that need to be copied in and out.
5599 * In particular, for each array that is possibly written anywhere in
5600 * gen->prog and that is visible outside the corresponding scop,
5601 * we copy out its entire extent.
5603 * Any array elements that is read without first being written needs
5604 * to be copied in. Furthermore, if there are any array elements that
5605 * are copied out, but that may not be written inside gen->prog, then
5606 * they also need to be copied in to ensure that the value after execution
5607 * is the same as the value before execution, at least for those array
5608 * elements that may have their values preserved by the scop.
5609 * In case the array elements are structures, we need to take into
5610 * account that all members of the structures need to be written
5611 * by gen->prog before we can avoid copying the data structure in.
5613 * While computing the set of array elements that are copied out but
5614 * not necessarily written, we intersect both sets with the context.
5615 * This helps in those cases where the arrays are declared with a fixed size,
5616 * while the accesses are parametric and the context assigns a fixed value
5617 * to the parameters.
5619 * If an element from a local array is read without first being written,
5620 * then there is no point in copying it in since it cannot have been
5621 * written prior to the scop. Warn about the uninitialized read instead.
5623 static void compute_copy_in_and_out(struct gpu_gen *gen)
5625 int i;
5626 isl_union_set *local;
5627 isl_union_set *may_write, *must_write;
5628 isl_union_set *copy_in, *copy_out;
5629 isl_union_set *not_written;
5630 isl_union_map *uninitialized;
5631 isl_union_map *local_uninitialized;
5633 must_write = isl_union_map_range(
5634 isl_union_map_copy(gen->prog->must_write));
5635 must_write = isl_union_set_intersect_params(must_write,
5636 isl_set_copy(gen->prog->context));
5637 may_write = isl_union_map_range(
5638 isl_union_map_copy(gen->prog->may_write));
5639 may_write = isl_union_set_intersect_params(may_write,
5640 isl_set_copy(gen->prog->context));
5641 may_write = isl_union_set_universe(may_write);
5642 may_write = isl_union_set_apply(may_write,
5643 isl_union_map_copy(gen->prog->to_outer));
5644 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5645 local = isl_union_set_copy(copy_out);
5647 for (i = 0; i < gen->prog->n_array; ++i) {
5648 isl_space *space;
5649 isl_set *write_i;
5650 int empty;
5652 space = isl_space_copy(gen->prog->array[i].space);
5654 if (gen->prog->array[i].local) {
5655 isl_set *set;
5657 set = isl_set_universe(space);
5658 local = isl_union_set_add_set(local, set);
5659 continue;
5662 write_i = isl_union_set_extract_set(may_write, space);
5663 empty = isl_set_plain_is_empty(write_i);
5664 isl_set_free(write_i);
5665 if (empty)
5666 continue;
5668 write_i = isl_set_copy(gen->prog->array[i].extent);
5669 copy_out = isl_union_set_add_set(copy_out, write_i);
5671 isl_union_set_free(may_write);
5673 copy_out = isl_union_set_intersect_params(copy_out,
5674 isl_set_copy(gen->prog->context));
5676 gen->prog->copy_out = isl_union_set_copy(copy_out);
5678 copy_out = isl_union_set_apply(copy_out,
5679 isl_union_map_copy(gen->prog->to_inner));
5680 copy_out = isl_union_set_intersect(copy_out,
5681 isl_union_set_copy(gen->prog->may_persist));
5682 not_written = isl_union_set_subtract(copy_out, must_write);
5684 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5685 local_uninitialized = isl_union_map_copy(uninitialized);
5687 local = isl_union_set_apply(local,
5688 isl_union_map_copy(gen->prog->to_inner));
5689 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5690 local);
5691 if (!isl_union_map_is_empty(local_uninitialized)) {
5692 fprintf(stderr,
5693 "possibly uninitialized reads (not copied in):\n");
5694 isl_union_map_dump(local_uninitialized);
5696 uninitialized = isl_union_map_subtract(uninitialized,
5697 local_uninitialized);
5698 copy_in = isl_union_map_range(uninitialized);
5699 copy_in = isl_union_set_union(copy_in, not_written);
5700 copy_in = isl_union_set_apply(copy_in,
5701 isl_union_map_copy(gen->prog->to_outer));
5703 gen->prog->copy_in = copy_in;
5706 /* Internal data structure for extract_access.
5707 * "next_access" points to the end of a linked list that is extended
5708 * by extract_access.
5709 * "single_expression" is set if the access expressions belong to
5710 * an expression statement (i.e., a statement without internal control).
5711 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5713 struct ppcg_extract_access_data {
5714 struct gpu_stmt_access **next_access;
5715 int single_expression;
5716 isl_union_map *any_to_outer;
5719 /* Extract a gpu_stmt_access from "expr", append it to the list
5720 * that ends in *data->next_access and update the end of the list.
5721 * If the access expression performs a write, then it is considered
5722 * exact only if it appears in a single expression statement and
5723 * if its may access relation is equal to its must access relation.
5725 * The combined set of may accesses may be union if member accesses
5726 * are involved, but the entire set is derived from a single reference and
5727 * therefore from a single index expression. These accesses therefore
5728 * all map to the same outer array.
5730 static int extract_access(__isl_keep pet_expr *expr, void *user)
5732 struct ppcg_extract_access_data *data = user;
5733 isl_union_map *may, *tagged;
5734 struct gpu_stmt_access *access;
5735 isl_ctx *ctx;
5736 isl_multi_pw_aff *index;
5738 may = pet_expr_access_get_may_read(expr);
5739 may = isl_union_map_union(may, pet_expr_access_get_may_write(expr));
5740 may = isl_union_map_apply_range(may,
5741 isl_union_map_copy(data->any_to_outer));
5742 ctx = isl_union_map_get_ctx(may);
5743 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5744 assert(access);
5745 access->next = NULL;
5746 access->read = pet_expr_access_is_read(expr);
5747 access->write = pet_expr_access_is_write(expr);
5748 tagged = pet_expr_access_get_tagged_may_read(expr);
5749 tagged = isl_union_map_union(tagged,
5750 pet_expr_access_get_tagged_may_write(expr));
5751 tagged = isl_union_map_apply_range(tagged,
5752 isl_union_map_copy(data->any_to_outer));
5753 access->tagged_access = isl_map_from_union_map(tagged);
5754 if (!access->write) {
5755 access->exact_write = 1;
5756 } else if (!data->single_expression) {
5757 access->exact_write = 0;
5758 } else {
5759 isl_union_map *must;
5760 must = pet_expr_access_get_must_write(expr);
5761 access->exact_write = isl_union_map_is_equal(must, may);
5762 isl_union_map_free(must);
5764 access->access = isl_map_from_union_map(may);
5765 index = pet_expr_access_get_index(expr);
5766 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5767 isl_multi_pw_aff_free(index);
5768 access->ref_id = pet_expr_access_get_ref_id(expr);
5769 access->group = -1;
5771 *data->next_access = access;
5772 data->next_access = &(*data->next_access)->next;
5774 return 0;
5777 /* Construct a linked list of gpu_stmt_access objects,
5778 * one for each access expression in the statement body.
5779 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5781 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5782 __isl_keep isl_union_map *any_to_outer)
5784 struct ppcg_extract_access_data data;
5786 stmt->accesses = NULL;
5787 data.next_access = &stmt->accesses;
5788 data.single_expression =
5789 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5790 data.any_to_outer = any_to_outer;
5791 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5794 /* Return an array of gpu_stmt representing the statements in "scop".
5796 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5797 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5799 int i;
5800 struct gpu_stmt *stmts;
5802 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5803 if (!stmts)
5804 return NULL;
5806 for (i = 0; i < scop->pet->n_stmt; ++i) {
5807 struct gpu_stmt *s = &stmts[i];
5809 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5810 s->stmt = scop->pet->stmts[i];
5811 pet_stmt_extract_accesses(s, any_to_outer);
5814 return stmts;
5817 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5819 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5821 struct gpu_gen *gen = user;
5823 return gen->print(p, gen->prog, gen->tree, &gen->types,
5824 gen->print_user);
5827 /* Generate CUDA code for "scop" and print it to "p".
5828 * After generating an AST for the transformed scop as explained below,
5829 * we call "gen->print" to print the AST in the desired output format
5830 * to "p".
5832 * If it turns out that it does not make sense to generate GPU code,
5833 * then we generate CPU code instead.
5835 * The GPU code is generated in a context where at least one
5836 * statement instance is executed. The corresponding guard (if any) is printed
5837 * around the entire generated GPU code, except for the declaration
5838 * of the arrays that are visible outside of the scop and that therefore
5839 * cannot be declared inside the body of any possible guard.
5841 * We first compute a schedule that respects the dependences
5842 * of the original program and select the outermost band
5843 * of tilable dimensions that has at least one parallel loop.
5844 * We then have three blocks of dimensions
5846 * H B G
5848 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5849 * in
5851 * H T P G
5853 * For each iteration of the T loop and for each array, we compute
5854 * the array elements accessed by that iteration, construct a rectangular
5855 * box around it and shift it to the origin. The result is used
5856 * as shared memory for the array.
5858 * We then split off at most 2 parallel loops from the T loops and
5859 * at most 3 parallel loops from the P loops
5861 * H T1 T2 P1 P2 G
5863 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5864 * according to "grid"/"block" sizes.
5866 * H T1T T1P T2 P1T P1P P2 G
5868 * Finally, the T1P and P1P iterators are equated to the block and
5869 * thread dimensions respectively and so are effectively removed.
5870 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5871 * are run on the GPU.
5873 * Code is generated in three stages. We first generate code for the
5874 * host (the H loops), with iterators h%d. Then, for each leaf node
5875 * of the resulting AST, we generate code for the shared loops (up to
5876 * and including T2), with iterators g%d and after equating the H loops
5877 * to h%d parameters and the T1P loops to the block dimensions.
5878 * Finally, we generate code for the remaining loops in a similar fashion.
5880 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5881 struct gpu_gen *gen, struct ppcg_scop *scop,
5882 struct ppcg_options *options)
5884 struct gpu_prog *prog;
5885 isl_ctx *ctx;
5886 isl_set *context, *guard;
5888 if (!scop)
5889 return isl_printer_free(p);
5891 ctx = isl_printer_get_ctx(p);
5892 prog = gpu_prog_alloc(ctx, scop);
5893 if (!prog)
5894 return isl_printer_free(p);
5896 context = isl_set_copy(prog->context);
5897 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5898 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5900 gen->prog = prog;
5901 gen->any_parallelism = 0;
5902 compute_schedule(gen);
5904 if (!gen->any_parallelism) {
5905 isl_set_free(context);
5906 isl_set_free(guard);
5907 p = print_cpu(p, scop, options);
5908 } else {
5909 compute_copy_in_and_out(gen);
5910 gen->tree = generate_host_code(gen);
5911 p = ppcg_print_exposed_declarations(p, prog->scop);
5912 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5913 isl_ast_node_free(gen->tree);
5916 isl_union_map_free(gen->sched);
5918 gpu_prog_free(prog);
5920 return p;
5923 /* Wrapper around generate for use as a ppcg_transform callback.
5925 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5926 struct ppcg_scop *scop, void *user)
5928 struct gpu_gen *gen = user;
5930 return generate(p, gen, scop, gen->options);
5933 /* Transform the code in the file called "input" by replacing
5934 * all scops by corresponding GPU code and write the results to "out".
5936 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5937 struct ppcg_options *options,
5938 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5939 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5940 struct gpu_types *types, void *user), void *user)
5942 struct gpu_gen gen;
5943 int r;
5944 int i;
5946 gen.ctx = ctx;
5947 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5948 gen.options = options;
5949 gen.kernel_id = 0;
5950 gen.print = print;
5951 gen.print_user = user;
5952 gen.types.n = 0;
5953 gen.types.name = NULL;
5955 if (options->debug->dump_sizes) {
5956 isl_space *space = isl_space_params_alloc(ctx, 0);
5957 gen.used_sizes = isl_union_map_empty(space);
5960 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5962 if (options->debug->dump_sizes) {
5963 isl_union_map_dump(gen.used_sizes);
5964 isl_union_map_free(gen.used_sizes);
5967 isl_union_map_free(gen.sizes);
5968 for (i = 0; i < gen.types.n; ++i)
5969 free(gen.types.name[i]);
5970 free(gen.types.name);
5972 return r;
5975 /* Compute the set of inner array elements that may have their values
5976 * preserved by "prog". In particular, collect the array elements of
5977 * arrays that are not local to "prog" and remove those elements that
5978 * are definitely killed or definitely written by "prog".
5980 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5982 int i;
5983 isl_union_set *may_persist, *killed;
5984 isl_union_map *must_kill;
5986 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5987 for (i = 0; i < prog->n_array; ++i) {
5988 isl_set *extent;
5990 if (prog->array[i].local)
5991 continue;
5993 extent = isl_set_copy(prog->array[i].extent);
5994 may_persist = isl_union_set_add_set(may_persist, extent);
5997 may_persist = isl_union_set_intersect_params(may_persist,
5998 isl_set_copy(prog->context));
5999 may_persist = isl_union_set_apply(may_persist,
6000 isl_union_map_copy(prog->to_inner));
6001 must_kill = isl_union_map_copy(prog->tagged_must_kill);
6002 killed = isl_union_map_range(must_kill);
6003 must_kill = isl_union_map_copy(prog->must_write);
6004 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
6006 may_persist = isl_union_set_subtract(may_persist, killed);
6007 return may_persist;
6010 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
6012 struct gpu_prog *prog;
6013 isl_space *space;
6014 isl_map *id;
6016 if (!scop)
6017 return NULL;
6019 prog = isl_calloc_type(ctx, struct gpu_prog);
6020 assert(prog);
6022 prog->ctx = ctx;
6023 prog->scop = scop;
6024 prog->context = isl_set_copy(scop->context);
6025 prog->n_stmts = scop->pet->n_stmt;
6026 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
6027 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
6028 space = isl_union_map_get_space(prog->any_to_outer);
6029 space = isl_space_set_from_params(space);
6030 space = isl_space_add_dims(space, isl_dim_set, 1);
6031 space = isl_space_map_from_set(space);
6032 id = isl_map_identity(space);
6033 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
6034 prog->stmts = extract_stmts(ctx, scop,
6035 prog->context, prog->any_to_outer);
6036 prog->read = isl_union_map_copy(scop->reads);
6037 prog->may_write = isl_union_map_copy(scop->may_writes);
6038 prog->must_write = isl_union_map_copy(scop->must_writes);
6039 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
6040 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
6041 prog->to_outer = isl_union_map_copy(prog->to_inner);
6042 prog->to_outer = isl_union_map_reverse(prog->to_outer);
6044 if (!prog->stmts)
6045 return gpu_prog_free(prog);
6047 if (collect_array_info(prog) < 0)
6048 return gpu_prog_free(prog);
6049 prog->may_persist = compute_may_persist(prog);
6051 return prog;
6054 void *gpu_prog_free(struct gpu_prog *prog)
6056 if (!prog)
6057 return NULL;
6058 free_array_info(prog);
6059 free_stmts(prog->stmts, prog->n_stmts);
6060 isl_union_map_free(prog->any_to_outer);
6061 isl_union_map_free(prog->to_outer);
6062 isl_union_map_free(prog->to_inner);
6063 isl_union_set_free(prog->copy_in);
6064 isl_union_set_free(prog->copy_out);
6065 isl_union_map_free(prog->read);
6066 isl_union_map_free(prog->may_write);
6067 isl_union_map_free(prog->must_write);
6068 isl_union_map_free(prog->tagged_must_kill);
6069 isl_union_map_free(prog->array_order);
6070 isl_union_set_free(prog->may_persist);
6071 isl_set_free(prog->context);
6072 free(prog);
6073 return NULL;