opencl backend: do not declare or allocate arrays that are not accessed
[ppcg.git] / gpu.c
blob621decf1769610e69f52e9ffb6a21ba846b99353
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 an array that is not accessed
3972 * at all, then this means the value of the expression is not used,
3973 * so we might as well print zero (NULL pointer) instead.
3975 * If the AST expression refers to a global scalar that is not
3976 * a read-only scalar, then its address was passed to the kernel and
3977 * we need to dereference it.
3979 * If the AST expression refers to an access to a global array,
3980 * then we linearize the access exploiting the bounds in data->local_array.
3982 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3983 __isl_keep isl_id *id, void *user)
3985 struct ppcg_transform_data *data = user;
3987 if (!data->array)
3988 return expr;
3989 if (!data->array->accessed) {
3990 isl_ctx *ctx;
3992 ctx = isl_ast_expr_get_ctx(expr);
3993 isl_ast_expr_free(expr);
3994 return isl_ast_expr_from_val(isl_val_zero(ctx));
3996 if (gpu_array_is_read_only_scalar(data->array))
3997 return expr;
3998 if (!data->global)
3999 return expr;
4000 if (data->array->n_index == 0)
4001 return dereference(expr);
4002 if (!data->array->linearize)
4003 return expr;
4005 return gpu_local_array_info_linearize_index(data->local_array, expr);
4008 /* This function is called for each instance of a user statement
4009 * in the kernel.
4011 * We attach a struct ppcg_kernel_stmt to the "node", containing
4012 * a computed AST expression for each access.
4013 * These AST expressions are computed from iterator_map,
4014 * which expresses the domain
4015 * elements in terms of the generated loops, and sched2shared,
4016 * which expresses the first shared_len dimensions of the schedule
4017 * computed by PPCG in terms of the generated loops.
4019 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
4020 __isl_keep isl_ast_build *build, void *user)
4022 struct ppcg_transform_data data;
4023 struct gpu_gen *gen = (struct gpu_gen *) user;
4024 struct ppcg_kernel_stmt *stmt;
4025 isl_id *id;
4026 isl_pw_multi_aff *sched2shared;
4027 isl_map *map;
4028 isl_pw_multi_aff *iterator_map;
4029 isl_ast_expr *expr, *arg;
4030 isl_union_map *schedule;
4032 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4033 if (!stmt)
4034 return isl_ast_node_free(node);
4036 expr = isl_ast_node_user_get_expr(node);
4037 arg = isl_ast_expr_get_op_arg(expr, 0);
4038 id = isl_ast_expr_get_id(arg);
4040 schedule = isl_ast_build_get_schedule(build);
4041 map = isl_map_reverse(isl_map_from_union_map(schedule));
4042 iterator_map = isl_pw_multi_aff_from_map(map);
4043 sched2shared = compute_sched_to_shared(gen,
4044 isl_pw_multi_aff_copy(iterator_map));
4046 stmt->type = ppcg_kernel_domain;
4047 stmt->u.d.stmt = find_stmt(gen->prog, id);
4048 if (!stmt->u.d.stmt)
4049 isl_die(gen->ctx, isl_error_internal,
4050 "statement not found", goto error);
4052 data.gen = gen;
4053 data.accesses = stmt->u.d.stmt->accesses;
4054 data.iterator_map = iterator_map;
4055 data.sched2shared = sched2shared;
4056 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4057 build, &transform_index, &data,
4058 &transform_expr, &data);
4060 isl_id_free(id);
4061 isl_pw_multi_aff_free(iterator_map);
4062 isl_pw_multi_aff_free(sched2shared);
4063 isl_ast_expr_free(arg);
4064 isl_ast_expr_free(expr);
4066 id = isl_id_alloc(gen->ctx, NULL, stmt);
4067 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4068 return isl_ast_node_set_annotation(node, id);
4069 error:
4070 isl_id_free(id);
4071 isl_pw_multi_aff_free(iterator_map);
4072 ppcg_kernel_stmt_free(stmt);
4073 isl_pw_multi_aff_free(sched2shared);
4074 return isl_ast_node_free(node);
4077 /* This function is called when code has been generated for the shared
4078 * tile loops. The "schedule" refers only to the original statements.
4080 * We extend the schedule with that part of gen->local_sched that hasn't
4081 * been taken into account yet. This introduces parameters referring
4082 * to thread ids in the schedule, so we add them (with the appropriate
4083 * bounds to the context as well).
4084 * Finally, we set the appropriate unrolling options
4085 * if gen->first_unroll is set.
4087 static __isl_give isl_ast_node *create_domain_leaf(
4088 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4089 void *user)
4091 struct gpu_gen *gen = (struct gpu_gen *) user;
4092 isl_space *space;
4093 isl_union_map *sched;
4094 isl_ast_node *tree;
4095 isl_set *set;
4096 isl_id_list *iterators;
4097 int n;
4099 schedule = extend_schedule(schedule,
4100 isl_union_map_copy(gen->local_sched),
4101 gen->shared_len, gen->thread_tiled_len);
4103 space = isl_ast_build_get_schedule_space(build);
4104 set = isl_set_universe(space);
4105 set = add_bounded_parameters(set, gen->kernel->block_dim,
4106 gen->kernel->thread_ids);
4107 build = isl_ast_build_restrict(build, set);
4109 n = gen->thread_tiled_len - gen->shared_len;
4111 if (gen->first_unroll >= 0) {
4112 space = isl_space_set_alloc(gen->ctx, 0, n);
4113 build = set_unroll(build, space, gen->first_unroll);
4115 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
4116 build = isl_ast_build_set_iterators(build, iterators);
4117 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4118 tree = isl_ast_build_ast_from_schedule(build, schedule);
4119 isl_ast_build_free(build);
4121 return tree;
4124 /* This function is called for each statement node in the AST of the code
4125 * for copying to or from shared/private memory.
4126 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4127 * statement to the node.
4128 * The statement name is "read" or "write", depending on whether we are
4129 * reading from global memory or writing to global memory.
4130 * The name of the T space is {shared,private}_<array>.
4132 * The schedule is of the form
4134 * type[A -> T] -> L
4136 * where A refers to a piece of an array and T to the corresponding
4137 * shifted tile. We split this schedule into mappings L -> A and L -> T
4138 * and store the corresponding expressions in stmt->index and stmt->local_index,
4139 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4141 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4142 __isl_keep isl_ast_build *build, void *user)
4144 struct gpu_gen *gen = (struct gpu_gen *) user;
4145 struct ppcg_kernel_stmt *stmt;
4146 isl_id *id;
4147 isl_ast_expr *expr;
4148 isl_space *space;
4149 isl_map *access, *local_access, *map;
4150 isl_pw_multi_aff *pma;
4151 const char *type;
4152 int array_index;
4154 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4155 if (!stmt)
4156 return isl_ast_node_free(node);
4158 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4159 type = isl_map_get_tuple_name(access, isl_dim_in);
4160 stmt->u.c.read = !strcmp(type, "read");
4161 access = isl_map_reverse(access);
4162 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4163 local_access = isl_map_copy(access);
4165 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4166 id = isl_map_get_tuple_id(access, isl_dim_out);
4167 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4168 access = isl_map_apply_range(access, map);
4169 pma = isl_pw_multi_aff_from_map(access);
4170 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4171 stmt->u.c.index = expr;
4173 map = isl_map_range_map(isl_map_universe(space));
4174 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4175 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4176 local_access = isl_map_apply_range(local_access, map);
4177 pma = isl_pw_multi_aff_from_map(local_access);
4178 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4179 stmt->u.c.local_index = expr;
4181 stmt->u.c.array = gen->copy_group->array;
4182 array_index = stmt->u.c.array - gen->prog->array;
4183 stmt->u.c.local_array = &gen->kernel->array[array_index];
4184 stmt->type = ppcg_kernel_copy;
4186 id = isl_id_alloc(gen->ctx, NULL, stmt);
4187 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4188 return isl_ast_node_set_annotation(node, id);
4191 /* Given a schedule of the form
4193 * [S -> A] -> L
4195 * (with S the first shared_len dimensions of the computed schedule,
4196 * A the array and L the schedule correponding to the generated loops),
4197 * indicating where to copy the array elements that need to be copied,
4198 * construct code for performing the copying.
4200 * "group" is the array reference group that is being copied
4201 * "type" is either "read" or "write"
4202 * private is set if copying needs to be performed to/from registers
4204 * We first construct a mapping to a shifted tile of the array,
4206 * [S -> A] -> T(S,A) (1)
4208 * If private is set, then we also use this mapping as a schedule
4209 * (which is already thread-specific and will be completely unrolled).
4210 * Otherwise, we wrap/tile the range over the threads.
4211 * The result is
4213 * [S -> A] -> T'(S,A)
4215 * Combined with the given schedule, we have
4217 * [S -> A] -> [L -> T'(S,A)] (2)
4219 * From the shifted tile mapping, we construct a mapping
4221 * [S -> A] -> [A -> T(S,A)]
4223 * and apply it to the schedule (2), obtaining
4225 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4227 * Note that we can project out S because it is uniquely defined by L.
4229 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4230 __isl_take isl_map *sched,
4231 const char *type, struct gpu_array_ref_group *group,
4232 __isl_take isl_ast_build *build, int private)
4234 isl_space *space;
4235 isl_ast_node *tree;
4236 isl_map *schedule, *shift, *map;
4237 isl_set *set;
4238 isl_id_list *iterators;
4239 int n;
4241 shift = shift_access(group);
4243 schedule = isl_map_copy(shift);
4244 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4245 if (!private)
4246 schedule = tile_access_schedule(gen, schedule);
4248 n = isl_map_dim(schedule, isl_dim_out);
4249 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4250 set = add_bounded_parameters(set, gen->kernel->block_dim,
4251 gen->kernel->thread_ids);
4253 schedule = isl_map_range_product(sched, schedule);
4255 space = isl_space_domain(isl_map_get_space(shift));
4256 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4257 map = isl_map_range_product(map, shift);
4259 schedule = isl_map_apply_domain(schedule, map);
4261 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4263 build = isl_ast_build_restrict(build, set);
4265 gen->copy_group = group;
4267 if (private) {
4268 space = isl_space_range(isl_map_get_space(schedule));
4269 space = isl_space_range(isl_space_unwrap(space));
4270 build = set_unroll(build, space, 0);
4272 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
4273 build = isl_ast_build_set_iterators(build, iterators);
4274 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4275 tree = isl_ast_build_ast_from_schedule(build,
4276 isl_union_map_from_map(schedule));
4277 isl_ast_build_free(build);
4279 return tree;
4282 /* Return code for reading into or writing from shared memory
4283 * the given array reference group.
4285 * If we are performing a read from global memory to shared memory and
4286 * if the array involved is not a scalar, then we copy
4287 * the entire tile to shared memory. This may result in some extra
4288 * elements getting copied, but it should lead to simpler code
4289 * (which means that fewer registers may be needed) and less divergence.
4291 * Otherwise, we only copy the elements that will be read or have been written
4292 * in the kernel.
4295 * The input "sched" is of the form.
4297 * type[S -> A] -> L
4299 * with S the first shared_len dimensions of the computed schedule,
4300 * A the array and L the schedule correponding to the generated loops.
4302 * We first drop "type",
4304 * [S -> A] -> L
4306 * If the above conditions are satisfied, we project out A,
4307 * resulting in
4309 * S -> L
4311 * and then introduce the group tile [S -> T], resulting in
4313 * [S -> T] -> L
4315 static __isl_give isl_ast_node *copy_group_shared_accesses(
4316 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4317 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4319 const char *type;
4320 int read;
4321 isl_union_map *access;
4323 type = isl_map_get_tuple_name(sched, isl_dim_in);
4324 read = !strcmp(type, "read");
4326 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4328 if (read && !gpu_array_is_scalar(group->array)) {
4329 isl_space *space;
4330 isl_map *map;
4332 space = isl_space_domain(isl_map_get_space(sched));
4333 space = isl_space_unwrap(space);
4334 map = isl_map_domain_map(isl_map_universe(space));
4335 sched = isl_map_apply_domain(sched, map);
4337 map = group_tile(group);
4338 map = isl_map_reverse(isl_map_domain_map(map));
4339 sched = isl_map_apply_domain(sched, map);
4342 return copy_access(gen, sched, type, group, build, 0);
4345 /* Return code for reading into or writing from private memory
4346 * the given array reference group.
4348 * Let S be the first shared_len dimensions of the computed schedule,
4349 * D the iteration domains, A the array and L the schedule correponding
4350 * to the generated loops.
4351 * "sched" is of the form
4353 * type[S -> A] -> L
4355 * where type is either "read" or "write".
4356 * We apply the privatization D -> S(t), with t the thread ids,
4357 * to the access relation D -> A to obtain the privatized access relation
4359 * S(t) -> A
4361 * We drop the type from "sched" and intersect with the privatized access
4362 * relation to obtain
4364 * [S(t) -> A] -> L
4366 static __isl_give isl_ast_node *copy_group_private_accesses(
4367 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4368 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4370 const char *type;
4371 int read;
4372 isl_union_map *priv;
4373 isl_union_map *access;
4374 isl_map *access_map;
4376 type = isl_map_get_tuple_name(sched, isl_dim_in);
4377 read = !strcmp(type, "read");
4379 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4380 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4381 priv);
4383 access = group_access_relation(group, read, !read);
4384 access = isl_union_map_apply_domain(access, priv);
4385 access_map = isl_map_from_union_map(access);
4387 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4388 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4390 return copy_access(gen, sched, type, group, build, 1);
4393 /* Return code for reading into or writing from shared or private memory.
4395 * "schedule" is of the form
4397 * type[S -> A] -> L
4399 * with S be the first shared_len dimensions of the computed schedule,
4400 * A the array and L the schedule correponding to the generated loops.
4401 * The array reference group is attached to "type".
4403 static __isl_give isl_ast_node *create_access_leaf(
4404 struct gpu_gen *gen, __isl_take isl_map *schedule,
4405 __isl_take isl_ast_build *build)
4407 struct gpu_array_ref_group *group;
4408 isl_id *id;
4410 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4411 group = isl_id_get_user(id);
4412 isl_id_free(id);
4414 if (group->private_tile)
4415 return copy_group_private_accesses(gen, group, schedule,
4416 build);
4417 else
4418 return copy_group_shared_accesses(gen, group, schedule,
4419 build);
4422 /* Create a domain node representing a synchronization.
4424 static __isl_give isl_ast_node *create_sync_leaf(
4425 struct gpu_gen *gen, __isl_take isl_map *schedule,
4426 __isl_take isl_ast_build *build)
4428 struct ppcg_kernel_stmt *stmt;
4429 isl_id *id;
4430 isl_space *space;
4431 isl_ast_node *node;
4432 isl_ast_expr *expr;
4434 isl_map_free(schedule);
4436 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4437 if (!stmt)
4438 return NULL;
4440 stmt->type = ppcg_kernel_sync;
4442 space = isl_ast_build_get_schedule_space(build);
4443 space = isl_space_from_domain(space);
4444 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4445 expr = isl_ast_build_call_from_pw_multi_aff(build,
4446 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4447 node = isl_ast_node_alloc_user(expr);
4448 isl_ast_build_free(build);
4450 id = isl_id_alloc(gen->ctx, NULL, stmt);
4451 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4452 return isl_ast_node_set_annotation(node, id);
4455 /* This function is called during the code generation at the point
4456 * where the schedule domain element is completely determined by
4457 * the generated code. The input schedule contains the original
4458 * statements as well as synchronization and copy "statements".
4459 * The latter are scheduled at different points than any of the original
4460 * statements, so they will only arrive here in isolation.
4462 * If the current schedule only refers to a single statement,
4463 * we check if it is a copy or synchronization statement and
4464 * call the appropriate functions.
4465 * Otherwise, we assume we are dealing with the original statements
4466 * and we call create_domain_leaf.
4468 static __isl_give isl_ast_node *create_kernel_leaf(
4469 __isl_take isl_ast_build *build, void *user)
4471 struct gpu_gen *gen = (struct gpu_gen *) user;
4472 isl_map *map;
4473 isl_union_map *schedule;
4474 const char *name;
4476 schedule = isl_ast_build_get_schedule(build);
4478 if (isl_union_map_n_map(schedule) != 1)
4479 return create_domain_leaf(schedule, build, user);
4481 map = isl_map_from_union_map(schedule);
4482 name = isl_map_get_tuple_name(map, isl_dim_in);
4483 if (!strcmp(name, "read") || !strcmp(name, "write"))
4484 return create_access_leaf(gen, map, build);
4485 if (!strcmp(name, "sync"))
4486 return create_sync_leaf(gen, map, build);
4488 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4491 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4492 * have value 0) and all even schedule dimensions as "unroll".
4494 * That is, the options look as follows
4496 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4497 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4499 * The even positions are used to be able to schedule copying blocks
4500 * and synchronization before or after each level of the shared memory
4501 * tile loops and we want to make sure that code for these is generated
4502 * separately (within each level).
4504 static __isl_give isl_ast_build *set_atomic_and_unroll(
4505 __isl_take isl_ast_build *build,
4506 __isl_take isl_space *space, int sched_len)
4508 isl_ctx *ctx;
4509 isl_map *map;
4510 isl_constraint *c;
4511 isl_union_map *opt;
4512 isl_local_space *ls;
4513 int i, n;
4515 ctx = isl_ast_build_get_ctx(build);
4517 space = isl_space_params(space);
4518 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4519 space = isl_space_from_domain(space);
4520 space = isl_space_add_dims(space, isl_dim_out, 2);
4521 map = isl_map_universe(isl_space_copy(space));
4522 for (i = 0; i < sched_len; i += 2)
4523 map = isl_map_fix_si(map, isl_dim_in, i, 0);
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 c = isl_constraint_set_constant_si(c, 1);
4529 map = isl_map_add_constraint(map, c);
4530 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4531 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4532 opt = isl_union_map_from_map(map);
4534 map = isl_map_universe(space);
4535 ls = isl_local_space_from_space(isl_map_get_space(map));
4536 c = isl_equality_alloc(ls);
4537 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4538 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4539 map = isl_map_add_constraint(map, c);
4540 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4541 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4542 opt = isl_union_map_add_map(opt, map);
4544 build = isl_ast_build_set_options(build, opt);
4546 return build;
4549 /* Return a map that maps a space of dimension gen->shared_len
4550 * to its last dimensions starting at gen->tile_first.
4551 * The range is of dimension
4553 * 2 * (gen->shared_len - gen->tile_first) + 1
4555 * The input dimensions are mapped to the odd dimensions in the output,
4556 * while the even dimensions (except 2*pos) are fixed to 0.
4557 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4558 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4559 * are mapped to the output. The remaining input dimensions are projected
4560 * out and the corresponding output dimensions are fixed to 0.
4562 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4563 __isl_take isl_space *space, int pos, int val)
4565 int i, n;
4566 isl_map *proj;
4568 space = isl_space_set_from_params(space);
4569 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4570 space = isl_space_map_from_set(space);
4571 proj = isl_map_identity(space);
4572 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4573 n = gen->shared_len - gen->tile_first;
4574 for (i = 0; i <= n; ++i) {
4575 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4576 if (i == pos)
4577 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4578 else
4579 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4582 if (pos < 0)
4583 return proj;
4585 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4586 gen->shared_len - (gen->tile_first + pos));
4587 for (i = pos; i < n; ++i)
4588 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4590 return proj;
4593 /* Given the AST context schedule "schedule" and the mapping from
4594 * domains to the shared tile loops "shared_sched", add a schedule
4595 * for a synchronization operation at position "val" of loop level "pos".
4597 * schedule is of the form
4599 * D -> L
4601 * (with D the iteration domains and L the already generated loops),
4602 * while shared_sched is of the form
4604 * D -> S
4606 * We combine them into
4608 * L -> S
4610 * apply a mapping
4612 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4614 * and use the result as a schedule for "sync".
4616 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4617 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4618 __isl_keep isl_union_map *shared_sched, int pos, int val)
4620 isl_space *space;
4621 isl_map *proj, *map;
4623 shared_sched = isl_union_map_copy(shared_sched);
4624 schedule = isl_union_map_copy(schedule);
4626 space = isl_union_map_get_space(shared_sched);
4627 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4628 map = isl_map_from_union_map(schedule);
4630 proj = insert_even(gen, space, pos, val);
4631 map = isl_map_apply_range(map, proj);
4632 map = isl_map_from_range(isl_map_wrap(map));
4633 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4635 res = isl_union_map_add_map(res, map);
4637 return res;
4640 /* Given a set of wrapped references "ref", return the corresponding
4641 * access relations based on the tagged access relations "tagged".
4643 * The elements of "ref" are of the form
4645 * [D -> R]
4647 * with D an iteration domains and R a reference.
4648 * The elements of "tagged" are of the form
4650 * [D -> R] -> A
4652 * with A an array.
4654 * Extend "tagged" to include the iteration domain in the range, i.e.,
4656 * [D -> R] -> [D -> A]
4658 * apply the result to "ref" and then unwrap the resulting set
4659 * to obtain relations of the form
4661 * D -> A
4663 static __isl_give isl_union_map *wrapped_reference_to_access(
4664 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4666 isl_union_map *tag2access;
4668 tag2access = isl_union_map_copy(tagged);
4669 tag2access = isl_union_map_universe(tag2access);
4670 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4671 tag2access = isl_union_map_domain_map(tag2access);
4672 tag2access = isl_union_map_range_product(tag2access, tagged);
4674 ref = isl_union_set_coalesce(ref);
4675 ref = isl_union_set_apply(ref, tag2access);
4677 return isl_union_set_unwrap(ref);
4680 /* Given an access relation "access" from "group", remove those reads
4681 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4682 * communicate data within the same iteration of the last_shared dimension
4683 * of the group.
4685 * If the access is a read then it is either an element of
4687 * live_in union (range flow)
4689 * where live_in and flow may be overapproximations, or
4690 * it reads an uninitialized value (that is not live-in because
4691 * there is an intermediate kill) or it reads a value that was
4692 * written within the same (compound) statement instance.
4693 * If the access is a write then it is either an element of
4695 * live_out union (domain flow)
4697 * or it writes a value that is never read (and is not live-out
4698 * because of an intermediate kill) or only
4699 * within the same (compound) statement instance.
4700 * In both cases, the access relation is also a subset of
4701 * the group access relation.
4703 * The cases where an uninitialized value is read or a value is written
4704 * that is never read or where the dataflow occurs within a statement
4705 * instance are also considered local and may also be removed.
4707 * Essentially, we compute the intersection of "access" with either
4709 * live_in union (range non-local-flow)
4711 * or
4713 * live_out union (domain non-local-flow)
4715 * We first construct a relation "local"
4717 * [[D -> R] -> [D' -> R']]
4719 * of pairs of domain iterations accessing the reference group
4720 * and references in the group that are scheduled to the same iteration
4721 * of the last_shared dimension.
4723 * If this relation does not intersect the dataflow dependences,
4724 * then there is nothing we can possibly remove, unless the dataflow
4725 * dependences themselves only relate a subset of the accesses.
4726 * In particular, the accesses may not be involved in any dataflow
4727 * dependences, either because they are uninitialized reads/dead writes
4728 * or because the dataflow occurs inside a statement instance.
4730 * Since the computation below may break up the access relation
4731 * into smaller pieces, we only perform the intersection with
4732 * the non-local dependent accesses if the local pairs
4733 * intersect the dataflow dependences. Otherwise, we intersect
4734 * with the universe of the non-local dependent accesses.
4735 * This should at least remove accesses from statements that
4736 * do not participate in any dependences.
4738 * In particular, we remove the "local" dataflow dependences from
4739 * the set of all dataflow dependences.
4740 * Note that if the potential dataflow dependences are an overapproximation
4741 * of the actual dataflow dependences, then the result remains an
4742 * overapproximation of the non-local dataflow dependences.
4743 * Copying to/from global memory is only needed for the references
4744 * in the domain/range of the result or for accesses that are live out/in
4745 * for the entire scop.
4747 * We therefore map the domain/range of the "external" relation
4748 * to the corresponding access relation and take the union with
4749 * the live out/in relation.
4751 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4752 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4753 int read)
4755 int empty;
4756 isl_union_map *tagger;
4757 isl_union_set *domain;
4758 isl_space *space;
4759 isl_union_map *sched, *local, *tagged, *external;
4760 isl_union_set *tag_set;
4761 isl_map *proj;
4763 if (isl_union_map_is_empty(access))
4764 return access;
4766 tagged = group_tagged_access_relation(group);
4768 sched = isl_union_map_copy(gen->sched);
4770 space = isl_union_map_get_space(sched);
4771 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4772 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4774 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4775 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4776 tagger = isl_union_map_intersect_range(tagger, domain);
4777 sched = isl_union_map_apply_domain(sched, tagger);
4779 local = isl_union_map_apply_range(sched,
4780 isl_union_map_reverse(isl_union_map_copy(sched)));
4781 local = isl_union_map_intersect(local,
4782 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4784 empty = isl_union_map_is_empty(local);
4786 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4787 external = isl_union_map_intersect_params(external,
4788 isl_set_copy(gen->prog->scop->context));
4789 external = isl_union_map_subtract(external, local);
4791 if (read) {
4792 tag_set = isl_union_map_range(external);
4793 external = wrapped_reference_to_access(tag_set, tagged);
4794 external = isl_union_map_union(external,
4795 isl_union_map_copy(gen->prog->scop->live_in));
4796 } else {
4797 tag_set = isl_union_map_domain(external);
4798 external = wrapped_reference_to_access(tag_set, tagged);
4799 external = isl_union_map_union(external,
4800 isl_union_map_copy(gen->prog->scop->live_out));
4803 if (empty < 0)
4804 external = isl_union_map_free(external);
4805 else if (empty)
4806 external = isl_union_map_universe(external);
4808 access = isl_union_map_intersect(access, external);
4810 return access;
4813 /* Given the AST context schedule "schedule" and the mapping from
4814 * domains to the shared tile loops "shared_sched", add a schedule
4815 * for copying an array reference group to/from shared/private memory.
4816 * "read" is set if data should be copied from global memory
4817 * to shared/private memory.
4818 * "k" represents the current group
4819 * "s" is the total number of groups
4821 * We schedule an operation before or after the innermost loop
4822 * of "shared_sched" that affects the tile of the array reference group.
4824 * schedule is of the form
4826 * D -> L
4828 * (with D the iteration domains and L the already generated loops),
4829 * while shared_sched is of the form
4831 * D -> S
4833 * We first compute the access relation for the reference group
4835 * D -> A
4837 * and remove from this access relation those reads or writes
4838 * that only needed to communicate data within the same iteration
4839 * of the last_shared dimension of the group.
4840 * We then combine what is left with shared_sched into
4842 * D -> [S -> A]
4844 * If this results in an empty relation, no copying needs to be performed
4845 * at this point.
4846 * Otherwise, we invert the relation and combine it with "schedule" into
4848 * [S -> A] -> L
4850 * The actual additional piece of the schedule is obtained from combining
4852 * [S -> A] -> S
4854 * with a mapping
4856 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4858 * The position of "val" corresponds to the innermost loop that affects
4859 * the tile and the value indicates where the copying is scheduled
4860 * with respect to the actual kernel code (at value 0).
4861 * Reads are schedule before the code, writes to global memory from
4862 * private memory are scheduled at values 1 to s, writes to global
4863 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4865 * If we are scheduling a read from global memory to shared memory,
4866 * we insert a synchronization before the kernel code (at the innermost
4867 * level).
4868 * If we are scheduling a write to global memory, then we add
4869 * a synchronization after all writes (at value 2 *s + 2).
4870 * However, there is no need for a synchronization after the outermost loop.
4871 * A write to global memory from private memory at the innermost level
4872 * does not require a synchronization, because it is covered by
4873 * the synchronization after the kernel inserted by body_schedule.
4875 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4876 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4877 __isl_keep isl_union_map *shared_sched,
4878 struct gpu_array_ref_group *group, int read, int k, int s)
4880 int n;
4881 int pos, val;
4882 isl_space *space;
4883 isl_union_map *access;
4884 isl_map *map, *proj, *access_map;
4885 isl_id *id;
4887 access = group_access_relation(group, read, !read);
4888 access = remove_local_accesses(gen, group, access, read);
4889 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4890 access);
4892 if (isl_union_map_is_empty(access)) {
4893 isl_union_map_free(access);
4894 return res;
4897 access = isl_union_map_reverse(access);
4898 access = isl_union_map_apply_range(access,
4899 isl_union_map_copy(schedule));
4900 access_map = isl_map_from_union_map(access);
4902 space = isl_space_copy(group->array->space);
4903 space = isl_space_from_range(space);
4904 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4905 map = isl_map_domain_map(isl_map_universe(space));
4907 space = isl_union_map_get_space(schedule);
4908 pos = group->last_shared + 1 - gen->tile_first;
4909 assert(pos >= 0);
4910 if (read)
4911 val = -2 - k;
4912 else if (group->private_tile)
4913 val = 1 + k;
4914 else
4915 val = 1 + s + 1 + k;
4916 proj = insert_even(gen, space, pos, val);
4917 map = isl_map_apply_range(map, proj);
4919 access_map = isl_map_range_product(access_map, map);
4921 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4922 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4924 res = isl_union_map_add_map(res, access_map);
4926 n = gen->shared_len - gen->tile_first;
4927 if (read) {
4928 if (!group->private_tile)
4929 res = add_sync_schedule(gen, res, schedule,
4930 shared_sched, n, -1);
4931 } else {
4932 if (pos == 0)
4933 return res;
4934 if (pos == n && group->private_tile)
4935 return res;
4936 res = add_sync_schedule(gen, res, schedule, shared_sched,
4937 pos, 2 * s + 2);
4940 return res;
4943 /* Return a schedule for the shared tile loops based on the current
4944 * AST context schedule.
4946 * We create a "shared_sched" that maps the domains to the first
4947 * shared_len dimensions of the computed schedule, project out the
4948 * first tile_first dimensions (as these are already covered by
4949 * the host code) and insert "statement-level" dimensions at even
4950 * positions so that we can schedule copy blocks and synchronization
4951 * before/after each level.
4953 * In particular, copy blocks are inserted inside the innermost
4954 * level that affect the tile. For the copying to global memory,
4955 * those from private memory are scheduled before those from shared
4956 * memory such that synchronization can be inserted between the two
4957 * at the innermost level.
4958 * Synchronization is inserted at the innermost level before the
4959 * actual kernel code if there is any copying from global memory
4960 * to shared memory. It is inserted unconditionally at the innermost
4961 * level after the actual kernel code and the copying to global memory
4962 * from private memory (if any). Finally, it is inserted after
4963 * any copying to global memory, except at the outermost level
4964 * and at the innermost level if there is no copying from shared
4965 * memory. The copying from private memory is covered by the unconditional
4966 * synchronization at the innermost level.
4968 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4969 __isl_take isl_union_map *schedule)
4971 isl_space *space;
4972 isl_union_map *res;
4973 isl_union_map *shared_sched;
4974 isl_union_map *sched;
4975 isl_map *proj, *map;
4976 int i, j, k, s;
4978 shared_sched = isl_union_map_copy(gen->tiled_sched);
4979 proj = projection(isl_union_map_get_space(shared_sched),
4980 gen->tiled_len, gen->shared_len);
4981 shared_sched = isl_union_map_apply_range(shared_sched,
4982 isl_union_map_from_map(proj));
4983 space = isl_union_map_get_space(shared_sched);
4984 proj = insert_even(gen, space, -1, 0);
4985 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4986 isl_union_map_from_map(proj));
4988 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4990 s = 0;
4991 for (i = 0; i < gen->prog->n_array; ++i)
4992 s += gen->prog->array[i].n_group;
4994 k = 0;
4995 for (i = 0; i < gen->prog->n_array; ++i) {
4996 struct gpu_array_info *array = &gen->prog->array[i];
4998 for (j = 0; j < array->n_group; ++j) {
4999 struct gpu_array_ref_group *group;
5001 group = array->groups[j];
5002 if (!group->private_tile && !group->shared_tile)
5003 continue;
5004 res = add_group_schedule(gen, res, schedule,
5005 shared_sched, group, 0, k, s);
5006 res = add_group_schedule(gen, res, schedule,
5007 shared_sched, group, 1, k, s);
5008 ++k;
5012 res = add_sync_schedule(gen, res, schedule, shared_sched,
5013 gen->shared_len - gen->tile_first, 1 + s);
5015 isl_union_map_free(shared_sched);
5016 isl_union_map_free(schedule);
5018 return res;
5021 /* Generate code for "kernel" in the given "context".
5023 * We first generate code for the shared tile loops (T1T, T1P and T2)
5024 * in a context that includes the block ids.
5025 * Within each iteration of these loops an additional code generation
5026 * is performed (within create_kernel_leaf) for the rest of the schedule
5027 * in a context that includes the thread ids.
5029 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
5030 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
5031 __isl_keep isl_multi_pw_aff *grid_size)
5033 isl_space *space;
5034 isl_set *set;
5035 isl_id_list *iterators;
5036 isl_union_map *schedule;
5037 isl_ast_node *tree;
5038 int sched_len;
5040 schedule = isl_ast_build_get_schedule(build);
5042 build = isl_ast_build_copy(build);
5043 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5044 space = isl_ast_build_get_schedule_space(build);
5045 set = isl_set_universe(isl_space_copy(space));
5046 set = add_bounded_parameters_dynamic(set, grid_size,
5047 gen->kernel->block_ids);
5048 build = isl_ast_build_restrict(build, set);
5050 schedule = body_schedule(gen, schedule);
5052 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5054 build = set_atomic_and_unroll(build, space, sched_len);
5055 iterators = ppcg_scop_generate_names(gen->prog->scop, sched_len, "g");
5056 build = isl_ast_build_set_iterators(build, iterators);
5057 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5058 tree = isl_ast_build_ast_from_schedule(build, schedule);
5059 isl_ast_build_free(build);
5061 return tree;
5064 /* Attach "id" to the given node.
5066 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5067 __isl_keep isl_ast_build *build, void *user)
5069 isl_id *id = user;
5071 node = isl_ast_node_set_annotation(node, id);
5073 return node;
5076 /* Construct an AST node for performing a kernel launch and attach
5077 * the information about the kernel to that node.
5079 * The kernel AST has been constructed in the context of the range
5080 * of "schedule". In particular, the grid size has been computed
5081 * in the context. We therefore still need to make sure that these
5082 * constraints are expressed in the code. We do this by creating a schedule
5084 * kernel[] -> [S -> []]
5086 * where S is the schedule domain, i.e., the range of "schedule".
5087 * The AST generation will then create a single call surrounded by
5088 * all the condition in "S" that have not been expressed yet.
5090 * The kernel information is attached to this node in attach_id.
5092 static __isl_give isl_ast_node *construct_launch(
5093 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5094 __isl_take struct ppcg_kernel *kernel)
5096 isl_id *id;
5097 isl_ctx *ctx;
5098 isl_union_set *domain;
5099 isl_set *set;
5100 isl_map *map;
5101 isl_ast_node *node;
5103 ctx = isl_ast_build_get_ctx(build);
5105 id = isl_id_alloc(ctx, NULL, kernel);
5106 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5108 domain = isl_union_map_range(schedule);
5109 set = isl_set_from_union_set(domain);
5110 map = isl_map_from_domain(set);
5111 map = isl_map_from_range(isl_map_wrap(map));
5112 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5113 schedule = isl_union_map_from_map(map);
5115 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5116 node = isl_ast_build_ast_from_schedule(build, schedule);
5117 isl_ast_build_free(build);
5119 return node;
5122 /* This function is called for each leaf in the AST of the host code.
5123 * We first specialize the schedule to the site of the leaf, compute
5124 * the size of shared memory and then construct the body of the host code
5125 * and the associated kernel.
5127 * The necessary information for printing the kernel launch is
5128 * stored in a struct ppcg_kernel and attached to the leaf node
5129 * created to represent the launch.
5131 static __isl_give isl_ast_node *create_host_leaf(
5132 __isl_take isl_ast_build *build, void *user)
5134 struct gpu_gen *gen = (struct gpu_gen *) user;
5135 isl_id *id;
5136 isl_ast_node *node;
5137 struct ppcg_kernel *kernel;
5138 isl_set *host_domain;
5139 isl_union_map *schedule;
5140 isl_union_map *local_sched;
5141 isl_union_map *access;
5142 isl_union_set *domain;
5143 int i;
5145 schedule = isl_ast_build_get_schedule(build);
5147 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5148 read_sizes(gen);
5150 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5152 local_sched = isl_union_map_copy(gen->sched);
5153 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5154 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5155 isl_union_map_copy(gen->prog->may_write));
5156 access = isl_union_map_apply_domain(access,
5157 isl_union_map_copy(local_sched));
5159 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5160 if (!kernel)
5161 goto error;
5162 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
5163 gen->n_grid, "b");
5164 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
5165 gen->n_block, "t");
5167 gen->tiled_sched = tile_schedule(gen, local_sched);
5168 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5169 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5171 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5172 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5173 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5175 kernel->id = gen->kernel_id++;
5176 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5177 kernel->grid_size = extract_grid_size(gen, kernel);
5178 extract_block_size(gen, kernel);
5179 kernel->arrays = isl_union_map_range(access);
5180 kernel->arrays = isl_union_set_apply(kernel->arrays,
5181 isl_union_map_copy(gen->prog->to_outer));
5182 kernel->space = isl_ast_build_get_schedule_space(build);
5184 compute_shared_sched(gen);
5185 gen->privatization = compute_privatization(gen);
5186 check_scalar_live_ranges(gen);
5187 if (group_references(gen) < 0)
5188 schedule = isl_union_map_free(schedule);
5189 host_domain = isl_set_from_union_set(isl_union_map_range(
5190 isl_union_map_copy(schedule)));
5191 localize_bounds(gen, kernel, host_domain);
5193 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5194 check_shared_memory_bound(gen);
5195 compute_group_tilings(gen);
5197 kernel->tree = generate_kernel(gen, build, host_domain,
5198 kernel->grid_size);
5199 create_kernel_vars(gen, kernel);
5201 free_local_array_info(gen);
5202 isl_map_free(gen->privatization);
5203 isl_union_map_free(gen->local_sched);
5204 isl_union_map_free(gen->tiled_sched);
5205 isl_union_map_free(gen->shared_sched);
5206 isl_union_map_free(gen->shared_proj);
5207 isl_set_free(host_domain);
5208 free(gen->tile_size);
5210 node = construct_launch(build, schedule, kernel);
5212 return node;
5213 error:
5214 isl_union_map_free(schedule);
5215 return NULL;
5218 /* Use isl to generate code for the outer gen->tile_first loops
5219 * of the global schedule in gen->sched, resulting in the host code.
5220 * Within each iteration of this partial schedule, i.e., for each kernel
5221 * launch, create_host_leaf takes care of generating the kernel code.
5223 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5225 isl_ast_build *build;
5226 isl_ast_node *tree;
5227 isl_union_map *sched;
5228 isl_map *proj;
5229 isl_id_list *iterators;
5231 sched = isl_union_map_copy(gen->sched);
5232 proj = projection(isl_union_map_get_space(sched),
5233 gen->untiled_len, gen->tile_first);
5234 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5236 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5237 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5238 iterators = ppcg_scop_generate_names(gen->prog->scop,
5239 gen->tile_first, "h");
5240 build = isl_ast_build_set_iterators(build, iterators);
5241 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5242 tree = isl_ast_build_ast_from_schedule(build, sched);
5243 isl_ast_build_free(build);
5245 return tree;
5248 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5250 if (!str)
5251 return NULL;
5252 return isl_union_map_read_from_str(ctx, str);
5255 /* Information about the outermost tilable bands in the forest of bands.
5257 * tile_len and n_parallel are only sets on band_info structures
5258 * that correspond to outermost bands. For other bands (in particular,
5259 * ancestors of the outermost bands), n_parallal is set to 0.
5261 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5263 * tile_first is the number of schedule dimensions in prefix.
5265 * suffix is the schedule of the outermost tilable bands and their descendants.
5267 struct band_info {
5268 struct gpu_gen *gen;
5269 int tile_first;
5270 int tile_len;
5271 int n_parallel;
5272 isl_union_map *prefix;
5273 isl_union_map *suffix;
5276 /* Set tile_len and n_parallel of the statement to that of
5277 * their outermost band, recorded in the band_info.
5279 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5281 struct band_info *info = user;
5282 struct gpu_stmt *stmt;
5283 isl_id *id;
5285 id = isl_map_get_tuple_id(map, isl_dim_in);
5286 stmt = find_stmt(info->gen->prog, id);
5287 isl_id_free(id);
5289 stmt->tile_len = info->tile_len;
5290 stmt->n_parallel = info->n_parallel;
5292 isl_map_free(map);
5294 return 0;
5297 static void list_select_outer_band(struct gpu_gen *gen,
5298 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5300 /* Check if this band has any parallel loops. If so, take it as
5301 * the outermost tilable band. If not, continue looking for the
5302 * outermost tilable band in the children of the current band.
5304 static void band_select_outer_band(struct gpu_gen *gen,
5305 __isl_take isl_band *band, int pos, struct band_info *info)
5307 int n = isl_band_n_member(band);
5308 int n_parallel;
5310 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5311 if (!isl_band_member_is_coincident(band, n_parallel))
5312 break;
5314 info->n_parallel = n_parallel;
5315 if (n_parallel) {
5316 gen->any_parallelism = 1;
5317 info->gen = gen;
5318 info->tile_first = pos;
5319 info->tile_len = n;
5320 info->prefix = isl_band_get_prefix_schedule(band);
5321 info->suffix = isl_union_map_flat_range_product(
5322 isl_band_get_partial_schedule(band),
5323 isl_band_get_suffix_schedule(band));
5324 isl_union_map_foreach_map(info->prefix,
5325 &set_stmt_tile_len, info);
5326 } else if (isl_band_has_children(band)) {
5327 isl_band_list *children;
5328 children = isl_band_get_children(band);
5329 list_select_outer_band(gen, children, pos + n, info);
5330 } else {
5331 info->gen = gen;
5332 info->tile_first = pos + n;
5333 info->tile_len = 0;
5334 info->prefix = isl_union_map_flat_range_product(
5335 isl_band_get_prefix_schedule(band),
5336 isl_band_get_partial_schedule(band));
5337 info->suffix = isl_band_get_suffix_schedule(band);
5338 isl_union_map_foreach_map(info->prefix,
5339 &set_stmt_tile_len, info);
5342 isl_band_free(band);
5345 /* Comparison function that returns a non-zero value for band_infos
5346 * with different tile_len fields or different n_parallel fields.
5348 static int cmp_band(const void *p1, const void *p2)
5350 const struct band_info *info1 = p1;
5351 const struct band_info *info2 = p2;
5353 if (info1->tile_len != info2->tile_len)
5354 return info1->tile_len - info2->tile_len;
5356 return info1->n_parallel - info2->n_parallel;
5359 /* Extend "umap" with coordinates with fixed value "val"
5360 * to a total length of "dst_len", assuming the original dimension is "src_len".
5362 static __isl_give isl_union_map *extend_range(
5363 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5365 isl_space *dim;
5366 isl_map *map;
5367 int i;
5369 dim = isl_union_map_get_space(umap);
5370 map = isl_map_reverse(projection(dim, dst_len, src_len));
5371 for (i = src_len; i < dst_len; ++i)
5372 map = isl_map_fix_si(map, isl_dim_out, i, val);
5374 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5376 return umap;
5379 /* Group bands with the same values for tile_len and n_parallel.
5380 * The prefix schedule is then extended with a fixed coordinate that
5381 * is different for each such group.
5382 * Note that the actual values for this coordinate are not important.
5383 * The bands have already been effectively separated at a higher level
5384 * or they are independent and may be executed in parallel.
5385 * The list of band_info has been sorted before this functions is called.
5387 static void separate_bands(struct band_info *info, int n)
5389 int i;
5390 int j = 0;
5392 for (i = 0; i < n; ++i) {
5393 int l = info[i].tile_first;
5395 if (i &&
5396 (info[i].tile_len != info[i - 1].tile_len ||
5397 info[i].n_parallel != info[i - 1].n_parallel))
5398 j++;
5400 info[i].prefix = extend_range(info[i].prefix,
5401 l, l + 1, j);
5402 info[i].tile_first = l + 1;
5406 /* Select the outermost bands in the elements of the list, align
5407 * their prefix schedules, separate bands with different values
5408 * for tile_len and/or n_parallel and then combine the resulting
5409 * prefix and suffix schedules into a single pair of prefix and
5410 * suffix schedules for the entire list.
5412 static void list_select_outer_band(struct gpu_gen *gen,
5413 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5415 isl_band *band;
5416 int i;
5417 int n = isl_band_list_n_band(list);
5418 isl_ctx *ctx = isl_band_list_get_ctx(list);
5419 struct band_info *info;
5420 int max_tile_first;
5421 isl_union_map *prefix;
5422 isl_union_map *suffix;
5424 assert(n >= 1);
5425 info = isl_calloc_array(ctx, struct band_info, n);
5426 assert(info);
5428 max_tile_first = 0;
5429 for (i = 0; i < n; ++i) {
5430 band = isl_band_list_get_band(list, i);
5431 band_select_outer_band(gen, band, pos, &info[i]);
5432 if (info[i].tile_first > max_tile_first)
5433 max_tile_first = info[i].tile_first;
5436 for (i = 0; i < n; ++i) {
5437 if (info[i].tile_first == max_tile_first)
5438 continue;
5439 info[i].prefix = extend_range(info[i].prefix,
5440 info[i].tile_first, max_tile_first, 0);
5441 info[i].tile_first = max_tile_first;
5444 qsort(info, n, sizeof(struct band_info), &cmp_band);
5446 for (i = 0; i < n - 1; ++i)
5447 if (info[i].tile_len != info[i + 1].tile_len ||
5448 info[i].n_parallel != info[i + 1].n_parallel)
5449 break;
5451 if (i < n -1)
5452 separate_bands(info, n);
5454 prefix = info[0].prefix;
5455 suffix = info[0].suffix;
5457 for (i = 1; i < n; ++i) {
5458 prefix = isl_union_map_union(prefix, info[i].prefix);
5459 suffix = isl_union_map_union(suffix, info[i].suffix);
5462 list_info->tile_first = info[0].tile_first;
5463 list_info->tile_len = -1;
5464 list_info->prefix = prefix;
5465 list_info->suffix = suffix;
5467 isl_band_list_free(list);
5468 free(info);
5471 /* Select the outermost tilable band that (by construction)
5472 * has at least one parallel loop.
5473 * The starting position of the aligned band is stored in the pair
5474 * gen->tile_first.
5475 * The sizes and number of parallel loops may be different in different
5476 * parts of the band forest and are therefore stored in the gpu_stmts.
5478 * Return the complete schedule, with the tilable bands aligned
5479 * at gen->tile_first and padded with zero, if needed.
5481 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5482 __isl_keep isl_schedule *schedule)
5484 isl_band_list *list;
5485 struct band_info info;
5487 gen->n_parallel = 0;
5488 gen->tile_len = -1;
5490 list = isl_schedule_get_band_forest(schedule);
5492 if (isl_band_list_n_band(list) == 0) {
5493 isl_band_list_free(list);
5494 return isl_schedule_get_map(schedule);
5497 list_select_outer_band(gen, list, 0, &info);
5499 gen->tile_first = info.tile_first;
5500 info.suffix = align_range(info.suffix);
5502 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5505 /* Set gen->untiled_len to the number of scheduling dimensions
5506 * for the schedule of the first domain.
5507 * We assume here that this number is the same for all domains.
5509 static int set_untiled_len(__isl_take isl_map *map, void *user)
5511 unsigned *untiled_len = user;
5513 *untiled_len = isl_map_dim(map, isl_dim_out);
5515 isl_map_free(map);
5516 return -1;
5519 /* Compute an appropriate schedule based on the accesses in
5520 * gen->read and gen->write.
5522 * We use the dependences in gen->prog->scop to compute
5523 * a schedule that has a parallel loop in each tilable band.
5524 * Finally, we select the outermost tilable band.
5526 * If live range reordering is allowed, then we need to make sure
5527 * that live ranges on arrays are not run in parallel since doing
5528 * so would require array expansion. We therefore add the array
5529 * order dependences to the coincidence dependences. Non-zero array
5530 * order dependences will then prevent a schedule dimension from being
5531 * considered parallel.
5532 * Live ranges derived from scalars are allowed to be run in parallel
5533 * since we force the scalars to be mapped to private memory in
5534 * check_scalar_live_ranges.
5535 * If live range reordering is allowed, then the false dependences
5536 * are not added to the validity constraints as that would prevent
5537 * reordering. Instead, the external false dependences that enforce that reads
5538 * from potentially live-in data precede any later write and
5539 * that writes of potentially live-out data follow any other earlier write
5540 * are added to the validity and the coincidence constraints.
5541 * The false dependences are still added to the proximity constraints
5542 * for consistency with the case where live range reordering is not allowed.
5543 * The coincidence constraints then consist of flow dependences,
5544 * external false dependences and array order dependences.
5545 * The independences can be filtered out from the first two sets.
5546 * They have already been filtered out from the array order dependences
5547 * on a per array basis in collect_order_dependences.
5548 * There is no need for a per array handling of the other two sets
5549 * as there should be no flow or external false dependence on local
5550 * variables that can be filtered out.
5552 static void compute_schedule(struct gpu_gen *gen)
5554 isl_union_set *domain;
5555 isl_union_map *dep_raw, *dep;
5556 isl_union_map *validity, *proximity, *coincidence;
5557 isl_union_map *sched;
5558 isl_schedule_constraints *sc;
5559 isl_schedule *schedule;
5561 domain = isl_union_set_copy(gen->prog->scop->domain);
5562 domain = isl_union_set_intersect_params(domain,
5563 isl_set_copy(gen->prog->scop->context));
5564 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5565 if (gen->options->live_range_reordering) {
5566 sc = isl_schedule_constraints_set_conditional_validity(sc,
5567 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5568 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5569 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5570 validity = isl_union_map_copy(proximity);
5571 validity = isl_union_map_union(validity,
5572 isl_union_map_copy(gen->prog->scop->dep_external));
5573 proximity = isl_union_map_union(proximity,
5574 isl_union_map_copy(gen->prog->scop->dep_false));
5575 coincidence = isl_union_map_copy(validity);
5576 coincidence = isl_union_map_subtract(coincidence,
5577 isl_union_map_copy(gen->prog->scop->independence));
5578 coincidence = isl_union_map_union(coincidence,
5579 isl_union_map_copy(gen->prog->array_order));
5580 } else {
5581 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5582 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5583 dep = isl_union_map_union(dep, dep_raw);
5584 dep = isl_union_map_coalesce(dep);
5585 proximity = isl_union_map_copy(dep);
5586 coincidence = isl_union_map_copy(dep);
5587 validity = dep;
5589 sc = isl_schedule_constraints_set_validity(sc, validity);
5590 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5591 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5593 if (gen->options->debug->dump_schedule_constraints)
5594 isl_schedule_constraints_dump(sc);
5595 schedule = isl_schedule_constraints_compute_schedule(sc);
5596 if (gen->options->debug->dump_schedule)
5597 isl_schedule_dump(schedule);
5599 sched = select_outer_tilable_band(gen, schedule);
5601 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5602 sched = isl_union_map_intersect_domain(sched, domain);
5603 gen->sched = sched;
5605 isl_schedule_free(schedule);
5608 /* Compute the sets of outer array elements that need to be copied in and out.
5610 * In particular, for each array that is possibly written anywhere in
5611 * gen->prog and that is visible outside the corresponding scop,
5612 * we copy out its entire extent.
5614 * Any array elements that is read without first being written needs
5615 * to be copied in. Furthermore, if there are any array elements that
5616 * are copied out, but that may not be written inside gen->prog, then
5617 * they also need to be copied in to ensure that the value after execution
5618 * is the same as the value before execution, at least for those array
5619 * elements that may have their values preserved by the scop.
5620 * In case the array elements are structures, we need to take into
5621 * account that all members of the structures need to be written
5622 * by gen->prog before we can avoid copying the data structure in.
5624 * While computing the set of array elements that are copied out but
5625 * not necessarily written, we intersect both sets with the context.
5626 * This helps in those cases where the arrays are declared with a fixed size,
5627 * while the accesses are parametric and the context assigns a fixed value
5628 * to the parameters.
5630 * If an element from a local array is read without first being written,
5631 * then there is no point in copying it in since it cannot have been
5632 * written prior to the scop. Warn about the uninitialized read instead.
5634 static void compute_copy_in_and_out(struct gpu_gen *gen)
5636 int i;
5637 isl_union_set *local;
5638 isl_union_set *may_write, *must_write;
5639 isl_union_set *copy_in, *copy_out;
5640 isl_union_set *not_written;
5641 isl_union_map *uninitialized;
5642 isl_union_map *local_uninitialized;
5644 must_write = isl_union_map_range(
5645 isl_union_map_copy(gen->prog->must_write));
5646 must_write = isl_union_set_intersect_params(must_write,
5647 isl_set_copy(gen->prog->context));
5648 may_write = isl_union_map_range(
5649 isl_union_map_copy(gen->prog->may_write));
5650 may_write = isl_union_set_intersect_params(may_write,
5651 isl_set_copy(gen->prog->context));
5652 may_write = isl_union_set_universe(may_write);
5653 may_write = isl_union_set_apply(may_write,
5654 isl_union_map_copy(gen->prog->to_outer));
5655 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5656 local = isl_union_set_copy(copy_out);
5658 for (i = 0; i < gen->prog->n_array; ++i) {
5659 isl_space *space;
5660 isl_set *write_i;
5661 int empty;
5663 space = isl_space_copy(gen->prog->array[i].space);
5665 if (gen->prog->array[i].local) {
5666 isl_set *set;
5668 set = isl_set_universe(space);
5669 local = isl_union_set_add_set(local, set);
5670 continue;
5673 write_i = isl_union_set_extract_set(may_write, space);
5674 empty = isl_set_plain_is_empty(write_i);
5675 isl_set_free(write_i);
5676 if (empty)
5677 continue;
5679 write_i = isl_set_copy(gen->prog->array[i].extent);
5680 copy_out = isl_union_set_add_set(copy_out, write_i);
5682 isl_union_set_free(may_write);
5684 copy_out = isl_union_set_intersect_params(copy_out,
5685 isl_set_copy(gen->prog->context));
5687 gen->prog->copy_out = isl_union_set_copy(copy_out);
5689 copy_out = isl_union_set_apply(copy_out,
5690 isl_union_map_copy(gen->prog->to_inner));
5691 copy_out = isl_union_set_intersect(copy_out,
5692 isl_union_set_copy(gen->prog->may_persist));
5693 not_written = isl_union_set_subtract(copy_out, must_write);
5695 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5696 local_uninitialized = isl_union_map_copy(uninitialized);
5698 local = isl_union_set_apply(local,
5699 isl_union_map_copy(gen->prog->to_inner));
5700 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5701 local);
5702 if (!isl_union_map_is_empty(local_uninitialized)) {
5703 fprintf(stderr,
5704 "possibly uninitialized reads (not copied in):\n");
5705 isl_union_map_dump(local_uninitialized);
5707 uninitialized = isl_union_map_subtract(uninitialized,
5708 local_uninitialized);
5709 copy_in = isl_union_map_range(uninitialized);
5710 copy_in = isl_union_set_union(copy_in, not_written);
5711 copy_in = isl_union_set_apply(copy_in,
5712 isl_union_map_copy(gen->prog->to_outer));
5714 gen->prog->copy_in = copy_in;
5717 /* Internal data structure for extract_access.
5718 * "next_access" points to the end of a linked list that is extended
5719 * by extract_access.
5720 * "single_expression" is set if the access expressions belong to
5721 * an expression statement (i.e., a statement without internal control).
5722 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5724 struct ppcg_extract_access_data {
5725 struct gpu_stmt_access **next_access;
5726 int single_expression;
5727 isl_union_map *any_to_outer;
5730 /* Extract a gpu_stmt_access from "expr", append it to the list
5731 * that ends in *data->next_access and update the end of the list.
5732 * If the access expression performs a write, then it is considered
5733 * exact only if it appears in a single expression statement and
5734 * if its may access relation is equal to its must access relation.
5736 * The combined set of may accesses may be union if member accesses
5737 * are involved, but the entire set is derived from a single reference and
5738 * therefore from a single index expression. These accesses therefore
5739 * all map to the same outer array.
5741 static int extract_access(__isl_keep pet_expr *expr, void *user)
5743 struct ppcg_extract_access_data *data = user;
5744 isl_union_map *may, *tagged;
5745 struct gpu_stmt_access *access;
5746 isl_ctx *ctx;
5747 isl_multi_pw_aff *index;
5749 may = pet_expr_access_get_may_read(expr);
5750 may = isl_union_map_union(may, pet_expr_access_get_may_write(expr));
5751 may = isl_union_map_apply_range(may,
5752 isl_union_map_copy(data->any_to_outer));
5753 ctx = isl_union_map_get_ctx(may);
5754 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5755 assert(access);
5756 access->next = NULL;
5757 access->read = pet_expr_access_is_read(expr);
5758 access->write = pet_expr_access_is_write(expr);
5759 tagged = pet_expr_access_get_tagged_may_read(expr);
5760 tagged = isl_union_map_union(tagged,
5761 pet_expr_access_get_tagged_may_write(expr));
5762 tagged = isl_union_map_apply_range(tagged,
5763 isl_union_map_copy(data->any_to_outer));
5764 access->tagged_access = isl_map_from_union_map(tagged);
5765 if (!access->write) {
5766 access->exact_write = 1;
5767 } else if (!data->single_expression) {
5768 access->exact_write = 0;
5769 } else {
5770 isl_union_map *must;
5771 must = pet_expr_access_get_must_write(expr);
5772 access->exact_write = isl_union_map_is_equal(must, may);
5773 isl_union_map_free(must);
5775 access->access = isl_map_from_union_map(may);
5776 index = pet_expr_access_get_index(expr);
5777 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5778 isl_multi_pw_aff_free(index);
5779 access->ref_id = pet_expr_access_get_ref_id(expr);
5780 access->group = -1;
5782 *data->next_access = access;
5783 data->next_access = &(*data->next_access)->next;
5785 return 0;
5788 /* Construct a linked list of gpu_stmt_access objects,
5789 * one for each access expression in the statement body.
5790 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5792 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5793 __isl_keep isl_union_map *any_to_outer)
5795 struct ppcg_extract_access_data data;
5797 stmt->accesses = NULL;
5798 data.next_access = &stmt->accesses;
5799 data.single_expression =
5800 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5801 data.any_to_outer = any_to_outer;
5802 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5805 /* Return an array of gpu_stmt representing the statements in "scop".
5807 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5808 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5810 int i;
5811 struct gpu_stmt *stmts;
5813 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5814 if (!stmts)
5815 return NULL;
5817 for (i = 0; i < scop->pet->n_stmt; ++i) {
5818 struct gpu_stmt *s = &stmts[i];
5820 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5821 s->stmt = scop->pet->stmts[i];
5822 pet_stmt_extract_accesses(s, any_to_outer);
5825 return stmts;
5828 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5830 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5832 struct gpu_gen *gen = user;
5834 return gen->print(p, gen->prog, gen->tree, &gen->types,
5835 gen->print_user);
5838 /* Generate CUDA code for "scop" and print it to "p".
5839 * After generating an AST for the transformed scop as explained below,
5840 * we call "gen->print" to print the AST in the desired output format
5841 * to "p".
5843 * If it turns out that it does not make sense to generate GPU code,
5844 * then we generate CPU code instead.
5846 * The GPU code is generated in a context where at least one
5847 * statement instance is executed. The corresponding guard (if any) is printed
5848 * around the entire generated GPU code, except for the declaration
5849 * of the arrays that are visible outside of the scop and that therefore
5850 * cannot be declared inside the body of any possible guard.
5852 * We first compute a schedule that respects the dependences
5853 * of the original program and select the outermost band
5854 * of tilable dimensions that has at least one parallel loop.
5855 * We then have three blocks of dimensions
5857 * H B G
5859 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5860 * in
5862 * H T P G
5864 * For each iteration of the T loop and for each array, we compute
5865 * the array elements accessed by that iteration, construct a rectangular
5866 * box around it and shift it to the origin. The result is used
5867 * as shared memory for the array.
5869 * We then split off at most 2 parallel loops from the T loops and
5870 * at most 3 parallel loops from the P loops
5872 * H T1 T2 P1 P2 G
5874 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5875 * according to "grid"/"block" sizes.
5877 * H T1T T1P T2 P1T P1P P2 G
5879 * Finally, the T1P and P1P iterators are equated to the block and
5880 * thread dimensions respectively and so are effectively removed.
5881 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5882 * are run on the GPU.
5884 * Code is generated in three stages. We first generate code for the
5885 * host (the H loops), with iterators h%d. Then, for each leaf node
5886 * of the resulting AST, we generate code for the shared loops (up to
5887 * and including T2), with iterators g%d and after equating the H loops
5888 * to h%d parameters and the T1P loops to the block dimensions.
5889 * Finally, we generate code for the remaining loops in a similar fashion.
5891 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5892 struct gpu_gen *gen, struct ppcg_scop *scop,
5893 struct ppcg_options *options)
5895 struct gpu_prog *prog;
5896 isl_ctx *ctx;
5897 isl_set *context, *guard;
5899 if (!scop)
5900 return isl_printer_free(p);
5902 ctx = isl_printer_get_ctx(p);
5903 prog = gpu_prog_alloc(ctx, scop);
5904 if (!prog)
5905 return isl_printer_free(p);
5907 context = isl_set_copy(prog->context);
5908 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5909 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5911 gen->prog = prog;
5912 gen->any_parallelism = 0;
5913 compute_schedule(gen);
5915 if (!gen->any_parallelism) {
5916 isl_set_free(context);
5917 isl_set_free(guard);
5918 p = print_cpu(p, scop, options);
5919 } else {
5920 compute_copy_in_and_out(gen);
5921 gen->tree = generate_host_code(gen);
5922 p = ppcg_print_exposed_declarations(p, prog->scop);
5923 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5924 isl_ast_node_free(gen->tree);
5927 isl_union_map_free(gen->sched);
5929 gpu_prog_free(prog);
5931 return p;
5934 /* Wrapper around generate for use as a ppcg_transform callback.
5936 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5937 struct ppcg_scop *scop, void *user)
5939 struct gpu_gen *gen = user;
5941 return generate(p, gen, scop, gen->options);
5944 /* Transform the code in the file called "input" by replacing
5945 * all scops by corresponding GPU code and write the results to "out".
5947 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5948 struct ppcg_options *options,
5949 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5950 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5951 struct gpu_types *types, void *user), void *user)
5953 struct gpu_gen gen;
5954 int r;
5955 int i;
5957 gen.ctx = ctx;
5958 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5959 gen.options = options;
5960 gen.kernel_id = 0;
5961 gen.print = print;
5962 gen.print_user = user;
5963 gen.types.n = 0;
5964 gen.types.name = NULL;
5966 if (options->debug->dump_sizes) {
5967 isl_space *space = isl_space_params_alloc(ctx, 0);
5968 gen.used_sizes = isl_union_map_empty(space);
5971 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5973 if (options->debug->dump_sizes) {
5974 isl_union_map_dump(gen.used_sizes);
5975 isl_union_map_free(gen.used_sizes);
5978 isl_union_map_free(gen.sizes);
5979 for (i = 0; i < gen.types.n; ++i)
5980 free(gen.types.name[i]);
5981 free(gen.types.name);
5983 return r;
5986 /* Compute the set of inner array elements that may have their values
5987 * preserved by "prog". In particular, collect the array elements of
5988 * arrays that are not local to "prog" and remove those elements that
5989 * are definitely killed or definitely written by "prog".
5991 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5993 int i;
5994 isl_union_set *may_persist, *killed;
5995 isl_union_map *must_kill;
5997 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5998 for (i = 0; i < prog->n_array; ++i) {
5999 isl_set *extent;
6001 if (prog->array[i].local)
6002 continue;
6004 extent = isl_set_copy(prog->array[i].extent);
6005 may_persist = isl_union_set_add_set(may_persist, extent);
6008 may_persist = isl_union_set_intersect_params(may_persist,
6009 isl_set_copy(prog->context));
6010 may_persist = isl_union_set_apply(may_persist,
6011 isl_union_map_copy(prog->to_inner));
6012 must_kill = isl_union_map_copy(prog->tagged_must_kill);
6013 killed = isl_union_map_range(must_kill);
6014 must_kill = isl_union_map_copy(prog->must_write);
6015 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
6017 may_persist = isl_union_set_subtract(may_persist, killed);
6018 return may_persist;
6021 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
6023 struct gpu_prog *prog;
6024 isl_space *space;
6025 isl_map *id;
6027 if (!scop)
6028 return NULL;
6030 prog = isl_calloc_type(ctx, struct gpu_prog);
6031 assert(prog);
6033 prog->ctx = ctx;
6034 prog->scop = scop;
6035 prog->context = isl_set_copy(scop->context);
6036 prog->n_stmts = scop->pet->n_stmt;
6037 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
6038 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
6039 space = isl_union_map_get_space(prog->any_to_outer);
6040 space = isl_space_set_from_params(space);
6041 space = isl_space_add_dims(space, isl_dim_set, 1);
6042 space = isl_space_map_from_set(space);
6043 id = isl_map_identity(space);
6044 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
6045 prog->stmts = extract_stmts(ctx, scop,
6046 prog->context, prog->any_to_outer);
6047 prog->read = isl_union_map_copy(scop->reads);
6048 prog->may_write = isl_union_map_copy(scop->may_writes);
6049 prog->must_write = isl_union_map_copy(scop->must_writes);
6050 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
6051 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
6052 prog->to_outer = isl_union_map_copy(prog->to_inner);
6053 prog->to_outer = isl_union_map_reverse(prog->to_outer);
6055 if (!prog->stmts)
6056 return gpu_prog_free(prog);
6058 if (collect_array_info(prog) < 0)
6059 return gpu_prog_free(prog);
6060 prog->may_persist = compute_may_persist(prog);
6062 return prog;
6065 void *gpu_prog_free(struct gpu_prog *prog)
6067 if (!prog)
6068 return NULL;
6069 free_array_info(prog);
6070 free_stmts(prog->stmts, prog->n_stmts);
6071 isl_union_map_free(prog->any_to_outer);
6072 isl_union_map_free(prog->to_outer);
6073 isl_union_map_free(prog->to_inner);
6074 isl_union_set_free(prog->copy_in);
6075 isl_union_set_free(prog->copy_out);
6076 isl_union_map_free(prog->read);
6077 isl_union_map_free(prog->may_write);
6078 isl_union_map_free(prog->must_write);
6079 isl_union_map_free(prog->tagged_must_kill);
6080 isl_union_map_free(prog->array_order);
6081 isl_union_set_free(prog->may_persist);
6082 isl_set_free(prog->context);
6083 free(prog);
6084 return NULL;