gpu.c: fix typos in comment
[ppcg.git] / gpu.c
blob1f143cb14c851debb963b6fb192c91cfc735e535
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.
410 static int extract_array_info(__isl_take isl_set *array, void *user)
412 int i;
413 struct gpu_prog *prog = (struct gpu_prog *)user;
414 const char *name;
415 int n_index;
416 isl_pw_aff **bounds;
417 struct pet_array *pa;
418 struct gpu_array_info *info;
419 isl_set *extent;
421 info = &prog->array[prog->n_array];
422 prog->n_array++;
424 n_index = isl_set_dim(array, isl_dim_set);
425 name = isl_set_get_tuple_name(array);
426 bounds = isl_alloc_array(isl_set_get_ctx(array),
427 isl_pw_aff *, n_index);
428 if (!bounds)
429 goto error;
431 info->space = isl_set_get_space(array);
432 info->name = strdup(name);
433 info->n_index = n_index;
434 info->bound = bounds;
435 info->linearize = prog->scop->options->linearize_device_arrays;
437 pa = find_array(prog->scop, array);
438 if (!pa)
439 isl_die(isl_set_get_ctx(array), isl_error_internal,
440 "unable to find array in scop", goto error);
442 info->type = strdup(pa->element_type);
443 info->size = pa->element_size;
444 info->local = pa->declared && !pa->exposed;
445 info->has_compound_element = pa->element_is_record;
446 info->read_only_scalar = is_read_only_scalar(info, prog);
448 extent = compute_extent(pa, array);
449 info->extent = extent;
450 for (i = 0; i < n_index; ++i) {
451 isl_set *dom;
452 isl_local_space *ls;
453 isl_aff *one;
454 isl_pw_aff *bound;
456 dom = isl_set_copy(extent);
457 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
458 n_index - (i + 1));
459 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
460 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
461 fprintf(stderr, "unable to determine extent of '%s' "
462 "in dimension %d\n", info->name, i);
463 dom = isl_set_free(dom);
465 bound = isl_set_dim_max(dom, 0);
466 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
467 ls = isl_local_space_from_space(isl_set_get_space(dom));
468 one = isl_aff_zero_on_domain(ls);
469 one = isl_aff_add_constant_si(one, 1);
470 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
471 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
473 bounds[i] = bound;
474 if (!isl_pw_aff_is_cst(bound))
475 info->linearize = 1;
478 collect_references(prog, info);
480 isl_set_free(array);
481 return 0;
482 error:
483 isl_set_free(array);
484 return -1;
487 /* Remove independence from the order constraints "order" on array "array".
488 * Since the pairs of iterations in the filter relation of an independence
489 * are guaranteed to be completely independent by the user, there is
490 * no need to ensure that live ranges are ordered along thong pairs.
491 * We make an exception for local variables, though, as the independence
492 * guarantee does not apply to those.
494 * The order constraints are used in two places.
495 * Those on scalars are used in check_scalar_live_ranges to check if
496 * we need to force the scalar to be private. Any non-local scalar
497 * should not be forced scalar if it only appears in independent loops.
498 * Those on non-scalars are added to the coincidence constraints
499 * in compute_schedule because we do not support any array expansion.
500 * Accesses to non-local arrays should not prevent a loop from being
501 * considered coincident so we should indeed remove those constraints
502 * from the order constraints.
504 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
505 struct gpu_array_info *array, __isl_take isl_union_map *order)
507 int i;
509 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
510 struct pet_independence *pi = prog->scop->pet->independences[i];
511 if (isl_union_set_contains(pi->local, array->space))
512 continue;
514 order = isl_union_map_subtract(order,
515 isl_union_map_copy(pi->filter));
518 return order;
521 /* For each array in "prog", store the (untagged) order dependences
522 * derived from the array in array->dep_order.
523 * In particular, consider all references that access the given array
524 * and take the order dependences that have one of these references
525 * as source. (Since an order dependence relates two references to
526 * the same array, the target of these order dependences will also
527 * be one of these references.)
528 * Additionally, store the union of these array->dep_order relations
529 * for all non-scalar arrays in prog->array_order.
531 void collect_order_dependences(struct gpu_prog *prog)
533 int i;
534 isl_space *space;
535 isl_union_map *accesses;
537 space = isl_union_map_get_space(prog->read);
538 prog->array_order = isl_union_map_empty(space);
540 accesses = isl_union_map_copy(prog->scop->tagged_reads);
541 accesses = isl_union_map_union(accesses,
542 isl_union_map_copy(prog->scop->tagged_may_writes));
543 accesses = isl_union_map_universe(accesses);
544 accesses = isl_union_map_apply_range(accesses,
545 isl_union_map_copy(prog->to_outer));
547 for (i = 0; i < prog->n_array; ++i) {
548 struct gpu_array_info *array = &prog->array[i];
549 isl_set *set;
550 isl_union_set *uset;
551 isl_union_map *order;
553 set = isl_set_universe(isl_space_copy(array->space));
554 uset = isl_union_set_from_set(set);
555 uset = isl_union_map_domain(
556 isl_union_map_intersect_range(isl_union_map_copy(accesses),
557 uset));
558 order = isl_union_map_copy(prog->scop->tagged_dep_order);
559 order = isl_union_map_intersect_domain(order, uset);
560 order = isl_union_map_zip(order);
561 order = isl_union_set_unwrap(isl_union_map_domain(order));
562 order = remove_independences(prog, array, order);
563 array->dep_order = order;
565 if (gpu_array_is_scalar(array) && !array->has_compound_element)
566 continue;
568 prog->array_order = isl_union_map_union(prog->array_order,
569 isl_union_map_copy(array->dep_order));
572 isl_union_map_free(accesses);
575 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
576 * collect them in prog->array.
578 * If there are any member accesses involved, then they are first mapped
579 * to the outer arrays of structs.
581 * If we are allowing live range reordering, then also set
582 * the dep_order field. Otherwise leave it NULL.
584 static int collect_array_info(struct gpu_prog *prog)
586 int r;
587 isl_union_set *arrays;
589 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
590 arrays = isl_union_set_union(arrays,
591 isl_union_map_range(isl_union_map_copy(prog->may_write)));
593 arrays = isl_union_set_apply(arrays,
594 isl_union_map_copy(prog->to_outer));
596 arrays = isl_union_set_coalesce(arrays);
598 prog->n_array = isl_union_set_n_set(arrays);
599 prog->array = isl_calloc_array(prog->ctx,
600 struct gpu_array_info, prog->n_array);
601 assert(prog->array);
602 prog->n_array = 0;
603 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
604 isl_union_set_free(arrays);
606 if (prog->scop->options->live_range_reordering)
607 collect_order_dependences(prog);
609 return r;
612 static void free_array_info(struct gpu_prog *prog)
614 int i, j;
616 for (i = 0; i < prog->n_array; ++i) {
617 int n_index = prog->array[i].n_index;
618 free(prog->array[i].type);
619 free(prog->array[i].name);
620 for (j = 0; j < n_index; ++j)
621 isl_pw_aff_free(prog->array[i].bound[j]);
622 isl_space_free(prog->array[i].space);
623 isl_set_free(prog->array[i].extent);
624 free(prog->array[i].bound);
625 free(prog->array[i].refs);
626 isl_union_map_free(prog->array[i].dep_order);
628 free(prog->array);
631 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
632 * as an array or through a pointer reference, but as a single data element.
633 * At the moment, scalars are represented as zero-dimensional arrays.
634 * Note that the single data element may be an entire structure.
636 int gpu_array_is_scalar(struct gpu_array_info *array)
638 return array->n_index == 0;
641 /* Is "array" a read-only scalar?
643 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
645 return array->read_only_scalar;
648 /* Return the set of parameter values for which the array has a positive
649 * size in all dimensions.
650 * If the sizes are only valid for some parameter values, then those
651 * constraints are also taken into account.
653 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
655 int i;
656 isl_space *space;
657 isl_set *guard;
659 space = isl_space_params(isl_space_copy(array->space));
660 guard = isl_set_universe(space);
662 for (i = 0; i < array->n_index; ++i) {
663 isl_pw_aff *bound;
664 isl_set *guard_i, *zero;
666 bound = isl_pw_aff_copy(array->bound[i]);
667 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
668 zero = isl_pw_aff_zero_set(bound);
669 guard_i = isl_set_subtract(guard_i, zero);
670 guard = isl_set_intersect(guard, guard_i);
673 return guard;
676 /* Internal data structure for extract_size_of_type.
677 * "type" specifies the name of the space that we want to extract.
678 * "res" is used to store the subset of that space.
680 struct ppcg_extract_size_data {
681 const char *type;
682 isl_set *res;
685 /* This function is called for each set in a union_set.
686 * If the name of the set matches data->type, we store the
687 * set in data->res.
689 static int extract_size_of_type(__isl_take isl_set *size, void *user)
691 struct ppcg_extract_size_data *data = user;
692 const char *name;
694 name = isl_set_get_tuple_name(size);
695 if (name && !strcmp(name, data->type)) {
696 data->res = size;
697 return -1;
700 isl_set_free(size);
701 return 0;
704 /* Given a union map { kernel[i] -> *[...] },
705 * return the range in the space called "type" for the kernel with
706 * sequence number "id".
708 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
709 const char *type, int id)
711 isl_space *space;
712 isl_set *dom;
713 isl_union_set *local_sizes;
714 struct ppcg_extract_size_data data = { type, NULL };
716 if (!sizes)
717 return NULL;
719 space = isl_union_map_get_space(sizes);
720 space = isl_space_set_from_params(space);
721 space = isl_space_add_dims(space, isl_dim_set, 1);
722 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
723 dom = isl_set_universe(space);
724 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
726 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
727 isl_union_map_copy(sizes));
728 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
729 isl_union_set_free(local_sizes);
730 return data.res;
733 /* Given a singleton set, extract the first (at most *len) elements
734 * of the single integer tuple into *sizes and update *len if needed.
736 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
738 int i;
739 int dim;
741 if (!set)
742 return;
744 dim = isl_set_dim(set, isl_dim_set);
745 if (dim < *len)
746 *len = dim;
748 for (i = 0; i < *len; ++i) {
749 isl_val *v;
751 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
752 assert(v);
754 sizes[i] = isl_val_get_num_si(v);
755 isl_val_free(v);
758 isl_set_free(set);
761 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
762 * if the option debug->dump_sizes is set.
764 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
765 int *sizes, int len)
767 int i;
768 isl_space *space;
769 isl_map *map;
771 if (!gen->options->debug->dump_sizes)
772 return;
774 space = isl_union_map_get_space(gen->used_sizes);
775 space = isl_space_set_from_params(space);
776 space = isl_space_add_dims(space, isl_dim_set, 1);
777 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
778 space = isl_space_from_domain(space);
779 space = isl_space_add_dims(space, isl_dim_out, len);
780 space = isl_space_set_tuple_name(space, isl_dim_out, type);
782 map = isl_map_universe(space);
783 map = isl_map_fix_si(map, isl_dim_in, 0, id);
784 for (i = 0; i < len; ++i)
785 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
787 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
790 /* Extract user specified "tile" sizes from the "sizes" command line option,
791 * defaulting to option->tile_size in each dimension.
792 * Add the effectively used sizes to gen->used_sizes.
794 static void read_tile_sizes(struct gpu_gen *gen)
796 int n;
797 isl_set *size;
799 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
800 assert(gen->tile_size);
801 for (n = 0; n < gen->tile_len; ++n)
802 gen->tile_size[n] = gen->options->tile_size;
804 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
805 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
806 set_used_sizes(gen, "tile", gen->kernel_id,
807 gen->tile_size, gen->tile_len);
809 if (gen->n_parallel > gen->tile_len)
810 gen->n_parallel = gen->tile_len;
813 /* Extract user specified "block" sizes from the "sizes" command line option,
814 * after filling in some potentially useful defaults.
815 * Add the effectively used sizes to gen->used_sizes.
817 static void read_block_sizes(struct gpu_gen *gen)
819 int n;
820 isl_set *size;
822 n = gen->n_parallel;
823 gen->n_block = (n <= 3) ? n : 3;
824 switch (gen->n_block) {
825 case 1:
826 gen->block_dim[0] = 512;
827 break;
828 case 2:
829 gen->block_dim[0] = 32;
830 gen->block_dim[1] = 16;
831 break;
832 default:
833 gen->block_dim[0] = 32;
834 gen->block_dim[1] = 4;
835 gen->block_dim[2] = 4;
836 break;
839 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
840 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
841 set_used_sizes(gen, "block", gen->kernel_id,
842 gen->block_dim, gen->n_block);
845 /* Extract user specified "grid" sizes from the "sizes" command line option,
846 * after filling in some potentially useful defaults.
847 * Add the effectively used sizes to gen->used_sizes.
849 static void read_grid_sizes(struct gpu_gen *gen)
851 int n = gen->n_parallel;
852 isl_set *size;
854 gen->n_grid = (n <= 2) ? n : 2;
855 switch (gen->n_grid) {
856 case 1:
857 gen->grid_dim[0] = 32768;
858 break;
859 default:
860 gen->grid_dim[0] = 256;
861 gen->grid_dim[1] = 256;
862 break;
865 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
866 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
867 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
870 /* Extract user specified sizes from the "sizes" command line option
871 * after filling in some potentially useful defaults.
873 static void read_sizes(struct gpu_gen *gen)
875 read_tile_sizes(gen);
876 read_block_sizes(gen);
877 read_grid_sizes(gen);
880 static void *free_stmts(struct gpu_stmt *stmts, int n)
882 int i;
884 if (!stmts)
885 return NULL;
887 for (i = 0; i < n; ++i) {
888 struct gpu_stmt_access *access, *next;
890 for (access = stmts[i].accesses; access; access = next) {
891 next = access->next;
892 isl_id_free(access->ref_id);
893 isl_map_free(access->access);
894 isl_map_free(access->tagged_access);
895 free(access);
898 isl_id_free(stmts[i].id);
900 free(stmts);
902 return NULL;
905 /* Construct a map from a domain of dimensionality "len"
906 * to a domain of dimensionality "len" + "tile_len" that tiles
907 * the "tile_len" coordinates starting at "first".
908 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
909 * "dim" prescribes the parameters.
911 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
912 int first, int tile_len, int *tile_size)
914 int i;
915 isl_basic_map *bmap;
916 isl_constraint *c;
917 isl_local_space *ls;
919 dim = isl_space_add_dims(dim, isl_dim_in, len);
920 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
921 bmap = isl_basic_map_universe(isl_space_copy(dim));
922 ls = isl_local_space_from_space(dim);
924 for (i = 0; i < len - tile_len; ++i) {
925 int j = i < first ? i : i + tile_len;
926 int k = i < first ? i : i + 2 * tile_len;
928 c = isl_equality_alloc(isl_local_space_copy(ls));
929 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
930 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
931 bmap = isl_basic_map_add_constraint(bmap, c);
934 for (i = 0; i < tile_len; ++i) {
935 c = isl_equality_alloc(isl_local_space_copy(ls));
936 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
937 first + i, -1);
938 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
939 first + i, tile_size[i]);
940 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
941 first + i + tile_len, 1);
942 bmap = isl_basic_map_add_constraint(bmap, c);
944 c = isl_inequality_alloc(isl_local_space_copy(ls));
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 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
953 bmap = isl_basic_map_add_constraint(bmap, c);
956 isl_local_space_free(ls);
958 return isl_map_from_basic_map(bmap);
961 /* Construct a map from a domain of dimensionality "len"
962 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
963 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
964 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
965 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
966 * that are projected out at the end.
967 * "dim" prescribes the parameters.
969 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
970 int first, int wrap_len, int *wrap_size)
972 int i;
973 isl_basic_map *bmap;
974 isl_constraint *c;
975 isl_local_space *ls;
977 dim = isl_space_add_dims(dim, isl_dim_in, len);
978 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
979 bmap = isl_basic_map_universe(isl_space_copy(dim));
980 ls = isl_local_space_from_space(dim);
982 for (i = 0; i < len; ++i) {
983 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
985 c = isl_equality_alloc(isl_local_space_copy(ls));
986 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
987 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
988 bmap = isl_basic_map_add_constraint(bmap, c);
991 for (i = 0; i < wrap_len; ++i) {
992 c = isl_equality_alloc(isl_local_space_copy(ls));
993 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
994 first + i, -1);
995 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
996 first + wrap_len + i, 1);
997 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
998 first + 2 * wrap_len + i, wrap_size[i]);
999 bmap = isl_basic_map_add_constraint(bmap, c);
1001 c = isl_inequality_alloc(isl_local_space_copy(ls));
1002 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1003 first + wrap_len + i, 1);
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 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1010 bmap = isl_basic_map_add_constraint(bmap, c);
1013 isl_local_space_free(ls);
1015 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1016 first + 2 * wrap_len, wrap_len);
1018 return isl_map_from_basic_map(bmap);
1021 /* Add parameters with identifiers "ids" to "set".
1023 static __isl_give isl_set *add_params(__isl_take isl_set *set,
1024 __isl_keep isl_id_list *ids)
1026 int i, n;
1027 unsigned nparam;
1029 n = isl_id_list_n_id(ids);
1031 nparam = isl_set_dim(set, isl_dim_param);
1032 set = isl_set_add_dims(set, isl_dim_param, n);
1034 for (i = 0; i < n; ++i) {
1035 isl_id *id;
1037 id = isl_id_list_get_id(ids, i);
1038 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1041 return set;
1044 /* Equate the dimensions of "set" starting at "first" to
1045 * freshly created parameters with identifiers "ids".
1046 * The number of equated dimensions is equal to the number of elements in "ids".
1048 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1049 int first, __isl_keep isl_id_list *ids)
1051 int i, n;
1052 unsigned nparam;
1054 nparam = isl_set_dim(set, isl_dim_param);
1056 set = add_params(set, ids);
1058 n = isl_id_list_n_id(ids);
1059 for (i = 0; i < n; ++i)
1060 set = isl_set_equate(set, isl_dim_param, nparam + i,
1061 isl_dim_set, first + i);
1063 return set;
1066 /* Given a parameter space "space", create a set of dimension "len"
1067 * of which the dimensions starting at "first" are equated to
1068 * freshly created parameters with identifiers "ids".
1070 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1071 int len, int first, __isl_keep isl_id_list *ids)
1073 isl_set *set;
1075 space = isl_space_set_from_params(space);
1076 space = isl_space_add_dims(space, isl_dim_set, len);
1077 set = isl_set_universe(space);
1079 return parametrize(set, first, ids);
1082 /* Tile the B loops over the tile sizes and then tile/wrap
1083 * the T1 loops over the blocks.
1085 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1086 __isl_take isl_union_map *sched)
1088 isl_space *dim;
1089 isl_map *tiling, *block_tiling;
1091 dim = isl_union_map_get_space(sched);
1092 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1093 gen->tile_first, gen->tile_len, gen->tile_size);
1095 if (gen->options->wrap)
1096 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1097 gen->tile_first, gen->n_grid, gen->grid_dim);
1098 else
1099 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1100 gen->tile_first, gen->n_grid, gen->grid_dim);
1102 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1104 tiling = isl_map_apply_range(tiling, block_tiling);
1106 sched = isl_union_map_apply_range(sched,
1107 isl_union_map_from_map(tiling));
1109 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1111 return sched;
1114 /* Equate the "T1P" iterators in the tiled schedule "sched"
1115 * to the block dimensions.
1117 static __isl_give isl_union_map *parametrize_tiled_schedule(
1118 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1120 isl_space *dim;
1121 isl_set *par;
1123 dim = isl_union_map_get_space(sched);
1124 par = parametrization(dim, gen->tiled_len,
1125 gen->tile_first + gen->n_grid, gen->kernel->block_ids);
1126 sched = isl_union_map_intersect_range(sched,
1127 isl_union_set_from_set(par));
1129 return sched;
1132 /* Tile/wrap the P1 loops over the threads.
1134 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1135 __isl_take isl_union_map *sched)
1137 isl_space *dim;
1138 isl_map *tiling;
1139 isl_set *par;
1141 dim = isl_union_map_get_space(sched);
1143 if (gen->options->wrap)
1144 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1145 gen->shared_len, gen->n_block, gen->block_dim);
1146 else
1147 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1148 gen->shared_len, gen->n_block, gen->block_dim);
1149 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1151 sched = isl_union_map_apply_range(sched,
1152 isl_union_map_from_map(tiling));
1154 par = parametrization(dim, gen->thread_tiled_len,
1155 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1156 gen->kernel->thread_ids);
1157 sched = isl_union_map_intersect_range(sched,
1158 isl_union_set_from_set(par));
1160 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1162 return sched;
1165 /* If the user asked for it, scale the shared memory tile loops
1166 * (T1T and T2) of "sched" by gen->tile_size[i].
1167 * If we are not performing "wrapping", then additionally scale the T1P
1168 * loops by gen->grid_dim[i].
1170 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1171 __isl_take isl_union_map *sched)
1173 int i;
1174 isl_space *dim;
1175 isl_basic_map *scale;
1176 isl_constraint *c;
1177 isl_local_space *ls;
1179 if (!gen->options->scale_tile_loops)
1180 return sched;
1182 dim = isl_union_map_get_space(sched);
1183 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1184 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1185 scale = isl_basic_map_universe(isl_space_copy(dim));
1186 ls = isl_local_space_from_space(dim);
1188 for (i = 0; i < gen->tiled_len; ++i) {
1189 int f = 1;
1191 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1192 f = gen->tile_size[i - gen->tile_first];
1193 if (!gen->options->wrap)
1194 f *= gen->grid_dim[i - gen->tile_first];
1195 } else if (i >= gen->tile_first + gen->n_grid &&
1196 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1197 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1200 c = isl_equality_alloc(isl_local_space_copy(ls));
1201 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1202 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1203 scale = isl_basic_map_add_constraint(scale, c);
1206 isl_local_space_free(ls);
1208 sched = isl_union_map_apply_range(sched,
1209 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1211 return sched;
1214 /* If we are not performing "wrapping" and if the user asked for it,
1215 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1217 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1218 __isl_take isl_union_map *sched)
1220 int i;
1221 isl_space *dim;
1222 isl_basic_map *scale;
1223 isl_constraint *c;
1224 isl_local_space *ls;
1226 if (gen->options->wrap)
1227 return sched;
1228 if (!gen->options->scale_tile_loops)
1229 return sched;
1231 dim = isl_union_map_get_space(sched);
1232 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1233 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1234 scale = isl_basic_map_universe(isl_space_copy(dim));
1235 ls = isl_local_space_from_space(dim);
1237 for (i = 0; i < gen->thread_tiled_len; ++i) {
1238 int f = 1;
1240 if (i >= gen->shared_len &&
1241 i < gen->shared_len + gen->n_block)
1242 f = gen->block_dim[i - gen->shared_len];
1244 c = isl_equality_alloc(isl_local_space_copy(ls));
1245 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1246 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1247 scale = isl_basic_map_add_constraint(scale, c);
1250 isl_local_space_free(ls);
1252 sched = isl_union_map_apply_range(sched,
1253 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1255 return sched;
1258 /* If we are not performing "wrapping" and if the user asked for it,
1259 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1261 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1262 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1264 int i;
1265 isl_space *dim;
1266 isl_basic_map *scale;
1267 isl_constraint *c;
1268 isl_local_space *ls;
1270 if (gen->options->wrap)
1271 return sched;
1272 if (!gen->options->scale_tile_loops)
1273 return sched;
1275 dim = isl_union_map_get_space(sched);
1276 dim = isl_space_add_dims(dim, isl_dim_in, len);
1277 dim = isl_space_add_dims(dim, isl_dim_out, len);
1278 scale = isl_basic_map_universe(isl_space_copy(dim));
1279 ls = isl_local_space_from_space(dim);
1281 for (i = 0; i < len; ++i) {
1282 int f = 1;
1284 if (i >= first && i < first + n_tile)
1285 f = gen->kernel->block_dim[i - first];
1287 c = isl_equality_alloc(isl_local_space_copy(ls));
1288 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1289 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1290 scale = isl_basic_map_add_constraint(scale, c);
1293 isl_local_space_free(ls);
1295 sched = isl_union_map_apply_range(sched,
1296 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1298 return sched;
1301 /* Add parameters p[i] with identifiers "ids" to "set",
1302 * with bounds to 0 <= p[i] < size[i].
1304 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1305 int *size, __isl_keep isl_id_list *ids)
1307 int i, len;
1308 unsigned nparam;
1310 len = isl_id_list_n_id(ids);
1311 nparam = isl_set_dim(set, isl_dim_param);
1312 set = isl_set_add_dims(set, isl_dim_param, len);
1314 for (i = 0; i < len; ++i) {
1315 isl_id *id;
1317 id = isl_id_list_get_id(ids, i);
1318 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1319 set = isl_set_lower_bound_si(set, isl_dim_param, nparam + i, 0);
1320 set = isl_set_upper_bound_si(set, isl_dim_param,
1321 nparam + i, size[i] - 1);
1324 return set;
1327 /* Add "len" parameters p[i] with identifiers "ids" and intersect "set"
1328 * with
1330 * { : 0 <= p[i] < size[i] }
1332 * or an overapproximation.
1334 static __isl_give isl_set *add_bounded_parameters_dynamic(
1335 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1336 __isl_keep isl_id_list *ids)
1338 int i, len;
1339 unsigned nparam;
1340 isl_space *space;
1341 isl_local_space *ls;
1343 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1344 nparam = isl_set_dim(set, isl_dim_param);
1345 set = isl_set_add_dims(set, isl_dim_param, len);
1347 for (i = 0; i < len; ++i) {
1348 isl_id *id;
1350 id = isl_id_list_get_id(ids, i);
1351 set = isl_set_set_dim_id(set, isl_dim_param, nparam + i, id);
1354 space = isl_space_params(isl_set_get_space(set));
1355 ls = isl_local_space_from_space(space);
1356 for (i = 0; i < len; ++i) {
1357 isl_pw_aff *param, *size_i, *zero;
1358 isl_set *bound;
1360 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1361 isl_dim_param, nparam + i);
1363 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1364 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1365 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1366 set = isl_set_intersect_params(set, bound);
1368 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1369 bound = isl_pw_aff_ge_set(param, zero);
1370 set = isl_set_intersect_params(set, bound);
1372 isl_local_space_free(ls);
1374 return set;
1377 /* Construct a map from an access to group->array to the corresponding
1378 * shared/private memory tile.
1379 * The map is of the form
1381 * { [D[i] -> A[a]] -> T[t] }
1383 * where D represents the initial shared_len dimensions
1384 * of the computed schedule.
1386 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1388 struct gpu_array_tile *tile;
1389 isl_multi_aff *tiling;
1391 tile = group->private_tile;
1392 if (!tile)
1393 tile = group->shared_tile;
1395 tiling = isl_multi_aff_copy(tile->tiling);
1397 return isl_map_from_multi_aff(tiling);
1400 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1402 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1403 unsigned pos)
1405 isl_val *v;
1406 int fixed;
1408 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1409 if (!v)
1410 return -1;
1411 fixed = isl_val_is_int(v);
1412 isl_val_free(v);
1414 return fixed;
1417 /* Given a schedule that iterates over all elements in a piece of an array,
1418 * perform tiling/wrapping over the threads.
1420 * In particular, we tile the final iterators so that the final thread
1421 * dimension runs over the final array dimension.
1422 * However, if those final iterators have only a single iteration,
1423 * we try to tile earlier iterators instead.
1425 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1426 __isl_take isl_map *sched)
1428 isl_space *dim;
1429 isl_union_map *usched;
1430 isl_map *tiling;
1431 isl_set *par;
1432 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1433 int n_tile;
1434 int first;
1436 n_tile = gen->kernel->n_block;
1437 if (n_tile > nvar) {
1438 int i;
1439 sched = isl_map_insert_dims(sched,
1440 isl_dim_out, 0, n_tile - nvar);
1441 for (i = 0; i < n_tile - nvar; ++i)
1442 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1443 nvar = n_tile;
1446 first = nvar - n_tile;
1448 for (; first > 0; first --)
1449 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1450 break;
1452 dim = isl_map_get_space(sched);
1453 dim = isl_space_params(dim);
1454 if (gen->options->wrap)
1455 tiling = wrap(isl_space_copy(dim), nvar, first,
1456 n_tile, gen->kernel->block_dim);
1457 else
1458 tiling = tile(isl_space_copy(dim), nvar, first,
1459 n_tile, gen->kernel->block_dim);
1460 sched = isl_map_apply_range(sched, tiling);
1462 par = parametrization(dim, nvar + n_tile, first + n_tile,
1463 gen->kernel->thread_ids);
1464 sched = isl_map_intersect_range(sched, par);
1466 usched = isl_union_map_from_map(sched);
1467 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1468 first, n_tile);
1469 sched = isl_map_from_union_map(usched);
1471 return sched;
1474 /* Return the union of all read (read = 1) and/or write (write = 1)
1475 * access relations in the group.
1477 static __isl_give isl_union_map *group_access_relation(
1478 struct gpu_array_ref_group *group, int read, int write)
1480 int i;
1481 isl_union_map *access;
1483 access = isl_union_map_empty(isl_map_get_space(group->access));
1484 for (i = 0; i < group->n_ref; ++i) {
1485 isl_map *map_i;
1487 if (!((read && group->refs[i]->read) ||
1488 (write && group->refs[i]->write)))
1489 continue;
1490 map_i = isl_map_copy(group->refs[i]->access);
1491 access = isl_union_map_union(access,
1492 isl_union_map_from_map(map_i));
1495 return access;
1498 /* Return the union of all tagged access relations in the group.
1500 static __isl_give isl_union_map *group_tagged_access_relation(
1501 struct gpu_array_ref_group *group)
1503 int i;
1504 isl_union_map *access;
1506 access = isl_union_map_empty(isl_map_get_space(group->access));
1507 for (i = 0; i < group->n_ref; ++i) {
1508 isl_map *map_i;
1510 map_i = isl_map_copy(group->refs[i]->tagged_access);
1511 access = isl_union_map_union(access,
1512 isl_union_map_from_map(map_i));
1515 return access;
1518 /* Return the extent of "array", recomputed from the bounds.
1519 * The recomputed extent may be simpler than the original extent.
1521 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1523 int i;
1524 isl_id *id;
1525 isl_space *space;
1526 isl_local_space *ls;
1527 isl_set *extent;
1529 id = isl_set_get_tuple_id(array->extent);
1530 space = isl_set_get_space(array->extent);
1531 extent = isl_set_universe(isl_space_copy(space));
1532 ls = isl_local_space_from_space(space);
1533 for (i = 0; i < array->n_index; ++i) {
1534 isl_pw_aff *bound;
1535 isl_aff *aff;
1536 isl_pw_aff *index;
1537 isl_set *lt;
1539 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1541 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1542 isl_dim_set, i);
1543 index = isl_pw_aff_from_aff(aff);
1544 bound = isl_pw_aff_copy(array->bound[i]);
1545 bound = isl_pw_aff_from_range(bound);
1546 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1547 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1548 isl_id_copy(id));
1549 lt = isl_pw_aff_lt_set(index, bound);
1550 extent = isl_set_intersect(extent, lt);
1552 isl_local_space_free(ls);
1553 isl_id_free(id);
1555 return extent;
1558 /* Return a map from the first shared_len dimensions of the computed
1559 * schedule to the array tile in
1560 * global memory that corresponds to the shared memory copy.
1562 * In particular, return a map
1564 * { D[i] -> A[a] }
1566 * with constraints
1568 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1570 * and
1572 * 0 <= a <= array_size - 1 (2)
1574 * Note that if some stride has been detected (i.e., when
1575 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1576 * to the shifted and scaled down version.
1578 * Constraints (1) are obtained by mapping the size constraints on the
1579 * shared/private memory tile back to the access relation.
1580 * Constraints (2) are obtained from the (recomputed) extent.
1582 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1584 int i;
1585 int n_index = group->array->n_index;
1586 isl_map *tile;
1587 isl_space *space;
1588 isl_set *local;
1589 isl_set *extent;
1591 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1592 space = isl_space_range(space);
1593 local = isl_set_universe(space);
1594 for (i = 0; i < n_index; ++i) {
1595 isl_val *bound;
1597 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1598 bound = isl_val_copy(group->shared_tile->bound[i].size);
1599 bound = isl_val_sub_ui(bound, 1);
1600 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1602 local = isl_set_preimage_multi_aff(local,
1603 isl_multi_aff_copy(group->shared_tile->tiling));
1604 tile = isl_set_unwrap(local);
1605 extent = array_extent(group->array);
1606 tile = isl_map_intersect_range(tile, extent);
1608 return tile;
1611 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1612 * return the corresponding mapping from the AST schedule to
1613 * to the first shared_len dimensions of the schedule computed by PPCG.
1615 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1616 __isl_take isl_pw_multi_aff *iterator_map)
1618 isl_union_map *umap;
1619 isl_space *space;
1620 isl_map *map, *sched;;
1622 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1623 space = isl_space_from_domain(space);
1624 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1626 umap = isl_union_map_copy(gen->shared_sched);
1627 umap = isl_union_map_apply_range(umap,
1628 isl_union_map_copy(gen->shared_proj));
1629 map = isl_union_map_extract_map(umap, space);
1630 isl_union_map_free(umap);
1632 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1633 sched = isl_map_detect_equalities(sched);
1635 return isl_pw_multi_aff_from_map(sched);
1638 /* Set unroll[j] if the input dimension j is involved in
1639 * the index expression represented by ma.
1641 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1642 void *user)
1644 int i, j;
1645 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1646 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1647 int *unroll = user;
1649 for (i = 0; i < n_out; ++i) {
1650 isl_aff *aff;
1652 aff = isl_multi_aff_get_aff(ma, i);
1653 for (j = 0; j < n_in; ++j)
1654 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1655 unroll[j] = 1;
1656 isl_aff_free(aff);
1659 isl_set_free(set);
1660 isl_multi_aff_free(ma);
1661 return 0;
1664 /* Given an array pos mapping input dimensions to the corresponding
1665 * output dimension, construct the corresponding map.
1667 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1668 int *pos, int len)
1670 int i;
1671 isl_constraint *c;
1672 isl_basic_map *bmap;
1673 isl_local_space *ls;
1675 dim = isl_space_add_dims(dim, isl_dim_in, len);
1676 dim = isl_space_add_dims(dim, isl_dim_out, len);
1677 bmap = isl_basic_map_universe(isl_space_copy(dim));
1678 ls = isl_local_space_from_space(dim);
1680 for (i = 0; i < len; ++i) {
1681 c = isl_equality_alloc(isl_local_space_copy(ls));
1682 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1683 -1);
1684 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1686 bmap = isl_basic_map_add_constraint(bmap, c);
1688 isl_local_space_free(ls);
1690 return isl_map_from_basic_map(bmap);
1693 /* Remove the private tiles from all array reference groups,
1694 * except for the groups of arrays that are marked force_private.
1696 static void remove_private_tiles(struct gpu_gen *gen)
1698 int i, j;
1700 for (i = 0; i < gen->prog->n_array; ++i) {
1701 struct gpu_array_info *array = &gen->prog->array[i];
1703 if (array->force_private)
1704 continue;
1706 for (j = 0; j < array->n_group; ++j) {
1707 struct gpu_array_ref_group *group = array->groups[j];
1709 group->private_tile = free_tile(group->private_tile);
1714 /* Find all loops involved in any of the index expressions for any of
1715 * the private accesses, move them innermost and then mark them as
1716 * requiring unrolling by setting gen->first_unroll.
1717 * The loops involved should all be parallel because of the checks
1718 * we performed in check_private_group_access. Moving them innermost
1719 * is therefore a valid transformation.
1721 * If any of the arrays are marked force_private, however, then
1722 * those loops may not be parallel with respect to the marked arrays.
1723 * If any of the loops would have to be moved innermost for the
1724 * (non forced) private accesses and if there are any force_private
1725 * arrays, then we revert the decision to map the selected arrays
1726 * to private memory. An alternative solution would be to expand
1727 * the force_private arrays.
1729 * Loops up to gen->shared_len are generated before the mapping to
1730 * threads is applied. They should therefore be ignored.
1732 * We compute the hidden equalities of the schedule first
1733 * since we will need them in our calls to isl_pw_multi_aff_from_map
1734 * and because we want to make sure that the same equalities
1735 * are also available to the code generator.
1737 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1738 __isl_take isl_union_map *sched)
1740 int i, j;
1741 int unroll[gen->thread_tiled_len];
1742 int perm[gen->thread_tiled_len];
1743 isl_space *dim;
1744 isl_map *permute;
1745 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1747 gen->first_unroll = -1;
1749 sched = isl_union_map_detect_equalities(sched);
1750 for (i = 0; i < gen->thread_tiled_len; ++i)
1751 unroll[i] = 0;
1752 for (i = 0; i < gen->prog->n_array; ++i) {
1753 struct gpu_array_info *array = &gen->prog->array[i];
1755 for (j = 0; j < array->n_group; ++j) {
1756 isl_union_map *access;
1757 isl_map *acc;
1758 isl_pw_multi_aff *pma;
1760 if (!array->groups[j]->private_tile)
1761 continue;
1763 access = group_access_relation(array->groups[j], 1, 1);
1764 access = isl_union_map_apply_domain(access,
1765 isl_union_map_copy(sched));
1767 acc = isl_map_from_union_map(access);
1768 pma = isl_pw_multi_aff_from_map(acc);
1769 isl_pw_multi_aff_foreach_piece(pma,
1770 &check_unroll, unroll);
1772 isl_pw_multi_aff_free(pma);
1776 for (i = gen->shared_len; i < len; ++i)
1777 if (unroll[i])
1778 break;
1780 if (i >= len)
1781 return sched;
1783 for (i = len; i < gen->thread_tiled_len; ++i)
1784 if (unroll[i])
1785 return sched;
1787 if (gen->any_force_private) {
1788 remove_private_tiles(gen);
1789 return sched;
1792 j = 0;
1793 for (i = 0; i < gen->shared_len; ++i)
1794 perm[i] = j++;
1795 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1796 if (!unroll[i])
1797 perm[i] = j++;
1798 gen->first_unroll = j - gen->shared_len;
1799 for (i = gen->shared_len; i < len; ++i)
1800 if (unroll[i])
1801 perm[i] = j++;
1803 dim = isl_union_map_get_space(sched);
1804 permute = permutation(dim, perm, gen->thread_tiled_len);
1805 sched = isl_union_map_apply_range(sched,
1806 isl_union_map_from_map(permute));
1808 return sched;
1811 /* Given a constraint
1813 * a(p,i) + j = g f(e)
1815 * or -a(p,i) - j = g f(e) if sign < 0,
1816 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1817 * a(p,i) is assumed to be an expression in only the parameters
1818 * and the input dimensions.
1820 static void extract_stride(__isl_keep isl_constraint *c,
1821 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1823 int i;
1824 isl_val *v;
1825 isl_space *space;
1826 unsigned nparam;
1827 unsigned nvar;
1828 isl_aff *aff;
1830 isl_val_free(bound->stride);
1831 bound->stride = isl_val_copy(stride);
1833 space = isl_constraint_get_space(c);
1834 space = isl_space_domain(space);
1836 nparam = isl_space_dim(space, isl_dim_param);
1837 nvar = isl_space_dim(space, isl_dim_set);
1839 v = isl_constraint_get_constant_val(c);
1840 if (sign < 0)
1841 v = isl_val_neg(v);
1842 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1843 aff = isl_aff_set_constant_val(aff, v);
1845 for (i = 0; i < nparam; ++i) {
1846 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1847 continue;
1848 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1849 if (sign < 0)
1850 v = isl_val_neg(v);
1851 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1854 for (i = 0; i < nvar; ++i) {
1855 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1856 continue;
1857 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1858 if (sign < 0)
1859 v = isl_val_neg(v);
1860 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1863 bound->shift = aff;
1866 /* Given an equality constraint of a map with a single output dimension j,
1867 * check if the constraint is of the form
1869 * a(p,i) + j = g f(e)
1871 * with a(p,i) an expression in the parameters and input dimensions
1872 * and f(e) an expression in the existentially quantified variables.
1873 * If so, and if g is larger than any such g from a previously considered
1874 * constraint, then call extract_stride to record the stride information
1875 * in bound.
1877 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1879 int i;
1880 isl_ctx *ctx;
1881 isl_val *v;
1882 unsigned n_div;
1883 struct gpu_array_bound *bound = user;
1885 ctx = isl_constraint_get_ctx(c);
1886 n_div = isl_constraint_dim(c, isl_dim_div);
1887 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1889 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1890 int s = isl_val_sgn(v);
1891 isl_val *stride = isl_val_zero(ctx);
1893 isl_val_free(v);
1894 for (i = 0; i < n_div; ++i) {
1895 v = isl_constraint_get_coefficient_val(c,
1896 isl_dim_div, i);
1897 stride = isl_val_gcd(stride, v);
1899 if (!isl_val_is_zero(stride) &&
1900 isl_val_gt(stride, bound->stride))
1901 extract_stride(c, bound, stride, s);
1903 isl_val_free(stride);
1904 } else
1905 isl_val_free(v);
1907 isl_constraint_free(c);
1908 return 0;
1911 /* Given contraints on an array index i, check if we can find
1912 * a shift a(p) and a stride g such that
1914 * a(p) + i = 0 mod g
1916 * If so, record the information in bound and apply the mapping
1917 * i -> (i + a(p))/g to the array index in bounds and return
1918 * the new constraints.
1919 * If not, simply return the original constraints.
1921 * If bounds is a subset of the space
1923 * D -> i
1925 * then the bound recorded in bound->shift is of the form
1927 * D -> s(D)
1929 * with s(D) equal to a(p) above.
1930 * Next, we construct a mapping of the form
1932 * [D -> i] -> [D -> (i + S(D))/g]
1934 * This mapping is computed as follows.
1935 * We first introduce "i" in the domain through precomposition
1936 * with [D -> i] -> D obtaining
1938 * [D -> i] -> s(D)
1940 * Adding [D -> i] -> i produces
1942 * [D -> i] -> i + s(D)
1944 * and the domain product with [D -> i] -> D yields
1946 * [D -> i] -> [D -> i + s(D)]
1948 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1950 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1951 __isl_take isl_basic_map *bounds)
1953 isl_space *space;
1954 isl_basic_map *hull;
1955 isl_basic_map *shift, *id, *bmap, *scale;
1956 isl_basic_set *bset;
1957 isl_aff *aff;
1959 bound->stride = NULL;
1961 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1963 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1965 isl_basic_map_free(hull);
1967 if (!bound->stride)
1968 return bounds;
1970 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1971 space = isl_basic_map_get_space(bounds);
1972 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1973 shift = isl_basic_map_apply_range(bmap, shift);
1974 space = isl_basic_map_get_space(bounds);
1975 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1976 shift = isl_basic_map_sum(id, shift);
1977 space = isl_basic_map_get_space(bounds);
1978 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1979 shift = isl_basic_map_range_product(id, shift);
1981 space = isl_space_domain(isl_basic_map_get_space(bounds));
1982 id = isl_basic_map_identity(isl_space_map_from_set(space));
1983 space = isl_space_range(isl_basic_map_get_space(bounds));
1984 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1985 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1986 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1987 scale = isl_basic_map_from_aff(aff);
1988 scale = isl_basic_map_product(id, scale);
1990 bmap = isl_basic_map_apply_range(shift, scale);
1991 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1992 bounds = isl_basic_set_unwrap(bset);
1994 return bounds;
1997 /* Data used in compute_array_dim_size and compute_size_in_direction.
1999 * pos is the position of the variable representing the array index,
2000 * i.e., the variable for which want to compute the size. This variable
2001 * is also the last variable in the set.
2003 struct gpu_size_info {
2004 isl_basic_set *bset;
2005 struct gpu_array_bound *bound;
2006 int pos;
2009 /* Given a constraint from the basic set describing the bounds on
2010 * an array index, check if it is a lower bound, say m i >= b(x), and,
2011 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2012 * upper bound. If so, and if this bound is smaller than any bound
2013 * derived from earlier constraints, set the size to this bound on
2014 * the expression and the lower bound to ceil(b(x)/m).
2016 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2018 struct gpu_size_info *size = user;
2019 unsigned nparam;
2020 unsigned n_div;
2021 isl_val *v;
2022 isl_aff *aff;
2023 isl_aff *lb;
2025 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2026 n_div = isl_constraint_dim(c, isl_dim_div);
2028 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2029 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2030 isl_constraint_free(c);
2031 return 0;
2034 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2035 aff = isl_aff_ceil(aff);
2037 lb = isl_aff_copy(aff);
2039 aff = isl_aff_neg(aff);
2040 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2042 v = isl_basic_set_max_val(size->bset, aff);
2043 isl_aff_free(aff);
2045 if (isl_val_is_int(v)) {
2046 v = isl_val_add_ui(v, 1);
2047 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2048 isl_val_free(size->bound->size);
2049 size->bound->size = isl_val_copy(v);
2050 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2051 isl_aff_free(size->bound->lb);
2052 size->bound->lb = isl_aff_copy(lb);
2055 isl_val_free(v);
2056 isl_aff_free(lb);
2058 isl_constraint_free(c);
2060 return 0;
2063 /* Given a basic map "bounds" that maps parameters and input dimensions
2064 * to a single output dimension, look for an expression in the parameters
2065 * and input dimensions such that the range of the output dimension shifted
2066 * by this expression is a constant.
2068 * In particular, we currently only consider lower bounds on the output
2069 * dimension as candidate expressions.
2071 static int compute_array_dim_size(struct gpu_array_bound *bound,
2072 __isl_take isl_basic_map *bounds)
2074 struct gpu_size_info size;
2076 bounds = isl_basic_map_detect_equalities(bounds);
2077 bounds = check_stride(bound, bounds);
2079 bound->size = NULL;
2080 bound->lb = NULL;
2082 size.bound = bound;
2083 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2084 size.bset = isl_basic_map_wrap(bounds);
2085 size.bset = isl_basic_set_flatten(size.bset);
2086 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2087 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2088 &size);
2089 isl_basic_set_free(size.bset);
2091 return bound->size ? 0 : -1;
2094 /* Check if we can find a memory tile for the given array
2095 * based on the given accesses, and if so, put the results in "tile".
2097 * We project the accesses on each index in turn and look for a parametric
2098 * offset such that the size is constant.
2100 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2102 int i;
2104 for (i = 0; i < tile->n; ++i) {
2105 isl_map *access_i;
2106 isl_basic_map *hull;
2108 access_i = isl_map_copy(access);
2109 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2110 access_i = isl_map_project_out(access_i, isl_dim_out,
2111 1, tile->n - (i + 1));
2112 access_i = isl_map_compute_divs(access_i);
2113 hull = isl_map_simple_hull(access_i);
2114 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2115 return 0;
2118 return 1;
2121 /* Construct a map with input the shared tile loops and the loops that
2122 * will be wrapped around the threads that relates these later loops
2123 * to the thread indices and then projects them out.
2125 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2127 isl_map *priv;
2128 isl_map *tiling;
2129 isl_map *proj;
2130 isl_set *par;
2131 isl_space *dim;
2133 dim = isl_union_map_get_space(gen->shared_sched);
2135 if (gen->options->wrap)
2136 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2137 gen->shared_len, gen->n_block, gen->block_dim);
2138 else
2139 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2140 gen->shared_len, gen->n_block, gen->block_dim);
2142 priv = tiling;
2144 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2145 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2146 gen->kernel->thread_ids);
2148 priv = isl_map_align_params(priv, isl_set_get_space(par));
2149 priv = isl_map_intersect_range(priv, par);
2151 dim = isl_map_get_space(priv);
2152 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2153 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2154 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2155 gen->shared_len);
2157 priv = isl_map_apply_range(priv, proj);
2159 return priv;
2162 /* Construct a map from domain_dim to domain_dim that increments
2163 * the dimension at position "pos" and leaves all other dimensions
2164 * constant.
2166 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2168 int i;
2169 int len = isl_space_dim(domain_dim, isl_dim_set);
2170 isl_space *dim;
2171 isl_basic_map *next;
2172 isl_local_space *ls;
2174 dim = isl_space_map_from_set(domain_dim);
2175 next = isl_basic_map_universe(isl_space_copy(dim));
2176 ls = isl_local_space_from_space(dim);
2178 for (i = 0; i < len; ++i) {
2179 isl_constraint *c;
2181 c = isl_equality_alloc(isl_local_space_copy(ls));
2182 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2183 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2184 if (i == pos)
2185 c = isl_constraint_set_constant_si(c, 1);
2186 next = isl_basic_map_add_constraint(next, c);
2189 isl_local_space_free(ls);
2191 return isl_map_from_basic_map(next);
2194 /* Check if the given access is coalesced.
2195 * That is, check whether incrementing the dimension that will get
2196 * wrapped over the last thread index results in incrementing
2197 * the last array index.
2199 * This function is only called for access relations without reuse and
2200 * kernels with at least one block dimension.
2202 static int access_is_coalesced(struct gpu_gen *gen,
2203 __isl_keep isl_union_map *access)
2205 isl_space *dim;
2206 isl_map *access_map;
2207 isl_map *next_thread_x;
2208 isl_map *next_element;
2209 isl_map *map;
2210 int coalesced;
2212 access = isl_union_map_copy(access);
2213 access = isl_union_map_apply_domain(access,
2214 isl_union_map_copy(gen->tiled_sched));
2215 access_map = isl_map_from_union_map(access);
2217 dim = isl_map_get_space(access_map);
2218 dim = isl_space_domain(dim);
2219 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2221 dim = isl_map_get_space(access_map);
2222 dim = isl_space_range(dim);
2223 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2225 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2226 map = isl_map_apply_range(map, access_map);
2228 coalesced = isl_map_is_subset(map, next_element);
2230 isl_map_free(next_element);
2231 isl_map_free(map);
2233 return coalesced;
2236 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2237 * dimensions of the computed schedule, check if it is bijective for
2238 * fixed values of the first gen->shared_len dimensions.
2239 * We perform this check by equating these dimensions to parameters.
2241 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2243 int res;
2244 isl_set *par;
2245 isl_space *space;
2246 isl_id_list *ids;
2248 access = isl_map_copy(access);
2249 space = isl_space_params(isl_map_get_space(access));
2250 ids = ppcg_scop_generate_names(gen->prog->scop, gen->shared_len, "s");
2251 par = parametrization(space, gen->shared_len + gen->n_block, 0, ids);
2252 isl_id_list_free(ids);
2253 access = isl_map_intersect_domain(access, par);
2254 res = isl_map_is_bijective(access);
2255 isl_map_free(access);
2257 return res;
2260 /* Look for the last shared tile loop that affects the offset of "tile"
2261 * and return the result.
2262 * If there is no such loop, then return the index of the loop
2263 * before the first shared tile loop, in particular gen->tile_first - 1.
2265 static int compute_tile_last_shared(struct gpu_gen *gen,
2266 struct gpu_array_tile *tile)
2268 int i, j;
2270 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2271 for (i = 0; i < tile->n; ++i) {
2272 isl_aff *lb;
2273 isl_aff *shift;
2275 lb = tile->bound[i].lb;
2276 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2277 break;
2279 shift = tile->bound[i].shift;
2280 if (!shift)
2281 continue;
2282 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2283 break;
2285 if (i < tile->n)
2286 break;
2289 return j;
2292 /* Look for the last shared tile loop that affects the offset of the
2293 * shared or private tile and store the result in group->last_shared.
2294 * If there is no such loop, then group->last_shared is set to a value
2295 * before the first shared tile loop, in particular gen->tile_first - 1.
2296 * If there is no tile defined on the array reference group,
2297 * then set group->last_shared to gen->shared_len - 1.
2299 static void set_last_shared(struct gpu_gen *gen,
2300 struct gpu_array_ref_group *group)
2302 struct gpu_array_tile *tile;
2304 group->last_shared = gen->shared_len - 1;
2306 tile = group->private_tile;
2307 if (!tile)
2308 tile = group->shared_tile;
2309 if (!tile)
2310 return;
2312 group->last_shared = compute_tile_last_shared(gen, tile);
2315 /* Compute the size of the tile specified by "tile"
2316 * in number of elements and return the result.
2318 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2320 int i;
2321 isl_val *size;
2323 size = isl_val_one(ctx);
2325 for (i = 0; i < tile->n; ++i)
2326 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2328 return size;
2331 /* If max_shared_memory is not set to infinity (-1), then make
2332 * sure that the total amount of shared memory required by the
2333 * array reference groups mapped to shared memory is no larger
2334 * than this maximum.
2336 * We apply a greedy approach and discard (keep in global memory)
2337 * those groups that would result in a total memory size that
2338 * is larger than the maximum.
2340 * This function should be called after any function that may
2341 * affect the decision on whether to place a reference group
2342 * in private, shared or global memory.
2344 static void check_shared_memory_bound(struct gpu_gen *gen)
2346 int i, j;
2347 isl_val *left, *size;
2349 if (gen->options->max_shared_memory < 0)
2350 return;
2352 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2354 for (i = 0; i < gen->prog->n_array; ++i) {
2355 struct gpu_array_info *array = &gen->prog->array[i];
2357 for (j = 0; j < array->n_group; ++j) {
2358 struct gpu_array_ref_group *group;
2360 group = array->groups[j];
2361 if (group->private_tile)
2362 continue;
2363 if (!group->shared_tile)
2364 continue;
2366 size = tile_size(gen->ctx, group->shared_tile);
2367 size = isl_val_mul_ui(size, array->size);
2369 if (isl_val_le(size, left)) {
2370 left = isl_val_sub(left, size);
2371 continue;
2373 isl_val_free(size);
2375 group->shared_tile = free_tile(group->shared_tile);
2379 isl_val_free(left);
2382 /* Given a description of an array tile "tile" and the "space"
2384 * { D -> A }
2386 * where D represents the first shared_len schedule dimensions
2387 * and A represents the array, construct an isl_multi_aff
2389 * { [D[i] -> A[a]] -> A'[a'] }
2391 * with A' a scaled down copy of A according to the shifts and strides
2392 * in "tile". In particular,
2394 * a' = (a + shift(i))/stride
2396 * "insert_array" represents
2398 * { [D -> A] -> D }
2400 * and is used to insert A into the domain of functions that only
2401 * reference D.
2403 static __isl_give isl_multi_aff *strided_tile(
2404 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2405 __isl_keep isl_multi_aff *insert_array)
2407 int i;
2408 isl_ctx *ctx;
2409 isl_multi_aff *shift;
2410 isl_multi_val *stride;
2411 isl_space *space2;
2412 isl_local_space *ls;
2413 isl_multi_aff *tiling;
2415 ctx = isl_space_get_ctx(space);
2416 space2 = isl_space_domain(isl_space_copy(space));
2417 ls = isl_local_space_from_space(space2);
2418 space2 = isl_space_range(isl_space_copy(space));
2419 stride = isl_multi_val_zero(space2);
2420 shift = isl_multi_aff_zero(isl_space_copy(space));
2422 for (i = 0; i < tile->n; ++i) {
2423 struct gpu_array_bound *bound = &tile->bound[i];
2424 isl_val *stride_i;
2425 isl_aff *shift_i;
2427 if (tile->bound[i].shift) {
2428 stride_i = isl_val_copy(bound->stride);
2429 shift_i = isl_aff_copy(bound->shift);
2430 } else {
2431 stride_i = isl_val_one(ctx);
2432 shift_i = isl_aff_zero_on_domain(
2433 isl_local_space_copy(ls));
2436 stride = isl_multi_val_set_val(stride, i, stride_i);
2437 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2439 isl_local_space_free(ls);
2441 shift = isl_multi_aff_pullback_multi_aff(shift,
2442 isl_multi_aff_copy(insert_array));
2444 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2445 tiling = isl_multi_aff_add(tiling, shift);
2446 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2448 return tiling;
2451 /* Compute a tiling for the array reference group "group".
2453 * The tiling is of the form
2455 * { [D[i] -> A[a]] -> T[t] }
2457 * where D represents the first shared_len schedule dimensions,
2458 * A represents the global array and T represents the shared or
2459 * private memory tile. The name of T is the name of the local
2460 * array.
2462 * If there is any stride in the accesses, then the mapping is
2464 * t = (a + shift(i))/stride - lb(i)
2466 * otherwise, it is simply
2468 * t = a - lb(i)
2470 static void compute_group_tiling(struct gpu_array_ref_group *group)
2472 int i;
2473 struct gpu_array_tile *tile;
2474 struct gpu_array_info *array = group->array;
2475 isl_space *space;
2476 isl_multi_aff *tiling, *lb, *insert_array;
2477 isl_printer *p;
2478 char *local_name;
2480 tile = group->private_tile;
2481 if (!tile)
2482 tile = group->shared_tile;
2483 if (!tile)
2484 return;
2486 space = isl_map_get_space(group->access);
2487 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2489 for (i = 0; i < tile->n; ++i)
2490 if (tile->bound[i].shift)
2491 break;
2493 if (i < tile->n)
2494 tiling = strided_tile(tile, space, insert_array);
2495 else
2496 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2498 lb = isl_multi_aff_zero(space);
2499 for (i = 0; i < tile->n; ++i) {
2500 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2501 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2503 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2505 tiling = isl_multi_aff_sub(tiling, lb);
2507 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2508 p = print_array_name(p, group);
2509 local_name = isl_printer_get_str(p);
2510 isl_printer_free(p);
2511 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2512 free(local_name);
2514 tile->tiling = tiling;
2517 /* Compute a tiling for all the array reference groups.
2519 static void compute_group_tilings(struct gpu_gen *gen)
2521 int i, j;
2523 for (i = 0; i < gen->prog->n_array; ++i) {
2524 struct gpu_array_info *array = &gen->prog->array[i];
2526 for (j = 0; j < array->n_group; ++j)
2527 compute_group_tiling(array->groups[j]);
2531 /* Fill up the groups array with singleton groups, i.e., one group
2532 * per reference, initializing the array, access, write, n_ref and refs fields.
2533 * In particular the access field is initialized to the scheduled
2534 * access relation of the array reference.
2536 * Return the number of elements initialized, i.e., the number of
2537 * active references in the current kernel.
2539 static int populate_array_references(struct gpu_array_info *array,
2540 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2542 int i;
2543 int n;
2544 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2546 n = 0;
2547 for (i = 0; i < array->n_ref; ++i) {
2548 isl_union_map *umap;
2549 isl_map *map;
2550 struct gpu_array_ref_group *group;
2551 struct gpu_stmt_access *access = array->refs[i];
2553 map = isl_map_copy(access->access);
2554 umap = isl_union_map_from_map(map);
2555 umap = isl_union_map_apply_domain(umap,
2556 isl_union_map_copy(sched));
2558 if (isl_union_map_is_empty(umap)) {
2559 isl_union_map_free(umap);
2560 continue;
2563 map = isl_map_from_union_map(umap);
2564 map = isl_map_detect_equalities(map);
2566 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2567 assert(group);
2568 group->array = array;
2569 group->access = map;
2570 group->write = access->write;
2571 group->exact_write = access->exact_write;
2572 group->slice = access->n_index < array->n_index;
2573 group->refs = &array->refs[i];
2574 group->n_ref = 1;
2576 groups[n++] = group;
2579 return n;
2582 /* If group->n_ref == 1, then group->refs was set by
2583 * populate_array_references to point directly into
2584 * group->array->refs and should not be freed.
2585 * If group->n_ref > 1, then group->refs was set by join_groups
2586 * to point to a newly allocated array.
2588 static void free_array_ref_group(struct gpu_array_ref_group *group)
2590 if (!group)
2591 return;
2592 free_tile(group->shared_tile);
2593 free_tile(group->private_tile);
2594 isl_map_free(group->access);
2595 if (group->n_ref > 1)
2596 free(group->refs);
2597 free(group);
2600 /* Given a map where the input dimensions represent the tile loops,
2601 * eliminate the innermost of those that have a fixed value
2602 * until we reach one that does not (obviously) have a fixed value.
2604 static __isl_give isl_map *eliminate_fixed_inner_loops(
2605 __isl_take isl_map *access)
2607 int i, n;
2609 n = isl_map_dim(access, isl_dim_in);
2611 for (i = n - 1; i >= 0; --i) {
2612 if (!map_plain_is_fixed(access, isl_dim_in, i))
2613 break;
2614 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2616 return access;
2619 /* Check if the access relations of group1 and group2 overlap within
2620 * the innermost loop. In particular, ignore any inner dimension
2621 * with a fixed value.
2622 * The copying to and from shared memory will be performed within
2623 * the innermost actual loop so we are only allowed to consider
2624 * the dimensions up to that innermost loop while checking whether
2625 * two access relations overlap.
2627 static int accesses_overlap(struct gpu_array_ref_group *group1,
2628 struct gpu_array_ref_group *group2)
2630 int empty;
2631 isl_map *access1, *access2;
2633 access1 = isl_map_copy(group1->access);
2634 access1 = eliminate_fixed_inner_loops(access1);
2635 access2 = isl_map_copy(group2->access);
2636 access2 = eliminate_fixed_inner_loops(access2);
2637 access1 = isl_map_intersect(access1, access2);
2638 empty = isl_map_is_empty(access1);
2639 isl_map_free(access1);
2641 return !empty;
2644 /* Combine the given two groups into a single group, containing
2645 * the references of both groups.
2647 static struct gpu_array_ref_group *join_groups(
2648 struct gpu_array_ref_group *group1,
2649 struct gpu_array_ref_group *group2)
2651 int i;
2652 isl_ctx *ctx;
2653 struct gpu_array_ref_group *group;
2655 ctx = isl_map_get_ctx(group1->access);
2656 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2657 assert(group);
2658 group->array = group1->array;
2659 group->access = isl_map_union(isl_map_copy(group1->access),
2660 isl_map_copy(group2->access));
2661 group->write = group1->write || group2->write;
2662 group->exact_write = group1->exact_write && group2->exact_write;
2663 group->slice = group1->slice || group2->slice;
2664 group->n_ref = group1->n_ref + group2->n_ref;
2665 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2666 group->n_ref);
2667 assert(group->refs);
2668 for (i = 0; i < group1->n_ref; ++i)
2669 group->refs[i] = group1->refs[i];
2670 for (i = 0; i < group2->n_ref; ++i)
2671 group->refs[group1->n_ref + i] = group2->refs[i];
2673 return group;
2676 /* Combine the given two groups into a single group and free
2677 * the original two groups.
2679 static struct gpu_array_ref_group *join_groups_and_free(
2680 struct gpu_array_ref_group *group1,
2681 struct gpu_array_ref_group *group2)
2683 struct gpu_array_ref_group *group;
2685 group = join_groups(group1, group2);
2686 free_array_ref_group(group1);
2687 free_array_ref_group(group2);
2688 return group;
2691 /* Report that the array reference group with the given access relation
2692 * is not mapped to shared memory in the given kernel because
2693 * it does not exhibit any reuse and is considered to be coalesced.
2695 static void report_no_reuse_and_coalesced(struct ppcg_kernel *kernel,
2696 __isl_keep isl_union_map *access)
2698 isl_ctx *ctx;
2699 isl_printer *p;
2701 ctx = isl_union_map_get_ctx(access);
2702 p = isl_printer_to_file(ctx, stdout);
2703 p = isl_printer_print_str(p, "Array reference group ");
2704 p = isl_printer_print_union_map(p, access);
2705 p = isl_printer_print_str(p,
2706 " not considered for mapping to shared memory in kernel");
2707 p = isl_printer_print_int(p, kernel->id);
2708 p = isl_printer_print_str(p,
2709 " because it exhibits no reuse and is considered to be coalesced");
2710 p = isl_printer_end_line(p);
2711 isl_printer_free(p);
2714 /* Compute the private and/or shared memory tiles for the array
2715 * reference group "group" of array "array".
2716 * Return 0 on success and -1 on error.
2718 * If the array is a read-only scalar or if the user requested
2719 * not to use shared or private memory, then we do not need to do anything.
2721 * If any reference in the reference group accesses more than one element,
2722 * then we would have to make sure that the layout in shared memory
2723 * is the same as that in global memory. Since we do not handle this yet
2724 * (and it may not even be possible), we refuse to map to private or
2725 * shared memory in such cases.
2727 * If the array group involves any may writes (that are not must writes),
2728 * then we would have to make sure that we load the data into shared/private
2729 * memory first in case the data is not written by the kernel
2730 * (but still written back out to global memory).
2731 * Since we don't have any such mechanism at the moment, we don't
2732 * compute shared/private tiles for groups involving may writes.
2734 * We only try to compute a shared memory tile if there is any reuse
2735 * or if the access is not coalesced.
2737 * For computing a private memory tile, we also require that there is
2738 * some reuse. Moreover, we require that the access is private
2739 * to the thread. That is, we check that any given array element
2740 * is only accessed by a single thread.
2741 * We compute an access relation that maps the shared tile loop iterators
2742 * and the shared point loop iterators that will be wrapped over the
2743 * threads to the array elements.
2744 * We actually check that those iterators that will be wrapped
2745 * partition the array space. This check is stricter than necessary
2746 * since several iterations may be mapped onto the same thread
2747 * and then they could be allowed to access the same memory elements,
2748 * but our check does not allow this situation.
2750 * We also check that the index expression only depends on parallel
2751 * loops. That way, we can move those loops innermost and unroll them.
2752 * Again, we use a test that is stricter than necessary.
2753 * We actually check whether the index expression only depends
2754 * on the iterators that are wrapped over the threads.
2755 * These are necessarily parallel, but there may be more parallel loops.
2757 * Combining the injectivity of the first test with the single-valuedness
2758 * of the second test, we simply test for bijectivity.
2760 * If the array is marked force_private, then we bypass all checks
2761 * and assume we can (and should) use registers.
2763 * If it turns out we can (or have to) use registers, we compute
2764 * the private memory tile size using can_tile, after introducing a dependence
2765 * on the thread indices.
2767 static int compute_group_bounds_core(struct gpu_gen *gen,
2768 struct gpu_array_ref_group *group)
2770 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2771 isl_union_map *access;
2772 int n_index = group->array->n_index;
2773 int no_reuse, coalesced;
2774 isl_map *acc;
2775 int force_private = group->array->force_private;
2776 int use_shared = gen->options->use_shared_memory && gen->n_block > 0;
2777 int use_private = force_private || gen->options->use_private_memory;
2779 if (!use_shared && !use_private)
2780 return 0;
2781 if (gpu_array_is_read_only_scalar(group->array))
2782 return 0;
2783 if (!force_private && !group->exact_write)
2784 return 0;
2785 if (group->slice)
2786 return 0;
2788 access = group_access_relation(group, 1, 1);
2789 no_reuse = isl_union_map_is_injective(access);
2790 if (use_shared && no_reuse)
2791 coalesced = access_is_coalesced(gen, access);
2793 if (gen->options->debug->verbose && use_shared && no_reuse && coalesced)
2794 report_no_reuse_and_coalesced(gen->kernel, access);
2796 if (use_shared && (!no_reuse || !coalesced)) {
2797 group->shared_tile = create_tile(ctx, group->array->n_index);
2798 if (!can_tile(group->access, group->shared_tile))
2799 group->shared_tile = free_tile(group->shared_tile);
2802 if (!force_private && (!use_private || no_reuse)) {
2803 isl_union_map_free(access);
2804 return 0;
2807 access = isl_union_map_apply_domain(access,
2808 isl_union_map_copy(gen->shared_sched));
2810 acc = isl_map_from_union_map(access);
2812 if (!force_private && !access_is_bijective(gen, acc)) {
2813 isl_map_free(acc);
2814 return 0;
2817 group->private_tile = create_tile(gen->ctx, n_index);
2818 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2819 if (!can_tile(acc, group->private_tile))
2820 group->private_tile = free_tile(group->private_tile);
2822 isl_map_free(acc);
2824 if (force_private && !group->private_tile)
2825 isl_die(ctx, isl_error_internal,
2826 "unable to map array reference group to registers",
2827 return -1);
2829 return 0;
2832 /* Compute the private and/or shared memory tiles for the array
2833 * reference group "group" of array "array" and set last_shared.
2834 * Return 0 on success and -1 on error.
2836 static int compute_group_bounds(struct gpu_gen *gen,
2837 struct gpu_array_ref_group *group)
2839 if (compute_group_bounds_core(gen, group) < 0)
2840 return -1;
2841 set_last_shared(gen, group);
2843 return 0;
2846 /* If two groups have overlapping access relations (as determined by
2847 * the "overlap" function) and if one of them involves a write,
2848 * then merge the two groups into one.
2849 * If "compute_bounds" is set, then call compute_group_bounds
2850 * on the merged groups.
2852 * Return the updated number of groups.
2853 * Return -1 on error.
2855 static int group_writes(struct gpu_gen *gen,
2856 int n, struct gpu_array_ref_group **groups,
2857 int (*overlap)(struct gpu_array_ref_group *group1,
2858 struct gpu_array_ref_group *group2), int compute_bounds)
2860 int i, j;
2862 for (i = 0; i < n; ++i) {
2863 for (j = n - 1; j > i; --j) {
2864 if (!groups[i]->write && !groups[j]->write)
2865 continue;
2867 if (!overlap(groups[i], groups[j]))
2868 continue;
2870 groups[i] = join_groups_and_free(groups[i], groups[j]);
2871 if (j != n - 1)
2872 groups[j] = groups[n - 1];
2873 groups[n - 1] = NULL;
2874 n--;
2876 if (compute_bounds &&
2877 compute_group_bounds(gen, groups[i]) < 0)
2878 return -1;
2882 return n;
2885 /* If two groups have overlapping access relations (within the innermost
2886 * loop) and if one of them involves a write, then merge the two groups
2887 * into one.
2889 * Return the updated number of groups.
2891 static int group_overlapping_writes(struct gpu_gen *gen,
2892 int n, struct gpu_array_ref_group **groups)
2894 return group_writes(gen, n, groups, &accesses_overlap, 0);
2897 /* Check if the access relations of group1 and group2 overlap within
2898 * the outermost min(group1->last_shared, group2->last_shared) loops.
2900 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2901 struct gpu_array_ref_group *group2)
2903 int last_shared;
2904 int dim;
2905 int empty;
2906 isl_map *map_i, *map_j, *map;
2908 last_shared = group1->last_shared;
2909 if (group2->last_shared < last_shared)
2910 last_shared = group2->last_shared;
2911 map_i = isl_map_copy(group1->access);
2912 dim = isl_map_dim(map_i, isl_dim_in);
2913 map_i = isl_map_eliminate(map_i, isl_dim_in,
2914 last_shared + 1, dim - (last_shared + 1));
2915 map_j = isl_map_copy(group2->access);
2916 map_j = isl_map_eliminate(map_j, isl_dim_in,
2917 last_shared + 1, dim - (last_shared + 1));
2918 map = isl_map_intersect(map_i, map_j);
2919 empty = isl_map_is_empty(map);
2920 isl_map_free(map);
2922 return !empty;
2925 /* If two groups have overlapping access relations (within the outer
2926 * last_shared loops) and if one of them involves a write,
2927 * then merge the two groups into one.
2929 * Return the updated number of groups.
2931 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2932 struct gpu_array_ref_group **groups)
2934 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2937 /* Is the size of the tile specified by "tile" smaller than the sum of
2938 * the sizes of the tiles specified by "tile1" and "tile2"?
2940 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2941 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2943 int smaller;
2944 isl_val *size, *size1, *size2;
2946 size = tile_size(ctx, tile);
2947 size1 = tile_size(ctx, tile1);
2948 size2 = tile_size(ctx, tile2);
2950 size = isl_val_sub(size, size1);
2951 size = isl_val_sub(size, size2);
2952 smaller = isl_val_is_neg(size);
2954 isl_val_free(size);
2956 return smaller;
2959 /* Given an initial grouping of array references and shared memory tiles
2960 * for each group that allows for a shared memory tile, merge two groups
2961 * if both have a shared memory tile, the merged group also has
2962 * a shared memory tile and the size of the tile for the merge group
2963 * is smaller than the sum of the tile sizes of the individual groups.
2965 * If merging two groups decreases the "last_shared" dimension of
2966 * one or both of the two groups, then we need to check for overlapping
2967 * writes again.
2969 * Return the number of groups after merging.
2970 * Return -1 on error.
2972 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2973 struct gpu_array_info *array, int n,
2974 struct gpu_array_ref_group **groups)
2976 int i, j;
2977 int recompute_overlap = 0;
2978 isl_ctx *ctx = isl_space_get_ctx(array->space);
2980 for (i = 0; i < n; ++i) {
2981 if (!groups[i]->shared_tile)
2982 continue;
2983 for (j = n - 1; j > i; --j) {
2984 isl_map *map;
2985 int empty;
2986 struct gpu_array_ref_group *group;
2988 if (!groups[j]->shared_tile)
2989 continue;
2991 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2992 isl_map_copy(groups[j]->access));
2993 empty = isl_map_is_empty(map);
2994 isl_map_free(map);
2996 if (empty)
2997 continue;
2999 group = join_groups(groups[i], groups[j]);
3000 if (compute_group_bounds(gen, group) < 0) {
3001 free_array_ref_group(group);
3002 return -1;
3004 if (!group->shared_tile ||
3005 !smaller_tile(ctx, group->shared_tile,
3006 groups[i]->shared_tile,
3007 groups[j]->shared_tile)) {
3008 free_array_ref_group(group);
3009 continue;
3012 if (group->last_shared < groups[i]->last_shared ||
3013 group->last_shared < groups[j]->last_shared)
3014 recompute_overlap = 1;
3015 free_array_ref_group(groups[i]);
3016 free_array_ref_group(groups[j]);
3017 groups[i] = group;
3018 if (j != n - 1)
3019 groups[j] = groups[n - 1];
3020 n--;
3024 if (recompute_overlap)
3025 n = group_last_shared_overlapping_writes(gen, n, groups);
3026 return n;
3029 /* Set array->n_group and array->groups to n and groups.
3031 * Additionally, set the "nr" field of each group
3032 * and the "group" field of each reference in each group.
3034 static void set_array_groups(struct gpu_array_info *array,
3035 int n, struct gpu_array_ref_group **groups)
3037 int i, j;
3039 array->n_group = n;
3040 array->groups = groups;
3042 for (i = 0; i < n; ++i) {
3043 groups[i]->nr = i;
3045 for (j = 0; j < groups[i]->n_ref; ++j)
3046 groups[i]->refs[j]->group = i;
3050 /* Group array references that should be considered together when
3051 * deciding whether to access them from private, shared or global memory.
3052 * Return -1 on error.
3054 * In particular, if two array references overlap and if one of them
3055 * is a write, then the two references are grouped together.
3056 * We first perform an initial grouping based only on the access relation.
3057 * After computing shared and private memory tiles, we check for
3058 * overlapping writes again, but this time taking into account
3059 * the "last_shared" property.
3061 * Furthermore, if two groups admit a shared memory tile and if the
3062 * combination of the two also admits a shared memory tile, we merge
3063 * the two groups.
3065 * If the array contains structures, then there is no need to compute
3066 * reference groups since we do not map such arrays to private or shared
3067 * memory.
3069 static int group_array_references(struct gpu_gen *gen,
3070 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3072 int i;
3073 int n;
3074 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3075 struct gpu_array_ref_group **groups;
3077 if (array->has_compound_element)
3078 return 0;
3080 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3081 array->n_ref);
3082 if (!groups)
3083 return -1;
3085 n = populate_array_references(array, sched, groups);
3087 n = group_overlapping_writes(gen, n, groups);
3089 for (i = 0; i < n; ++i)
3090 if (compute_group_bounds(gen, groups[i]) < 0)
3091 n = -1;
3093 n = group_last_shared_overlapping_writes(gen, n, groups);
3095 n = group_common_shared_memory_tile(gen, array, n, groups);
3097 set_array_groups(array, n, groups);
3099 if (n >= 0)
3100 return 0;
3102 for (i = 0; i < array->n_ref; ++i)
3103 free_array_ref_group(groups[i]);
3104 return -1;
3107 /* Take tiled_sched, project it onto the shared tile loops and
3108 * the loops that will be wrapped over the threads and
3109 * store the result in gen->shared_sched.
3110 * Also compute a projection that projects out the loops that will be
3111 * wrapped over the threads and store this projection in gen->shared_proj.
3113 static void compute_shared_sched(struct gpu_gen *gen)
3115 isl_space *dim;
3116 isl_map *proj;
3117 isl_set *par;
3118 isl_union_map *sched;
3120 sched = isl_union_map_copy(gen->tiled_sched);
3122 dim = isl_union_map_get_space(sched);
3123 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3124 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3126 dim = isl_union_map_get_space(sched);
3127 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3129 gen->shared_sched = sched;
3130 gen->shared_proj = isl_union_map_from_map(proj);
3133 /* For each scalar in the input program, check if there are any
3134 * order dependences active inside the current kernel, within
3135 * the same iteration of the host schedule.
3136 * If so, mark the scalar as force_private so that it will be
3137 * mapped to a register.
3139 static void check_scalar_live_ranges(struct gpu_gen *gen)
3141 int i;
3142 isl_map *proj;
3143 isl_union_map *sched;
3144 isl_union_set *domain;
3145 isl_union_map *same_host_iteration;
3147 gen->any_force_private = 0;
3149 if (!gen->options->live_range_reordering)
3150 return;
3152 sched = gen->shared_sched;
3153 sched = isl_union_map_universe(isl_union_map_copy(sched));
3154 domain = isl_union_map_domain(sched);
3156 sched = isl_union_map_copy(gen->sched);
3157 proj = projection(isl_union_map_get_space(sched),
3158 gen->untiled_len, gen->tile_first);
3159 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3160 same_host_iteration = isl_union_map_apply_range(sched,
3161 isl_union_map_reverse(isl_union_map_copy(sched)));
3163 for (i = 0; i < gen->prog->n_array; ++i) {
3164 struct gpu_array_info *array = &gen->prog->array[i];
3165 isl_union_map *order;
3167 array->force_private = 0;
3168 if (array->n_index != 0)
3169 continue;
3170 order = isl_union_map_copy(array->dep_order);
3171 order = isl_union_map_intersect_domain(order,
3172 isl_union_set_copy(domain));
3173 order = isl_union_map_intersect_range(order,
3174 isl_union_set_copy(domain));
3175 order = isl_union_map_intersect(order,
3176 isl_union_map_copy(same_host_iteration));
3177 if (!isl_union_map_is_empty(order)) {
3178 array->force_private = 1;
3179 gen->any_force_private = 1;
3181 isl_union_map_free(order);
3184 isl_union_map_free(same_host_iteration);
3185 isl_union_set_free(domain);
3188 /* Group references of all arrays in the program.
3190 static int group_references(struct gpu_gen *gen)
3192 int i;
3193 int r = 0;
3194 isl_union_map *sched;
3196 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3197 isl_union_map_copy(gen->shared_proj));
3199 for (i = 0; i < gen->prog->n_array; ++i) {
3200 r = group_array_references(gen, &gen->prog->array[i], sched);
3201 if (r < 0)
3202 break;
3205 isl_union_map_free(sched);
3207 return r;
3210 /* Free all array information that is local to the current kernel.
3212 static void free_local_array_info(struct gpu_gen *gen)
3214 int i, j;
3216 for (i = 0; i < gen->prog->n_array; ++i) {
3217 struct gpu_array_info *array = &gen->prog->array[i];
3219 for (j = 0; j < array->n_group; ++j)
3220 free_array_ref_group(array->groups[j]);
3221 free(array->groups);
3225 /* Compute the size of a bounding box around the origin and "set",
3226 * where "set" is assumed to contain only non-negative elements.
3227 * In particular, compute the maximal value of "set" in each direction
3228 * and add one.
3230 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3231 __isl_keep isl_set *context)
3233 int i, n;
3234 isl_multi_pw_aff *mpa;
3236 n = isl_set_dim(set, isl_dim_set);
3237 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3238 for (i = 0; i < n; ++i) {
3239 isl_space *space;
3240 isl_aff *one;
3241 isl_pw_aff *bound;
3243 bound = isl_set_dim_max(isl_set_copy(set), i);
3244 bound = isl_pw_aff_coalesce(bound);
3245 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3247 space = isl_pw_aff_get_domain_space(bound);
3248 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3249 one = isl_aff_add_constant_si(one, 1);
3250 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3251 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3253 isl_set_free(set);
3255 return mpa;
3258 /* Compute the effective grid size as a list of the sizes in each dimension.
3260 * The grid size specified by the user or set by default
3261 * in read_grid_sizes() and applied in tile_schedule(),
3262 * may be too large for the given code in the sense that
3263 * it may contain blocks that don't need to execute anything.
3264 * We therefore don't return this grid size, but instead the
3265 * smallest grid size that ensures that all blocks that actually
3266 * execute code are included in the grid.
3268 * We first extract a description of the grid, i.e., the possible values
3269 * of the block ids, from gen->tiled_sched.
3270 * The block ids are parameters in gen->tiled_sched.
3271 * We simply need to change them into set dimensions.
3273 * Then, for each block dimension, we compute the maximal value of the block id
3274 * and add one.
3276 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3277 struct ppcg_kernel *kernel)
3279 int i;
3280 isl_set *grid;
3282 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3283 grid = isl_set_from_params(grid);
3284 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3285 for (i = 0; i < gen->n_grid; ++i) {
3286 int pos;
3287 isl_id *id;
3289 id = isl_id_list_get_id(kernel->block_ids, i);
3290 pos = isl_set_find_dim_by_id(grid, isl_dim_param, id);
3291 isl_id_free(id);
3292 assert(pos >= 0);
3293 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3294 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3297 return extract_size(grid, kernel->context);
3300 /* Compute the size of a fixed bounding box around the origin and "set",
3301 * where "set" is assumed to contain only non-negative elements,
3302 * and store the results in "size".
3303 * In particular, compute the maximal value of "set" in each direction
3304 * and add one.
3306 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3308 int i, n;
3309 isl_local_space *ls;
3310 isl_aff *obj;
3312 n = isl_set_dim(set, isl_dim_set);
3313 ls = isl_local_space_from_space(isl_set_get_space(set));
3314 obj = isl_aff_zero_on_domain(ls);
3315 for (i = 0; i < n; ++i) {
3316 isl_val *max;
3318 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3319 max = isl_set_max_val(set, obj);
3320 size[i] = isl_val_get_num_si(max) + 1;
3321 isl_val_free(max);
3322 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3324 isl_aff_free(obj);
3325 isl_set_free(set);
3328 /* Compute the effective block size as a list of the sizes in each dimension
3329 * and store the sizes in kernel->block_dim.
3331 * The block size specified by the user or set by default
3332 * in read_block_sizes() and applied in thread_tile_schedule(),
3333 * may be too large for the given code in the sense that
3334 * it may contain threads that don't need to execute anything.
3335 * We therefore don't store this block size in kernel->block_dim,
3336 * but instead the smallest block size that ensures that all threads
3337 * that actually execute code are included in the block.
3339 * The current implementation eliminates all parameters, ensuring
3340 * that the size is a fixed constant in each dimension.
3341 * In principle we could also compute parametric sizes.
3342 * We would have to make sure to project out all b%d and t%d parameters,
3343 * however.
3345 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3347 int i;
3348 int nparam;
3349 isl_set *block;
3350 isl_multi_pw_aff *mpa;
3352 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3353 block = isl_set_from_params(block);
3354 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3355 kernel->n_block = gen->n_block;
3356 for (i = 0; i < gen->n_block; ++i) {
3357 int pos;
3358 isl_id *id;
3360 id = isl_id_list_get_id(kernel->thread_ids, i);
3361 pos = isl_set_find_dim_by_id(block, isl_dim_param, id);
3362 isl_id_free(id);
3363 assert(pos >= 0);
3364 block = isl_set_equate(block, isl_dim_param, pos,
3365 isl_dim_set, i);
3367 nparam = isl_set_dim(block, isl_dim_param);
3368 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3370 extract_fixed_size(block, kernel->block_dim);
3373 void ppcg_kernel_free(void *user)
3375 struct ppcg_kernel *kernel = user;
3376 int i;
3378 if (!kernel)
3379 return;
3381 isl_id_list_free(kernel->block_ids);
3382 isl_id_list_free(kernel->thread_ids);
3383 isl_multi_pw_aff_free(kernel->grid_size);
3384 isl_set_free(kernel->context);
3385 isl_union_set_free(kernel->arrays);
3386 isl_space_free(kernel->space);
3387 isl_ast_node_free(kernel->tree);
3389 for (i = 0; i < kernel->n_array; ++i)
3390 isl_pw_aff_list_free(kernel->array[i].bound);
3391 free(kernel->array);
3393 for (i = 0; i < kernel->n_var; ++i) {
3394 free(kernel->var[i].name);
3395 isl_vec_free(kernel->var[i].size);
3397 free(kernel->var);
3399 free(kernel);
3402 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3403 struct ppcg_kernel_var *var)
3405 int j;
3406 struct gpu_array_tile *tile;
3407 isl_printer *p;
3408 char *name;
3410 var->array = group->array;
3412 tile = group->private_tile;
3413 var->type = ppcg_access_private;
3414 if (!tile) {
3415 tile = group->shared_tile;
3416 var->type = ppcg_access_shared;
3419 p = isl_printer_to_str(ctx);
3420 p = print_array_name(p, group);
3421 var->name = isl_printer_get_str(p);
3422 isl_printer_free(p);
3424 var->size = isl_vec_alloc(ctx, group->array->n_index);
3426 for (j = 0; j < group->array->n_index; ++j)
3427 var->size = isl_vec_set_element_val(var->size, j,
3428 isl_val_copy(tile->bound[j].size));
3431 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3433 int i, j, n;
3435 n = 0;
3436 for (i = 0; i < gen->prog->n_array; ++i) {
3437 struct gpu_array_info *array = &gen->prog->array[i];
3439 for (j = 0; j < array->n_group; ++j) {
3440 struct gpu_array_ref_group *group = array->groups[j];
3441 if (group->private_tile || group->shared_tile)
3442 ++n;
3446 kernel->n_var = n;
3447 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3448 assert(kernel->var);
3450 n = 0;
3451 for (i = 0; i < gen->prog->n_array; ++i) {
3452 struct gpu_array_info *array = &gen->prog->array[i];
3454 for (j = 0; j < array->n_group; ++j) {
3455 struct gpu_array_ref_group *group = array->groups[j];
3456 if (!group->private_tile && !group->shared_tile)
3457 continue;
3458 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3459 ++n;
3464 /* Replace "pa" by the zero function defined over the universe domain
3465 * in the space of "pa".
3467 static __isl_give isl_pw_aff *set_universally_zero(__isl_take isl_pw_aff *pa)
3469 isl_space *space;
3470 isl_aff *zero;
3472 space = isl_space_domain(isl_pw_aff_get_space(pa));
3473 isl_pw_aff_free(pa);
3474 zero = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3476 return isl_pw_aff_from_aff(zero);
3479 /* The sizes of the arrays on the host that have been computed by
3480 * extract_array_info may depend on the parameters. Use the extra
3481 * constraints on the parameters that are valid at "host_domain"
3482 * to simplify these expressions and store the results in kernel->array.
3484 * We only need these localized bounds for arrays that are accessed
3485 * by the current kernel. If we have found at least one reference group
3486 * then the array is accessed by the kernel. If the array has compound
3487 * elements then we skipped the construction of array reference groups.
3489 * The resulting sizes may be functions that are nowhere defined
3490 * in case the access function cannot possibly access anything inside
3491 * the kernel for some reason. If so, they are replaced by the zero
3492 * function. Since the access function cannot actually access anything,
3493 * there is no harm in printing the array sizes as zero.
3495 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3496 __isl_keep isl_set *host_domain)
3498 int i, j;
3499 isl_set *context;
3501 kernel->array = isl_calloc_array(gen->ctx,
3502 struct gpu_local_array_info, gen->prog->n_array);
3503 assert(kernel->array);
3504 kernel->n_array = gen->prog->n_array;
3506 context = isl_set_copy(host_domain);
3507 context = isl_set_params(context);
3509 for (i = 0; i < gen->prog->n_array; ++i) {
3510 struct gpu_array_info *array = &gen->prog->array[i];
3511 isl_pw_aff_list *local;
3513 if (array->n_group == 0 && !array->has_compound_element)
3514 continue;
3516 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3518 for (j = 0; j < array->n_index; ++j) {
3519 isl_pw_aff *pwaff;
3520 int empty;
3522 pwaff = isl_pw_aff_copy(array->bound[j]);
3523 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3524 empty = isl_pw_aff_is_empty(pwaff);
3525 if (empty < 0)
3526 pwaff = isl_pw_aff_free(pwaff);
3527 else if (empty)
3528 pwaff = set_universally_zero(pwaff);
3529 local = isl_pw_aff_list_add(local, pwaff);
3532 kernel->array[i].n_index = array->n_index;
3533 kernel->array[i].bound = local;
3535 isl_set_free(context);
3538 /* Find the element in gen->stmt that has the given "id".
3539 * Return NULL if no such gpu_stmt can be found.
3541 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3543 int i;
3545 for (i = 0; i < prog->n_stmts; ++i) {
3546 if (id == prog->stmts[i].id)
3547 break;
3550 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3553 /* Set gen->tile_len and gen->n_parallel to those of the statement
3554 * affected by the first map (part of the schedule)
3555 * on which this function is called.
3556 * Because of the way the schedule is constructed, the other statements
3557 * in the list, if any, should have the same values for these properties.
3559 static int extract_tile_len(__isl_take isl_map *map, void *user)
3561 struct gpu_gen *gen = (struct gpu_gen *) user;
3562 isl_id *id;
3563 struct gpu_stmt *stmt;
3565 id = isl_map_get_tuple_id(map, isl_dim_in);
3566 stmt = find_stmt(gen->prog, id);
3567 isl_id_free(id);
3569 isl_map_free(map);
3571 if (!stmt)
3572 isl_die(gen->ctx, isl_error_unknown,
3573 "statement not found", return -1);
3575 gen->tile_len = stmt->tile_len;
3576 gen->n_parallel = stmt->n_parallel;
3578 return -1;
3581 void ppcg_kernel_stmt_free(void *user)
3583 int i;
3584 struct ppcg_kernel_stmt *stmt = user;
3586 if (!stmt)
3587 return;
3589 switch (stmt->type) {
3590 case ppcg_kernel_copy:
3591 isl_ast_expr_free(stmt->u.c.index);
3592 isl_ast_expr_free(stmt->u.c.local_index);
3593 break;
3594 case ppcg_kernel_domain:
3595 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3596 break;
3597 case ppcg_kernel_sync:
3598 break;
3601 free(stmt);
3604 /* Set the options of "context" to
3606 * { space -> [x] : x >= first }
3608 static __isl_give isl_ast_build *set_unroll(
3609 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3610 int first)
3612 isl_ctx *ctx;
3613 isl_map *unroll;
3614 isl_union_map *opt;
3616 ctx = isl_ast_build_get_ctx(build);
3618 space = isl_space_from_domain(space);
3619 space = isl_space_add_dims(space, isl_dim_out, 1);
3620 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3621 unroll = isl_map_universe(space);
3622 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3623 opt = isl_union_map_from_map(unroll);
3625 build = isl_ast_build_set_options(build, opt);
3627 return build;
3630 /* Extend the schedule "schedule" with the part of "extension"
3631 * starting at "first" up to "len".
3633 static __isl_give isl_union_map *extend_schedule(
3634 __isl_take isl_union_map *schedule,
3635 __isl_take isl_union_map *extension, int first, int len)
3637 isl_space *space;
3638 isl_map *proj;
3639 isl_union_map *umap;
3640 isl_set *set;
3642 space = isl_union_map_get_space(schedule);
3643 space = isl_space_set_from_params(space);
3644 space = isl_space_add_dims(space, isl_dim_set, len);
3645 proj = isl_set_identity(isl_set_universe(space));
3646 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3647 extension = isl_union_map_apply_range(extension,
3648 isl_union_map_from_map(proj));
3650 schedule = isl_union_map_range_product(schedule, extension);
3652 return schedule;
3655 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3656 * to "ref_id".
3658 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3659 __isl_keep isl_id *ref_id)
3661 struct gpu_stmt_access *access;
3663 for (access = accesses; access; access = access->next)
3664 if (access->ref_id == ref_id)
3665 return access;
3667 return NULL;
3670 /* Return the index of the array called "name" in the list of arrays.
3672 static int find_array_index(struct gpu_gen *gen, const char *name)
3674 int i;
3676 for (i = 0; i < gen->prog->n_array; ++i)
3677 if (!strcmp(name, gen->prog->array[i].name))
3678 return i;
3680 return -1;
3683 /* Internal data structure for the index and AST expression transformation
3684 * callbacks for pet_stmt_build_ast_exprs.
3686 * "accesses" is the list of gpu_stmt_access in the statement.
3687 * "iterator_map" expresses the statement iterators in terms of
3688 * the AST loop iterators.
3689 * "sched2shared" expresses the first shared_len dimensions of
3690 * the computed schedule in terms of the AST loop iterators.
3692 * The following fields are set in transform_index and used in transform_expr.
3693 * "array" is the array that is being accessed.
3694 * "global" is set if the global array is accessed (rather than
3695 * shared/private memory).
3696 * "local_array" refers to information on the array specialized
3697 * to the current kernel.
3699 struct ppcg_transform_data {
3700 struct gpu_gen *gen;
3701 struct gpu_stmt_access *accesses;
3702 isl_pw_multi_aff *iterator_map;
3703 isl_pw_multi_aff *sched2shared;
3705 struct gpu_array_info *array;
3706 int global;
3707 struct gpu_local_array_info *local_array;
3710 /* Return the name of the outer array (of structs) accessed by "access".
3712 static const char *get_outer_array_name(__isl_keep isl_map *access)
3714 isl_space *space;
3715 const char *name;
3717 space = isl_space_range(isl_map_get_space(access));
3718 while (space && isl_space_is_wrapping(space))
3719 space = isl_space_domain(isl_space_unwrap(space));
3720 name = isl_space_get_tuple_name(space, isl_dim_set);
3721 isl_space_free(space);
3723 return name;
3726 /* Index transformation callback for pet_stmt_build_ast_exprs.
3728 * "index" expresses the array indices in terms of statement iterators
3730 * We first reformulate "index" in terms of the AST loop iterators.
3731 * Then we check if we are accessing the global array or
3732 * a shared/private copy. In the former case, we simply return
3733 * the updated index. If "index" is an affine expression rather
3734 * than an array access, then we also return the updated index here.
3736 * If no reference groups have been computed for the array,
3737 * then we can only be accessing the global array.
3739 * Otherwise, we apply the tiling to the index.
3740 * This tiling is of the form
3742 * [D -> A] -> T
3744 * The index is of the form
3746 * L -> A
3748 * We update the tiling to refer to the AST loop iterators
3750 * [L -> A] -> T
3752 * and modify index to keep track of those iterators
3754 * L -> [L -> A]
3756 * Combining these two yields a tiled index expression in terms
3757 * of the AST loop iterators
3759 * L -> T
3761 static __isl_give isl_multi_pw_aff *transform_index(
3762 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3763 void *user)
3765 struct ppcg_transform_data *data = user;
3766 struct gpu_stmt_access *access;
3767 struct gpu_array_ref_group *group;
3768 struct gpu_array_tile *tile;
3769 isl_pw_multi_aff *iterator_map;
3770 int i;
3771 const char *name;
3772 isl_space *space;
3773 isl_multi_pw_aff *tiling;
3774 isl_pw_multi_aff *pma;
3775 isl_multi_pw_aff *mpa;
3777 data->array = NULL;
3779 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3780 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3782 access = find_access(data->accesses, ref_id);
3783 if (!access)
3784 return index;
3785 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3786 return index;
3788 name = get_outer_array_name(access->access);
3789 i = find_array_index(data->gen, name);
3790 if (i < 0)
3791 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3792 "cannot find array",
3793 return isl_multi_pw_aff_free(index));
3794 data->array = &data->gen->prog->array[i];
3795 data->local_array = &data->gen->kernel->array[i];
3797 if (access->group < 0) {
3798 data->global = 1;
3799 return index;
3802 group = data->array->groups[access->group];
3803 tile = group->private_tile;
3804 if (!tile)
3805 tile = group->shared_tile;
3806 data->global = !tile;
3807 if (!tile)
3808 return index;
3810 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3811 space = isl_space_map_from_set(space);
3812 pma = isl_pw_multi_aff_identity(space);
3813 pma = isl_pw_multi_aff_product(
3814 isl_pw_multi_aff_copy(data->sched2shared), pma);
3815 tiling = isl_multi_pw_aff_from_multi_aff(
3816 isl_multi_aff_copy(tile->tiling));
3817 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3819 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3820 space = isl_space_map_from_set(space);
3821 mpa = isl_multi_pw_aff_identity(space);
3822 index = isl_multi_pw_aff_range_product(mpa, index);
3823 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3825 return index;
3828 /* Dereference "expr" by adding an index [0].
3829 * The original "expr" is assumed not to have any indices.
3831 * If "expr" is a member access, then the dereferencing needs
3832 * to be applied to the structure argument of this member access.
3834 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3836 isl_ctx *ctx;
3837 isl_ast_expr *arg0, *res;
3838 isl_ast_expr_list *list;
3840 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3841 if (!arg0)
3842 return isl_ast_expr_free(expr);
3843 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3844 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3845 isl_ast_expr *arg;
3847 arg = isl_ast_expr_get_op_arg(arg0, 0);
3848 arg = dereference(arg);
3849 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3850 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3852 return expr;
3854 isl_ast_expr_free(arg0);
3856 ctx = isl_ast_expr_get_ctx(expr);
3857 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3858 list = isl_ast_expr_list_from_ast_expr(res);
3859 res = isl_ast_expr_get_op_arg(expr, 0);
3860 res = isl_ast_expr_access(res, list);
3861 isl_ast_expr_free(expr);
3863 return res;
3866 /* Linearize the index expression "expr" based on the array bounds
3867 * of "array".
3869 * That is, transform expression
3871 * A[i_0][i_1]...[i_n]
3873 * to
3875 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3877 * where b_0, b_1, ..., b_n are the bounds on the array.
3879 * If the base of "expr" is a member access, then the linearization needs
3880 * to be applied to the structure argument of this member access.
3882 * In the base case, if "expr" has no arguments (other than the name of
3883 * the array), then we are passing an entire array to a function.
3884 * In this case, there is nothing to linearize.
3885 * Note that at this point an expression with no arguments can
3886 * only be an entire array because the scalar case and
3887 * the case of single struct are handled by the caller.
3889 * If the number of specified index expressions in "expr"
3890 * is smaller than the dimension of the accessed array,
3891 * then the missing i_j also do not appear in the linearized expression.
3892 * Furthermore, since such an expression does not refer to a single
3893 * element while the default linearized expression would refer to
3894 * a single element, we return the expression
3896 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
3898 * instead. Note that because of the special case handling above,
3899 * we can assume here that here that there is at least one index expression.
3901 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3902 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3904 int i, n;
3905 isl_ctx *ctx;
3906 isl_set *context;
3907 isl_ast_expr *arg0;
3908 isl_ast_expr *res;
3909 isl_ast_expr_list *list;
3910 isl_ast_build *build;
3912 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3913 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3914 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3915 isl_ast_expr *arg;
3917 arg = isl_ast_expr_get_op_arg(arg0, 0);
3918 arg = gpu_local_array_info_linearize_index(array, arg);
3919 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3920 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3922 return expr;
3924 isl_ast_expr_free(arg0);
3926 if (isl_ast_expr_get_op_n_arg(expr) == 1)
3927 return expr;
3929 ctx = isl_ast_expr_get_ctx(expr);
3930 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3931 build = isl_ast_build_from_context(context);
3933 n = isl_ast_expr_get_op_n_arg(expr);
3934 res = isl_ast_expr_get_op_arg(expr, 1);
3935 for (i = 1; i < array->n_index; ++i) {
3936 isl_pw_aff *bound_i;
3937 isl_ast_expr *expr_i;
3939 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
3940 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3941 res = isl_ast_expr_mul(res, expr_i);
3943 if (i + 1 >= n)
3944 continue;
3945 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
3946 res = isl_ast_expr_add(res, expr_i);
3949 isl_ast_build_free(build);
3951 if (1 + array->n_index > n) {
3952 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
3953 } else {
3954 list = isl_ast_expr_list_from_ast_expr(res);
3955 res = isl_ast_expr_get_op_arg(expr, 0);
3956 res = isl_ast_expr_access(res, list);
3959 isl_ast_expr_free(expr);
3961 return res;
3964 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
3966 * If the AST expression refers to a global scalar that is not
3967 * a read-only scalar, then its address was passed to the kernel and
3968 * we need to dereference it.
3970 * If the AST expression refers to an access to a global array,
3971 * then we linearize the access exploiting the bounds in data->local_array.
3973 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
3974 __isl_keep isl_id *id, void *user)
3976 struct ppcg_transform_data *data = user;
3978 if (!data->array)
3979 return expr;
3980 if (gpu_array_is_read_only_scalar(data->array))
3981 return expr;
3982 if (!data->global)
3983 return expr;
3984 if (data->array->n_index == 0)
3985 return dereference(expr);
3986 if (!data->array->linearize)
3987 return expr;
3989 return gpu_local_array_info_linearize_index(data->local_array, expr);
3992 /* This function is called for each instance of a user statement
3993 * in the kernel.
3995 * We attach a struct ppcg_kernel_stmt to the "node", containing
3996 * a computed AST expression for each access.
3997 * These AST expressions are computed from iterator_map,
3998 * which expresses the domain
3999 * elements in terms of the generated loops, and sched2shared,
4000 * which expresses the first shared_len dimensions of the schedule
4001 * computed by PPCG in terms of the generated loops.
4003 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
4004 __isl_keep isl_ast_build *build, void *user)
4006 struct ppcg_transform_data data;
4007 struct gpu_gen *gen = (struct gpu_gen *) user;
4008 struct ppcg_kernel_stmt *stmt;
4009 isl_id *id;
4010 isl_pw_multi_aff *sched2shared;
4011 isl_map *map;
4012 isl_pw_multi_aff *iterator_map;
4013 isl_ast_expr *expr, *arg;
4014 isl_union_map *schedule;
4016 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4017 if (!stmt)
4018 return isl_ast_node_free(node);
4020 expr = isl_ast_node_user_get_expr(node);
4021 arg = isl_ast_expr_get_op_arg(expr, 0);
4022 id = isl_ast_expr_get_id(arg);
4024 schedule = isl_ast_build_get_schedule(build);
4025 map = isl_map_reverse(isl_map_from_union_map(schedule));
4026 iterator_map = isl_pw_multi_aff_from_map(map);
4027 sched2shared = compute_sched_to_shared(gen,
4028 isl_pw_multi_aff_copy(iterator_map));
4030 stmt->type = ppcg_kernel_domain;
4031 stmt->u.d.stmt = find_stmt(gen->prog, id);
4032 if (!stmt->u.d.stmt)
4033 isl_die(gen->ctx, isl_error_internal,
4034 "statement not found", goto error);
4036 data.gen = gen;
4037 data.accesses = stmt->u.d.stmt->accesses;
4038 data.iterator_map = iterator_map;
4039 data.sched2shared = sched2shared;
4040 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4041 build, &transform_index, &data,
4042 &transform_expr, &data);
4044 isl_id_free(id);
4045 isl_pw_multi_aff_free(iterator_map);
4046 isl_pw_multi_aff_free(sched2shared);
4047 isl_ast_expr_free(arg);
4048 isl_ast_expr_free(expr);
4050 id = isl_id_alloc(gen->ctx, NULL, stmt);
4051 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4052 return isl_ast_node_set_annotation(node, id);
4053 error:
4054 isl_id_free(id);
4055 isl_pw_multi_aff_free(iterator_map);
4056 ppcg_kernel_stmt_free(stmt);
4057 isl_pw_multi_aff_free(sched2shared);
4058 return isl_ast_node_free(node);
4061 /* This function is called when code has been generated for the shared
4062 * tile loops. The "schedule" refers only to the original statements.
4064 * We extend the schedule with that part of gen->local_sched that hasn't
4065 * been taken into account yet. This introduces parameters referring
4066 * to thread ids in the schedule, so we add them (with the appropriate
4067 * bounds to the context as well).
4068 * Finally, we set the appropriate unrolling options
4069 * if gen->first_unroll is set.
4071 static __isl_give isl_ast_node *create_domain_leaf(
4072 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4073 void *user)
4075 struct gpu_gen *gen = (struct gpu_gen *) user;
4076 isl_space *space;
4077 isl_union_map *sched;
4078 isl_ast_node *tree;
4079 isl_set *set;
4080 isl_id_list *iterators;
4081 int n;
4083 schedule = extend_schedule(schedule,
4084 isl_union_map_copy(gen->local_sched),
4085 gen->shared_len, gen->thread_tiled_len);
4087 space = isl_ast_build_get_schedule_space(build);
4088 set = isl_set_universe(space);
4089 set = add_bounded_parameters(set, gen->kernel->block_dim,
4090 gen->kernel->thread_ids);
4091 build = isl_ast_build_restrict(build, set);
4093 n = gen->thread_tiled_len - gen->shared_len;
4095 if (gen->first_unroll >= 0) {
4096 space = isl_space_set_alloc(gen->ctx, 0, n);
4097 build = set_unroll(build, space, gen->first_unroll);
4099 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
4100 build = isl_ast_build_set_iterators(build, iterators);
4101 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4102 tree = isl_ast_build_ast_from_schedule(build, schedule);
4103 isl_ast_build_free(build);
4105 return tree;
4108 /* This function is called for each statement node in the AST of the code
4109 * for copying to or from shared/private memory.
4110 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4111 * statement to the node.
4112 * The statement name is "read" or "write", depending on whether we are
4113 * reading from global memory or writing to global memory.
4114 * The name of the T space is {shared,private}_<array>.
4116 * The schedule is of the form
4118 * type[A -> T] -> L
4120 * where A refers to a piece of an array and T to the corresponding
4121 * shifted tile. We split this schedule into mappings L -> A and L -> T
4122 * and store the corresponding expressions in stmt->index and stmt->local_index,
4123 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4125 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4126 __isl_keep isl_ast_build *build, void *user)
4128 struct gpu_gen *gen = (struct gpu_gen *) user;
4129 struct ppcg_kernel_stmt *stmt;
4130 isl_id *id;
4131 isl_ast_expr *expr;
4132 isl_space *space;
4133 isl_map *access, *local_access, *map;
4134 isl_pw_multi_aff *pma;
4135 const char *type;
4136 int array_index;
4138 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4139 if (!stmt)
4140 return isl_ast_node_free(node);
4142 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4143 type = isl_map_get_tuple_name(access, isl_dim_in);
4144 stmt->u.c.read = !strcmp(type, "read");
4145 access = isl_map_reverse(access);
4146 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4147 local_access = isl_map_copy(access);
4149 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4150 id = isl_map_get_tuple_id(access, isl_dim_out);
4151 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4152 access = isl_map_apply_range(access, map);
4153 pma = isl_pw_multi_aff_from_map(access);
4154 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4155 stmt->u.c.index = expr;
4157 map = isl_map_range_map(isl_map_universe(space));
4158 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4159 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4160 local_access = isl_map_apply_range(local_access, map);
4161 pma = isl_pw_multi_aff_from_map(local_access);
4162 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4163 stmt->u.c.local_index = expr;
4165 stmt->u.c.array = gen->copy_group->array;
4166 array_index = stmt->u.c.array - gen->prog->array;
4167 stmt->u.c.local_array = &gen->kernel->array[array_index];
4168 stmt->type = ppcg_kernel_copy;
4170 id = isl_id_alloc(gen->ctx, NULL, stmt);
4171 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4172 return isl_ast_node_set_annotation(node, id);
4175 /* Given a schedule of the form
4177 * [S -> A] -> L
4179 * (with S the first shared_len dimensions of the computed schedule,
4180 * A the array and L the schedule correponding to the generated loops),
4181 * indicating where to copy the array elements that need to be copied,
4182 * construct code for performing the copying.
4184 * "group" is the array reference group that is being copied
4185 * "type" is either "read" or "write"
4186 * private is set if copying needs to be performed to/from registers
4188 * We first construct a mapping to a shifted tile of the array,
4190 * [S -> A] -> T(S,A) (1)
4192 * If private is set, then we also use this mapping as a schedule
4193 * (which is already thread-specific and will be completely unrolled).
4194 * Otherwise, we wrap/tile the range over the threads.
4195 * The result is
4197 * [S -> A] -> T'(S,A)
4199 * Combined with the given schedule, we have
4201 * [S -> A] -> [L -> T'(S,A)] (2)
4203 * From the shifted tile mapping, we construct a mapping
4205 * [S -> A] -> [A -> T(S,A)]
4207 * and apply it to the schedule (2), obtaining
4209 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4211 * Note that we can project out S because it is uniquely defined by L.
4213 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4214 __isl_take isl_map *sched,
4215 const char *type, struct gpu_array_ref_group *group,
4216 __isl_take isl_ast_build *build, int private)
4218 isl_space *space;
4219 isl_ast_node *tree;
4220 isl_map *schedule, *shift, *map;
4221 isl_set *set;
4222 isl_id_list *iterators;
4223 int n;
4225 shift = shift_access(group);
4227 schedule = isl_map_copy(shift);
4228 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4229 if (!private)
4230 schedule = tile_access_schedule(gen, schedule);
4232 n = isl_map_dim(schedule, isl_dim_out);
4233 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4234 set = add_bounded_parameters(set, gen->kernel->block_dim,
4235 gen->kernel->thread_ids);
4237 schedule = isl_map_range_product(sched, schedule);
4239 space = isl_space_domain(isl_map_get_space(shift));
4240 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4241 map = isl_map_range_product(map, shift);
4243 schedule = isl_map_apply_domain(schedule, map);
4245 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4247 build = isl_ast_build_restrict(build, set);
4249 gen->copy_group = group;
4251 if (private) {
4252 space = isl_space_range(isl_map_get_space(schedule));
4253 space = isl_space_range(isl_space_unwrap(space));
4254 build = set_unroll(build, space, 0);
4256 iterators = ppcg_scop_generate_names(gen->prog->scop, n, "c");
4257 build = isl_ast_build_set_iterators(build, iterators);
4258 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4259 tree = isl_ast_build_ast_from_schedule(build,
4260 isl_union_map_from_map(schedule));
4261 isl_ast_build_free(build);
4263 return tree;
4266 /* Return code for reading into or writing from shared memory
4267 * the given array reference group.
4269 * If we are performing a read from global memory to shared memory and
4270 * if the array involved is not a scalar, then we copy
4271 * the entire tile to shared memory. This may result in some extra
4272 * elements getting copied, but it should lead to simpler code
4273 * (which means that fewer registers may be needed) and less divergence.
4275 * Otherwise, we only copy the elements that will be read or have been written
4276 * in the kernel.
4279 * The input "sched" is of the form.
4281 * type[S -> A] -> L
4283 * with S the first shared_len dimensions of the computed schedule,
4284 * A the array and L the schedule correponding to the generated loops.
4286 * We first drop "type",
4288 * [S -> A] -> L
4290 * If the above conditions are satisfied, we project out A,
4291 * resulting in
4293 * S -> L
4295 * and then introduce the group tile [S -> T], resulting in
4297 * [S -> T] -> L
4299 static __isl_give isl_ast_node *copy_group_shared_accesses(
4300 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4301 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4303 const char *type;
4304 int read;
4305 isl_union_map *access;
4307 type = isl_map_get_tuple_name(sched, isl_dim_in);
4308 read = !strcmp(type, "read");
4310 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4312 if (read && !gpu_array_is_scalar(group->array)) {
4313 isl_space *space;
4314 isl_map *map;
4316 space = isl_space_domain(isl_map_get_space(sched));
4317 space = isl_space_unwrap(space);
4318 map = isl_map_domain_map(isl_map_universe(space));
4319 sched = isl_map_apply_domain(sched, map);
4321 map = group_tile(group);
4322 map = isl_map_reverse(isl_map_domain_map(map));
4323 sched = isl_map_apply_domain(sched, map);
4326 return copy_access(gen, sched, type, group, build, 0);
4329 /* Return code for reading into or writing from private memory
4330 * the given array reference group.
4332 * Let S be the first shared_len dimensions of the computed schedule,
4333 * D the iteration domains, A the array and L the schedule correponding
4334 * to the generated loops.
4335 * "sched" is of the form
4337 * type[S -> A] -> L
4339 * where type is either "read" or "write".
4340 * We apply the privatization D -> S(t), with t the thread ids,
4341 * to the access relation D -> A to obtain the privatized access relation
4343 * S(t) -> A
4345 * We drop the type from "sched" and intersect with the privatized access
4346 * relation to obtain
4348 * [S(t) -> A] -> L
4350 static __isl_give isl_ast_node *copy_group_private_accesses(
4351 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4352 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4354 const char *type;
4355 int read;
4356 isl_union_map *priv;
4357 isl_union_map *access;
4358 isl_map *access_map;
4360 type = isl_map_get_tuple_name(sched, isl_dim_in);
4361 read = !strcmp(type, "read");
4363 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4364 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4365 priv);
4367 access = group_access_relation(group, read, !read);
4368 access = isl_union_map_apply_domain(access, priv);
4369 access_map = isl_map_from_union_map(access);
4371 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4372 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4374 return copy_access(gen, sched, type, group, build, 1);
4377 /* Return code for reading into or writing from shared or private memory.
4379 * "schedule" is of the form
4381 * type[S -> A] -> L
4383 * with S be the first shared_len dimensions of the computed schedule,
4384 * A the array and L the schedule correponding to the generated loops.
4385 * The array reference group is attached to "type".
4387 static __isl_give isl_ast_node *create_access_leaf(
4388 struct gpu_gen *gen, __isl_take isl_map *schedule,
4389 __isl_take isl_ast_build *build)
4391 struct gpu_array_ref_group *group;
4392 isl_id *id;
4394 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4395 group = isl_id_get_user(id);
4396 isl_id_free(id);
4398 if (group->private_tile)
4399 return copy_group_private_accesses(gen, group, schedule,
4400 build);
4401 else
4402 return copy_group_shared_accesses(gen, group, schedule,
4403 build);
4406 /* Create a domain node representing a synchronization.
4408 static __isl_give isl_ast_node *create_sync_leaf(
4409 struct gpu_gen *gen, __isl_take isl_map *schedule,
4410 __isl_take isl_ast_build *build)
4412 struct ppcg_kernel_stmt *stmt;
4413 isl_id *id;
4414 isl_space *space;
4415 isl_ast_node *node;
4416 isl_ast_expr *expr;
4418 isl_map_free(schedule);
4420 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4421 if (!stmt)
4422 return NULL;
4424 stmt->type = ppcg_kernel_sync;
4426 space = isl_ast_build_get_schedule_space(build);
4427 space = isl_space_from_domain(space);
4428 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4429 expr = isl_ast_build_call_from_pw_multi_aff(build,
4430 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4431 node = isl_ast_node_alloc_user(expr);
4432 isl_ast_build_free(build);
4434 id = isl_id_alloc(gen->ctx, NULL, stmt);
4435 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4436 return isl_ast_node_set_annotation(node, id);
4439 /* This function is called during the code generation at the point
4440 * where the schedule domain element is completely determined by
4441 * the generated code. The input schedule contains the original
4442 * statements as well as synchronization and copy "statements".
4443 * The latter are scheduled at different points than any of the original
4444 * statements, so they will only arrive here in isolation.
4446 * If the current schedule only refers to a single statement,
4447 * we check if it is a copy or synchronization statement and
4448 * call the appropriate functions.
4449 * Otherwise, we assume we are dealing with the original statements
4450 * and we call create_domain_leaf.
4452 static __isl_give isl_ast_node *create_kernel_leaf(
4453 __isl_take isl_ast_build *build, void *user)
4455 struct gpu_gen *gen = (struct gpu_gen *) user;
4456 isl_map *map;
4457 isl_union_map *schedule;
4458 const char *name;
4460 schedule = isl_ast_build_get_schedule(build);
4462 if (isl_union_map_n_map(schedule) != 1)
4463 return create_domain_leaf(schedule, build, user);
4465 map = isl_map_from_union_map(schedule);
4466 name = isl_map_get_tuple_name(map, isl_dim_in);
4467 if (!strcmp(name, "read") || !strcmp(name, "write"))
4468 return create_access_leaf(gen, map, build);
4469 if (!strcmp(name, "sync"))
4470 return create_sync_leaf(gen, map, build);
4472 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4475 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4476 * have value 0) and all even schedule dimensions as "unroll".
4478 * That is, the options look as follows
4480 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4481 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4483 * The even positions are used to be able to schedule copying blocks
4484 * and synchronization before or after each level of the shared memory
4485 * tile loops and we want to make sure that code for these is generated
4486 * separately (within each level).
4488 static __isl_give isl_ast_build *set_atomic_and_unroll(
4489 __isl_take isl_ast_build *build,
4490 __isl_take isl_space *space, int sched_len)
4492 isl_ctx *ctx;
4493 isl_map *map;
4494 isl_constraint *c;
4495 isl_union_map *opt;
4496 isl_local_space *ls;
4497 int i, n;
4499 ctx = isl_ast_build_get_ctx(build);
4501 space = isl_space_params(space);
4502 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4503 space = isl_space_from_domain(space);
4504 space = isl_space_add_dims(space, isl_dim_out, 2);
4505 map = isl_map_universe(isl_space_copy(space));
4506 for (i = 0; i < sched_len; i += 2)
4507 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4508 ls = isl_local_space_from_space(isl_map_get_space(map));
4509 c = isl_equality_alloc(ls);
4510 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4511 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4512 c = isl_constraint_set_constant_si(c, 1);
4513 map = isl_map_add_constraint(map, c);
4514 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4515 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4516 opt = isl_union_map_from_map(map);
4518 map = isl_map_universe(space);
4519 ls = isl_local_space_from_space(isl_map_get_space(map));
4520 c = isl_equality_alloc(ls);
4521 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4522 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4523 map = isl_map_add_constraint(map, c);
4524 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4525 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4526 opt = isl_union_map_add_map(opt, map);
4528 build = isl_ast_build_set_options(build, opt);
4530 return build;
4533 /* Return a map that maps a space of dimension gen->shared_len
4534 * to its last dimensions starting at gen->tile_first.
4535 * The range is of dimension
4537 * 2 * (gen->shared_len - gen->tile_first) + 1
4539 * The input dimensions are mapped to the odd dimensions in the output,
4540 * while the even dimensions (except 2*pos) are fixed to 0.
4541 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4542 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4543 * are mapped to the output. The remaining input dimensions are projected
4544 * out and the corresponding output dimensions are fixed to 0.
4546 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4547 __isl_take isl_space *space, int pos, int val)
4549 int i, n;
4550 isl_map *proj;
4552 space = isl_space_set_from_params(space);
4553 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4554 space = isl_space_map_from_set(space);
4555 proj = isl_map_identity(space);
4556 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4557 n = gen->shared_len - gen->tile_first;
4558 for (i = 0; i <= n; ++i) {
4559 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4560 if (i == pos)
4561 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4562 else
4563 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4566 if (pos < 0)
4567 return proj;
4569 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4570 gen->shared_len - (gen->tile_first + pos));
4571 for (i = pos; i < n; ++i)
4572 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4574 return proj;
4577 /* Given the AST context schedule "schedule" and the mapping from
4578 * domains to the shared tile loops "shared_sched", add a schedule
4579 * for a synchronization operation at position "val" of loop level "pos".
4581 * schedule is of the form
4583 * D -> L
4585 * (with D the iteration domains and L the already generated loops),
4586 * while shared_sched is of the form
4588 * D -> S
4590 * We combine them into
4592 * L -> S
4594 * apply a mapping
4596 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4598 * and use the result as a schedule for "sync".
4600 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4601 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4602 __isl_keep isl_union_map *shared_sched, int pos, int val)
4604 isl_space *space;
4605 isl_map *proj, *map;
4607 shared_sched = isl_union_map_copy(shared_sched);
4608 schedule = isl_union_map_copy(schedule);
4610 space = isl_union_map_get_space(shared_sched);
4611 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4612 map = isl_map_from_union_map(schedule);
4614 proj = insert_even(gen, space, pos, val);
4615 map = isl_map_apply_range(map, proj);
4616 map = isl_map_from_range(isl_map_wrap(map));
4617 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4619 res = isl_union_map_add_map(res, map);
4621 return res;
4624 /* Given a set of wrapped references "ref", return the corresponding
4625 * access relations based on the tagged access relations "tagged".
4627 * The elements of "ref" are of the form
4629 * [D -> R]
4631 * with D an iteration domains and R a reference.
4632 * The elements of "tagged" are of the form
4634 * [D -> R] -> A
4636 * with A an array.
4638 * Extend "tagged" to include the iteration domain in the range, i.e.,
4640 * [D -> R] -> [D -> A]
4642 * apply the result to "ref" and then unwrap the resulting set
4643 * to obtain relations of the form
4645 * D -> A
4647 static __isl_give isl_union_map *wrapped_reference_to_access(
4648 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4650 isl_union_map *tag2access;
4652 tag2access = isl_union_map_copy(tagged);
4653 tag2access = isl_union_map_universe(tag2access);
4654 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4655 tag2access = isl_union_map_domain_map(tag2access);
4656 tag2access = isl_union_map_range_product(tag2access, tagged);
4658 ref = isl_union_set_coalesce(ref);
4659 ref = isl_union_set_apply(ref, tag2access);
4661 return isl_union_set_unwrap(ref);
4664 /* Given an access relation "access" from "group", remove those reads
4665 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4666 * communicate data within the same iteration of the last_shared dimension
4667 * of the group.
4669 * If the access is a read then it is either an element of
4671 * live_in union (range flow)
4673 * where live_in and flow may be overapproximations, or
4674 * it reads an uninitialized value (that is not live-in because
4675 * there is an intermediate kill) or it reads a value that was
4676 * written within the same (compound) statement instance.
4677 * If the access is a write then it is either an element of
4679 * live_out union (domain flow)
4681 * or it writes a value that is never read (and is not live-out
4682 * because of an intermediate kill) or only
4683 * within the same (compound) statement instance.
4684 * In both cases, the access relation is also a subset of
4685 * the group access relation.
4687 * The cases where an uninitialized value is read or a value is written
4688 * that is never read or where the dataflow occurs within a statement
4689 * instance are also considered local and may also be removed.
4691 * Essentially, we compute the intersection of "access" with either
4693 * live_in union (range non-local-flow)
4695 * or
4697 * live_out union (domain non-local-flow)
4699 * We first construct a relation "local"
4701 * [[D -> R] -> [D' -> R']]
4703 * of pairs of domain iterations accessing the reference group
4704 * and references in the group that are scheduled to the same iteration
4705 * of the last_shared dimension.
4707 * If this relation does not intersect the dataflow dependences,
4708 * then there is nothing we can possibly remove, unless the dataflow
4709 * dependences themselves only relate a subset of the accesses.
4710 * In particular, the accesses may not be involved in any dataflow
4711 * dependences, either because they are uninitialized reads/dead writes
4712 * or because the dataflow occurs inside a statement instance.
4714 * Since the computation below may break up the access relation
4715 * into smaller pieces, we only perform the intersection with
4716 * the non-local dependent accesses if the local pairs
4717 * intersect the dataflow dependences. Otherwise, we intersect
4718 * with the universe of the non-local dependent accesses.
4719 * This should at least remove accesses from statements that
4720 * do not participate in any dependences.
4722 * In particular, we remove the "local" dataflow dependences from
4723 * the set of all dataflow dependences.
4724 * Note that if the potential dataflow dependences are an overapproximation
4725 * of the actual dataflow dependences, then the result remains an
4726 * overapproximation of the non-local dataflow dependences.
4727 * Copying to/from global memory is only needed for the references
4728 * in the domain/range of the result or for accesses that are live out/in
4729 * for the entire scop.
4731 * We therefore map the domain/range of the "external" relation
4732 * to the corresponding access relation and take the union with
4733 * the live out/in relation.
4735 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4736 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4737 int read)
4739 int empty;
4740 isl_union_map *tagger;
4741 isl_union_set *domain;
4742 isl_space *space;
4743 isl_union_map *sched, *local, *tagged, *external;
4744 isl_union_set *tag_set;
4745 isl_map *proj;
4747 if (isl_union_map_is_empty(access))
4748 return access;
4750 tagged = group_tagged_access_relation(group);
4752 sched = isl_union_map_copy(gen->sched);
4754 space = isl_union_map_get_space(sched);
4755 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4756 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4758 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4759 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4760 tagger = isl_union_map_intersect_range(tagger, domain);
4761 sched = isl_union_map_apply_domain(sched, tagger);
4763 local = isl_union_map_apply_range(sched,
4764 isl_union_map_reverse(isl_union_map_copy(sched)));
4765 local = isl_union_map_intersect(local,
4766 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4768 empty = isl_union_map_is_empty(local);
4770 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4771 external = isl_union_map_intersect_params(external,
4772 isl_set_copy(gen->prog->scop->context));
4773 external = isl_union_map_subtract(external, local);
4775 if (read) {
4776 tag_set = isl_union_map_range(external);
4777 external = wrapped_reference_to_access(tag_set, tagged);
4778 external = isl_union_map_union(external,
4779 isl_union_map_copy(gen->prog->scop->live_in));
4780 } else {
4781 tag_set = isl_union_map_domain(external);
4782 external = wrapped_reference_to_access(tag_set, tagged);
4783 external = isl_union_map_union(external,
4784 isl_union_map_copy(gen->prog->scop->live_out));
4787 if (empty < 0)
4788 external = isl_union_map_free(external);
4789 else if (empty)
4790 external = isl_union_map_universe(external);
4792 access = isl_union_map_intersect(access, external);
4794 return access;
4797 /* Given the AST context schedule "schedule" and the mapping from
4798 * domains to the shared tile loops "shared_sched", add a schedule
4799 * for copying an array reference group to/from shared/private memory.
4800 * "read" is set if data should be copied from global memory
4801 * to shared/private memory.
4802 * "k" represents the current group
4803 * "s" is the total number of groups
4805 * We schedule an operation before or after the innermost loop
4806 * of "shared_sched" that affects the tile of the array reference group.
4808 * schedule is of the form
4810 * D -> L
4812 * (with D the iteration domains and L the already generated loops),
4813 * while shared_sched is of the form
4815 * D -> S
4817 * We first compute the access relation for the reference group
4819 * D -> A
4821 * and remove from this access relation those reads or writes
4822 * that only needed to communicate data within the same iteration
4823 * of the last_shared dimension of the group.
4824 * We then combine what is left with shared_sched into
4826 * D -> [S -> A]
4828 * If this results in an empty relation, no copying needs to be performed
4829 * at this point.
4830 * Otherwise, we invert the relation and combine it with "schedule" into
4832 * [S -> A] -> L
4834 * The actual additional piece of the schedule is obtained from combining
4836 * [S -> A] -> S
4838 * with a mapping
4840 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4842 * The position of "val" corresponds to the innermost loop that affects
4843 * the tile and the value indicates where the copying is scheduled
4844 * with respect to the actual kernel code (at value 0).
4845 * Reads are schedule before the code, writes to global memory from
4846 * private memory are scheduled at values 1 to s, writes to global
4847 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4849 * If we are scheduling a read from global memory to shared memory,
4850 * we insert a synchronization before the kernel code (at the innermost
4851 * level).
4852 * If we are scheduling a write to global memory, then we add
4853 * a synchronization after all writes (at value 2 *s + 2).
4854 * However, there is no need for a synchronization after the outermost loop.
4855 * A write to global memory from private memory at the innermost level
4856 * does not require a synchronization, because it is covered by
4857 * the synchronization after the kernel inserted by body_schedule.
4859 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4860 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4861 __isl_keep isl_union_map *shared_sched,
4862 struct gpu_array_ref_group *group, int read, int k, int s)
4864 int n;
4865 int pos, val;
4866 isl_space *space;
4867 isl_union_map *access;
4868 isl_map *map, *proj, *access_map;
4869 isl_id *id;
4871 access = group_access_relation(group, read, !read);
4872 access = remove_local_accesses(gen, group, access, read);
4873 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4874 access);
4876 if (isl_union_map_is_empty(access)) {
4877 isl_union_map_free(access);
4878 return res;
4881 access = isl_union_map_reverse(access);
4882 access = isl_union_map_apply_range(access,
4883 isl_union_map_copy(schedule));
4884 access_map = isl_map_from_union_map(access);
4886 space = isl_space_copy(group->array->space);
4887 space = isl_space_from_range(space);
4888 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4889 map = isl_map_domain_map(isl_map_universe(space));
4891 space = isl_union_map_get_space(schedule);
4892 pos = group->last_shared + 1 - gen->tile_first;
4893 assert(pos >= 0);
4894 if (read)
4895 val = -2 - k;
4896 else if (group->private_tile)
4897 val = 1 + k;
4898 else
4899 val = 1 + s + 1 + k;
4900 proj = insert_even(gen, space, pos, val);
4901 map = isl_map_apply_range(map, proj);
4903 access_map = isl_map_range_product(access_map, map);
4905 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4906 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4908 res = isl_union_map_add_map(res, access_map);
4910 n = gen->shared_len - gen->tile_first;
4911 if (read) {
4912 if (!group->private_tile)
4913 res = add_sync_schedule(gen, res, schedule,
4914 shared_sched, n, -1);
4915 } else {
4916 if (pos == 0)
4917 return res;
4918 if (pos == n && group->private_tile)
4919 return res;
4920 res = add_sync_schedule(gen, res, schedule, shared_sched,
4921 pos, 2 * s + 2);
4924 return res;
4927 /* Return a schedule for the shared tile loops based on the current
4928 * AST context schedule.
4930 * We create a "shared_sched" that maps the domains to the first
4931 * shared_len dimensions of the computed schedule, project out the
4932 * first tile_first dimensions (as these are already covered by
4933 * the host code) and insert "statement-level" dimensions at even
4934 * positions so that we can schedule copy blocks and synchronization
4935 * before/after each level.
4937 * In particular, copy blocks are inserted inside the innermost
4938 * level that affect the tile. For the copying to global memory,
4939 * those from private memory are scheduled before those from shared
4940 * memory such that synchronization can be inserted between the two
4941 * at the innermost level.
4942 * Synchronization is inserted at the innermost level before the
4943 * actual kernel code if there is any copying from global memory
4944 * to shared memory. It is inserted unconditionally at the innermost
4945 * level after the actual kernel code and the copying to global memory
4946 * from private memory (if any). Finally, it is inserted after
4947 * any copying to global memory, except at the outermost level
4948 * and at the innermost level if there is no copying from shared
4949 * memory. The copying from private memory is covered by the unconditional
4950 * synchronization at the innermost level.
4952 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4953 __isl_take isl_union_map *schedule)
4955 isl_space *space;
4956 isl_union_map *res;
4957 isl_union_map *shared_sched;
4958 isl_union_map *sched;
4959 isl_map *proj, *map;
4960 int i, j, k, s;
4962 shared_sched = isl_union_map_copy(gen->tiled_sched);
4963 proj = projection(isl_union_map_get_space(shared_sched),
4964 gen->tiled_len, gen->shared_len);
4965 shared_sched = isl_union_map_apply_range(shared_sched,
4966 isl_union_map_from_map(proj));
4967 space = isl_union_map_get_space(shared_sched);
4968 proj = insert_even(gen, space, -1, 0);
4969 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4970 isl_union_map_from_map(proj));
4972 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4974 s = 0;
4975 for (i = 0; i < gen->prog->n_array; ++i)
4976 s += gen->prog->array[i].n_group;
4978 k = 0;
4979 for (i = 0; i < gen->prog->n_array; ++i) {
4980 struct gpu_array_info *array = &gen->prog->array[i];
4982 for (j = 0; j < array->n_group; ++j) {
4983 struct gpu_array_ref_group *group;
4985 group = array->groups[j];
4986 if (!group->private_tile && !group->shared_tile)
4987 continue;
4988 res = add_group_schedule(gen, res, schedule,
4989 shared_sched, group, 0, k, s);
4990 res = add_group_schedule(gen, res, schedule,
4991 shared_sched, group, 1, k, s);
4992 ++k;
4996 res = add_sync_schedule(gen, res, schedule, shared_sched,
4997 gen->shared_len - gen->tile_first, 1 + s);
4999 isl_union_map_free(shared_sched);
5000 isl_union_map_free(schedule);
5002 return res;
5005 /* Generate code for "kernel" in the given "context".
5007 * We first generate code for the shared tile loops (T1T, T1P and T2)
5008 * in a context that includes the block ids.
5009 * Within each iteration of these loops an additional code generation
5010 * is performed (within create_kernel_leaf) for the rest of the schedule
5011 * in a context that includes the thread ids.
5013 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
5014 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
5015 __isl_keep isl_multi_pw_aff *grid_size)
5017 isl_space *space;
5018 isl_set *set;
5019 isl_id_list *iterators;
5020 isl_union_map *schedule;
5021 isl_ast_node *tree;
5022 int sched_len;
5024 schedule = isl_ast_build_get_schedule(build);
5026 build = isl_ast_build_copy(build);
5027 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5028 space = isl_ast_build_get_schedule_space(build);
5029 set = isl_set_universe(isl_space_copy(space));
5030 set = add_bounded_parameters_dynamic(set, grid_size,
5031 gen->kernel->block_ids);
5032 build = isl_ast_build_restrict(build, set);
5034 schedule = body_schedule(gen, schedule);
5036 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5038 build = set_atomic_and_unroll(build, space, sched_len);
5039 iterators = ppcg_scop_generate_names(gen->prog->scop, sched_len, "g");
5040 build = isl_ast_build_set_iterators(build, iterators);
5041 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5042 tree = isl_ast_build_ast_from_schedule(build, schedule);
5043 isl_ast_build_free(build);
5045 return tree;
5048 /* Attach "id" to the given node.
5050 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5051 __isl_keep isl_ast_build *build, void *user)
5053 isl_id *id = user;
5055 node = isl_ast_node_set_annotation(node, id);
5057 return node;
5060 /* Construct an AST node for performing a kernel launch and attach
5061 * the information about the kernel to that node.
5063 * The kernel AST has been constructed in the context of the range
5064 * of "schedule". In particular, the grid size has been computed
5065 * in the context. We therefore still need to make sure that these
5066 * constraints are expressed in the code. We do this by creating a schedule
5068 * kernel[] -> [S -> []]
5070 * where S is the schedule domain, i.e., the range of "schedule".
5071 * The AST generation will then create a single call surrounded by
5072 * all the condition in "S" that have not been expressed yet.
5074 * The kernel information is attached to this node in attach_id.
5076 static __isl_give isl_ast_node *construct_launch(
5077 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5078 __isl_take struct ppcg_kernel *kernel)
5080 isl_id *id;
5081 isl_ctx *ctx;
5082 isl_union_set *domain;
5083 isl_set *set;
5084 isl_map *map;
5085 isl_ast_node *node;
5087 ctx = isl_ast_build_get_ctx(build);
5089 id = isl_id_alloc(ctx, NULL, kernel);
5090 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5092 domain = isl_union_map_range(schedule);
5093 set = isl_set_from_union_set(domain);
5094 map = isl_map_from_domain(set);
5095 map = isl_map_from_range(isl_map_wrap(map));
5096 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5097 schedule = isl_union_map_from_map(map);
5099 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5100 node = isl_ast_build_ast_from_schedule(build, schedule);
5101 isl_ast_build_free(build);
5103 return node;
5106 /* This function is called for each leaf in the AST of the host code.
5107 * We first specialize the schedule to the site of the leaf, compute
5108 * the size of shared memory and then construct the body of the host code
5109 * and the associated kernel.
5111 * The necessary information for printing the kernel launch is
5112 * stored in a struct ppcg_kernel and attached to the leaf node
5113 * created to represent the launch.
5115 static __isl_give isl_ast_node *create_host_leaf(
5116 __isl_take isl_ast_build *build, void *user)
5118 struct gpu_gen *gen = (struct gpu_gen *) user;
5119 isl_id *id;
5120 isl_ast_node *node;
5121 struct ppcg_kernel *kernel;
5122 isl_set *host_domain;
5123 isl_union_map *schedule;
5124 isl_union_map *local_sched;
5125 isl_union_map *access;
5126 isl_union_set *domain;
5127 int i;
5129 schedule = isl_ast_build_get_schedule(build);
5131 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5132 read_sizes(gen);
5134 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5136 local_sched = isl_union_map_copy(gen->sched);
5137 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5138 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5139 isl_union_map_copy(gen->prog->may_write));
5140 access = isl_union_map_apply_domain(access,
5141 isl_union_map_copy(local_sched));
5143 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5144 if (!kernel)
5145 goto error;
5146 kernel->block_ids = ppcg_scop_generate_names(gen->prog->scop,
5147 gen->n_grid, "b");
5148 kernel->thread_ids = ppcg_scop_generate_names(gen->prog->scop,
5149 gen->n_block, "t");
5151 gen->tiled_sched = tile_schedule(gen, local_sched);
5152 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5153 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5155 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5156 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5157 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5159 kernel->id = gen->kernel_id++;
5160 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5161 kernel->grid_size = extract_grid_size(gen, kernel);
5162 extract_block_size(gen, kernel);
5163 kernel->arrays = isl_union_map_range(access);
5164 kernel->arrays = isl_union_set_apply(kernel->arrays,
5165 isl_union_map_copy(gen->prog->to_outer));
5166 kernel->space = isl_ast_build_get_schedule_space(build);
5168 compute_shared_sched(gen);
5169 gen->privatization = compute_privatization(gen);
5170 check_scalar_live_ranges(gen);
5171 if (group_references(gen) < 0)
5172 schedule = isl_union_map_free(schedule);
5173 host_domain = isl_set_from_union_set(isl_union_map_range(
5174 isl_union_map_copy(schedule)));
5175 localize_bounds(gen, kernel, host_domain);
5177 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5178 check_shared_memory_bound(gen);
5179 compute_group_tilings(gen);
5181 kernel->tree = generate_kernel(gen, build, host_domain,
5182 kernel->grid_size);
5183 create_kernel_vars(gen, kernel);
5185 free_local_array_info(gen);
5186 isl_map_free(gen->privatization);
5187 isl_union_map_free(gen->local_sched);
5188 isl_union_map_free(gen->tiled_sched);
5189 isl_union_map_free(gen->shared_sched);
5190 isl_union_map_free(gen->shared_proj);
5191 isl_set_free(host_domain);
5192 free(gen->tile_size);
5194 node = construct_launch(build, schedule, kernel);
5196 return node;
5197 error:
5198 isl_union_map_free(schedule);
5199 return NULL;
5202 /* Use isl to generate code for the outer gen->tile_first loops
5203 * of the global schedule in gen->sched, resulting in the host code.
5204 * Within each iteration of this partial schedule, i.e., for each kernel
5205 * launch, create_host_leaf takes care of generating the kernel code.
5207 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5209 isl_ast_build *build;
5210 isl_ast_node *tree;
5211 isl_union_map *sched;
5212 isl_map *proj;
5213 isl_id_list *iterators;
5215 sched = isl_union_map_copy(gen->sched);
5216 proj = projection(isl_union_map_get_space(sched),
5217 gen->untiled_len, gen->tile_first);
5218 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5220 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5221 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5222 iterators = ppcg_scop_generate_names(gen->prog->scop,
5223 gen->tile_first, "h");
5224 build = isl_ast_build_set_iterators(build, iterators);
5225 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5226 tree = isl_ast_build_ast_from_schedule(build, sched);
5227 isl_ast_build_free(build);
5229 return tree;
5232 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5234 if (!str)
5235 return NULL;
5236 return isl_union_map_read_from_str(ctx, str);
5239 /* Information about the outermost tilable bands in the forest of bands.
5241 * tile_len and n_parallel are only sets on band_info structures
5242 * that correspond to outermost bands. For other bands (in particular,
5243 * ancestors of the outermost bands), n_parallal is set to 0.
5245 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5247 * tile_first is the number of schedule dimensions in prefix.
5249 * suffix is the schedule of the outermost tilable bands and their descendants.
5251 struct band_info {
5252 struct gpu_gen *gen;
5253 int tile_first;
5254 int tile_len;
5255 int n_parallel;
5256 isl_union_map *prefix;
5257 isl_union_map *suffix;
5260 /* Set tile_len and n_parallel of the statement to that of
5261 * their outermost band, recorded in the band_info.
5263 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5265 struct band_info *info = user;
5266 struct gpu_stmt *stmt;
5267 isl_id *id;
5269 id = isl_map_get_tuple_id(map, isl_dim_in);
5270 stmt = find_stmt(info->gen->prog, id);
5271 isl_id_free(id);
5273 stmt->tile_len = info->tile_len;
5274 stmt->n_parallel = info->n_parallel;
5276 isl_map_free(map);
5278 return 0;
5281 static void list_select_outer_band(struct gpu_gen *gen,
5282 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5284 /* Check if this band has any parallel loops. If so, take it as
5285 * the outermost tilable band. If not, continue looking for the
5286 * outermost tilable band in the children of the current band.
5288 static void band_select_outer_band(struct gpu_gen *gen,
5289 __isl_take isl_band *band, int pos, struct band_info *info)
5291 int n = isl_band_n_member(band);
5292 int n_parallel;
5294 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5295 if (!isl_band_member_is_coincident(band, n_parallel))
5296 break;
5298 info->n_parallel = n_parallel;
5299 if (n_parallel) {
5300 gen->any_parallelism = 1;
5301 info->gen = gen;
5302 info->tile_first = pos;
5303 info->tile_len = n;
5304 info->prefix = isl_band_get_prefix_schedule(band);
5305 info->suffix = isl_union_map_flat_range_product(
5306 isl_band_get_partial_schedule(band),
5307 isl_band_get_suffix_schedule(band));
5308 isl_union_map_foreach_map(info->prefix,
5309 &set_stmt_tile_len, info);
5310 } else if (isl_band_has_children(band)) {
5311 isl_band_list *children;
5312 children = isl_band_get_children(band);
5313 list_select_outer_band(gen, children, pos + n, info);
5314 } else {
5315 info->gen = gen;
5316 info->tile_first = pos + n;
5317 info->tile_len = 0;
5318 info->prefix = isl_union_map_flat_range_product(
5319 isl_band_get_prefix_schedule(band),
5320 isl_band_get_partial_schedule(band));
5321 info->suffix = isl_band_get_suffix_schedule(band);
5322 isl_union_map_foreach_map(info->prefix,
5323 &set_stmt_tile_len, info);
5326 isl_band_free(band);
5329 /* Comparison function that returns a non-zero value for band_infos
5330 * with different tile_len fields or different n_parallel fields.
5332 static int cmp_band(const void *p1, const void *p2)
5334 const struct band_info *info1 = p1;
5335 const struct band_info *info2 = p2;
5337 if (info1->tile_len != info2->tile_len)
5338 return info1->tile_len - info2->tile_len;
5340 return info1->n_parallel - info2->n_parallel;
5343 /* Extend "umap" with coordinates with fixed value "val"
5344 * to a total length of "dst_len", assuming the original dimension is "src_len".
5346 static __isl_give isl_union_map *extend_range(
5347 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5349 isl_space *dim;
5350 isl_map *map;
5351 int i;
5353 dim = isl_union_map_get_space(umap);
5354 map = isl_map_reverse(projection(dim, dst_len, src_len));
5355 for (i = src_len; i < dst_len; ++i)
5356 map = isl_map_fix_si(map, isl_dim_out, i, val);
5358 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5360 return umap;
5363 /* Group bands with the same values for tile_len and n_parallel.
5364 * The prefix schedule is then extended with a fixed coordinate that
5365 * is different for each such group.
5366 * Note that the actual values for this coordinate are not important.
5367 * The bands have already been effectively separated at a higher level
5368 * or they are independent and may be executed in parallel.
5369 * The list of band_info has been sorted before this functions is called.
5371 static void separate_bands(struct band_info *info, int n)
5373 int i;
5374 int j = 0;
5376 for (i = 0; i < n; ++i) {
5377 int l = info[i].tile_first;
5379 if (i &&
5380 (info[i].tile_len != info[i - 1].tile_len ||
5381 info[i].n_parallel != info[i - 1].n_parallel))
5382 j++;
5384 info[i].prefix = extend_range(info[i].prefix,
5385 l, l + 1, j);
5386 info[i].tile_first = l + 1;
5390 /* Select the outermost bands in the elements of the list, align
5391 * their prefix schedules, separate bands with different values
5392 * for tile_len and/or n_parallel and then combine the resulting
5393 * prefix and suffix schedules into a single pair of prefix and
5394 * suffix schedules for the entire list.
5396 static void list_select_outer_band(struct gpu_gen *gen,
5397 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5399 isl_band *band;
5400 int i;
5401 int n = isl_band_list_n_band(list);
5402 isl_ctx *ctx = isl_band_list_get_ctx(list);
5403 struct band_info *info;
5404 int max_tile_first;
5405 isl_union_map *prefix;
5406 isl_union_map *suffix;
5408 assert(n >= 1);
5409 info = isl_calloc_array(ctx, struct band_info, n);
5410 assert(info);
5412 max_tile_first = 0;
5413 for (i = 0; i < n; ++i) {
5414 band = isl_band_list_get_band(list, i);
5415 band_select_outer_band(gen, band, pos, &info[i]);
5416 if (info[i].tile_first > max_tile_first)
5417 max_tile_first = info[i].tile_first;
5420 for (i = 0; i < n; ++i) {
5421 if (info[i].tile_first == max_tile_first)
5422 continue;
5423 info[i].prefix = extend_range(info[i].prefix,
5424 info[i].tile_first, max_tile_first, 0);
5425 info[i].tile_first = max_tile_first;
5428 qsort(info, n, sizeof(struct band_info), &cmp_band);
5430 for (i = 0; i < n - 1; ++i)
5431 if (info[i].tile_len != info[i + 1].tile_len ||
5432 info[i].n_parallel != info[i + 1].n_parallel)
5433 break;
5435 if (i < n -1)
5436 separate_bands(info, n);
5438 prefix = info[0].prefix;
5439 suffix = info[0].suffix;
5441 for (i = 1; i < n; ++i) {
5442 prefix = isl_union_map_union(prefix, info[i].prefix);
5443 suffix = isl_union_map_union(suffix, info[i].suffix);
5446 list_info->tile_first = info[0].tile_first;
5447 list_info->tile_len = -1;
5448 list_info->prefix = prefix;
5449 list_info->suffix = suffix;
5451 isl_band_list_free(list);
5452 free(info);
5455 /* Select the outermost tilable band that (by construction)
5456 * has at least one parallel loop.
5457 * The starting position of the aligned band is stored in the pair
5458 * gen->tile_first.
5459 * The sizes and number of parallel loops may be different in different
5460 * parts of the band forest and are therefore stored in the gpu_stmts.
5462 * Return the complete schedule, with the tilable bands aligned
5463 * at gen->tile_first and padded with zero, if needed.
5465 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5466 __isl_keep isl_schedule *schedule)
5468 isl_band_list *list;
5469 struct band_info info;
5471 gen->n_parallel = 0;
5472 gen->tile_len = -1;
5474 list = isl_schedule_get_band_forest(schedule);
5476 if (isl_band_list_n_band(list) == 0) {
5477 isl_band_list_free(list);
5478 return isl_schedule_get_map(schedule);
5481 list_select_outer_band(gen, list, 0, &info);
5483 gen->tile_first = info.tile_first;
5484 info.suffix = align_range(info.suffix);
5486 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5489 /* Set gen->untiled_len to the number of scheduling dimensions
5490 * for the schedule of the first domain.
5491 * We assume here that this number is the same for all domains.
5493 static int set_untiled_len(__isl_take isl_map *map, void *user)
5495 unsigned *untiled_len = user;
5497 *untiled_len = isl_map_dim(map, isl_dim_out);
5499 isl_map_free(map);
5500 return -1;
5503 /* Compute an appropriate schedule based on the accesses in
5504 * gen->read and gen->write.
5506 * We use the dependences in gen->prog->scop to compute
5507 * a schedule that has a parallel loop in each tilable band.
5508 * Finally, we select the outermost tilable band.
5510 * If live range reordering is allowed, then we need to make sure
5511 * that live ranges on arrays are not run in parallel since doing
5512 * so would require array expansion. We therefore add the array
5513 * order dependences to the coincidence dependences. Non-zero array
5514 * order dependences will then prevent a schedule dimension from being
5515 * considered parallel.
5516 * Live ranges derived from scalars are allowed to be run in parallel
5517 * since we force the scalars to be mapped to private memory in
5518 * check_scalar_live_ranges.
5519 * If live range reordering is allowed, then the false dependences
5520 * are not added to the validity constraints as that would prevent
5521 * reordering. Instead, the external false dependences that enforce that reads
5522 * from potentially live-in data precede any later write and
5523 * that writes of potentially live-out data follow any other earlier write
5524 * are added to the validity and the coincidence constraints.
5525 * The false dependences are still added to the proximity constraints
5526 * for consistency with the case where live range reordering is not allowed.
5527 * The coincidence constraints then consist of flow dependences,
5528 * external false dependences and array order dependences.
5529 * The independences can be filtered out from the first two sets.
5530 * They have already been filtered out from the array order dependences
5531 * on a per array basis in collect_order_dependences.
5532 * There is no need for a per array handling of the other two sets
5533 * as there should be no flow or external false dependence on local
5534 * variables that can be filtered out.
5536 static void compute_schedule(struct gpu_gen *gen)
5538 isl_union_set *domain;
5539 isl_union_map *dep_raw, *dep;
5540 isl_union_map *validity, *proximity, *coincidence;
5541 isl_union_map *sched;
5542 isl_schedule_constraints *sc;
5543 isl_schedule *schedule;
5545 domain = isl_union_set_copy(gen->prog->scop->domain);
5546 domain = isl_union_set_intersect_params(domain,
5547 isl_set_copy(gen->prog->scop->context));
5548 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5549 if (gen->options->live_range_reordering) {
5550 sc = isl_schedule_constraints_set_conditional_validity(sc,
5551 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5552 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5553 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5554 validity = isl_union_map_copy(proximity);
5555 validity = isl_union_map_union(validity,
5556 isl_union_map_copy(gen->prog->scop->dep_external));
5557 proximity = isl_union_map_union(proximity,
5558 isl_union_map_copy(gen->prog->scop->dep_false));
5559 coincidence = isl_union_map_copy(validity);
5560 coincidence = isl_union_map_subtract(coincidence,
5561 isl_union_map_copy(gen->prog->scop->independence));
5562 coincidence = isl_union_map_union(coincidence,
5563 isl_union_map_copy(gen->prog->array_order));
5564 } else {
5565 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5566 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5567 dep = isl_union_map_union(dep, dep_raw);
5568 dep = isl_union_map_coalesce(dep);
5569 proximity = isl_union_map_copy(dep);
5570 coincidence = isl_union_map_copy(dep);
5571 validity = dep;
5573 sc = isl_schedule_constraints_set_validity(sc, validity);
5574 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5575 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5577 if (gen->options->debug->dump_schedule_constraints)
5578 isl_schedule_constraints_dump(sc);
5579 schedule = isl_schedule_constraints_compute_schedule(sc);
5580 if (gen->options->debug->dump_schedule)
5581 isl_schedule_dump(schedule);
5583 sched = select_outer_tilable_band(gen, schedule);
5585 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5586 sched = isl_union_map_intersect_domain(sched, domain);
5587 gen->sched = sched;
5589 isl_schedule_free(schedule);
5592 /* Compute the sets of outer array elements that need to be copied in and out.
5594 * In particular, for each array that is possibly written anywhere in
5595 * gen->prog and that is visible outside the corresponding scop,
5596 * we copy out its entire extent.
5598 * Any array elements that is read without first being written needs
5599 * to be copied in. Furthermore, if there are any array elements that
5600 * are copied out, but that may not be written inside gen->prog, then
5601 * they also need to be copied in to ensure that the value after execution
5602 * is the same as the value before execution, at least for those array
5603 * elements that may have their values preserved by the scop.
5604 * In case the array elements are structures, we need to take into
5605 * account that all members of the structures need to be written
5606 * by gen->prog before we can avoid copying the data structure in.
5608 * While computing the set of array elements that are copied out but
5609 * not necessarily written, we intersect both sets with the context.
5610 * This helps in those cases where the arrays are declared with a fixed size,
5611 * while the accesses are parametric and the context assigns a fixed value
5612 * to the parameters.
5614 * If an element from a local array is read without first being written,
5615 * then there is no point in copying it in since it cannot have been
5616 * written prior to the scop. Warn about the uninitialized read instead.
5618 static void compute_copy_in_and_out(struct gpu_gen *gen)
5620 int i;
5621 isl_union_set *local;
5622 isl_union_set *may_write, *must_write;
5623 isl_union_set *copy_in, *copy_out;
5624 isl_union_set *not_written;
5625 isl_union_map *uninitialized;
5626 isl_union_map *local_uninitialized;
5628 must_write = isl_union_map_range(
5629 isl_union_map_copy(gen->prog->must_write));
5630 must_write = isl_union_set_intersect_params(must_write,
5631 isl_set_copy(gen->prog->context));
5632 may_write = isl_union_map_range(
5633 isl_union_map_copy(gen->prog->may_write));
5634 may_write = isl_union_set_intersect_params(may_write,
5635 isl_set_copy(gen->prog->context));
5636 may_write = isl_union_set_universe(may_write);
5637 may_write = isl_union_set_apply(may_write,
5638 isl_union_map_copy(gen->prog->to_outer));
5639 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5640 local = isl_union_set_copy(copy_out);
5642 for (i = 0; i < gen->prog->n_array; ++i) {
5643 isl_space *space;
5644 isl_set *write_i;
5645 int empty;
5647 space = isl_space_copy(gen->prog->array[i].space);
5649 if (gen->prog->array[i].local) {
5650 isl_set *set;
5652 set = isl_set_universe(space);
5653 local = isl_union_set_add_set(local, set);
5654 continue;
5657 write_i = isl_union_set_extract_set(may_write, space);
5658 empty = isl_set_plain_is_empty(write_i);
5659 isl_set_free(write_i);
5660 if (empty)
5661 continue;
5663 write_i = isl_set_copy(gen->prog->array[i].extent);
5664 copy_out = isl_union_set_add_set(copy_out, write_i);
5666 isl_union_set_free(may_write);
5668 copy_out = isl_union_set_intersect_params(copy_out,
5669 isl_set_copy(gen->prog->context));
5671 gen->prog->copy_out = isl_union_set_copy(copy_out);
5673 copy_out = isl_union_set_apply(copy_out,
5674 isl_union_map_copy(gen->prog->to_inner));
5675 copy_out = isl_union_set_intersect(copy_out,
5676 isl_union_set_copy(gen->prog->may_persist));
5677 not_written = isl_union_set_subtract(copy_out, must_write);
5679 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5680 local_uninitialized = isl_union_map_copy(uninitialized);
5682 local = isl_union_set_apply(local,
5683 isl_union_map_copy(gen->prog->to_inner));
5684 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5685 local);
5686 if (!isl_union_map_is_empty(local_uninitialized)) {
5687 fprintf(stderr,
5688 "possibly uninitialized reads (not copied in):\n");
5689 isl_union_map_dump(local_uninitialized);
5691 uninitialized = isl_union_map_subtract(uninitialized,
5692 local_uninitialized);
5693 copy_in = isl_union_map_range(uninitialized);
5694 copy_in = isl_union_set_union(copy_in, not_written);
5695 copy_in = isl_union_set_apply(copy_in,
5696 isl_union_map_copy(gen->prog->to_outer));
5698 gen->prog->copy_in = copy_in;
5701 /* Internal data structure for extract_access.
5702 * "next_access" points to the end of a linked list that is extended
5703 * by extract_access.
5704 * "single_expression" is set if the access expressions belong to
5705 * an expression statement (i.e., a statement without internal control).
5706 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5708 struct ppcg_extract_access_data {
5709 struct gpu_stmt_access **next_access;
5710 int single_expression;
5711 isl_union_map *any_to_outer;
5714 /* Extract a gpu_stmt_access from "expr", append it to the list
5715 * that ends in *data->next_access and update the end of the list.
5716 * If the access expression performs a write, then it is considered
5717 * exact only if it appears in a single expression statement and
5718 * if its may access relation is equal to its must access relation.
5720 * The combined set of may accesses may be union if member accesses
5721 * are involved, but the entire set is derived from a single reference and
5722 * therefore from a single index expression. These accesses therefore
5723 * all map to the same outer array.
5725 static int extract_access(__isl_keep pet_expr *expr, void *user)
5727 struct ppcg_extract_access_data *data = user;
5728 isl_union_map *may, *tagged;
5729 struct gpu_stmt_access *access;
5730 isl_ctx *ctx;
5731 isl_multi_pw_aff *index;
5733 may = pet_expr_access_get_may_read(expr);
5734 may = isl_union_map_union(may, pet_expr_access_get_may_write(expr));
5735 may = isl_union_map_apply_range(may,
5736 isl_union_map_copy(data->any_to_outer));
5737 ctx = isl_union_map_get_ctx(may);
5738 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5739 assert(access);
5740 access->next = NULL;
5741 access->read = pet_expr_access_is_read(expr);
5742 access->write = pet_expr_access_is_write(expr);
5743 tagged = pet_expr_access_get_tagged_may_read(expr);
5744 tagged = isl_union_map_union(tagged,
5745 pet_expr_access_get_tagged_may_write(expr));
5746 tagged = isl_union_map_apply_range(tagged,
5747 isl_union_map_copy(data->any_to_outer));
5748 access->tagged_access = isl_map_from_union_map(tagged);
5749 if (!access->write) {
5750 access->exact_write = 1;
5751 } else if (!data->single_expression) {
5752 access->exact_write = 0;
5753 } else {
5754 isl_union_map *must;
5755 must = pet_expr_access_get_must_write(expr);
5756 access->exact_write = isl_union_map_is_equal(must, may);
5757 isl_union_map_free(must);
5759 access->access = isl_map_from_union_map(may);
5760 index = pet_expr_access_get_index(expr);
5761 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5762 isl_multi_pw_aff_free(index);
5763 access->ref_id = pet_expr_access_get_ref_id(expr);
5764 access->group = -1;
5766 *data->next_access = access;
5767 data->next_access = &(*data->next_access)->next;
5769 return 0;
5772 /* Construct a linked list of gpu_stmt_access objects,
5773 * one for each access expression in the statement body.
5774 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5776 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5777 __isl_keep isl_union_map *any_to_outer)
5779 struct ppcg_extract_access_data data;
5781 stmt->accesses = NULL;
5782 data.next_access = &stmt->accesses;
5783 data.single_expression =
5784 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5785 data.any_to_outer = any_to_outer;
5786 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5789 /* Return an array of gpu_stmt representing the statements in "scop".
5791 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5792 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5794 int i;
5795 struct gpu_stmt *stmts;
5797 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5798 if (!stmts)
5799 return NULL;
5801 for (i = 0; i < scop->pet->n_stmt; ++i) {
5802 struct gpu_stmt *s = &stmts[i];
5804 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5805 s->stmt = scop->pet->stmts[i];
5806 pet_stmt_extract_accesses(s, any_to_outer);
5809 return stmts;
5812 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5814 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5816 struct gpu_gen *gen = user;
5818 return gen->print(p, gen->prog, gen->tree, &gen->types,
5819 gen->print_user);
5822 /* Generate CUDA code for "scop" and print it to "p".
5823 * After generating an AST for the transformed scop as explained below,
5824 * we call "gen->print" to print the AST in the desired output format
5825 * to "p".
5827 * If it turns out that it does not make sense to generate GPU code,
5828 * then we generate CPU code instead.
5830 * The GPU code is generated in a context where at least one
5831 * statement instance is executed. The corresponding guard (if any) is printed
5832 * around the entire generated GPU code, except for the declaration
5833 * of the arrays that are visible outside of the scop and that therefore
5834 * cannot be declared inside the body of any possible guard.
5836 * We first compute a schedule that respects the dependences
5837 * of the original program and select the outermost band
5838 * of tilable dimensions that has at least one parallel loop.
5839 * We then have three blocks of dimensions
5841 * H B G
5843 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5844 * in
5846 * H T P G
5848 * For each iteration of the T loop and for each array, we compute
5849 * the array elements accessed by that iteration, construct a rectangular
5850 * box around it and shift it to the origin. The result is used
5851 * as shared memory for the array.
5853 * We then split off at most 2 parallel loops from the T loops and
5854 * at most 3 parallel loops from the P loops
5856 * H T1 T2 P1 P2 G
5858 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5859 * according to "grid"/"block" sizes.
5861 * H T1T T1P T2 P1T P1P P2 G
5863 * Finally, the T1P and P1P iterators are equated to the block and
5864 * thread dimensions respectively and so are effectively removed.
5865 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5866 * are run on the GPU.
5868 * Code is generated in three stages. We first generate code for the
5869 * host (the H loops), with iterators h%d. Then, for each leaf node
5870 * of the resulting AST, we generate code for the shared loops (up to
5871 * and including T2), with iterators g%d and after equating the H loops
5872 * to h%d parameters and the T1P loops to the block dimensions.
5873 * Finally, we generate code for the remaining loops in a similar fashion.
5875 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5876 struct gpu_gen *gen, struct ppcg_scop *scop,
5877 struct ppcg_options *options)
5879 struct gpu_prog *prog;
5880 isl_ctx *ctx;
5881 isl_set *context, *guard;
5883 if (!scop)
5884 return isl_printer_free(p);
5886 ctx = isl_printer_get_ctx(p);
5887 prog = gpu_prog_alloc(ctx, scop);
5888 if (!prog)
5889 return isl_printer_free(p);
5891 context = isl_set_copy(prog->context);
5892 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5893 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5895 gen->prog = prog;
5896 gen->any_parallelism = 0;
5897 compute_schedule(gen);
5899 if (!gen->any_parallelism) {
5900 isl_set_free(context);
5901 isl_set_free(guard);
5902 p = print_cpu(p, scop, options);
5903 } else {
5904 compute_copy_in_and_out(gen);
5905 gen->tree = generate_host_code(gen);
5906 p = ppcg_print_exposed_declarations(p, prog->scop);
5907 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5908 isl_ast_node_free(gen->tree);
5911 isl_union_map_free(gen->sched);
5913 gpu_prog_free(prog);
5915 return p;
5918 /* Wrapper around generate for use as a ppcg_transform callback.
5920 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5921 struct ppcg_scop *scop, void *user)
5923 struct gpu_gen *gen = user;
5925 return generate(p, gen, scop, gen->options);
5928 /* Transform the code in the file called "input" by replacing
5929 * all scops by corresponding GPU code and write the results to "out".
5931 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5932 struct ppcg_options *options,
5933 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5934 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5935 struct gpu_types *types, void *user), void *user)
5937 struct gpu_gen gen;
5938 int r;
5939 int i;
5941 gen.ctx = ctx;
5942 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5943 gen.options = options;
5944 gen.kernel_id = 0;
5945 gen.print = print;
5946 gen.print_user = user;
5947 gen.types.n = 0;
5948 gen.types.name = NULL;
5950 if (options->debug->dump_sizes) {
5951 isl_space *space = isl_space_params_alloc(ctx, 0);
5952 gen.used_sizes = isl_union_map_empty(space);
5955 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5957 if (options->debug->dump_sizes) {
5958 isl_union_map_dump(gen.used_sizes);
5959 isl_union_map_free(gen.used_sizes);
5962 isl_union_map_free(gen.sizes);
5963 for (i = 0; i < gen.types.n; ++i)
5964 free(gen.types.name[i]);
5965 free(gen.types.name);
5967 return r;
5970 /* Compute the set of inner array elements that may have their values
5971 * preserved by "prog". In particular, collect the array elements of
5972 * arrays that are not local to "prog" and remove those elements that
5973 * are definitely killed or definitely written by "prog".
5975 static __isl_give isl_union_set *compute_may_persist(struct gpu_prog *prog)
5977 int i;
5978 isl_union_set *may_persist, *killed;
5979 isl_union_map *must_kill;
5981 may_persist = isl_union_set_empty(isl_set_get_space(prog->context));
5982 for (i = 0; i < prog->n_array; ++i) {
5983 isl_set *extent;
5985 if (prog->array[i].local)
5986 continue;
5988 extent = isl_set_copy(prog->array[i].extent);
5989 may_persist = isl_union_set_add_set(may_persist, extent);
5992 may_persist = isl_union_set_intersect_params(may_persist,
5993 isl_set_copy(prog->context));
5994 may_persist = isl_union_set_apply(may_persist,
5995 isl_union_map_copy(prog->to_inner));
5996 must_kill = isl_union_map_copy(prog->tagged_must_kill);
5997 killed = isl_union_map_range(must_kill);
5998 must_kill = isl_union_map_copy(prog->must_write);
5999 killed = isl_union_set_union(killed, isl_union_map_range(must_kill));
6001 may_persist = isl_union_set_subtract(may_persist, killed);
6002 return may_persist;
6005 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
6007 struct gpu_prog *prog;
6008 isl_space *space;
6009 isl_map *id;
6011 if (!scop)
6012 return NULL;
6014 prog = isl_calloc_type(ctx, struct gpu_prog);
6015 assert(prog);
6017 prog->ctx = ctx;
6018 prog->scop = scop;
6019 prog->context = isl_set_copy(scop->context);
6020 prog->n_stmts = scop->pet->n_stmt;
6021 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
6022 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
6023 space = isl_union_map_get_space(prog->any_to_outer);
6024 space = isl_space_set_from_params(space);
6025 space = isl_space_add_dims(space, isl_dim_set, 1);
6026 space = isl_space_map_from_set(space);
6027 id = isl_map_identity(space);
6028 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
6029 prog->stmts = extract_stmts(ctx, scop,
6030 prog->context, prog->any_to_outer);
6031 prog->read = isl_union_map_copy(scop->reads);
6032 prog->may_write = isl_union_map_copy(scop->may_writes);
6033 prog->must_write = isl_union_map_copy(scop->must_writes);
6034 prog->tagged_must_kill = isl_union_map_copy(scop->tagged_must_kills);
6035 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
6036 prog->to_outer = isl_union_map_copy(prog->to_inner);
6037 prog->to_outer = isl_union_map_reverse(prog->to_outer);
6039 if (!prog->stmts)
6040 return gpu_prog_free(prog);
6042 if (collect_array_info(prog) < 0)
6043 return gpu_prog_free(prog);
6044 prog->may_persist = compute_may_persist(prog);
6046 return prog;
6049 void *gpu_prog_free(struct gpu_prog *prog)
6051 if (!prog)
6052 return NULL;
6053 free_array_info(prog);
6054 free_stmts(prog->stmts, prog->n_stmts);
6055 isl_union_map_free(prog->any_to_outer);
6056 isl_union_map_free(prog->to_outer);
6057 isl_union_map_free(prog->to_inner);
6058 isl_union_set_free(prog->copy_in);
6059 isl_union_set_free(prog->copy_out);
6060 isl_union_map_free(prog->read);
6061 isl_union_map_free(prog->may_write);
6062 isl_union_map_free(prog->must_write);
6063 isl_union_map_free(prog->tagged_must_kill);
6064 isl_union_map_free(prog->array_order);
6065 isl_union_set_free(prog->may_persist);
6066 isl_set_free(prog->context);
6067 free(prog);
6068 return NULL;