optionally dump effectively used tile, grid and block sizes
[ppcg.git] / gpu.c
blobac91303fd89d5ba8697765afae119136a7bf37be
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, shift and shift_map 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 * shift_map contains the mapping
39 * i -> (i + shift)/stride
41 * Let D represent the initial shared_len dimensions of the computed schedule.
42 * The spaces of "lb" and "shift" are of the form
44 * D -> [b]
46 * "shift_map" is of the form
48 * [D -> i] -> [D -> (i + shift(D))/stride]
50 struct gpu_array_bound {
51 isl_val *size;
52 isl_aff *lb;
54 isl_val *stride;
55 isl_aff *shift;
56 isl_basic_map *shift_map;
59 /* A tile of an array.
61 * n is the dimension of the array.
62 * bound is an array of size "n" representing the lower bound
63 * and size for each index.
65 * tiling maps a tile in the global array to the corresponding
66 * shared/private memory tile and is of the form
68 * { [D[i] -> A[a]] -> T[(a + shift(i))/stride - lb(i)] }
70 * where D represents the initial shared_len dimensions
71 * of the computed schedule.
73 struct gpu_array_tile {
74 int n;
75 struct gpu_array_bound *bound;
76 isl_multi_aff *tiling;
79 struct gpu_array_info;
81 /* A group of array references in a kernel that should be handled together.
82 * If private_tile is not NULL, then it is mapped to registers.
83 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
84 * Otherwise, it is accessed from global memory.
86 struct gpu_array_ref_group {
87 /* The references in this group access this array. */
88 struct gpu_array_info *array;
89 /* Position of this group in the list of reference groups of array. */
90 int nr;
92 /* The following fields are use during the construction of the groups.
93 * access is the combined access relation relative to the shared
94 * memory tiling. In particular, the domain of the map corresponds
95 * to the first shared_len dimensions of the computed schedule.
96 * write is set if any access in the group is a write.
97 * exact_write is set if all writes are definite writes.
99 isl_map *access;
100 int write;
101 int exact_write;
103 /* The shared memory tile, NULL if none. */
104 struct gpu_array_tile *shared_tile;
106 /* The private memory tile, NULL if none. */
107 struct gpu_array_tile *private_tile;
109 /* References in this group; point to elements of a linked list. */
110 int n_ref;
111 struct gpu_stmt_access **refs;
113 /* Last shared memory tile dimension that affects tile of this group. */
114 int last_shared;
117 struct gpu_gen {
118 isl_ctx *ctx;
119 struct ppcg_options *options;
121 /* Callback for printing of AST in appropriate format. */
122 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
123 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
124 struct gpu_types *types, void *user);
125 void *print_user;
127 struct gpu_prog *prog;
128 /* The generated AST. */
129 isl_ast_node *tree;
131 /* The sequence of types for which a definition has been printed. */
132 struct gpu_types types;
134 /* User specified tile, grid and block sizes for each kernel */
135 isl_union_map *sizes;
137 /* Effectively used tile, grid and block sizes for each kernel */
138 isl_union_map *used_sizes;
140 /* Identifier of current kernel. */
141 int kernel_id;
142 /* Pointer to the current kernel. */
143 struct ppcg_kernel *kernel;
144 /* Does the computed schedule exhibit any parallelism? */
145 int any_parallelism;
147 /* First tile dimension. */
148 int tile_first;
149 /* Number of tile dimensions. */
150 int tile_len;
151 /* Number of initial parallel loops among tile dimensions. */
152 int n_parallel;
154 /* Number of dimensions determining shared memory. */
155 int shared_len;
157 /* Number of rows in the untiled schedule. */
158 int untiled_len;
159 /* Number of rows in the tiled schedule. */
160 int tiled_len;
161 /* Number of rows in schedule after tiling/wrapping over threads. */
162 int thread_tiled_len;
164 /* Global untiled schedule. */
165 isl_union_map *sched;
166 /* Local (per kernel launch) tiled schedule. */
167 isl_union_map *tiled_sched;
168 /* Local schedule per shared memory tile loop iteration. */
169 isl_union_map *local_sched;
171 /* Local tiled schedule projected onto the shared tile loops and
172 * the loops that will be wrapped over the threads,
173 * with all shared tile loops parametrized.
175 isl_union_map *shared_sched;
176 /* Projects out the loops that will be wrapped over the threads
177 * from shared_sched.
179 isl_union_map *shared_proj;
181 /* A map that takes the range of shared_sched as input,
182 * wraps the appropriate loops over the threads and then projects
183 * out these loops.
185 isl_map *privatization;
187 /* A map from the shared memory tile loops and the thread indices
188 * (as parameters) to the set of accessed memory elements that
189 * will be accessed through private copies.
191 isl_union_map *private_access;
193 /* The schedule for the current private/shared access
194 * (within print_private_access or print_shared_access).
196 isl_map *copy_sched;
197 /* The array reference group corresponding to copy_sched. */
198 struct gpu_array_ref_group *copy_group;
200 /* Is any array in the current kernel marked force_private? */
201 int any_force_private;
203 /* First loop to unroll (or -1 if none) in the current part of the
204 * schedule.
206 int first_unroll;
208 int n_grid;
209 int n_block;
210 /* Note: in the input file, the sizes of the grid and the blocks
211 * are specified in the order x, y, z, but internally, the sizes
212 * are stored in reverse order, so that the last element always
213 * refers to the x dimension.
215 int grid_dim[2];
216 int block_dim[3];
217 int *tile_size;
220 /* Print the name of the local copy of a given group of array references.
222 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
223 struct gpu_array_ref_group *group)
225 int global = 0;
227 if (group->private_tile)
228 p = isl_printer_print_str(p, "private_");
229 else if (group->shared_tile)
230 p = isl_printer_print_str(p, "shared_");
231 else
232 global = 1;
233 p = isl_printer_print_str(p, group->array->name);
234 if (!global && group->array->n_group > 1) {
235 p = isl_printer_print_str(p, "_");
236 p = isl_printer_print_int(p, group->nr);
239 return p;
242 /* Collect all references to the given array and store pointers to them
243 * in array->refs.
245 * If the array contains structures, then there is no need to collect
246 * the references since we will not be computing any reference groups.
248 static void collect_references(struct gpu_prog *prog,
249 struct gpu_array_info *array)
251 int i;
252 int n;
254 if (array->has_compound_element)
255 return;
257 n = 0;
258 for (i = 0; i < prog->n_stmts; ++i) {
259 struct gpu_stmt *stmt = &prog->stmts[i];
260 struct gpu_stmt_access *access;
262 for (access = stmt->accesses; access; access = access->next) {
263 const char *name;
264 name = isl_map_get_tuple_name(access->access,
265 isl_dim_out);
266 if (name && !strcmp(array->name, name))
267 n++;
271 array->n_ref = n;
272 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
273 assert(array->refs);
275 n = 0;
276 for (i = 0; i < prog->n_stmts; ++i) {
277 struct gpu_stmt *stmt = &prog->stmts[i];
278 struct gpu_stmt_access *access;
280 for (access = stmt->accesses; access; access = access->next) {
281 const char *name;
282 name = isl_map_get_tuple_name(access->access,
283 isl_dim_out);
284 if (!name || strcmp(array->name, name))
285 continue;
287 array->refs[n++] = access;
292 /* Create a gpu_array_tile for an array of dimension "n_index".
294 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
296 int i;
297 struct gpu_array_tile *tile;
299 tile = isl_calloc_type(ctx, struct gpu_array_tile);
300 assert(tile);
302 tile->n = n_index;
304 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
305 assert(tile->bound);
307 for (i = 0; i < n_index; ++i) {
308 tile->bound[i].size = NULL;
309 tile->bound[i].lb = NULL;
310 tile->bound[i].stride = NULL;
311 tile->bound[i].shift = NULL;
312 tile->bound[i].shift_map = NULL;
315 return tile;
318 static void *free_tile(struct gpu_array_tile *tile)
320 int j;
322 if (!tile)
323 return NULL;
325 for (j = 0; j < tile->n; ++j) {
326 isl_val_free(tile->bound[j].size);
327 isl_val_free(tile->bound[j].stride);
328 isl_aff_free(tile->bound[j].lb);
329 isl_aff_free(tile->bound[j].shift);
330 isl_basic_map_free(tile->bound[j].shift_map);
332 free(tile->bound);
333 isl_multi_aff_free(tile->tiling);
334 free(tile);
336 return NULL;
339 static struct pet_array *find_array(struct ppcg_scop *scop,
340 __isl_keep isl_set *accessed)
342 int i;
343 isl_id *id;
345 id = isl_set_get_tuple_id(accessed);
347 for (i = 0; i < scop->n_array; ++i) {
348 isl_id *id_i;
350 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
351 isl_id_free(id_i);
352 if (id == id_i)
353 break;
355 isl_id_free(id);
357 return i < scop->n_array ? scop->arrays[i] : NULL;
360 /* Compute and return the extent of "array", taking into account the set of
361 * accessed elements.
363 * In particular, the extent in the outer dimension is taken
364 * from "accessed", while then extent in the remaing dimensions
365 * are taken from array->extent.
367 * The extent in the outer dimension cannot be taken from array->extent
368 * because that may be unbounded. Furthermore, even if it is bounded,
369 * it may be larger than the piece of the array that is being accessed.
371 static __isl_give isl_set *compute_extent(struct pet_array *array,
372 __isl_keep isl_set *accessed)
374 int n_index;
375 isl_id *id;
376 isl_set *outer;
377 isl_set *extent;
379 extent = isl_set_copy(array->extent);
381 n_index = isl_set_dim(accessed, isl_dim_set);
382 if (n_index == 0)
383 return extent;
385 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
386 outer = isl_set_copy(accessed);
387 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
388 extent = isl_set_flat_product(outer, extent);
389 id = isl_set_get_tuple_id(accessed);
390 extent = isl_set_set_tuple_id(extent, id);
392 return extent;
395 /* Is the array "array" being extracted a read-only scalar?
397 * That is, is "array" a scalar that is never possibly written to.
398 * An array containing structures is never considered to be a scalar.
400 static int is_read_only_scalar(struct gpu_array_info *array,
401 struct gpu_prog *prog)
403 isl_set *space;
404 isl_union_map *write;
405 int empty;
407 if (array->has_compound_element)
408 return 0;
409 if (array->n_index != 0)
410 return 0;
412 write = isl_union_map_copy(prog->may_write);
413 space = isl_set_universe(isl_space_copy(array->space));
414 write = isl_union_map_intersect_range(write,
415 isl_union_set_from_set(space));
416 empty = isl_union_map_is_empty(write);
417 isl_union_map_free(write);
419 return empty;
422 /* Compute bounds on the host arrays based on the accessed elements
423 * and collect all references to the array.
425 * If the array is zero-dimensional and does not contain structures,
426 * i.e., if the array is a scalar, we check whether it is read-only.
428 static int extract_array_info(__isl_take isl_set *array, void *user)
430 int i;
431 struct gpu_prog *prog = (struct gpu_prog *)user;
432 const char *name;
433 int n_index;
434 isl_pw_aff **bounds;
435 struct pet_array *pa;
436 struct gpu_array_info *info;
437 isl_set *extent;
439 info = &prog->array[prog->n_array];
440 prog->n_array++;
442 n_index = isl_set_dim(array, isl_dim_set);
443 name = isl_set_get_tuple_name(array);
444 bounds = isl_alloc_array(isl_set_get_ctx(array),
445 isl_pw_aff *, n_index);
446 if (!bounds)
447 goto error;
449 info->space = isl_set_get_space(array);
450 info->name = strdup(name);
451 info->n_index = n_index;
452 info->bound = bounds;
453 info->linearize = prog->scop->options->linearize_device_arrays;
455 pa = find_array(prog->scop, array);
456 if (!pa)
457 isl_die(isl_set_get_ctx(array), isl_error_internal,
458 "unable to find array in scop", goto error);
460 info->type = strdup(pa->element_type);
461 info->size = pa->element_size;
462 info->local = pa->declared && !pa->exposed;
463 info->has_compound_element = pa->element_is_record;
464 info->read_only_scalar = is_read_only_scalar(info, prog);
466 extent = compute_extent(pa, array);
467 info->extent = extent;
468 for (i = 0; i < n_index; ++i) {
469 isl_set *dom;
470 isl_local_space *ls;
471 isl_aff *one;
472 isl_pw_aff *bound;
474 dom = isl_set_copy(extent);
475 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
476 n_index - (i + 1));
477 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
478 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
479 fprintf(stderr, "unable to determine extent of '%s' "
480 "in dimension %d\n", info->name, i);
481 dom = isl_set_free(dom);
483 bound = isl_set_dim_max(dom, 0);
484 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
485 ls = isl_local_space_from_space(isl_set_get_space(dom));
486 one = isl_aff_zero_on_domain(ls);
487 one = isl_aff_add_constant_si(one, 1);
488 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
489 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
491 bounds[i] = bound;
492 if (!isl_pw_aff_is_cst(bound))
493 info->linearize = 1;
496 collect_references(prog, info);
498 isl_set_free(array);
499 return 0;
500 error:
501 isl_set_free(array);
502 return -1;
505 /* Compute a mapping from all outer arrays (of structs) in scop
506 * to their innermost arrays.
508 * In particular, for each array of a primitive type, the result
509 * contains the identity mapping on that array.
510 * For each array involving member accesses, the result
511 * contains a mapping from the elements of the outer array of structs
512 * to all corresponding elements of the innermost nested arrays.
514 static __isl_give isl_union_map *compute_to_inner(struct ppcg_scop *scop)
516 int i;
517 isl_union_map *to_inner;
519 to_inner = isl_union_map_empty(isl_set_get_space(scop->context));
521 for (i = 0; i < scop->n_array; ++i) {
522 struct pet_array *array = scop->arrays[i];
523 isl_set *set;
524 isl_map *map;
526 if (array->element_is_record)
527 continue;
529 set = isl_set_copy(array->extent);
530 map = isl_set_identity(isl_set_copy(set));
532 while (set && isl_set_is_wrapping(set)) {
533 isl_id *id;
534 isl_map *wrapped;
536 id = isl_set_get_tuple_id(set);
537 wrapped = isl_set_unwrap(set);
538 wrapped = isl_map_domain_map(wrapped);
539 wrapped = isl_map_set_tuple_id(wrapped, isl_dim_in, id);
540 map = isl_map_apply_domain(map, wrapped);
541 set = isl_map_domain(isl_map_copy(map));
544 map = isl_map_gist_domain(map, set);
546 to_inner = isl_union_map_add_map(to_inner, map);
549 return to_inner;
552 /* Remove independence from the order constraints "order" on array "array".
553 * Since the pairs of iterations in the filter relation of an independence
554 * are guaranteed to be completely independent by the user, there is
555 * no need to ensure that live ranges are ordered along thong pairs.
556 * We make an exception for local variables, though, as the independence
557 * guarantee does not apply to those.
559 * The order constraints are used in two places.
560 * Those on scalars are used in check_scalar_live_ranges to check if
561 * we need to force the scalar to be private. Any non-local scalar
562 * should not be forced scalar if it only appears in independent loops.
563 * Those on non-scalars are added to the coincidence constraints
564 * in compute_schedule because we do not support any array expansion.
565 * Accesses to non-local arrays should not prevent a loop from being
566 * considered coincident so we should indeed remove those constraints
567 * from the order constraints.
569 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
570 struct gpu_array_info *array, __isl_take isl_union_map *order)
572 int i;
574 for (i = 0; i < prog->scop->n_independence; ++i) {
575 struct pet_independence *pi = prog->scop->independences[i];
576 if (isl_union_set_contains(pi->local, array->space))
577 continue;
579 order = isl_union_map_subtract(order,
580 isl_union_map_copy(pi->filter));
583 return order;
586 /* For each array in "prog", store the (untagged) order dependences
587 * derived from the array in array->dep_order.
588 * In particular, consider all references that access the given array
589 * and take the order dependences that have one of these references
590 * as source. (Since an order dependence relates two references to
591 * the same array, the target of these order dependences will also
592 * be one of these references.)
593 * Additionally, store the union of these array->dep_order relations
594 * for all non-scalar arrays in prog->array_order.
596 void collect_order_dependences(struct gpu_prog *prog)
598 int i;
599 isl_space *space;
600 isl_union_map *accesses;
602 space = isl_union_map_get_space(prog->read);
603 prog->array_order = isl_union_map_empty(space);
605 accesses = isl_union_map_copy(prog->scop->tagged_reads);
606 accesses = isl_union_map_union(accesses,
607 isl_union_map_copy(prog->scop->tagged_may_writes));
608 accesses = isl_union_map_universe(accesses);
609 accesses = isl_union_map_apply_range(accesses,
610 isl_union_map_copy(prog->to_outer));
612 for (i = 0; i < prog->n_array; ++i) {
613 struct gpu_array_info *array = &prog->array[i];
614 isl_set *set;
615 isl_union_set *uset;
616 isl_union_map *order;
618 set = isl_set_universe(isl_space_copy(array->space));
619 uset = isl_union_set_from_set(set);
620 uset = isl_union_map_domain(
621 isl_union_map_intersect_range(isl_union_map_copy(accesses),
622 uset));
623 order = isl_union_map_copy(prog->scop->tagged_dep_order);
624 order = isl_union_map_intersect_domain(order, uset);
625 order = isl_union_map_zip(order);
626 order = isl_union_set_unwrap(isl_union_map_domain(order));
627 order = remove_independences(prog, array, order);
628 array->dep_order = order;
630 if (gpu_array_is_scalar(array))
631 continue;
633 prog->array_order = isl_union_map_union(prog->array_order,
634 isl_union_map_copy(array->dep_order));
637 isl_union_map_free(accesses);
640 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
641 * collect them in prog->array.
643 * If there are any member accesses involved, then they are first mapped
644 * to the outer arrays of structs.
646 * If we are allowing live range reordering, then also set
647 * the dep_order field. Otherwise leave it NULL.
649 static int collect_array_info(struct gpu_prog *prog)
651 int r;
652 isl_union_set *arrays;
654 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
655 arrays = isl_union_set_union(arrays,
656 isl_union_map_range(isl_union_map_copy(prog->may_write)));
658 arrays = isl_union_set_apply(arrays,
659 isl_union_map_copy(prog->to_outer));
661 arrays = isl_union_set_coalesce(arrays);
663 prog->n_array = isl_union_set_n_set(arrays);
664 prog->array = isl_calloc_array(prog->ctx,
665 struct gpu_array_info, prog->n_array);
666 assert(prog->array);
667 prog->n_array = 0;
668 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
669 isl_union_set_free(arrays);
671 if (prog->scop->options->live_range_reordering)
672 collect_order_dependences(prog);
674 return r;
677 static void free_array_info(struct gpu_prog *prog)
679 int i, j;
681 for (i = 0; i < prog->n_array; ++i) {
682 int n_index = prog->array[i].n_index;
683 free(prog->array[i].type);
684 free(prog->array[i].name);
685 for (j = 0; j < n_index; ++j)
686 isl_pw_aff_free(prog->array[i].bound[j]);
687 isl_space_free(prog->array[i].space);
688 isl_set_free(prog->array[i].extent);
689 free(prog->array[i].bound);
690 free(prog->array[i].refs);
691 isl_union_map_free(prog->array[i].dep_order);
693 free(prog->array);
696 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
697 * as an array or through a pointer reference, but as a single data element.
698 * At the moment, scalars are represented as zero-dimensional arrays.
699 * A zero-dimensional array containing structures is not considered
700 * to be a scalar.
702 int gpu_array_is_scalar(struct gpu_array_info *array)
704 return !array->has_compound_element && array->n_index == 0;
707 /* Is "array" a read-only scalar?
709 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
711 return array->read_only_scalar;
714 /* Return the set of parameter values for which the array has a positive
715 * size in all dimensions.
716 * If the sizes are only valid for some parameter values, then those
717 * constraints are also taken into account.
719 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
721 int i;
722 isl_space *space;
723 isl_set *guard;
725 space = isl_space_params(isl_space_copy(array->space));
726 guard = isl_set_universe(space);
728 for (i = 0; i < array->n_index; ++i) {
729 isl_pw_aff *bound;
730 isl_set *guard_i, *zero;
732 bound = isl_pw_aff_copy(array->bound[i]);
733 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
734 zero = isl_pw_aff_zero_set(bound);
735 guard_i = isl_set_subtract(guard_i, zero);
736 guard = isl_set_intersect(guard, guard_i);
739 return guard;
742 /* Internal data structure for extract_size_of_type.
743 * "type" specifies the name of the space that we want to extract.
744 * "res" is used to store the subset of that space.
746 struct ppcg_extract_size_data {
747 const char *type;
748 isl_set *res;
751 /* This function is called for each set in a union_set.
752 * If the name of the set matches data->type, we store the
753 * set in data->res.
755 static int extract_size_of_type(__isl_take isl_set *size, void *user)
757 struct ppcg_extract_size_data *data = user;
758 const char *name;
760 name = isl_set_get_tuple_name(size);
761 if (name && !strcmp(name, data->type)) {
762 data->res = size;
763 return -1;
766 isl_set_free(size);
767 return 0;
770 /* Given a union map { kernel[i] -> *[...] },
771 * return the range in the space called "type" for the kernel with
772 * sequence number "id".
774 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
775 const char *type, int id)
777 isl_space *space;
778 isl_set *dom;
779 isl_union_set *local_sizes;
780 struct ppcg_extract_size_data data = { type, NULL };
782 if (!sizes)
783 return NULL;
785 space = isl_union_map_get_space(sizes);
786 space = isl_space_set_from_params(space);
787 space = isl_space_add_dims(space, isl_dim_set, 1);
788 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
789 dom = isl_set_universe(space);
790 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
792 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
793 isl_union_map_copy(sizes));
794 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
795 isl_union_set_free(local_sizes);
796 return data.res;
799 /* Given a singleton set, extract the first (at most *len) elements
800 * of the single integer tuple into *sizes and update *len if needed.
802 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
804 int i;
805 int dim;
807 if (!set)
808 return;
810 dim = isl_set_dim(set, isl_dim_set);
811 if (dim < *len)
812 *len = dim;
814 for (i = 0; i < *len; ++i) {
815 isl_val *v;
817 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
818 assert(v);
820 sizes[i] = isl_val_get_num_si(v);
821 isl_val_free(v);
824 isl_set_free(set);
827 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
828 * if the option debug->dump_sizes is set.
830 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
831 int *sizes, int len)
833 int i;
834 isl_space *space;
835 isl_map *map;
837 if (!gen->options->debug->dump_sizes)
838 return;
840 space = isl_union_map_get_space(gen->used_sizes);
841 space = isl_space_set_from_params(space);
842 space = isl_space_add_dims(space, isl_dim_set, 1);
843 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
844 space = isl_space_from_domain(space);
845 space = isl_space_add_dims(space, isl_dim_out, len);
846 space = isl_space_set_tuple_name(space, isl_dim_out, type);
848 map = isl_map_universe(space);
849 map = isl_map_fix_si(map, isl_dim_in, 0, id);
850 for (i = 0; i < len; ++i)
851 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
853 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
856 /* Extract user specified "tile" sizes from the "sizes" command line option,
857 * defaulting to option->tile_size in each dimension.
858 * Add the effectively used sizes to gen->used_sizes.
860 static void read_tile_sizes(struct gpu_gen *gen)
862 int n;
863 isl_set *size;
865 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
866 assert(gen->tile_size);
867 for (n = 0; n < gen->tile_len; ++n)
868 gen->tile_size[n] = gen->options->tile_size;
870 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
871 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
872 set_used_sizes(gen, "tile", gen->kernel_id,
873 gen->tile_size, gen->tile_len);
875 if (gen->n_parallel > gen->tile_len)
876 gen->n_parallel = gen->tile_len;
879 /* Extract user specified "block" sizes from the "sizes" command line option,
880 * after filling in some potentially useful defaults.
881 * Add the effectively used sizes to gen->used_sizes.
883 static void read_block_sizes(struct gpu_gen *gen)
885 int n;
886 isl_set *size;
888 n = gen->n_parallel;
889 gen->n_block = (n <= 3) ? n : 3;
890 switch (gen->n_block) {
891 case 1:
892 gen->block_dim[0] = 512;
893 break;
894 case 2:
895 gen->block_dim[0] = 32;
896 gen->block_dim[1] = 16;
897 break;
898 default:
899 gen->block_dim[0] = 32;
900 gen->block_dim[1] = 4;
901 gen->block_dim[2] = 4;
902 break;
905 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
906 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
907 set_used_sizes(gen, "block", gen->kernel_id,
908 gen->block_dim, gen->n_block);
911 /* Extract user specified "grid" sizes from the "sizes" command line option,
912 * after filling in some potentially useful defaults.
913 * Add the effectively used sizes to gen->used_sizes.
915 static void read_grid_sizes(struct gpu_gen *gen)
917 int n = gen->n_parallel;
918 isl_set *size;
920 gen->n_grid = (n <= 2) ? n : 2;
921 switch (gen->n_grid) {
922 case 1:
923 gen->grid_dim[0] = 32768;
924 break;
925 default:
926 gen->grid_dim[0] = 256;
927 gen->grid_dim[1] = 256;
928 break;
931 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
932 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
933 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
936 /* Extract user specified sizes from the "sizes" command line option
937 * after filling in some potentially useful defaults.
939 static void read_sizes(struct gpu_gen *gen)
941 read_tile_sizes(gen);
942 read_block_sizes(gen);
943 read_grid_sizes(gen);
946 static void *free_stmts(struct gpu_stmt *stmts, int n)
948 int i;
950 if (!stmts)
951 return NULL;
953 for (i = 0; i < n; ++i) {
954 struct gpu_stmt_access *access, *next;
956 for (access = stmts[i].accesses; access; access = next) {
957 next = access->next;
958 isl_id_free(access->ref_id);
959 isl_map_free(access->access);
960 isl_map_free(access->tagged_access);
961 free(access);
964 isl_id_free(stmts[i].id);
966 free(stmts);
968 return NULL;
971 /* Construct a map from a domain of dimensionality "len"
972 * to a domain of dimensionality "len" + "tile_len" that tiles
973 * the "tile_len" coordinates starting at "first".
974 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
975 * "dim" prescribes the parameters.
977 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
978 int first, int tile_len, int *tile_size)
980 int i;
981 isl_basic_map *bmap;
982 isl_constraint *c;
983 isl_local_space *ls;
985 dim = isl_space_add_dims(dim, isl_dim_in, len);
986 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
987 bmap = isl_basic_map_universe(isl_space_copy(dim));
988 ls = isl_local_space_from_space(dim);
990 for (i = 0; i < len - tile_len; ++i) {
991 int j = i < first ? i : i + tile_len;
992 int k = i < first ? i : i + 2 * tile_len;
994 c = isl_equality_alloc(isl_local_space_copy(ls));
995 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
996 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
997 bmap = isl_basic_map_add_constraint(bmap, c);
1000 for (i = 0; i < tile_len; ++i) {
1001 c = isl_equality_alloc(isl_local_space_copy(ls));
1002 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
1003 first + i, -1);
1004 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1005 first + i, tile_size[i]);
1006 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1007 first + i + tile_len, 1);
1008 bmap = isl_basic_map_add_constraint(bmap, c);
1010 c = isl_inequality_alloc(isl_local_space_copy(ls));
1011 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1012 first + i + tile_len, 1);
1013 bmap = isl_basic_map_add_constraint(bmap, c);
1015 c = isl_inequality_alloc(isl_local_space_copy(ls));
1016 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1017 first + i + tile_len, -1);
1018 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
1019 bmap = isl_basic_map_add_constraint(bmap, c);
1022 isl_local_space_free(ls);
1024 return isl_map_from_basic_map(bmap);
1027 /* Construct a map from a domain of dimensionality "len"
1028 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
1029 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
1030 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
1031 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
1032 * that are projected out at the end.
1033 * "dim" prescribes the parameters.
1035 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
1036 int first, int wrap_len, int *wrap_size)
1038 int i;
1039 isl_basic_map *bmap;
1040 isl_constraint *c;
1041 isl_local_space *ls;
1043 dim = isl_space_add_dims(dim, isl_dim_in, len);
1044 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
1045 bmap = isl_basic_map_universe(isl_space_copy(dim));
1046 ls = isl_local_space_from_space(dim);
1048 for (i = 0; i < len; ++i) {
1049 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
1051 c = isl_equality_alloc(isl_local_space_copy(ls));
1052 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
1053 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
1054 bmap = isl_basic_map_add_constraint(bmap, c);
1057 for (i = 0; i < wrap_len; ++i) {
1058 c = isl_equality_alloc(isl_local_space_copy(ls));
1059 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1060 first + i, -1);
1061 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1062 first + wrap_len + i, 1);
1063 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1064 first + 2 * wrap_len + i, wrap_size[i]);
1065 bmap = isl_basic_map_add_constraint(bmap, c);
1067 c = isl_inequality_alloc(isl_local_space_copy(ls));
1068 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1069 first + wrap_len + i, 1);
1070 bmap = isl_basic_map_add_constraint(bmap, c);
1072 c = isl_inequality_alloc(isl_local_space_copy(ls));
1073 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1074 first + wrap_len + i, -1);
1075 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1076 bmap = isl_basic_map_add_constraint(bmap, c);
1079 isl_local_space_free(ls);
1081 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1082 first + 2 * wrap_len, wrap_len);
1084 return isl_map_from_basic_map(bmap);
1087 /* Add "n" parameters named prefix%d.
1089 static __isl_give isl_set *add_params( __isl_take isl_set *set,
1090 int n, const char *prefix)
1092 int i;
1093 unsigned nparam;
1094 char name[20];
1096 nparam = isl_set_dim(set, isl_dim_param);
1097 set = isl_set_add_dims(set, isl_dim_param, n);
1099 for (i = 0; i < n; ++i) {
1100 snprintf(name, sizeof(name), "%s%d", prefix, i);
1101 set = isl_set_set_dim_name(set, isl_dim_param,
1102 nparam + i, name);
1105 return set;
1108 /* Equate the "n" dimensions of "set" starting at "first" to
1109 * freshly created parameters named prefix%d.
1111 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1112 int first, int n, const char *prefix)
1114 int i;
1115 unsigned nparam;
1117 nparam = isl_set_dim(set, isl_dim_param);
1119 set = add_params(set, n, prefix);
1121 for (i = 0; i < n; ++i)
1122 set = isl_set_equate(set, isl_dim_param, nparam + i,
1123 isl_dim_set, first + i);
1125 return set;
1128 /* Given a parameter space "space", create a set of dimension "len"
1129 * of which the "n" dimensions starting at "first" are equated to
1130 * freshly created parameters named prefix%d.
1132 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1133 int len, int first, int n, const char *prefix)
1135 isl_set *set;
1137 space = isl_space_set_from_params(space);
1138 space = isl_space_add_dims(space, isl_dim_set, len);
1139 set = isl_set_universe(space);
1141 return parametrize(set, first, n, prefix);
1144 /* Tile the B loops over the tile sizes and then tile/wrap
1145 * the T1 loops over the blocks.
1147 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1148 __isl_take isl_union_map *sched)
1150 isl_space *dim;
1151 isl_map *tiling, *block_tiling;
1153 dim = isl_union_map_get_space(sched);
1154 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1155 gen->tile_first, gen->tile_len, gen->tile_size);
1157 if (gen->options->wrap)
1158 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1159 gen->tile_first, gen->n_grid, gen->grid_dim);
1160 else
1161 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1162 gen->tile_first, gen->n_grid, gen->grid_dim);
1164 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1166 tiling = isl_map_apply_range(tiling, block_tiling);
1168 sched = isl_union_map_apply_range(sched,
1169 isl_union_map_from_map(tiling));
1171 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1173 return sched;
1176 /* Equate the "T1P" iterators in the tiled schedule "sched"
1177 * to the block dimensions.
1179 static __isl_give isl_union_map *parametrize_tiled_schedule(
1180 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1182 isl_space *dim;
1183 isl_set *par;
1185 dim = isl_union_map_get_space(sched);
1186 par = parametrization(dim, gen->tiled_len,
1187 gen->tile_first + gen->n_grid, gen->n_grid, "b");
1188 sched = isl_union_map_intersect_range(sched,
1189 isl_union_set_from_set(par));
1191 return sched;
1194 /* Tile/wrap the P1 loops over the threads.
1196 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1197 __isl_take isl_union_map *sched)
1199 isl_space *dim;
1200 isl_map *tiling;
1201 isl_set *par;
1203 dim = isl_union_map_get_space(sched);
1205 if (gen->options->wrap)
1206 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1207 gen->shared_len, gen->n_block, gen->block_dim);
1208 else
1209 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1210 gen->shared_len, gen->n_block, gen->block_dim);
1211 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1213 sched = isl_union_map_apply_range(sched,
1214 isl_union_map_from_map(tiling));
1216 par = parametrization(dim, gen->thread_tiled_len,
1217 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1218 gen->n_block, "t");
1219 sched = isl_union_map_intersect_range(sched,
1220 isl_union_set_from_set(par));
1222 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1224 return sched;
1227 /* If the user asked for it, scale the shared memory tile loops
1228 * (T1T and T2) of "sched" by gen->tile_size[i].
1229 * If we are not performing "wrapping", then additionally scale the T1P
1230 * loops by gen->grid_dim[i].
1232 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1233 __isl_take isl_union_map *sched)
1235 int i;
1236 isl_space *dim;
1237 isl_basic_map *scale;
1238 isl_constraint *c;
1239 isl_local_space *ls;
1241 if (!gen->options->scale_tile_loops)
1242 return sched;
1244 dim = isl_union_map_get_space(sched);
1245 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1246 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1247 scale = isl_basic_map_universe(isl_space_copy(dim));
1248 ls = isl_local_space_from_space(dim);
1250 for (i = 0; i < gen->tiled_len; ++i) {
1251 int f = 1;
1253 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1254 f = gen->tile_size[i - gen->tile_first];
1255 if (!gen->options->wrap)
1256 f *= gen->grid_dim[i - gen->tile_first];
1257 } else if (i >= gen->tile_first + gen->n_grid &&
1258 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1259 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1262 c = isl_equality_alloc(isl_local_space_copy(ls));
1263 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1264 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1265 scale = isl_basic_map_add_constraint(scale, c);
1268 isl_local_space_free(ls);
1270 sched = isl_union_map_apply_range(sched,
1271 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1273 return sched;
1276 /* If we are not performing "wrapping" and if the user asked for it,
1277 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1279 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1280 __isl_take isl_union_map *sched)
1282 int i;
1283 isl_space *dim;
1284 isl_basic_map *scale;
1285 isl_constraint *c;
1286 isl_local_space *ls;
1288 if (gen->options->wrap)
1289 return sched;
1290 if (!gen->options->scale_tile_loops)
1291 return sched;
1293 dim = isl_union_map_get_space(sched);
1294 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1295 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1296 scale = isl_basic_map_universe(isl_space_copy(dim));
1297 ls = isl_local_space_from_space(dim);
1299 for (i = 0; i < gen->thread_tiled_len; ++i) {
1300 int f = 1;
1302 if (i >= gen->shared_len &&
1303 i < gen->shared_len + gen->n_block)
1304 f = gen->block_dim[i - gen->shared_len];
1306 c = isl_equality_alloc(isl_local_space_copy(ls));
1307 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1308 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1309 scale = isl_basic_map_add_constraint(scale, c);
1312 isl_local_space_free(ls);
1314 sched = isl_union_map_apply_range(sched,
1315 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1317 return sched;
1320 /* If we are not performing "wrapping" and if the user asked for it,
1321 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1323 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1324 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1326 int i;
1327 isl_space *dim;
1328 isl_basic_map *scale;
1329 isl_constraint *c;
1330 isl_local_space *ls;
1332 if (gen->options->wrap)
1333 return sched;
1334 if (!gen->options->scale_tile_loops)
1335 return sched;
1337 dim = isl_union_map_get_space(sched);
1338 dim = isl_space_add_dims(dim, isl_dim_in, len);
1339 dim = isl_space_add_dims(dim, isl_dim_out, len);
1340 scale = isl_basic_map_universe(isl_space_copy(dim));
1341 ls = isl_local_space_from_space(dim);
1343 for (i = 0; i < len; ++i) {
1344 int f = 1;
1346 if (i >= first && i < first + n_tile)
1347 f = gen->kernel->block_dim[i - first];
1349 c = isl_equality_alloc(isl_local_space_copy(ls));
1350 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1351 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1352 scale = isl_basic_map_add_constraint(scale, c);
1355 isl_local_space_free(ls);
1357 sched = isl_union_map_apply_range(sched,
1358 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1360 return sched;
1363 /* Add "len" parameters p[i] called prefix%d,
1364 * with bounds to 0 <= p[i] < size[i].
1366 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1367 int len, int *size, const char *prefix)
1369 int i;
1370 unsigned nparam;
1371 isl_space *dim;
1372 isl_basic_set *bset;
1373 isl_constraint *c;
1374 isl_local_space *ls;
1375 char name[20];
1377 nparam = isl_set_dim(set, isl_dim_param);
1378 set = isl_set_add_dims(set, isl_dim_param, len);
1380 for (i = 0; i < len; ++i) {
1381 snprintf(name, sizeof(name), "%s%d", prefix, i);
1382 set = isl_set_set_dim_name(set, isl_dim_param,
1383 nparam + i, name);
1386 dim = isl_set_get_space(set);
1387 bset = isl_basic_set_universe(isl_space_copy(dim));
1388 ls = isl_local_space_from_space(dim);
1390 for (i = 0; i < len; ++i) {
1391 c = isl_inequality_alloc(isl_local_space_copy(ls));
1392 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1393 nparam + i, 1);
1394 bset = isl_basic_set_add_constraint(bset, c);
1396 c = isl_inequality_alloc(isl_local_space_copy(ls));
1397 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1398 nparam + i, -1);
1399 c = isl_constraint_set_constant_si(c, size[i] - 1);
1400 bset = isl_basic_set_add_constraint(bset, c);
1403 isl_local_space_free(ls);
1405 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1408 /* Add "len" parameters p[i] called prefix%d and intersect "set"
1409 * with
1411 * { : 0 <= p[i] < size[i] }
1413 * or an overapproximation.
1415 static __isl_give isl_set *add_bounded_parameters_dynamic(
1416 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1417 const char *prefix)
1419 int i, len;
1420 unsigned nparam;
1421 isl_space *space;
1422 isl_local_space *ls;
1423 char name[20];
1425 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1426 nparam = isl_set_dim(set, isl_dim_param);
1427 set = isl_set_add_dims(set, isl_dim_param, len);
1429 for (i = 0; i < len; ++i) {
1430 snprintf(name, sizeof(name), "%s%d", prefix, i);
1431 set = isl_set_set_dim_name(set, isl_dim_param,
1432 nparam + i, name);
1435 space = isl_space_params(isl_set_get_space(set));
1436 ls = isl_local_space_from_space(space);
1437 for (i = 0; i < len; ++i) {
1438 isl_pw_aff *param, *size_i, *zero;
1439 isl_set *bound;
1441 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1442 isl_dim_param, nparam + i);
1444 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1445 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1446 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1447 set = isl_set_intersect_params(set, bound);
1449 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1450 bound = isl_pw_aff_ge_set(param, zero);
1451 set = isl_set_intersect_params(set, bound);
1453 isl_local_space_free(ls);
1455 return set;
1458 /* Construct a map from an access to group->array to the corresponding
1459 * shared/private memory tile.
1460 * The map is of the form
1462 * { [D[i] -> A[a]] -> T[t] }
1464 * where D represents the initial shared_len dimensions
1465 * of the computed schedule.
1467 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1469 struct gpu_array_tile *tile;
1470 isl_multi_aff *tiling;
1472 tile = group->private_tile;
1473 if (!tile)
1474 tile = group->shared_tile;
1476 tiling = isl_multi_aff_copy(tile->tiling);
1478 return isl_map_from_multi_aff(tiling);
1481 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1483 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1484 unsigned pos)
1486 isl_val *v;
1487 int fixed;
1489 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1490 if (!v)
1491 return -1;
1492 fixed = isl_val_is_int(v);
1493 isl_val_free(v);
1495 return fixed;
1498 /* Given a schedule that iterates over all elements in a piece of an array,
1499 * perform tiling/wrapping over the threads.
1501 * In particular, we tile the final iterators so that the final thread
1502 * dimension runs over the final array dimension.
1503 * However, if those final iterators have only a single iteration,
1504 * we try to tile earlier iterators instead.
1506 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1507 __isl_take isl_map *sched)
1509 isl_space *dim;
1510 isl_union_map *usched;
1511 isl_map *tiling;
1512 isl_set *par;
1513 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1514 int n_tile;
1515 int first;
1517 n_tile = gen->kernel->n_block;
1518 if (n_tile > nvar) {
1519 int i;
1520 sched = isl_map_insert_dims(sched,
1521 isl_dim_out, 0, n_tile - nvar);
1522 for (i = 0; i < n_tile - nvar; ++i)
1523 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1524 nvar = n_tile;
1527 first = nvar - n_tile;
1529 for (; first > 0; first --)
1530 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1531 break;
1533 dim = isl_map_get_space(sched);
1534 dim = isl_space_params(dim);
1535 if (gen->options->wrap)
1536 tiling = wrap(isl_space_copy(dim), nvar, first,
1537 n_tile, gen->kernel->block_dim);
1538 else
1539 tiling = tile(isl_space_copy(dim), nvar, first,
1540 n_tile, gen->kernel->block_dim);
1541 sched = isl_map_apply_range(sched, tiling);
1543 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1544 sched = isl_map_intersect_range(sched, par);
1546 usched = isl_union_map_from_map(sched);
1547 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1548 first, n_tile);
1549 sched = isl_map_from_union_map(usched);
1551 return sched;
1554 /* Return the union of all read (read = 1) and/or write (write = 1)
1555 * access relations in the group.
1557 static __isl_give isl_union_map *group_access_relation(
1558 struct gpu_array_ref_group *group, int read, int write)
1560 int i;
1561 isl_union_map *access;
1563 access = isl_union_map_empty(isl_map_get_space(group->access));
1564 for (i = 0; i < group->n_ref; ++i) {
1565 isl_map *map_i;
1567 if (!((read && group->refs[i]->read) ||
1568 (write && group->refs[i]->write)))
1569 continue;
1570 map_i = isl_map_copy(group->refs[i]->access);
1571 access = isl_union_map_union(access,
1572 isl_union_map_from_map(map_i));
1575 return access;
1578 /* Return the union of all tagged access relations in the group.
1580 static __isl_give isl_union_map *group_tagged_access_relation(
1581 struct gpu_array_ref_group *group)
1583 int i;
1584 isl_union_map *access;
1586 access = isl_union_map_empty(isl_map_get_space(group->access));
1587 for (i = 0; i < group->n_ref; ++i) {
1588 isl_map *map_i;
1590 map_i = isl_map_copy(group->refs[i]->tagged_access);
1591 access = isl_union_map_union(access,
1592 isl_union_map_from_map(map_i));
1595 return access;
1598 /* Return the extent of "array", recomputed from the bounds.
1599 * The recomputed extent may be simpler than the original extent.
1601 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1603 int i;
1604 isl_id *id;
1605 isl_space *space;
1606 isl_local_space *ls;
1607 isl_set *extent;
1609 id = isl_set_get_tuple_id(array->extent);
1610 space = isl_set_get_space(array->extent);
1611 extent = isl_set_universe(isl_space_copy(space));
1612 ls = isl_local_space_from_space(space);
1613 for (i = 0; i < array->n_index; ++i) {
1614 isl_pw_aff *bound;
1615 isl_aff *aff;
1616 isl_pw_aff *index;
1617 isl_set *lt;
1619 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1621 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1622 isl_dim_set, i);
1623 index = isl_pw_aff_from_aff(aff);
1624 bound = isl_pw_aff_copy(array->bound[i]);
1625 bound = isl_pw_aff_from_range(bound);
1626 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1627 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1628 isl_id_copy(id));
1629 lt = isl_pw_aff_lt_set(index, bound);
1630 extent = isl_set_intersect(extent, lt);
1632 isl_local_space_free(ls);
1633 isl_id_free(id);
1635 return extent;
1638 /* Return a map from the first shared_len dimensions of the computed
1639 * schedule to the array tile in
1640 * global memory that corresponds to the shared memory copy.
1642 * In particular, return a map
1644 * { D[i] -> A[a] }
1646 * with constraints
1648 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1650 * and
1652 * 0 <= a <= array_size - 1 (2)
1654 * Note that if some stride has been detected (i.e., when
1655 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1656 * to the shifted and scaled down version.
1658 * Constraints (1) are obtained by mapping the size constraints on the
1659 * shared/private memory tile back to the access relation.
1660 * Constraints (2) are obtained from the (recomputed) extent.
1662 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1664 int i;
1665 int n_index = group->array->n_index;
1666 isl_map *tile;
1667 isl_space *space;
1668 isl_set *local;
1669 isl_set *extent;
1671 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1672 space = isl_space_range(space);
1673 local = isl_set_universe(space);
1674 for (i = 0; i < n_index; ++i) {
1675 isl_val *bound;
1677 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1678 bound = isl_val_copy(group->shared_tile->bound[i].size);
1679 bound = isl_val_sub_ui(bound, 1);
1680 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1682 local = isl_set_preimage_multi_aff(local,
1683 isl_multi_aff_copy(group->shared_tile->tiling));
1684 tile = isl_set_unwrap(local);
1685 extent = array_extent(group->array);
1686 tile = isl_map_intersect_range(tile, extent);
1688 return tile;
1691 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1692 * return the corresponding mapping from the AST schedule to
1693 * to the first shared_len dimensions of the schedule computed by PPCG.
1695 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1696 __isl_take isl_pw_multi_aff *iterator_map)
1698 isl_union_map *umap;
1699 isl_space *space;
1700 isl_map *map, *sched;;
1702 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1703 space = isl_space_from_domain(space);
1704 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1706 umap = isl_union_map_copy(gen->shared_sched);
1707 umap = isl_union_map_apply_range(umap,
1708 isl_union_map_copy(gen->shared_proj));
1709 map = isl_union_map_extract_map(umap, space);
1710 isl_union_map_free(umap);
1712 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1713 sched = isl_map_detect_equalities(sched);
1715 return isl_pw_multi_aff_from_map(sched);
1718 /* Set unroll[j] if the input dimension j is involved in
1719 * the index expression represented by ma.
1721 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1722 void *user)
1724 int i, j;
1725 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1726 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1727 int *unroll = user;
1729 for (i = 0; i < n_out; ++i) {
1730 isl_aff *aff;
1732 aff = isl_multi_aff_get_aff(ma, i);
1733 for (j = 0; j < n_in; ++j)
1734 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1735 unroll[j] = 1;
1736 isl_aff_free(aff);
1739 isl_set_free(set);
1740 isl_multi_aff_free(ma);
1741 return 0;
1744 /* Given an array pos mapping input dimensions to the corresponding
1745 * output dimension, construct the corresponding map.
1747 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1748 int *pos, int len)
1750 int i;
1751 isl_constraint *c;
1752 isl_basic_map *bmap;
1753 isl_local_space *ls;
1755 dim = isl_space_add_dims(dim, isl_dim_in, len);
1756 dim = isl_space_add_dims(dim, isl_dim_out, len);
1757 bmap = isl_basic_map_universe(isl_space_copy(dim));
1758 ls = isl_local_space_from_space(dim);
1760 for (i = 0; i < len; ++i) {
1761 c = isl_equality_alloc(isl_local_space_copy(ls));
1762 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1763 -1);
1764 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1766 bmap = isl_basic_map_add_constraint(bmap, c);
1768 isl_local_space_free(ls);
1770 return isl_map_from_basic_map(bmap);
1773 /* Remove the private tiles from all array reference groups,
1774 * except for the groups of arrays that are marked force_private.
1776 static void remove_private_tiles(struct gpu_gen *gen)
1778 int i, j;
1780 for (i = 0; i < gen->prog->n_array; ++i) {
1781 struct gpu_array_info *array = &gen->prog->array[i];
1783 if (array->force_private)
1784 continue;
1786 for (j = 0; j < array->n_group; ++j) {
1787 struct gpu_array_ref_group *group = array->groups[j];
1789 group->private_tile = free_tile(group->private_tile);
1794 /* Find all loops involved in any of the index expressions for any of
1795 * the private accesses, move them innermost and then mark them as
1796 * requiring unrolling by setting gen->first_unroll.
1797 * The loops involved should all be parallel because of the checks
1798 * we performed in check_private_group_access. Moving them innermost
1799 * is therefore a valid transformation.
1801 * If any of the arrays are marked force_private, however, then
1802 * those loops may not be parallel with respect to the marked arrays.
1803 * If any of the loops would have to be moved innermost for the
1804 * (non forced) private accesses and if there are any force_private
1805 * arrays, then we revert the decision to map the selected arrays
1806 * to private memory. An alternative solution would be to expand
1807 * the force_private arrays.
1809 * Loops up to gen->shared_len are generated before the mapping to
1810 * threads is applied. They should therefore be ignored.
1812 * We compute the hidden equalities of the schedule first
1813 * since we will need them in our calls to isl_pw_multi_aff_from_map
1814 * and because we want to make sure that the same equalities
1815 * are also available to the code generator.
1817 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1818 __isl_take isl_union_map *sched)
1820 int i, j;
1821 int unroll[gen->thread_tiled_len];
1822 int perm[gen->thread_tiled_len];
1823 isl_space *dim;
1824 isl_map *permute;
1825 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1827 gen->first_unroll = -1;
1829 sched = isl_union_map_detect_equalities(sched);
1830 for (i = 0; i < gen->thread_tiled_len; ++i)
1831 unroll[i] = 0;
1832 for (i = 0; i < gen->prog->n_array; ++i) {
1833 struct gpu_array_info *array = &gen->prog->array[i];
1835 for (j = 0; j < array->n_group; ++j) {
1836 isl_union_map *access;
1837 isl_map *acc;
1838 isl_pw_multi_aff *pma;
1840 if (!array->groups[j]->private_tile)
1841 continue;
1843 access = group_access_relation(array->groups[j], 1, 1);
1844 access = isl_union_map_apply_domain(access,
1845 isl_union_map_copy(sched));
1847 acc = isl_map_from_union_map(access);
1848 pma = isl_pw_multi_aff_from_map(acc);
1849 isl_pw_multi_aff_foreach_piece(pma,
1850 &check_unroll, unroll);
1852 isl_pw_multi_aff_free(pma);
1856 for (i = gen->shared_len; i < len; ++i)
1857 if (unroll[i])
1858 break;
1860 if (i >= len)
1861 return sched;
1863 for (i = len; i < gen->thread_tiled_len; ++i)
1864 if (unroll[i])
1865 return sched;
1867 if (gen->any_force_private) {
1868 remove_private_tiles(gen);
1869 return sched;
1872 j = 0;
1873 for (i = 0; i < gen->shared_len; ++i)
1874 perm[i] = j++;
1875 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1876 if (!unroll[i])
1877 perm[i] = j++;
1878 gen->first_unroll = j - gen->shared_len;
1879 for (i = gen->shared_len; i < len; ++i)
1880 if (unroll[i])
1881 perm[i] = j++;
1883 dim = isl_union_map_get_space(sched);
1884 permute = permutation(dim, perm, gen->thread_tiled_len);
1885 sched = isl_union_map_apply_range(sched,
1886 isl_union_map_from_map(permute));
1888 return sched;
1891 /* Given a constraint
1893 * a(p,i) + j = g f(e)
1895 * or -a(p,i) - j = g f(e) if sign < 0,
1896 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1897 * a(p,i) is assumed to be an expression in only the parameters
1898 * and the input dimensions.
1900 static void extract_stride(__isl_keep isl_constraint *c,
1901 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1903 int i;
1904 isl_val *v;
1905 isl_space *space;
1906 unsigned nparam;
1907 unsigned nvar;
1908 isl_aff *aff;
1910 isl_val_free(bound->stride);
1911 bound->stride = isl_val_copy(stride);
1913 space = isl_constraint_get_space(c);
1914 space = isl_space_domain(space);
1916 nparam = isl_space_dim(space, isl_dim_param);
1917 nvar = isl_space_dim(space, isl_dim_set);
1919 v = isl_constraint_get_constant_val(c);
1920 if (sign < 0)
1921 v = isl_val_neg(v);
1922 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1923 aff = isl_aff_set_constant_val(aff, v);
1925 for (i = 0; i < nparam; ++i) {
1926 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1927 continue;
1928 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1929 if (sign < 0)
1930 v = isl_val_neg(v);
1931 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1934 for (i = 0; i < nvar; ++i) {
1935 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1936 continue;
1937 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1938 if (sign < 0)
1939 v = isl_val_neg(v);
1940 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1943 bound->shift = aff;
1946 /* Given an equality constraint of a map with a single output dimension j,
1947 * check if the constraint is of the form
1949 * a(p,i) + j = g f(e)
1951 * with a(p,i) an expression in the parameters and input dimensions
1952 * and f(e) an expression in the existentially quantified variables.
1953 * If so, and if g is larger than any such g from a previously considered
1954 * constraint, then call extract_stride to record the stride information
1955 * in bound.
1957 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1959 int i;
1960 isl_ctx *ctx;
1961 isl_val *v;
1962 unsigned n_div;
1963 struct gpu_array_bound *bound = user;
1965 ctx = isl_constraint_get_ctx(c);
1966 n_div = isl_constraint_dim(c, isl_dim_div);
1967 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1969 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1970 int s = isl_val_sgn(v);
1971 isl_val *stride = isl_val_zero(ctx);
1973 isl_val_free(v);
1974 for (i = 0; i < n_div; ++i) {
1975 v = isl_constraint_get_coefficient_val(c,
1976 isl_dim_div, i);
1977 stride = isl_val_gcd(stride, v);
1979 if (!isl_val_is_zero(stride) &&
1980 isl_val_gt(stride, bound->stride))
1981 extract_stride(c, bound, stride, s);
1983 isl_val_free(stride);
1984 } else
1985 isl_val_free(v);
1987 isl_constraint_free(c);
1988 return 0;
1991 /* Given contraints on an array index i, check if we can find
1992 * a shift a(p) and a stride g such that
1994 * a(p) + i = 0 mod g
1996 * If so, record the information in bound and apply the mapping
1997 * i -> (i + a(p))/g to the array index in bounds and return
1998 * the new constraints.
1999 * If not, simply return the original constraints.
2001 * If bounds is a subset of the space
2003 * D -> i
2005 * then the bound recorded in bound->shift is of the form
2007 * D -> s(D)
2009 * with s(D) equal to a(p) above.
2010 * The mapping recorded in bound->shift_map is of the form
2012 * [D -> i] -> [D -> (i + S(D))/g]
2014 * This mapping is computed as follows.
2015 * We first introduce "i" in the domain through precomposition
2016 * with [D -> i] -> D obtaining
2018 * [D -> i] -> s(D)
2020 * Adding [D -> i] -> i produces
2022 * [D -> i] -> i + s(D)
2024 * and the domain product with [D -> i] -> D yields
2026 * [D -> i] -> [D -> i + s(D)]
2028 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
2030 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
2031 __isl_take isl_basic_map *bounds)
2033 isl_space *space;
2034 isl_basic_map *hull;
2035 isl_basic_map *shift, *id, *bmap, *scale;
2036 isl_basic_set *bset;
2037 isl_aff *aff;
2039 bound->stride = NULL;
2041 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
2043 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
2045 isl_basic_map_free(hull);
2047 if (!bound->stride)
2048 return bounds;
2050 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
2051 space = isl_basic_map_get_space(bounds);
2052 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
2053 shift = isl_basic_map_apply_range(bmap, shift);
2054 space = isl_basic_map_get_space(bounds);
2055 id = isl_basic_map_range_map(isl_basic_map_universe(space));
2056 shift = isl_basic_map_sum(id, shift);
2057 space = isl_basic_map_get_space(bounds);
2058 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
2059 shift = isl_basic_map_range_product(id, shift);
2061 space = isl_space_domain(isl_basic_map_get_space(bounds));
2062 id = isl_basic_map_identity(isl_space_map_from_set(space));
2063 space = isl_space_range(isl_basic_map_get_space(bounds));
2064 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2065 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2066 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
2067 scale = isl_basic_map_from_aff(aff);
2068 scale = isl_basic_map_product(id, scale);
2070 bound->shift_map = isl_basic_map_apply_range(shift, scale);
2071 bmap = isl_basic_map_copy(bound->shift_map);
2072 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
2073 bounds = isl_basic_set_unwrap(bset);
2075 return bounds;
2078 /* Data used in compute_array_dim_size and compute_size_in_direction.
2080 * pos is the position of the variable representing the array index,
2081 * i.e., the variable for which want to compute the size. This variable
2082 * is also the last variable in the set.
2084 struct gpu_size_info {
2085 isl_basic_set *bset;
2086 struct gpu_array_bound *bound;
2087 int pos;
2090 /* Given a constraint from the basic set describing the bounds on
2091 * an array index, check if it is a lower bound, say m i >= b(x), and,
2092 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2093 * upper bound. If so, and if this bound is smaller than any bound
2094 * derived from earlier constraints, set the size to this bound on
2095 * the expression and the lower bound to ceil(b(x)/m).
2097 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2099 struct gpu_size_info *size = user;
2100 unsigned nparam;
2101 unsigned n_div;
2102 isl_val *v;
2103 isl_aff *aff;
2104 isl_aff *lb;
2106 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2107 n_div = isl_constraint_dim(c, isl_dim_div);
2109 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2110 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2111 isl_constraint_free(c);
2112 return 0;
2115 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2116 aff = isl_aff_ceil(aff);
2118 lb = isl_aff_copy(aff);
2120 aff = isl_aff_neg(aff);
2121 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2123 v = isl_basic_set_max_val(size->bset, aff);
2124 isl_aff_free(aff);
2126 if (isl_val_is_int(v)) {
2127 v = isl_val_add_ui(v, 1);
2128 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2129 isl_val_free(size->bound->size);
2130 size->bound->size = isl_val_copy(v);
2131 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2132 isl_aff_free(size->bound->lb);
2133 size->bound->lb = isl_aff_copy(lb);
2136 isl_val_free(v);
2137 isl_aff_free(lb);
2139 isl_constraint_free(c);
2141 return 0;
2144 /* Given a basic map "bounds" that maps parameters and input dimensions
2145 * to a single output dimension, look for an expression in the parameters
2146 * and input dimensions such that the range of the output dimension shifted
2147 * by this expression is a constant.
2149 * In particular, we currently only consider lower bounds on the output
2150 * dimension as candidate expressions.
2152 static int compute_array_dim_size(struct gpu_array_bound *bound,
2153 __isl_take isl_basic_map *bounds)
2155 struct gpu_size_info size;
2157 bounds = isl_basic_map_detect_equalities(bounds);
2158 bounds = check_stride(bound, bounds);
2160 bound->size = NULL;
2161 bound->lb = NULL;
2163 size.bound = bound;
2164 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2165 size.bset = isl_basic_map_wrap(bounds);
2166 size.bset = isl_basic_set_flatten(size.bset);
2167 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2168 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2169 &size);
2170 isl_basic_set_free(size.bset);
2172 return bound->size ? 0 : -1;
2175 /* Check if we can find a memory tile for the given array
2176 * based on the given accesses, and if so, put the results in "tile".
2178 * We project the accesses on each index in turn and look for a parametric
2179 * offset such that the size is constant.
2181 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2183 int i;
2185 for (i = 0; i < tile->n; ++i) {
2186 isl_map *access_i;
2187 isl_basic_map *hull;
2189 access_i = isl_map_copy(access);
2190 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2191 access_i = isl_map_project_out(access_i, isl_dim_out,
2192 1, tile->n - (i + 1));
2193 access_i = isl_map_compute_divs(access_i);
2194 hull = isl_map_simple_hull(access_i);
2195 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2196 return 0;
2199 return 1;
2202 /* Construct a map with input the shared tile loops and the loops that
2203 * will be wrapped around the threads that relates these later loops
2204 * to the thread indices and then projects them out.
2206 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2208 isl_map *priv;
2209 isl_map *tiling;
2210 isl_map *proj;
2211 isl_set *par;
2212 isl_space *dim;
2214 dim = isl_union_map_get_space(gen->shared_sched);
2216 if (gen->options->wrap)
2217 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2218 gen->shared_len, gen->n_block, gen->block_dim);
2219 else
2220 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2221 gen->shared_len, gen->n_block, gen->block_dim);
2223 priv = tiling;
2225 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2226 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2227 gen->n_block, "t");
2229 priv = isl_map_align_params(priv, isl_set_get_space(par));
2230 priv = isl_map_intersect_range(priv, par);
2232 dim = isl_map_get_space(priv);
2233 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2234 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2235 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2236 gen->shared_len);
2238 priv = isl_map_apply_range(priv, proj);
2240 return priv;
2243 /* Construct a map from domain_dim to domain_dim that increments
2244 * the dimension at position "pos" and leaves all other dimensions
2245 * constant.
2247 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2249 int i;
2250 int len = isl_space_dim(domain_dim, isl_dim_set);
2251 isl_space *dim;
2252 isl_basic_map *next;
2253 isl_local_space *ls;
2255 dim = isl_space_map_from_set(domain_dim);
2256 next = isl_basic_map_universe(isl_space_copy(dim));
2257 ls = isl_local_space_from_space(dim);
2259 for (i = 0; i < len; ++i) {
2260 isl_constraint *c;
2262 c = isl_equality_alloc(isl_local_space_copy(ls));
2263 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2264 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2265 if (i == pos)
2266 c = isl_constraint_set_constant_si(c, 1);
2267 next = isl_basic_map_add_constraint(next, c);
2270 isl_local_space_free(ls);
2272 return isl_map_from_basic_map(next);
2275 /* Check if the given access is coalesced.
2276 * That is, check whether incrementing the dimension that will get
2277 * wrapped over the last thread index results in incrementing
2278 * the last array index.
2280 * This function is only called for access relations without reuse.
2282 static int access_is_coalesced(struct gpu_gen *gen,
2283 __isl_keep isl_union_map *access)
2285 isl_space *dim;
2286 isl_map *access_map;
2287 isl_map *next_thread_x;
2288 isl_map *next_element;
2289 isl_map *map;
2290 int coalesced;
2292 access = isl_union_map_copy(access);
2293 access = isl_union_map_apply_domain(access,
2294 isl_union_map_copy(gen->tiled_sched));
2295 access_map = isl_map_from_union_map(access);
2297 dim = isl_map_get_space(access_map);
2298 dim = isl_space_domain(dim);
2299 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2301 dim = isl_map_get_space(access_map);
2302 dim = isl_space_range(dim);
2303 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2305 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2306 map = isl_map_apply_range(map, access_map);
2308 coalesced = isl_map_is_subset(map, next_element);
2310 isl_map_free(next_element);
2311 isl_map_free(map);
2313 return coalesced;
2316 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2317 * dimensions of the computed schedule, check if it is bijective for
2318 * fixed values of the first gen->shared_len dimensions.
2319 * We perform this check by equating these dimensions to parameters.
2321 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2323 int res;
2324 isl_set *par;
2325 isl_space *space;
2327 access = isl_map_copy(access);
2328 space = isl_space_params(isl_map_get_space(access));
2329 par = parametrization(space, gen->shared_len + gen->n_block,
2330 0, gen->shared_len, "s");
2331 access = isl_map_intersect_domain(access, par);
2332 res = isl_map_is_bijective(access);
2333 isl_map_free(access);
2335 return res;
2338 /* Look for the last shared tile loop that affects the offset of "tile"
2339 * and return the result.
2340 * If there is no such loop, then return the index of the loop
2341 * before the first shared tile loop, in particular gen->tile_first - 1.
2343 static int compute_tile_last_shared(struct gpu_gen *gen,
2344 struct gpu_array_tile *tile)
2346 int i, j;
2348 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2349 for (i = 0; i < tile->n; ++i) {
2350 isl_aff *lb;
2351 isl_aff *shift;
2353 lb = tile->bound[i].lb;
2354 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2355 break;
2357 shift = tile->bound[i].shift;
2358 if (!shift)
2359 continue;
2360 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2361 break;
2363 if (i < tile->n)
2364 break;
2367 return j;
2370 /* Look for the last shared tile loop that affects the offset of the
2371 * shared or private tile and store the result in group->last_shared.
2372 * If there is no such loop, then group->last_shared is set to a value
2373 * before the first shared tile loop, in particular gen->tile_first - 1.
2374 * If there is no tile defined on the array reference group,
2375 * then set group->last_shared to gen->shared_len - 1.
2377 static void set_last_shared(struct gpu_gen *gen,
2378 struct gpu_array_ref_group *group)
2380 struct gpu_array_tile *tile;
2382 group->last_shared = gen->shared_len - 1;
2384 tile = group->private_tile;
2385 if (!tile)
2386 tile = group->shared_tile;
2387 if (!tile)
2388 return;
2390 group->last_shared = compute_tile_last_shared(gen, tile);
2393 /* Compute a privatized copy of all access relations from reference groups that
2394 * are mapped to private memory and store the result in gen->privatization.
2396 * Read-only scalars and arrays containing structures are not mapped
2397 * to private memory.
2399 static void compute_private_access(struct gpu_gen *gen)
2401 int i, j;
2402 isl_union_map *private;
2404 if (!gen->options->use_private_memory)
2405 return;
2407 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2409 for (i = 0; i < gen->prog->n_array; ++i) {
2410 struct gpu_array_info *array = &gen->prog->array[i];
2412 if (gpu_array_is_read_only_scalar(array))
2413 continue;
2414 if (array->has_compound_element)
2415 continue;
2417 for (j = 0; j < array->n_group; ++j) {
2418 if (!array->groups[j]->private_tile)
2419 continue;
2421 private = isl_union_map_union(private,
2422 group_access_relation(array->groups[j], 1, 1));
2426 if (isl_union_map_is_empty(private))
2427 isl_union_map_free(private);
2428 else {
2429 isl_union_map *priv;
2431 private = isl_union_map_apply_domain(private,
2432 isl_union_map_copy(gen->shared_sched));
2433 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2434 private = isl_union_map_apply_domain(private, priv);
2435 gen->private_access = private;
2439 /* Compute the size of the tile specified by "tile"
2440 * in number of elements and return the result.
2442 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2444 int i;
2445 isl_val *size;
2447 size = isl_val_one(ctx);
2449 for (i = 0; i < tile->n; ++i)
2450 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2452 return size;
2455 /* If max_shared_memory is not set to infinity (-1), then make
2456 * sure that the total amount of shared memory required by the
2457 * array reference groups mapped to shared memory is no larger
2458 * than this maximum.
2460 * We apply a greedy approach and discard (keep in global memory)
2461 * those groups that would result in a total memory size that
2462 * is larger than the maximum.
2464 * This function should be called after any function that may
2465 * affect the decision on whether to place a reference group
2466 * in private, shared or global memory.
2468 static void check_shared_memory_bound(struct gpu_gen *gen)
2470 int i, j;
2471 isl_val *left, *size;
2473 if (gen->options->max_shared_memory < 0)
2474 return;
2476 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2478 for (i = 0; i < gen->prog->n_array; ++i) {
2479 struct gpu_array_info *array = &gen->prog->array[i];
2481 for (j = 0; j < array->n_group; ++j) {
2482 struct gpu_array_ref_group *group;
2484 group = array->groups[j];
2485 if (group->private_tile)
2486 continue;
2487 if (!group->shared_tile)
2488 continue;
2490 size = tile_size(gen->ctx, group->shared_tile);
2491 size = isl_val_mul_ui(size, array->size);
2493 if (isl_val_le(size, left)) {
2494 left = isl_val_sub(left, size);
2495 continue;
2497 isl_val_free(size);
2499 group->shared_tile = free_tile(group->shared_tile);
2503 isl_val_free(left);
2506 /* Given a description of an array tile "tile" and the "space"
2508 * { D -> A }
2510 * where D represents the first shared_len schedule dimensions
2511 * and A represents the array, construct an isl_multi_aff
2513 * { [D[i] -> A[a]] -> A'[a'] }
2515 * with A' a scaled down copy of A according to the shifts and strides
2516 * in "tile". In particular,
2518 * a' = (a + shift(i))/stride
2520 * "insert_array" represents
2522 * { [D -> A] -> D }
2524 * and is used to insert A into the domain of functions that only
2525 * reference D.
2527 static __isl_give isl_multi_aff *strided_tile(
2528 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2529 __isl_keep isl_multi_aff *insert_array)
2531 int i;
2532 isl_ctx *ctx;
2533 isl_multi_aff *shift;
2534 isl_multi_val *stride;
2535 isl_space *space2;
2536 isl_local_space *ls;
2537 isl_multi_aff *tiling;
2539 ctx = isl_space_get_ctx(space);
2540 space2 = isl_space_domain(isl_space_copy(space));
2541 ls = isl_local_space_from_space(space2);
2542 space2 = isl_space_range(isl_space_copy(space));
2543 stride = isl_multi_val_zero(space2);
2544 shift = isl_multi_aff_zero(isl_space_copy(space));
2546 for (i = 0; i < tile->n; ++i) {
2547 struct gpu_array_bound *bound = &tile->bound[i];
2548 isl_val *stride_i;
2549 isl_aff *shift_i;
2551 if (tile->bound[i].shift) {
2552 stride_i = isl_val_copy(bound->stride);
2553 shift_i = isl_aff_copy(bound->shift);
2554 } else {
2555 stride_i = isl_val_one(ctx);
2556 shift_i = isl_aff_zero_on_domain(
2557 isl_local_space_copy(ls));
2560 stride = isl_multi_val_set_val(stride, i, stride_i);
2561 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2563 isl_local_space_free(ls);
2565 shift = isl_multi_aff_pullback_multi_aff(shift,
2566 isl_multi_aff_copy(insert_array));
2568 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2569 tiling = isl_multi_aff_add(tiling, shift);
2570 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2572 return tiling;
2575 /* Compute a tiling for the array reference group "group".
2577 * The tiling is of the form
2579 * { [D[i] -> A[a]] -> T[t] }
2581 * where D represents the first shared_len schedule dimensions,
2582 * A represents the global array and T represents the shared or
2583 * private memory tile. The name of T is the name of the local
2584 * array.
2586 * If there is any stride in the accesses, then the mapping is
2588 * t = (a + shift(i))/stride - lb(i)
2590 * otherwise, it is simply
2592 * t = a - lb(i)
2594 static void compute_group_tiling(struct gpu_array_ref_group *group)
2596 int i;
2597 struct gpu_array_tile *tile;
2598 struct gpu_array_info *array = group->array;
2599 isl_space *space;
2600 isl_multi_aff *tiling, *lb, *insert_array;
2601 isl_printer *p;
2602 char *local_name;
2604 tile = group->private_tile;
2605 if (!tile)
2606 tile = group->shared_tile;
2607 if (!tile)
2608 return;
2610 space = isl_map_get_space(group->access);
2611 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2613 for (i = 0; i < tile->n; ++i)
2614 if (tile->bound[i].shift)
2615 break;
2617 if (i < tile->n)
2618 tiling = strided_tile(tile, space, insert_array);
2619 else
2620 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2622 lb = isl_multi_aff_zero(space);
2623 for (i = 0; i < tile->n; ++i) {
2624 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2625 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2627 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2629 tiling = isl_multi_aff_sub(tiling, lb);
2631 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2632 p = print_array_name(p, group);
2633 local_name = isl_printer_get_str(p);
2634 isl_printer_free(p);
2635 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2636 free(local_name);
2638 tile->tiling = tiling;
2641 /* Compute a tiling for all the array reference groups.
2643 static void compute_group_tilings(struct gpu_gen *gen)
2645 int i, j;
2647 for (i = 0; i < gen->prog->n_array; ++i) {
2648 struct gpu_array_info *array = &gen->prog->array[i];
2650 for (j = 0; j < array->n_group; ++j)
2651 compute_group_tiling(array->groups[j]);
2655 /* Fill up the groups array with singleton groups, i.e., one group
2656 * per reference, initializing the array, access, write, n_ref and refs fields.
2657 * In particular the access field is initialized to the scheduled
2658 * access relation of the array reference.
2660 * Return the number of elements initialized, i.e., the number of
2661 * active references in the current kernel.
2663 static int populate_array_references(struct gpu_array_info *array,
2664 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2666 int i;
2667 int n;
2668 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2670 n = 0;
2671 for (i = 0; i < array->n_ref; ++i) {
2672 isl_union_map *umap;
2673 isl_map *map;
2674 struct gpu_array_ref_group *group;
2675 struct gpu_stmt_access *access = array->refs[i];
2677 map = isl_map_copy(access->access);
2678 umap = isl_union_map_from_map(map);
2679 umap = isl_union_map_apply_domain(umap,
2680 isl_union_map_copy(sched));
2682 if (isl_union_map_is_empty(umap)) {
2683 isl_union_map_free(umap);
2684 continue;
2687 map = isl_map_from_union_map(umap);
2688 map = isl_map_detect_equalities(map);
2690 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2691 assert(group);
2692 group->array = array;
2693 group->access = map;
2694 group->write = access->write;
2695 group->exact_write = access->exact_write;
2696 group->refs = &array->refs[i];
2697 group->n_ref = 1;
2699 groups[n++] = group;
2702 return n;
2705 /* If group->n_ref == 1, then group->refs was set by
2706 * populate_array_references to point directly into
2707 * group->array->refs and should not be freed.
2708 * If group->n_ref > 1, then group->refs was set by join_groups
2709 * to point to a newly allocated array.
2711 static void free_array_ref_group(struct gpu_array_ref_group *group)
2713 if (!group)
2714 return;
2715 free_tile(group->shared_tile);
2716 free_tile(group->private_tile);
2717 isl_map_free(group->access);
2718 if (group->n_ref > 1)
2719 free(group->refs);
2720 free(group);
2723 /* Given a map where the input dimensions represent the tile loops,
2724 * eliminate the innermost of those that have a fixed value
2725 * until we reach one that does not (obviously) have a fixed value.
2727 static __isl_give isl_map *eliminate_fixed_inner_loops(
2728 __isl_take isl_map *access)
2730 int i, n;
2732 n = isl_map_dim(access, isl_dim_in);
2734 for (i = n - 1; i >= 0; --i) {
2735 if (!map_plain_is_fixed(access, isl_dim_in, i))
2736 break;
2737 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2739 return access;
2742 /* Check if the access relations of group1 and group2 overlap within
2743 * the innermost loop. In particular, ignore any inner dimension
2744 * with a fixed value.
2745 * The copying to and from shared memory will be performed within
2746 * the innermost actual loop so we are only allowed to consider
2747 * the dimensions up to that innermost loop while checking whether
2748 * two access relations overlap.
2750 static int accesses_overlap(struct gpu_array_ref_group *group1,
2751 struct gpu_array_ref_group *group2)
2753 int empty;
2754 isl_map *access1, *access2;
2756 access1 = isl_map_copy(group1->access);
2757 access1 = eliminate_fixed_inner_loops(access1);
2758 access2 = isl_map_copy(group2->access);
2759 access2 = eliminate_fixed_inner_loops(access2);
2760 access1 = isl_map_intersect(access1, access2);
2761 empty = isl_map_is_empty(access1);
2762 isl_map_free(access1);
2764 return !empty;
2767 /* Combine the given two groups into a single group, containing
2768 * the references of both groups.
2770 static struct gpu_array_ref_group *join_groups(
2771 struct gpu_array_ref_group *group1,
2772 struct gpu_array_ref_group *group2)
2774 int i;
2775 isl_ctx *ctx;
2776 struct gpu_array_ref_group *group;
2778 ctx = isl_map_get_ctx(group1->access);
2779 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2780 assert(group);
2781 group->array = group1->array;
2782 group->access = isl_map_union(isl_map_copy(group1->access),
2783 isl_map_copy(group2->access));
2784 group->write = group1->write || group2->write;
2785 group->exact_write = group1->exact_write && group2->exact_write;
2786 group->n_ref = group1->n_ref + group2->n_ref;
2787 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2788 group->n_ref);
2789 assert(group->refs);
2790 for (i = 0; i < group1->n_ref; ++i)
2791 group->refs[i] = group1->refs[i];
2792 for (i = 0; i < group2->n_ref; ++i)
2793 group->refs[group1->n_ref + i] = group2->refs[i];
2795 return group;
2798 /* Combine the given two groups into a single group and free
2799 * the original two groups.
2801 static struct gpu_array_ref_group *join_groups_and_free(
2802 struct gpu_array_ref_group *group1,
2803 struct gpu_array_ref_group *group2)
2805 struct gpu_array_ref_group *group;
2807 group = join_groups(group1, group2);
2808 free_array_ref_group(group1);
2809 free_array_ref_group(group2);
2810 return group;
2813 /* Compute the private and/or shared memory tiles for the array
2814 * reference group "group" of array "array".
2815 * Return 0 on success and -1 on error.
2817 * If the array is a read-only scalar or if the user requested
2818 * not to use shared or private memory, then we do not need to do anything.
2820 * If the array group involves any may writes (that are not must writes),
2821 * then we would have to make sure that we load the data into shared/private
2822 * memory first in case the data is not written by the kernel
2823 * (but still written back out to global memory).
2824 * Since we don't have any such mechanism at the moment, we don't
2825 * compute shared/private tiles for groups involving may writes.
2827 * We only try to compute a shared memory tile if there is any reuse
2828 * or if the access is not coalesced.
2830 * For computing a private memory tile, we also require that there is
2831 * some reuse. Moreover, we require that the access is private
2832 * to the thread. That is, we check that any given array element
2833 * is only accessed by a single thread.
2834 * We compute an access relation that maps the shared tile loop iterators
2835 * and the shared point loop iterators that will be wrapped over the
2836 * threads to the array elements.
2837 * We actually check that those iterators that will be wrapped
2838 * partition the array space. This check is stricter than necessary
2839 * since several iterations may be mapped onto the same thread
2840 * and then they could be allowed to access the same memory elements,
2841 * but our check does not allow this situation.
2843 * We also check that the index expression only depends on parallel
2844 * loops. That way, we can move those loops innermost and unroll them.
2845 * Again, we use a test that is stricter than necessary.
2846 * We actually check whether the index expression only depends
2847 * on the iterators that are wrapped over the threads.
2848 * These are necessarily parallel, but there may be more parallel loops.
2850 * Combining the injectivity of the first test with the single-valuedness
2851 * of the second test, we simply test for bijectivity.
2853 * If the array is marked force_private, then we bypass all checks
2854 * and assume we can (and should) use registers.
2856 * If it turns out we can (or have to) use registers, we compute
2857 * the private memory tile size using can_tile, after introducing a dependence
2858 * on the thread indices.
2860 static int compute_group_bounds_core(struct gpu_gen *gen,
2861 struct gpu_array_ref_group *group)
2863 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2864 isl_union_map *access;
2865 int n_index = group->array->n_index;
2866 int no_reuse;
2867 isl_map *acc;
2868 int force_private = group->array->force_private;
2869 int use_shared = gen->options->use_shared_memory;
2870 int use_private = force_private || gen->options->use_private_memory;
2872 if (!use_shared && !use_private)
2873 return 0;
2874 if (gpu_array_is_read_only_scalar(group->array))
2875 return 0;
2876 if (!force_private && !group->exact_write)
2877 return 0;
2879 access = group_access_relation(group, 1, 1);
2880 no_reuse = isl_union_map_is_injective(access);
2882 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2883 group->shared_tile = create_tile(ctx, group->array->n_index);
2884 if (!can_tile(group->access, group->shared_tile))
2885 group->shared_tile = free_tile(group->shared_tile);
2888 if (!force_private && (!use_private || no_reuse)) {
2889 isl_union_map_free(access);
2890 return 0;
2893 access = isl_union_map_apply_domain(access,
2894 isl_union_map_copy(gen->shared_sched));
2896 acc = isl_map_from_union_map(access);
2898 if (!force_private && !access_is_bijective(gen, acc)) {
2899 isl_map_free(acc);
2900 return 0;
2903 group->private_tile = create_tile(gen->ctx, n_index);
2904 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2905 if (!can_tile(acc, group->private_tile))
2906 group->private_tile = free_tile(group->private_tile);
2908 isl_map_free(acc);
2910 if (force_private && !group->private_tile)
2911 isl_die(ctx, isl_error_internal,
2912 "unable to map array reference group to registers",
2913 return -1);
2915 return 0;
2918 /* Compute the private and/or shared memory tiles for the array
2919 * reference group "group" of array "array" and set last_shared.
2920 * Return 0 on success and -1 on error.
2922 static int compute_group_bounds(struct gpu_gen *gen,
2923 struct gpu_array_ref_group *group)
2925 if (compute_group_bounds_core(gen, group) < 0)
2926 return -1;
2927 set_last_shared(gen, group);
2929 return 0;
2932 /* If two groups have overlapping access relations (as determined by
2933 * the "overlap" function) and if one of them involves a write,
2934 * then merge the two groups into one.
2935 * If "compute_bounds" is set, then call compute_group_bounds
2936 * on the merged groups.
2938 * Return the updated number of groups.
2939 * Return -1 on error.
2941 static int group_writes(struct gpu_gen *gen,
2942 int n, struct gpu_array_ref_group **groups,
2943 int (*overlap)(struct gpu_array_ref_group *group1,
2944 struct gpu_array_ref_group *group2), int compute_bounds)
2946 int i, j;
2948 for (i = 0; i < n; ++i) {
2949 for (j = n - 1; j > i; --j) {
2950 if (!groups[i]->write && !groups[j]->write)
2951 continue;
2953 if (!overlap(groups[i], groups[j]))
2954 continue;
2956 groups[i] = join_groups_and_free(groups[i], groups[j]);
2957 if (compute_bounds &&
2958 compute_group_bounds(gen, groups[i]) < 0)
2959 return -1;
2960 if (j != n - 1)
2961 groups[j] = groups[n - 1];
2962 groups[n - 1] = NULL;
2963 n--;
2967 return n;
2970 /* If two groups have overlapping access relations (within the innermost
2971 * loop) and if one of them involves a write, then merge the two groups
2972 * into one.
2974 * Return the updated number of groups.
2976 static int group_overlapping_writes(struct gpu_gen *gen,
2977 int n, struct gpu_array_ref_group **groups)
2979 return group_writes(gen, n, groups, &accesses_overlap, 0);
2982 /* Check if the access relations of group1 and group2 overlap within
2983 * the outermost min(group1->last_shared, group2->last_shared) loops.
2985 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2986 struct gpu_array_ref_group *group2)
2988 int last_shared;
2989 int dim;
2990 int empty;
2991 isl_map *map_i, *map_j, *map;
2993 last_shared = group1->last_shared;
2994 if (group2->last_shared < last_shared)
2995 last_shared = group2->last_shared;
2996 map_i = isl_map_copy(group1->access);
2997 dim = isl_map_dim(map_i, isl_dim_in);
2998 map_i = isl_map_eliminate(map_i, isl_dim_in,
2999 last_shared + 1, dim - (last_shared + 1));
3000 map_j = isl_map_copy(group2->access);
3001 map_j = isl_map_eliminate(map_j, isl_dim_in,
3002 last_shared + 1, dim - (last_shared + 1));
3003 map = isl_map_intersect(map_i, map_j);
3004 empty = isl_map_is_empty(map);
3005 isl_map_free(map);
3007 return !empty;
3010 /* If two groups have overlapping access relations (within the outer
3011 * last_shared loops) and if one of them involves a write,
3012 * then merge the two groups into one.
3014 * Return the updated number of groups.
3016 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
3017 struct gpu_array_ref_group **groups)
3019 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
3022 /* Is the size of the tile specified by "tile" smaller than the sum of
3023 * the sizes of the tiles specified by "tile1" and "tile2"?
3025 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
3026 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
3028 int smaller;
3029 isl_val *size, *size1, *size2;
3031 size = tile_size(ctx, tile);
3032 size1 = tile_size(ctx, tile1);
3033 size2 = tile_size(ctx, tile2);
3035 size = isl_val_sub(size, size1);
3036 size = isl_val_sub(size, size2);
3037 smaller = isl_val_is_neg(size);
3039 isl_val_free(size);
3041 return smaller;
3044 /* Given an initial grouping of array references and shared memory tiles
3045 * for each group that allows for a shared memory tile, merge two groups
3046 * if both have a shared memory tile, the merged group also has
3047 * a shared memory tile and the size of the tile for the merge group
3048 * is smaller than the sum of the tile sizes of the individual groups.
3050 * If merging two groups decreases the "last_shared" dimension of
3051 * one or both of the two groups, then we need to check for overlapping
3052 * writes again.
3054 * Return the number of groups after merging.
3055 * Return -1 on error.
3057 static int group_common_shared_memory_tile(struct gpu_gen *gen,
3058 struct gpu_array_info *array, int n,
3059 struct gpu_array_ref_group **groups)
3061 int i, j;
3062 int recompute_overlap = 0;
3063 isl_ctx *ctx = isl_space_get_ctx(array->space);
3065 for (i = 0; i < n; ++i) {
3066 if (!groups[i]->shared_tile)
3067 continue;
3068 for (j = n - 1; j > i; --j) {
3069 isl_map *map;
3070 int empty;
3071 struct gpu_array_ref_group *group;
3073 if (!groups[j]->shared_tile)
3074 continue;
3076 map = isl_map_intersect(isl_map_copy(groups[i]->access),
3077 isl_map_copy(groups[j]->access));
3078 empty = isl_map_is_empty(map);
3079 isl_map_free(map);
3081 if (empty)
3082 continue;
3084 group = join_groups(groups[i], groups[j]);
3085 if (compute_group_bounds(gen, group) < 0) {
3086 free_array_ref_group(group);
3087 return -1;
3089 if (!group->shared_tile ||
3090 !smaller_tile(ctx, group->shared_tile,
3091 groups[i]->shared_tile,
3092 groups[j]->shared_tile)) {
3093 free_array_ref_group(group);
3094 continue;
3097 if (group->last_shared < groups[i]->last_shared ||
3098 group->last_shared < groups[j]->last_shared)
3099 recompute_overlap = 1;
3100 free_array_ref_group(groups[i]);
3101 free_array_ref_group(groups[j]);
3102 groups[i] = group;
3103 if (j != n - 1)
3104 groups[j] = groups[n - 1];
3105 n--;
3109 if (recompute_overlap)
3110 n = group_last_shared_overlapping_writes(gen, n, groups);
3111 return n;
3114 /* Set array->n_group and array->groups to n and groups.
3116 * Additionally, set the "nr" field of each group
3117 * and the "group" field of each reference in each group.
3119 static void set_array_groups(struct gpu_array_info *array,
3120 int n, struct gpu_array_ref_group **groups)
3122 int i, j;
3124 array->n_group = n;
3125 array->groups = groups;
3127 for (i = 0; i < n; ++i) {
3128 groups[i]->nr = i;
3130 for (j = 0; j < groups[i]->n_ref; ++j)
3131 groups[i]->refs[j]->group = i;
3135 /* Group array references that should be considered together when
3136 * deciding whether to access them from private, shared or global memory.
3137 * Return -1 on error.
3139 * In particular, if two array references overlap and if one of them
3140 * is a write, then the two references are grouped together.
3141 * We first perform an initial grouping based only on the access relation.
3142 * After computing shared and private memory tiles, we check for
3143 * overlapping writes again, but this time taking into account
3144 * the "last_shared" property.
3146 * Furthermore, if two groups admit a shared memory tile and if the
3147 * combination of the two also admits a shared memory tile, we merge
3148 * the two groups.
3150 * If the array contains structures, then there is no need to compute
3151 * reference groups since we do not map such arrays to private or shared
3152 * memory.
3154 static int group_array_references(struct gpu_gen *gen,
3155 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3157 int i;
3158 int n;
3159 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3160 struct gpu_array_ref_group **groups;
3162 if (array->has_compound_element)
3163 return 0;
3165 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3166 array->n_ref);
3167 if (!groups)
3168 return -1;
3170 n = populate_array_references(array, sched, groups);
3172 n = group_overlapping_writes(gen, n, groups);
3174 for (i = 0; i < n; ++i)
3175 if (compute_group_bounds(gen, groups[i]) < 0)
3176 n = -1;
3178 n = group_last_shared_overlapping_writes(gen, n, groups);
3180 n = group_common_shared_memory_tile(gen, array, n, groups);
3182 set_array_groups(array, n, groups);
3184 if (n >= 0)
3185 return 0;
3187 for (i = 0; i < array->n_ref; ++i)
3188 free_array_ref_group(groups[i]);
3189 return -1;
3192 /* Take tiled_sched, project it onto the shared tile loops and
3193 * the loops that will be wrapped over the threads and
3194 * store the result in gen->shared_sched.
3195 * Also compute a projection that projects out the loops that will be
3196 * wrapped over the threads and store this projection in gen->shared_proj.
3198 static void compute_shared_sched(struct gpu_gen *gen)
3200 isl_space *dim;
3201 isl_map *proj;
3202 isl_set *par;
3203 isl_union_map *sched;
3205 sched = isl_union_map_copy(gen->tiled_sched);
3207 dim = isl_union_map_get_space(sched);
3208 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3209 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3211 dim = isl_union_map_get_space(sched);
3212 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3214 gen->shared_sched = sched;
3215 gen->shared_proj = isl_union_map_from_map(proj);
3218 /* For each scalar in the input program, check if there are any
3219 * order dependences active inside the current kernel, within
3220 * the same iteration of the host schedule.
3221 * If so, mark the scalar as force_private so that it will be
3222 * mapped to a register.
3224 static void check_scalar_live_ranges(struct gpu_gen *gen)
3226 int i;
3227 isl_map *proj;
3228 isl_union_map *sched;
3229 isl_union_set *domain;
3230 isl_union_map *same_host_iteration;
3232 gen->any_force_private = 0;
3234 if (!gen->options->live_range_reordering)
3235 return;
3237 sched = gen->shared_sched;
3238 sched = isl_union_map_universe(isl_union_map_copy(sched));
3239 domain = isl_union_map_domain(sched);
3241 sched = isl_union_map_copy(gen->sched);
3242 proj = projection(isl_union_map_get_space(sched),
3243 gen->untiled_len, gen->tile_first);
3244 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3245 same_host_iteration = isl_union_map_apply_range(sched,
3246 isl_union_map_reverse(isl_union_map_copy(sched)));
3248 for (i = 0; i < gen->prog->n_array; ++i) {
3249 struct gpu_array_info *array = &gen->prog->array[i];
3250 isl_union_map *order;
3252 array->force_private = 0;
3253 if (array->n_index != 0)
3254 continue;
3255 order = isl_union_map_copy(array->dep_order);
3256 order = isl_union_map_intersect_domain(order,
3257 isl_union_set_copy(domain));
3258 order = isl_union_map_intersect_range(order,
3259 isl_union_set_copy(domain));
3260 order = isl_union_map_intersect(order,
3261 isl_union_map_copy(same_host_iteration));
3262 if (!isl_union_map_is_empty(order)) {
3263 array->force_private = 1;
3264 gen->any_force_private = 1;
3266 isl_union_map_free(order);
3269 isl_union_map_free(same_host_iteration);
3270 isl_union_set_free(domain);
3273 /* Group references of all arrays in the program.
3275 static int group_references(struct gpu_gen *gen)
3277 int i;
3278 int r = 0;
3279 isl_union_map *sched;
3281 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3282 isl_union_map_copy(gen->shared_proj));
3284 for (i = 0; i < gen->prog->n_array; ++i) {
3285 r = group_array_references(gen, &gen->prog->array[i], sched);
3286 if (r < 0)
3287 break;
3290 isl_union_map_free(sched);
3292 return r;
3295 /* Free all array information that is local to the current kernel.
3297 static void free_local_array_info(struct gpu_gen *gen)
3299 int i, j;
3301 for (i = 0; i < gen->prog->n_array; ++i) {
3302 struct gpu_array_info *array = &gen->prog->array[i];
3304 for (j = 0; j < array->n_group; ++j)
3305 free_array_ref_group(array->groups[j]);
3306 free(array->groups);
3310 /* Compute the size of a bounding box around the origin and "set",
3311 * where "set" is assumed to contain only non-negative elements.
3312 * In particular, compute the maximal value of "set" in each direction
3313 * and add one.
3315 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3316 __isl_keep isl_set *context)
3318 int i, n;
3319 isl_multi_pw_aff *mpa;
3321 n = isl_set_dim(set, isl_dim_set);
3322 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3323 for (i = 0; i < n; ++i) {
3324 isl_space *space;
3325 isl_aff *one;
3326 isl_pw_aff *bound;
3328 bound = isl_set_dim_max(isl_set_copy(set), i);
3329 bound = isl_pw_aff_coalesce(bound);
3330 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3332 space = isl_pw_aff_get_domain_space(bound);
3333 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3334 one = isl_aff_add_constant_si(one, 1);
3335 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3336 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3338 isl_set_free(set);
3340 return mpa;
3343 /* Compute the effective grid size as a list of the sizes in each dimension.
3345 * The grid size specified by the user or set by default
3346 * in read_grid_sizes() and applied in tile_schedule(),
3347 * may be too large for the given code in the sense that
3348 * it may contain blocks that don't need to execute anything.
3349 * We therefore don't return this grid size, but instead the
3350 * smallest grid size that ensures that all blocks that actually
3351 * execute code are included in the grid.
3353 * We first extract a description of the grid, i.e., the possible values
3354 * of the block ids, from gen->tiled_sched.
3355 * The block ids are parameters in gen->tiled_sched.
3356 * We simply need to change them into set dimensions.
3358 * Then, for each block dimension, we compute the maximal value of the block id
3359 * and add one.
3361 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3362 struct ppcg_kernel *kernel)
3364 int i;
3365 isl_set *grid;
3367 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3368 grid = isl_set_from_params(grid);
3369 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3370 for (i = 0; i < gen->n_grid; ++i) {
3371 int pos;
3372 char name[20];
3374 snprintf(name, sizeof(name), "b%d", i);
3375 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
3376 assert(pos >= 0);
3377 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3378 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3381 return extract_size(grid, kernel->context);
3384 /* Compute the size of a fixed bounding box around the origin and "set",
3385 * where "set" is assumed to contain only non-negative elements,
3386 * and store the results in "size".
3387 * In particular, compute the maximal value of "set" in each direction
3388 * and add one.
3390 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3392 int i, n;
3393 isl_local_space *ls;
3394 isl_aff *obj;
3396 n = isl_set_dim(set, isl_dim_set);
3397 ls = isl_local_space_from_space(isl_set_get_space(set));
3398 obj = isl_aff_zero_on_domain(ls);
3399 for (i = 0; i < n; ++i) {
3400 isl_val *max;
3402 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3403 max = isl_set_max_val(set, obj);
3404 size[i] = isl_val_get_num_si(max) + 1;
3405 isl_val_free(max);
3406 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3408 isl_aff_free(obj);
3409 isl_set_free(set);
3412 /* Compute the effective block size as a list of the sizes in each dimension
3413 * and store the sizes in kernel->block_dim.
3415 * The block size specified by the user or set by default
3416 * in read_block_sizes() and applied in thread_tile_schedule(),
3417 * may be too large for the given code in the sense that
3418 * it may contain threads that don't need to execute anything.
3419 * We therefore don't store this block size in kernel->block_dim,
3420 * but instead the smallest block size that ensures that all threads
3421 * that actually execute code are included in the block.
3423 * The current implementation eliminates all parameters, ensuring
3424 * that the size is a fixed constant in each dimension.
3425 * In principle we could also compute parametric sizes.
3426 * We would have to make sure to project out all b%d and t%d parameters,
3427 * however.
3429 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3431 int i;
3432 int nparam;
3433 isl_set *block;
3434 isl_multi_pw_aff *mpa;
3436 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3437 block = isl_set_from_params(block);
3438 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3439 kernel->n_block = gen->n_block;
3440 for (i = 0; i < gen->n_block; ++i) {
3441 int pos;
3442 char name[20];
3444 snprintf(name, sizeof(name), "t%d", i);
3445 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3446 assert(pos >= 0);
3447 block = isl_set_equate(block, isl_dim_param, pos,
3448 isl_dim_set, i);
3450 nparam = isl_set_dim(block, isl_dim_param);
3451 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3453 extract_fixed_size(block, kernel->block_dim);
3456 void ppcg_kernel_free(void *user)
3458 struct ppcg_kernel *kernel = user;
3459 int i;
3461 if (!kernel)
3462 return;
3464 isl_multi_pw_aff_free(kernel->grid_size);
3465 isl_set_free(kernel->context);
3466 isl_union_set_free(kernel->arrays);
3467 isl_space_free(kernel->space);
3468 isl_ast_node_free(kernel->tree);
3470 for (i = 0; i < kernel->n_array; ++i)
3471 isl_pw_aff_list_free(kernel->array[i].bound);
3472 free(kernel->array);
3474 for (i = 0; i < kernel->n_var; ++i) {
3475 free(kernel->var[i].name);
3476 isl_vec_free(kernel->var[i].size);
3478 free(kernel->var);
3480 free(kernel);
3483 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3484 struct ppcg_kernel_var *var)
3486 int j;
3487 struct gpu_array_tile *tile;
3488 isl_printer *p;
3489 char *name;
3491 var->array = group->array;
3493 tile = group->private_tile;
3494 var->type = ppcg_access_private;
3495 if (!tile) {
3496 tile = group->shared_tile;
3497 var->type = ppcg_access_shared;
3500 p = isl_printer_to_str(ctx);
3501 p = print_array_name(p, group);
3502 var->name = isl_printer_get_str(p);
3503 isl_printer_free(p);
3505 var->size = isl_vec_alloc(ctx, group->array->n_index);
3507 for (j = 0; j < group->array->n_index; ++j)
3508 var->size = isl_vec_set_element_val(var->size, j,
3509 isl_val_copy(tile->bound[j].size));
3512 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3514 int i, j, n;
3516 n = 0;
3517 for (i = 0; i < gen->prog->n_array; ++i) {
3518 struct gpu_array_info *array = &gen->prog->array[i];
3520 for (j = 0; j < array->n_group; ++j) {
3521 struct gpu_array_ref_group *group = array->groups[j];
3522 if (group->private_tile || group->shared_tile)
3523 ++n;
3527 kernel->n_var = n;
3528 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3529 assert(kernel->var);
3531 n = 0;
3532 for (i = 0; i < gen->prog->n_array; ++i) {
3533 struct gpu_array_info *array = &gen->prog->array[i];
3535 for (j = 0; j < array->n_group; ++j) {
3536 struct gpu_array_ref_group *group = array->groups[j];
3537 if (!group->private_tile && !group->shared_tile)
3538 continue;
3539 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3540 ++n;
3545 /* The sizes of the arrays on the host that have been computed by
3546 * extract_array_info may depend on the parameters. Use the extra
3547 * constraints on the parameters that are valid at "host_domain"
3548 * to simplify these expressions and store the results in kernel->array.
3550 * We only need these localized bounds for arrays that are accessed
3551 * by the current kernel. If we have found at least one reference group
3552 * then the array is accessed by the kernel. If the array has compound
3553 * elements then we skipped the construction of array reference groups.
3555 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3556 __isl_keep isl_set *host_domain)
3558 int i, j;
3559 isl_set *context;
3561 kernel->array = isl_calloc_array(gen->ctx,
3562 struct gpu_local_array_info, gen->prog->n_array);
3563 assert(kernel->array);
3564 kernel->n_array = gen->prog->n_array;
3566 context = isl_set_copy(host_domain);
3567 context = isl_set_params(context);
3569 for (i = 0; i < gen->prog->n_array; ++i) {
3570 struct gpu_array_info *array = &gen->prog->array[i];
3571 isl_pw_aff_list *local;
3573 if (array->n_group == 0 && !array->has_compound_element)
3574 continue;
3576 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3578 for (j = 0; j < array->n_index; ++j) {
3579 isl_pw_aff *pwaff;
3581 pwaff = isl_pw_aff_copy(array->bound[j]);
3582 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3583 local = isl_pw_aff_list_add(local, pwaff);
3586 kernel->array[i].bound = local;
3588 isl_set_free(context);
3591 /* Find the element in gen->stmt that has the given "id".
3592 * Return NULL if no such gpu_stmt can be found.
3594 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3596 int i;
3598 for (i = 0; i < prog->n_stmts; ++i) {
3599 if (id == prog->stmts[i].id)
3600 break;
3603 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3606 /* Set gen->tile_len and gen->n_parallel to those of the statement
3607 * affected by the first map (part of the schedule)
3608 * on which this function is called.
3609 * Because of the way the schedule is constructed, the other statements
3610 * in the list, if any, should have the same values for these properties.
3612 static int extract_tile_len(__isl_take isl_map *map, void *user)
3614 struct gpu_gen *gen = (struct gpu_gen *) user;
3615 isl_id *id;
3616 struct gpu_stmt *stmt;
3618 id = isl_map_get_tuple_id(map, isl_dim_in);
3619 stmt = find_stmt(gen->prog, id);
3620 isl_id_free(id);
3622 isl_map_free(map);
3624 if (!stmt)
3625 isl_die(gen->ctx, isl_error_unknown,
3626 "statement not found", return -1);
3628 gen->tile_len = stmt->tile_len;
3629 gen->n_parallel = stmt->n_parallel;
3631 return -1;
3634 void ppcg_kernel_stmt_free(void *user)
3636 int i;
3637 struct ppcg_kernel_stmt *stmt = user;
3639 if (!stmt)
3640 return;
3642 switch (stmt->type) {
3643 case ppcg_kernel_copy:
3644 isl_ast_expr_free(stmt->u.c.index);
3645 isl_ast_expr_free(stmt->u.c.local_index);
3646 break;
3647 case ppcg_kernel_domain:
3648 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3649 break;
3650 case ppcg_kernel_sync:
3651 break;
3654 free(stmt);
3657 /* Set the options of "context" to
3659 * { space -> [x] : x >= first }
3661 static __isl_give isl_ast_build *set_unroll(
3662 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3663 int first)
3665 isl_ctx *ctx;
3666 isl_map *unroll;
3667 isl_union_map *opt;
3669 ctx = isl_ast_build_get_ctx(build);
3671 space = isl_space_from_domain(space);
3672 space = isl_space_add_dims(space, isl_dim_out, 1);
3673 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3674 unroll = isl_map_universe(space);
3675 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3676 opt = isl_union_map_from_map(unroll);
3678 build = isl_ast_build_set_options(build, opt);
3680 return build;
3683 /* Return a list of isl_ids of the form "prefix%d".
3685 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3686 int n, const char *prefix)
3688 int i;
3689 char name[10];
3690 isl_id_list *names;
3692 names = isl_id_list_alloc(ctx, n);
3693 for (i = 0; i < n; ++i) {
3694 isl_id *id;
3696 snprintf(name, sizeof(name), "%s%d", prefix, i);
3697 id = isl_id_alloc(ctx, name, NULL);
3698 names = isl_id_list_add(names, id);
3701 return names;
3704 /* Extend the schedule "schedule" with the part of "extension"
3705 * starting at "first" up to "len".
3707 static __isl_give isl_union_map *extend_schedule(
3708 __isl_take isl_union_map *schedule,
3709 __isl_take isl_union_map *extension, int first, int len)
3711 isl_space *space;
3712 isl_map *proj;
3713 isl_union_map *umap;
3714 isl_set *set;
3716 space = isl_union_map_get_space(schedule);
3717 space = isl_space_set_from_params(space);
3718 space = isl_space_add_dims(space, isl_dim_set, len);
3719 proj = isl_set_identity(isl_set_universe(space));
3720 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3721 extension = isl_union_map_apply_range(extension,
3722 isl_union_map_from_map(proj));
3724 schedule = isl_union_map_range_product(schedule, extension);
3726 return schedule;
3729 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3730 * to "ref_id".
3732 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3733 __isl_keep isl_id *ref_id)
3735 struct gpu_stmt_access *access;
3737 for (access = accesses; access; access = access->next)
3738 if (access->ref_id == ref_id)
3739 return access;
3741 return NULL;
3744 /* Return the index of the array called "name" in the list of arrays.
3746 static int find_array_index(struct gpu_gen *gen, const char *name)
3748 int i;
3750 for (i = 0; i < gen->prog->n_array; ++i)
3751 if (!strcmp(name, gen->prog->array[i].name))
3752 return i;
3754 return -1;
3757 /* Internal data structure for the index and AST expression transformation
3758 * callbacks for pet_stmt_build_ast_exprs.
3760 * "accesses" is the list of gpu_stmt_access in the statement.
3761 * "iterator_map" expresses the statement iterators in terms of
3762 * the AST loop iterators.
3763 * "sched2shared" expresses the first shared_len dimensions of
3764 * the computed schedule in terms of the AST loop iterators.
3766 * The following fields are set in transform_index and used in transform_expr.
3767 * "array" is the array that is being accessed.
3768 * "global" is set if the global array is accessed (rather than
3769 * shared/private memory).
3770 * "local_array" refers to information on the array specialized
3771 * to the current kernel.
3773 struct ppcg_transform_data {
3774 struct gpu_gen *gen;
3775 struct gpu_stmt_access *accesses;
3776 isl_pw_multi_aff *iterator_map;
3777 isl_pw_multi_aff *sched2shared;
3779 struct gpu_array_info *array;
3780 int global;
3781 struct gpu_local_array_info *local_array;
3784 /* Return the name of the outer array (of structs) accessed by "access".
3786 static const char *get_outer_array_name(__isl_keep isl_map *access)
3788 isl_space *space;
3789 const char *name;
3791 space = isl_space_range(isl_map_get_space(access));
3792 while (space && isl_space_is_wrapping(space))
3793 space = isl_space_domain(isl_space_unwrap(space));
3794 name = isl_space_get_tuple_name(space, isl_dim_set);
3795 isl_space_free(space);
3797 return name;
3800 /* Index transformation callback for pet_stmt_build_ast_exprs.
3802 * "index" expresses the array indices in terms of statement iterators
3804 * We first reformulate "index" in terms of the AST loop iterators.
3805 * Then we check if we are accessing the global array or
3806 * a shared/private copy. In the former case, we simply return
3807 * the updated index. If "index" is an affine expression rather
3808 * than an array access, then we also return the updated index here.
3810 * If no reference groups have been computed for the array,
3811 * then we can only be accessing the global array.
3813 * Otherwise, we apply the tiling to the index.
3814 * This tiling is of the form
3816 * [D -> A] -> T
3818 * The index is of the form
3820 * L -> A
3822 * We update the tiling to refer to the AST loop iteratos
3824 * [L -> A] -> T
3826 * and modify index to keep track of those iterators
3828 * L -> [L -> A]
3830 * Combining these two yields a tiled index expression in terms
3831 * of the AST loop iterators
3833 * L -> T
3835 static __isl_give isl_multi_pw_aff *transform_index(
3836 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3837 void *user)
3839 struct ppcg_transform_data *data = user;
3840 struct gpu_stmt_access *access;
3841 struct gpu_array_ref_group *group;
3842 struct gpu_array_tile *tile;
3843 isl_pw_multi_aff *iterator_map;
3844 int i;
3845 const char *name;
3846 isl_space *space;
3847 isl_multi_pw_aff *tiling;
3848 isl_pw_multi_aff *pma;
3849 isl_multi_pw_aff *mpa;
3851 data->array = NULL;
3853 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3854 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3856 access = find_access(data->accesses, ref_id);
3857 if (!access)
3858 return index;
3859 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3860 return index;
3862 name = get_outer_array_name(access->access);
3863 i = find_array_index(data->gen, name);
3864 if (i < 0)
3865 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3866 "cannot find array",
3867 return isl_multi_pw_aff_free(index));
3868 data->array = &data->gen->prog->array[i];
3869 data->local_array = &data->gen->kernel->array[i];
3871 if (access->group < 0) {
3872 data->global = 1;
3873 return index;
3876 group = data->array->groups[access->group];
3877 tile = group->private_tile;
3878 if (!tile)
3879 tile = group->shared_tile;
3880 data->global = !tile;
3881 if (!tile)
3882 return index;
3884 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3885 space = isl_space_map_from_set(space);
3886 pma = isl_pw_multi_aff_identity(space);
3887 pma = isl_pw_multi_aff_product(
3888 isl_pw_multi_aff_copy(data->sched2shared), pma);
3889 tiling = isl_multi_pw_aff_from_multi_aff(
3890 isl_multi_aff_copy(tile->tiling));
3891 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3893 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3894 space = isl_space_map_from_set(space);
3895 mpa = isl_multi_pw_aff_identity(space);
3896 index = isl_multi_pw_aff_range_product(mpa, index);
3897 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3899 return index;
3902 /* Dereference "expr" by adding an index [0].
3903 * The original "expr" is assumed not to have any indices.
3905 * If "expr" is a member access, then the dereferencing needs
3906 * to be applied to the structure argument of this member access.
3908 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3910 isl_ctx *ctx;
3911 isl_ast_expr *res;
3912 isl_ast_expr_list *list;
3914 if (isl_ast_expr_get_op_type(expr) == isl_ast_op_member) {
3915 isl_ast_expr *arg;
3917 arg = isl_ast_expr_get_op_arg(expr, 0);
3918 arg = dereference(arg);
3919 expr = isl_ast_expr_set_op_arg(expr, 0, arg);
3921 return expr;
3924 ctx = isl_ast_expr_get_ctx(expr);
3925 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3926 list = isl_ast_expr_list_from_ast_expr(res);
3927 res = isl_ast_expr_get_op_arg(expr, 0);
3928 res = isl_ast_expr_access(res, list);
3929 isl_ast_expr_free(expr);
3931 return res;
3934 /* Linearize the index expression "expr" based on the array bounds
3935 * of "array".
3937 * That is, transform expression
3939 * A[i_0][i_1]...[i_n]
3941 * to
3943 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3945 * where b_0, b_1, ..., b_n are the bounds on the array.
3947 * If the base of "expr" is a member access, then the linearization needs
3948 * to be applied to the structure argument of this member access.
3950 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3951 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3953 int i, n;
3954 isl_ctx *ctx;
3955 isl_set *context;
3956 isl_ast_expr *arg0;
3957 isl_ast_expr *res;
3958 isl_ast_expr_list *list;
3959 isl_ast_build *build;
3961 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3962 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3963 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3964 isl_ast_expr *arg;
3966 arg = isl_ast_expr_get_op_arg(arg0, 0);
3967 arg = gpu_local_array_info_linearize_index(array, arg);
3968 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3969 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3971 return expr;
3973 isl_ast_expr_free(arg0);
3975 ctx = isl_ast_expr_get_ctx(expr);
3976 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3977 build = isl_ast_build_from_context(context);
3979 n = isl_ast_expr_get_op_n_arg(expr);
3980 res = isl_ast_expr_get_op_arg(expr, 1);
3981 for (i = 2; i < n; ++i) {
3982 isl_pw_aff *bound_i;
3983 isl_ast_expr *expr_i;
3985 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i - 1);
3986 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3987 res = isl_ast_expr_mul(res, expr_i);
3988 expr_i = isl_ast_expr_get_op_arg(expr, i);
3989 res = isl_ast_expr_add(res, expr_i);
3992 isl_ast_build_free(build);
3994 list = isl_ast_expr_list_from_ast_expr(res);
3995 res = isl_ast_expr_get_op_arg(expr, 0);
3996 res = isl_ast_expr_access(res, list);
3998 isl_ast_expr_free(expr);
4000 return res;
4003 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
4005 * If the AST expression refers to a global scalar that is not
4006 * a read-only scalar, then its address was passed to the kernel and
4007 * we need to dereference it.
4009 * If the AST expression refers to an access to a global array,
4010 * then we linearize the access exploiting the bounds in data->local_array.
4012 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
4013 __isl_keep isl_id *id, void *user)
4015 struct ppcg_transform_data *data = user;
4017 if (!data->array)
4018 return expr;
4019 if (gpu_array_is_read_only_scalar(data->array))
4020 return expr;
4021 if (!data->global)
4022 return expr;
4023 if (data->array->n_index == 0)
4024 return dereference(expr);
4025 if (!data->array->linearize)
4026 return expr;
4028 return gpu_local_array_info_linearize_index(data->local_array, expr);
4031 /* This function is called for each instance of a user statement
4032 * in the kernel.
4034 * We attach a struct ppcg_kernel_stmt to the "node", containing
4035 * a computed AST expression for each access.
4036 * These AST expressions are computed from iterator_map,
4037 * which expresses the domain
4038 * elements in terms of the generated loops, and sched2shared,
4039 * which expresses the first shared_len dimensions of the schedule
4040 * computed by PPCG in terms of the generated loops.
4042 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
4043 __isl_keep isl_ast_build *build, void *user)
4045 struct ppcg_transform_data data;
4046 struct gpu_gen *gen = (struct gpu_gen *) user;
4047 struct ppcg_kernel_stmt *stmt;
4048 isl_id *id;
4049 isl_pw_multi_aff *sched2shared;
4050 isl_map *map;
4051 isl_pw_multi_aff *iterator_map;
4052 isl_ast_expr *expr, *arg;
4053 isl_union_map *schedule;
4054 int i, n;
4056 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4057 if (!stmt)
4058 return isl_ast_node_free(node);
4060 expr = isl_ast_node_user_get_expr(node);
4061 arg = isl_ast_expr_get_op_arg(expr, 0);
4062 id = isl_ast_expr_get_id(arg);
4064 schedule = isl_ast_build_get_schedule(build);
4065 map = isl_map_reverse(isl_map_from_union_map(schedule));
4066 iterator_map = isl_pw_multi_aff_from_map(map);
4067 sched2shared = compute_sched_to_shared(gen,
4068 isl_pw_multi_aff_copy(iterator_map));
4070 stmt->type = ppcg_kernel_domain;
4071 stmt->u.d.stmt = find_stmt(gen->prog, id);
4072 if (!stmt->u.d.stmt)
4073 goto error;
4075 data.gen = gen;
4076 data.accesses = stmt->u.d.stmt->accesses;
4077 data.iterator_map = iterator_map;
4078 data.sched2shared = sched2shared;
4079 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4080 build, &transform_index, &data,
4081 &transform_expr, &data);
4083 isl_id_free(id);
4084 isl_pw_multi_aff_free(iterator_map);
4085 isl_pw_multi_aff_free(sched2shared);
4086 isl_ast_expr_free(arg);
4087 isl_ast_expr_free(expr);
4089 id = isl_id_alloc(gen->ctx, NULL, stmt);
4090 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4091 return isl_ast_node_set_annotation(node, id);
4092 error:
4093 isl_id_free(id);
4094 isl_pw_multi_aff_free(iterator_map);
4095 ppcg_kernel_stmt_free(stmt);
4096 isl_pw_multi_aff_free(sched2shared);
4097 return isl_ast_node_free(node);
4100 /* This function is called when code has been generated for the shared
4101 * tile loops. The "schedule" refers only to the original statements.
4103 * We extend the schedule with that part of gen->local_sched that hasn't
4104 * been taken into account yet. This introduces parameters referring
4105 * to thread ids in the schedule, so we add them (with the appropriate
4106 * bounds to the context as well).
4107 * Finally, we set the appropriate unrolling options
4108 * if gen->first_unroll is set.
4110 static __isl_give isl_ast_node *create_domain_leaf(
4111 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4112 void *user)
4114 struct gpu_gen *gen = (struct gpu_gen *) user;
4115 isl_space *space;
4116 isl_union_map *sched;
4117 isl_ast_node *tree;
4118 isl_set *set;
4119 isl_id_list *iterators;
4120 int n;
4122 schedule = extend_schedule(schedule,
4123 isl_union_map_copy(gen->local_sched),
4124 gen->shared_len, gen->thread_tiled_len);
4126 space = isl_ast_build_get_schedule_space(build);
4127 set = isl_set_universe(space);
4128 set = add_bounded_parameters(set, gen->kernel->n_block,
4129 gen->kernel->block_dim, "t");
4130 build = isl_ast_build_restrict(build, set);
4132 n = gen->thread_tiled_len - gen->shared_len;
4134 if (gen->first_unroll >= 0) {
4135 space = isl_space_set_alloc(gen->ctx, 0, n);
4136 build = set_unroll(build, space, gen->first_unroll);
4138 iterators = generate_names(gen->ctx, n, "c");
4139 build = isl_ast_build_set_iterators(build, iterators);
4140 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4141 tree = isl_ast_build_ast_from_schedule(build, schedule);
4142 isl_ast_build_free(build);
4144 return tree;
4147 /* This function is called for each statement node in the AST of the code
4148 * for copying to or from shared/private memory.
4149 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4150 * statement to the node.
4151 * The statement name is "read" or "write", depending on whether we are
4152 * reading from global memory or writing to global memory.
4153 * The name of the T space is {shared,private}_<array>.
4155 * The schedule is of the form
4157 * type[A -> T] -> L
4159 * where A refers to a piece of an array and T to the corresponding
4160 * shifted tile. We split this schedule into mappings L -> A and L -> T
4161 * and store the corresponding expressions in stmt->index and stmt->local_index,
4162 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4164 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4165 __isl_keep isl_ast_build *build, void *user)
4167 struct gpu_gen *gen = (struct gpu_gen *) user;
4168 struct ppcg_kernel_stmt *stmt;
4169 isl_id *id;
4170 isl_ast_expr *expr;
4171 isl_space *space;
4172 isl_map *access, *local_access, *map;
4173 isl_pw_multi_aff *pma;
4174 const char *type;
4175 int array_index;
4177 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4178 if (!stmt)
4179 return isl_ast_node_free(node);
4181 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4182 type = isl_map_get_tuple_name(access, isl_dim_in);
4183 stmt->u.c.read = !strcmp(type, "read");
4184 access = isl_map_reverse(access);
4185 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4186 local_access = isl_map_copy(access);
4188 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4189 id = isl_map_get_tuple_id(access, isl_dim_out);
4190 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4191 access = isl_map_apply_range(access, map);
4192 pma = isl_pw_multi_aff_from_map(access);
4193 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4194 stmt->u.c.index = expr;
4196 map = isl_map_range_map(isl_map_universe(space));
4197 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4198 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4199 local_access = isl_map_apply_range(local_access, map);
4200 pma = isl_pw_multi_aff_from_map(local_access);
4201 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4202 stmt->u.c.local_index = expr;
4204 stmt->u.c.array = gen->copy_group->array;
4205 array_index = stmt->u.c.array - gen->prog->array;
4206 stmt->u.c.local_array = &gen->kernel->array[array_index];
4207 stmt->type = ppcg_kernel_copy;
4209 id = isl_id_alloc(gen->ctx, NULL, stmt);
4210 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4211 return isl_ast_node_set_annotation(node, id);
4214 /* Given a schedule of the form
4216 * [S -> A] -> L
4218 * (with S the first shared_len dimensions of the computed schedule,
4219 * A the array and L the schedule correponding to the generated loops),
4220 * indicating where to copy the array elements that need to be copied,
4221 * construct code for performing the copying.
4223 * "group" is the array reference group that is being copied
4224 * "type" is either "read" or "write"
4225 * private is set if copying needs to be performed to/from registers
4227 * We first construct a mapping to a shifted tile of the array,
4229 * [S -> A] -> T(S,A) (1)
4231 * If private is set, then we also use this mapping as a schedule
4232 * (which is already thread-specific and will be completely unrolled).
4233 * Otherwise, we wrap/tile the range over the threads.
4234 * The result is
4236 * [S -> A] -> T'(S,A)
4238 * Combined with the given schedule, we have
4240 * [S -> A] -> [L -> T'(S,A)] (2)
4242 * From the shifted tile mapping, we construct a mapping
4244 * [S -> A] -> [A -> T(S,A)]
4246 * and apply it to the schedule (2), obtaining
4248 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4250 * Note that we can project out S because it is uniquely defined by L.
4252 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4253 __isl_take isl_map *sched,
4254 const char *type, struct gpu_array_ref_group *group,
4255 __isl_take isl_ast_build *build, int private)
4257 isl_space *space;
4258 isl_ast_node *tree;
4259 isl_map *schedule, *shift, *map;
4260 isl_set *set;
4261 isl_id_list *iterators;
4262 int n;
4264 shift = shift_access(group);
4266 schedule = isl_map_copy(shift);
4267 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4268 if (!private)
4269 schedule = tile_access_schedule(gen, schedule);
4271 n = isl_map_dim(schedule, isl_dim_out);
4272 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4273 set = add_bounded_parameters(set, gen->kernel->n_block,
4274 gen->kernel->block_dim, "t");
4276 schedule = isl_map_range_product(sched, schedule);
4278 space = isl_space_domain(isl_map_get_space(shift));
4279 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4280 map = isl_map_range_product(map, shift);
4282 schedule = isl_map_apply_domain(schedule, map);
4284 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4286 build = isl_ast_build_restrict(build, set);
4288 gen->copy_group = group;
4290 if (private) {
4291 space = isl_space_range(isl_map_get_space(schedule));
4292 space = isl_space_range(isl_space_unwrap(space));
4293 build = set_unroll(build, space, 0);
4295 iterators = generate_names(gen->ctx, n, "c");
4296 build = isl_ast_build_set_iterators(build, iterators);
4297 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4298 tree = isl_ast_build_ast_from_schedule(build,
4299 isl_union_map_from_map(schedule));
4300 isl_ast_build_free(build);
4302 return tree;
4305 /* Return code for reading into or writing from shared memory
4306 * the given array reference group.
4308 * If we are performing a read from global memory to shared memory and
4309 * if the array involved is not a scalar, then we copy
4310 * the entire tile to shared memory. This may result in some extra
4311 * elements getting copied, but it should lead to simpler code
4312 * (which means that fewer registers may be needed) and less divergence.
4314 * Otherwise, we only copy the elements that will be read or have been written
4315 * in the kernel.
4318 * The input "sched" is of the form.
4320 * type[S -> A] -> L
4322 * with S the first shared_len dimensions of the computed schedule,
4323 * A the array and L the schedule correponding to the generated loops.
4325 * We first drop "type",
4327 * [S -> A] -> L
4329 * If the above conditions are satisfied, we project out A,
4330 * resulting in
4332 * S -> L
4334 * and then introduce the group tile [S -> T], resulting in
4336 * [S -> T] -> L
4338 static __isl_give isl_ast_node *copy_group_shared_accesses(
4339 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4340 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4342 const char *type;
4343 int read;
4344 isl_union_map *access;
4346 type = isl_map_get_tuple_name(sched, isl_dim_in);
4347 read = !strcmp(type, "read");
4349 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4351 if (read && !gpu_array_is_scalar(group->array)) {
4352 isl_space *space;
4353 isl_map *map;
4355 space = isl_space_domain(isl_map_get_space(sched));
4356 space = isl_space_unwrap(space);
4357 map = isl_map_domain_map(isl_map_universe(space));
4358 sched = isl_map_apply_domain(sched, map);
4360 map = group_tile(group);
4361 map = isl_map_reverse(isl_map_domain_map(map));
4362 sched = isl_map_apply_domain(sched, map);
4365 return copy_access(gen, sched, type, group, build, 0);
4368 /* Return code for reading into or writing from private memory
4369 * the given array reference group.
4371 * Let S be the first shared_len dimensions of the computed schedule,
4372 * D the iteration domains, A the array and L the schedule correponding
4373 * to the generated loops.
4374 * "sched" is of the form
4376 * type[S -> A] -> L
4378 * where type is either "read" or "write".
4379 * We apply the privatization D -> S(t), with t the thread ids,
4380 * to the access relation D -> A to obtain the privatized access relation
4382 * S(t) -> A
4384 * We drop the type from "sched" and intersect with the privatized access
4385 * relation to obtain
4387 * [S(t) -> A] -> L
4389 static __isl_give isl_ast_node *copy_group_private_accesses(
4390 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4391 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4393 const char *type;
4394 int read;
4395 isl_union_map *priv;
4396 isl_union_map *access;
4397 isl_map *access_map;
4399 type = isl_map_get_tuple_name(sched, isl_dim_in);
4400 read = !strcmp(type, "read");
4402 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4403 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4404 priv);
4406 access = group_access_relation(group, read, !read);
4407 access = isl_union_map_apply_domain(access, priv);
4408 access_map = isl_map_from_union_map(access);
4410 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4411 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4413 return copy_access(gen, sched, type, group, build, 1);
4416 /* Return code for reading into or writing from shared or private memory.
4418 * "schedule" is of the form
4420 * type[S -> A] -> L
4422 * with S be the first shared_len dimensions of the computed schedule,
4423 * A the array and L the schedule correponding to the generated loops.
4424 * The array reference group is attached to "type".
4426 static __isl_give isl_ast_node *create_access_leaf(
4427 struct gpu_gen *gen, __isl_take isl_map *schedule,
4428 __isl_take isl_ast_build *build)
4430 struct gpu_array_ref_group *group;
4431 isl_id *id;
4433 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4434 group = isl_id_get_user(id);
4435 isl_id_free(id);
4437 if (group->private_tile)
4438 return copy_group_private_accesses(gen, group, schedule,
4439 build);
4440 else
4441 return copy_group_shared_accesses(gen, group, schedule,
4442 build);
4445 /* Create a domain node representing a synchronization.
4447 static __isl_give isl_ast_node *create_sync_leaf(
4448 struct gpu_gen *gen, __isl_take isl_map *schedule,
4449 __isl_take isl_ast_build *build)
4451 struct ppcg_kernel_stmt *stmt;
4452 isl_id *id;
4453 isl_space *space;
4454 isl_ast_node *node;
4455 isl_ast_expr *expr;
4457 isl_map_free(schedule);
4459 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4460 if (!stmt)
4461 return NULL;
4463 stmt->type = ppcg_kernel_sync;
4465 space = isl_ast_build_get_schedule_space(build);
4466 space = isl_space_from_domain(space);
4467 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4468 expr = isl_ast_build_call_from_pw_multi_aff(build,
4469 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4470 node = isl_ast_node_alloc_user(expr);
4471 isl_ast_build_free(build);
4473 id = isl_id_alloc(gen->ctx, NULL, stmt);
4474 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4475 return isl_ast_node_set_annotation(node, id);
4478 /* This function is called during the code generation at the point
4479 * where the schedule domain element is completely determined by
4480 * the generated code. The input schedule contains the original
4481 * statements as well as synchronization and copy "statements".
4482 * The latter are scheduled at different points than any of the original
4483 * statements, so they will only arrive here in isolation.
4485 * If the current schedule only refers to a single statement,
4486 * we check if it is a copy or synchronization statement and
4487 * call the appropriate functions.
4488 * Otherwise, we assume we are dealing with the original statements
4489 * and we call create_domain_leaf.
4491 static __isl_give isl_ast_node *create_kernel_leaf(
4492 __isl_take isl_ast_build *build, void *user)
4494 struct gpu_gen *gen = (struct gpu_gen *) user;
4495 isl_map *map;
4496 isl_union_map *schedule;
4497 const char *name;
4499 schedule = isl_ast_build_get_schedule(build);
4501 if (isl_union_map_n_map(schedule) != 1)
4502 return create_domain_leaf(schedule, build, user);
4504 map = isl_map_from_union_map(schedule);
4505 name = isl_map_get_tuple_name(map, isl_dim_in);
4506 if (!strcmp(name, "read") || !strcmp(name, "write"))
4507 return create_access_leaf(gen, map, build);
4508 if (!strcmp(name, "sync"))
4509 return create_sync_leaf(gen, map, build);
4511 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4514 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4515 * have value 0) and all even schedule dimensions as "unroll".
4517 * That is, the options look as follows
4519 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4520 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4522 * The even positions are used to be able to schedule copying blocks
4523 * and synchronization before or after each level of the shared memory
4524 * tile loops and we want to make sure that code for these is generated
4525 * separately (within each level).
4527 static __isl_give isl_ast_build *set_atomic_and_unroll(
4528 __isl_take isl_ast_build *build,
4529 __isl_take isl_space *space, int sched_len)
4531 isl_ctx *ctx;
4532 isl_map *map;
4533 isl_constraint *c;
4534 isl_union_map *opt;
4535 isl_local_space *ls;
4536 int i, n;
4538 ctx = isl_ast_build_get_ctx(build);
4540 space = isl_space_params(space);
4541 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4542 space = isl_space_from_domain(space);
4543 space = isl_space_add_dims(space, isl_dim_out, 2);
4544 map = isl_map_universe(isl_space_copy(space));
4545 for (i = 0; i < sched_len; i += 2)
4546 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4547 ls = isl_local_space_from_space(isl_map_get_space(map));
4548 c = isl_equality_alloc(ls);
4549 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4550 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4551 c = isl_constraint_set_constant_si(c, 1);
4552 map = isl_map_add_constraint(map, c);
4553 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4554 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4555 opt = isl_union_map_from_map(map);
4557 map = isl_map_universe(space);
4558 ls = isl_local_space_from_space(isl_map_get_space(map));
4559 c = isl_equality_alloc(ls);
4560 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4561 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4562 map = isl_map_add_constraint(map, c);
4563 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4564 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4565 opt = isl_union_map_add_map(opt, map);
4567 build = isl_ast_build_set_options(build, opt);
4569 return build;
4572 /* Return a map that maps a space of dimension gen->shared_len
4573 * to its last dimensions starting at gen->tile_first.
4574 * The range is of dimension
4576 * 2 * (gen->shared_len - gen->tile_first) + 1
4578 * The input dimensions are mapped to the odd dimensions in the output,
4579 * while the even dimensions (except 2*pos) are fixed to 0.
4580 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4581 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4582 * are mapped to the output. The remaining input dimensions are projected
4583 * out and the corresponding output dimensions are fixed to 0.
4585 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4586 __isl_take isl_space *space, int pos, int val)
4588 int i, n;
4589 isl_map *proj;
4591 space = isl_space_set_from_params(space);
4592 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4593 space = isl_space_map_from_set(space);
4594 proj = isl_map_identity(space);
4595 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4596 n = gen->shared_len - gen->tile_first;
4597 for (i = 0; i <= n; ++i) {
4598 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4599 if (i == pos)
4600 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4601 else
4602 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4605 if (pos < 0)
4606 return proj;
4608 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4609 gen->shared_len - (gen->tile_first + pos));
4610 for (i = pos; i < n; ++i)
4611 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4613 return proj;
4616 /* Given the AST context schedule "schedule" and the mapping from
4617 * domains to the shared tile loops "shared_sched", add a schedule
4618 * for a synchronization operation at position "val" of loop level "pos".
4620 * schedule is of the form
4622 * D -> L
4624 * (with D the iteration domains and L the already generated loops),
4625 * while shared_sched is of the form
4627 * D -> S
4629 * We combine them into
4631 * L -> S
4633 * apply a mapping
4635 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4637 * and use the result as a schedule for "sync".
4639 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4640 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4641 __isl_keep isl_union_map *shared_sched, int pos, int val)
4643 isl_space *space;
4644 isl_map *proj, *map;
4646 shared_sched = isl_union_map_copy(shared_sched);
4647 schedule = isl_union_map_copy(schedule);
4649 space = isl_union_map_get_space(shared_sched);
4650 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4651 map = isl_map_from_union_map(schedule);
4653 proj = insert_even(gen, space, pos, val);
4654 map = isl_map_apply_range(map, proj);
4655 map = isl_map_from_range(isl_map_wrap(map));
4656 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4658 res = isl_union_map_add_map(res, map);
4660 return res;
4663 /* Given a set of wrapped references "ref", return the corresponding
4664 * access relations based on the tagged access relations "tagged".
4666 * The elements of "ref" are of the form
4668 * [D -> R]
4670 * with D an iteration domains and R a reference.
4671 * The elements of "tagged" are of the form
4673 * [D -> R] -> A
4675 * with A an array.
4677 * Extend "tagged" to include the iteration domain in the range, i.e.,
4679 * [D -> R] -> [D -> A]
4681 * apply the result to "ref" and then unwrap the resulting set
4682 * to obtain relations of the form
4684 * D -> A
4686 static __isl_give isl_union_map *wrapped_reference_to_access(
4687 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4689 isl_union_map *tag2access;
4691 tag2access = isl_union_map_copy(tagged);
4692 tag2access = isl_union_map_universe(tag2access);
4693 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4694 tag2access = isl_union_map_domain_map(tag2access);
4695 tag2access = isl_union_map_range_product(tag2access, tagged);
4697 ref = isl_union_set_coalesce(ref);
4698 ref = isl_union_set_apply(ref, tag2access);
4700 return isl_union_set_unwrap(ref);
4703 /* Given an access relation "access" from "group", remove those reads
4704 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4705 * communicate data within the same iteration of the last_shared dimension
4706 * of the group.
4708 * If the access is a read then it is necessarily an element of
4710 * live_in union (range flow)
4712 * where live_in and flow may be overapproximations.
4713 * If the access is a write then it is necessarily an element of
4715 * live_out union (domain flow)
4717 * In both cases, the access relation is also a subset of
4718 * the group access relation.
4720 * Essentially, we compute the intersection of "access" with either
4722 * live_in union (range non-local-flow)
4724 * or
4726 * live_out union (domain non-local-flow)
4728 * We first construct a relation "local"
4730 * [[D -> R] -> [D' -> R']]
4732 * of pairs of domain iterations accessing the reference group
4733 * and references in the group that are scheduled to the same iteration
4734 * of the last_shared dimension.
4736 * If this relation does not intersect the dataflow dependences,
4737 * then there is nothing we can possibly remove and we simply
4738 * return the input.
4740 * Otherwise, we remove the "local" dataflow dependences from
4741 * the set of all dataflow dependences.
4742 * Note that if the potential dataflow dependences are an overapproximation
4743 * of the actual dataflow dependences, then the result remains an
4744 * overapproximation of the non-local dataflow dependences.
4745 * Copying to/from global memory is only needed for the references
4746 * in the domain/range of the result or for accesses that are live out/in
4747 * for the entire scop.
4749 * We therefore map the domain/range of the "external" relation
4750 * to the corresponding access relation and take the union with
4751 * the live out/in relation.
4753 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4754 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4755 int read)
4757 int empty;
4758 isl_union_map *tagger;
4759 isl_union_set *domain;
4760 isl_space *space;
4761 isl_union_map *sched, *local, *tagged, *external;
4762 isl_union_set *tag_set;
4763 isl_map *proj;
4765 if (isl_union_map_is_empty(access))
4766 return access;
4768 tagged = group_tagged_access_relation(group);
4770 sched = isl_union_map_copy(gen->sched);
4772 space = isl_union_map_get_space(sched);
4773 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4774 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4776 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4777 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4778 tagger = isl_union_map_intersect_range(tagger, domain);
4779 sched = isl_union_map_apply_domain(sched, tagger);
4781 local = isl_union_map_apply_range(sched,
4782 isl_union_map_reverse(isl_union_map_copy(sched)));
4783 local = isl_union_map_intersect(local,
4784 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4786 empty = isl_union_map_is_empty(local);
4787 if (empty < 0 || empty) {
4788 isl_union_map_free(tagged);
4789 isl_union_map_free(local);
4790 if (empty < 0)
4791 return isl_union_map_free(access);
4792 return access;
4795 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4796 external = isl_union_map_intersect_params(external,
4797 isl_set_copy(gen->prog->scop->context));
4798 external = isl_union_map_subtract(external, local);
4800 if (read) {
4801 tag_set = isl_union_map_range(external);
4802 external = wrapped_reference_to_access(tag_set, tagged);
4803 external = isl_union_map_union(external,
4804 isl_union_map_copy(gen->prog->scop->live_in));
4805 } else {
4806 tag_set = isl_union_map_domain(external);
4807 external = wrapped_reference_to_access(tag_set, tagged);
4808 external = isl_union_map_union(external,
4809 isl_union_map_copy(gen->prog->scop->live_out));
4812 access = isl_union_map_intersect(access, external);
4814 return access;
4817 /* Given the AST context schedule "schedule" and the mapping from
4818 * domains to the shared tile loops "shared_sched", add a schedule
4819 * for copying an array reference group to/from shared/private memory.
4820 * "read" is set if data should be copied from global memory
4821 * to shared/private memory.
4822 * "k" represents the current group
4823 * "s" is the total number of groups
4825 * We schedule an operation before or after the innermost loop
4826 * of "shared_sched" that affects the tile of the array reference group.
4828 * schedule is of the form
4830 * D -> L
4832 * (with D the iteration domains and L the already generated loops),
4833 * while shared_sched is of the form
4835 * D -> S
4837 * We first compute the access relation for the reference group
4839 * D -> A
4841 * and remove from this access relation those reads or writes
4842 * that only needed to communicate data within the same iteration
4843 * of the last_shared dimension of the group.
4844 * We then combine what is left with shared_sched into
4846 * D -> [S -> A]
4848 * If this results in an empty relation, no copying needs to be performed
4849 * at this point.
4850 * Otherwise, we invert the relation and combine it with "schedule" into
4852 * [S -> A] -> L
4854 * The actual additional piece of the schedule is obtained from combining
4856 * [S -> A] -> S
4858 * with a mapping
4860 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4862 * The position of "val" corresponds to the innermost loop that affects
4863 * the tile and the value indicates where the copying is scheduled
4864 * with respect to the actual kernel code (at value 0).
4865 * Reads are schedule before the code, writes to global memory from
4866 * private memory are scheduled at values 1 to s, writes to global
4867 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4869 * If we are scheduling a read from global memory to shared memory,
4870 * we insert a synchronization before the kernel code (at the innermost
4871 * level).
4872 * If we are scheduling a write to global memory, then we add
4873 * a synchronization after all writes (at value 2 *s + 2).
4874 * However, there is no need for a synchronization after the outermost loop.
4875 * A write to global memory from private memory at the innermost level
4876 * does not require a synchronization, because it is covered by
4877 * the synchronization after the kernel inserted by body_schedule.
4879 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4880 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4881 __isl_keep isl_union_map *shared_sched,
4882 struct gpu_array_ref_group *group, int read, int k, int s)
4884 int n;
4885 int pos, val;
4886 isl_space *space;
4887 isl_union_map *access;
4888 isl_map *map, *proj, *access_map;
4889 isl_id *id;
4891 access = group_access_relation(group, read, !read);
4892 access = remove_local_accesses(gen, group, access, read);
4893 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4894 access);
4896 if (isl_union_map_is_empty(access)) {
4897 isl_union_map_free(access);
4898 return res;
4901 access = isl_union_map_reverse(access);
4902 access = isl_union_map_apply_range(access,
4903 isl_union_map_copy(schedule));
4904 access_map = isl_map_from_union_map(access);
4906 space = isl_space_copy(group->array->space);
4907 space = isl_space_from_range(space);
4908 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4909 map = isl_map_domain_map(isl_map_universe(space));
4911 space = isl_union_map_get_space(schedule);
4912 pos = group->last_shared + 1 - gen->tile_first;
4913 assert(pos >= 0);
4914 if (read)
4915 val = -2 - k;
4916 else if (group->private_tile)
4917 val = 1 + k;
4918 else
4919 val = 1 + s + 1 + k;
4920 proj = insert_even(gen, space, pos, val);
4921 map = isl_map_apply_range(map, proj);
4923 access_map = isl_map_range_product(access_map, map);
4925 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4926 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4928 res = isl_union_map_add_map(res, access_map);
4930 n = gen->shared_len - gen->tile_first;
4931 if (read) {
4932 if (!group->private_tile)
4933 res = add_sync_schedule(gen, res, schedule,
4934 shared_sched, n, -1);
4935 } else {
4936 if (pos == 0)
4937 return res;
4938 if (pos == n && group->private_tile)
4939 return res;
4940 res = add_sync_schedule(gen, res, schedule, shared_sched,
4941 pos, 2 * s + 2);
4944 return res;
4947 /* Return a schedule for the shared tile loops based on the current
4948 * AST context schedule.
4950 * We create a "shared_sched" that maps the domains to the first
4951 * shared_len dimensions of the computed schedule, project out the
4952 * first tile_first dimensions (as these are already covered by
4953 * the host code) and insert "statement-level" dimensions at even
4954 * positions so that we can schedule copy blocks and synchronization
4955 * before/after each level.
4957 * In particular, copy blocks are inserted inside the innermost
4958 * level that affect the tile. For the copying to global memory,
4959 * those from private memory are scheduled before those from shared
4960 * memory such that synchronization can be inserted between the two
4961 * at the innermost level.
4962 * Synchronization is inserted at the innermost level before the
4963 * actual kernel code if there is any copying from global memory
4964 * to shared memory. It is inserted unconditionally at the innermost
4965 * level after the actual kernel code and the copying to global memory
4966 * from private memory (if any). Finally, it is inserted after
4967 * any copying to global memory, except at the outermost level
4968 * and at the innermost level if there is no copying from shared
4969 * memory. The copying from private memory is covered by the unconditional
4970 * synchronization at the innermost level.
4972 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4973 __isl_take isl_union_map *schedule)
4975 isl_space *space;
4976 isl_union_map *res;
4977 isl_union_map *shared_sched;
4978 isl_union_map *sched;
4979 isl_map *proj, *map;
4980 int i, j, k, s;
4982 shared_sched = isl_union_map_copy(gen->tiled_sched);
4983 proj = projection(isl_union_map_get_space(shared_sched),
4984 gen->tiled_len, gen->shared_len);
4985 shared_sched = isl_union_map_apply_range(shared_sched,
4986 isl_union_map_from_map(proj));
4987 space = isl_union_map_get_space(shared_sched);
4988 proj = insert_even(gen, space, -1, 0);
4989 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4990 isl_union_map_from_map(proj));
4992 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4994 s = 0;
4995 for (i = 0; i < gen->prog->n_array; ++i)
4996 s += gen->prog->array[i].n_group;
4998 k = 0;
4999 for (i = 0; i < gen->prog->n_array; ++i) {
5000 struct gpu_array_info *array = &gen->prog->array[i];
5002 for (j = 0; j < array->n_group; ++j) {
5003 struct gpu_array_ref_group *group;
5005 group = array->groups[j];
5006 if (!group->private_tile && !group->shared_tile)
5007 continue;
5008 res = add_group_schedule(gen, res, schedule,
5009 shared_sched, group, 0, k, s);
5010 res = add_group_schedule(gen, res, schedule,
5011 shared_sched, group, 1, k, s);
5012 ++k;
5016 res = add_sync_schedule(gen, res, schedule, shared_sched,
5017 gen->shared_len - gen->tile_first, 1 + s);
5019 isl_union_map_free(shared_sched);
5020 isl_union_map_free(schedule);
5022 return res;
5025 /* Generate code for "kernel" in the given "context".
5027 * We first generate code for the shared tile loops (T1T, T1P and T2)
5028 * in a context that includes the block ids.
5029 * Within each iteration of these loops an additional code generation
5030 * is performed (within create_kernel_leaf) for the rest of the schedule
5031 * in a context that includes the thread ids.
5033 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
5034 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
5035 __isl_keep isl_multi_pw_aff *grid_size)
5037 isl_space *space;
5038 isl_set *set;
5039 isl_id_list *iterators;
5040 isl_union_map *schedule;
5041 isl_ast_node *tree;
5042 int sched_len;
5044 schedule = isl_ast_build_get_schedule(build);
5046 build = isl_ast_build_copy(build);
5047 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5048 space = isl_ast_build_get_schedule_space(build);
5049 set = isl_set_universe(isl_space_copy(space));
5050 set = add_bounded_parameters_dynamic(set, grid_size, "b");
5051 build = isl_ast_build_restrict(build, set);
5053 schedule = body_schedule(gen, schedule);
5055 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5057 build = set_atomic_and_unroll(build, space, sched_len);
5058 iterators = generate_names(gen->ctx, sched_len, "g");
5059 build = isl_ast_build_set_iterators(build, iterators);
5060 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5061 tree = isl_ast_build_ast_from_schedule(build, schedule);
5062 isl_ast_build_free(build);
5064 return tree;
5067 /* Attach "id" to the given node.
5069 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5070 __isl_keep isl_ast_build *build, void *user)
5072 isl_id *id = user;
5074 node = isl_ast_node_set_annotation(node, id);
5076 return node;
5079 /* Construct an AST node for performing a kernel launch and attach
5080 * the information about the kernel to that node.
5082 * The kernel AST has been constructed in the context of the range
5083 * of "schedule". In particular, the grid size has been computed
5084 * in the context. We therefore still need to make sure that these
5085 * constraints are expressed in the code. We do this by creating a schedule
5087 * kernel[] -> [S -> []]
5089 * where S is the schedule domain, i.e., the range of "schedule".
5090 * The AST generation will then create a single call surrounded by
5091 * all the condition in "S" that have not been expressed yet.
5093 * The kernel information is attached to this node in attach_id.
5095 static __isl_give isl_ast_node *construct_launch(
5096 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5097 __isl_take struct ppcg_kernel *kernel)
5099 isl_id *id;
5100 isl_ctx *ctx;
5101 isl_union_set *domain;
5102 isl_set *set;
5103 isl_map *map;
5104 isl_ast_node *node;
5106 ctx = isl_ast_build_get_ctx(build);
5108 id = isl_id_alloc(ctx, NULL, kernel);
5109 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5111 domain = isl_union_map_range(schedule);
5112 set = isl_set_from_union_set(domain);
5113 map = isl_map_from_domain(set);
5114 map = isl_map_from_range(isl_map_wrap(map));
5115 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5116 schedule = isl_union_map_from_map(map);
5118 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5119 node = isl_ast_build_ast_from_schedule(build, schedule);
5120 isl_ast_build_free(build);
5122 return node;
5125 /* This function is called for each leaf in the AST of the host code.
5126 * We first specialize the schedule to the site of the leaf, compute
5127 * the size of shared memory and then construct the body of the host code
5128 * and the associated kernel.
5130 * The necessary information for printing the kernel launch is
5131 * stored in a struct ppcg_kernel and attached to the leaf node
5132 * created to represent the launch.
5134 static __isl_give isl_ast_node *create_host_leaf(
5135 __isl_take isl_ast_build *build, void *user)
5137 struct gpu_gen *gen = (struct gpu_gen *) user;
5138 isl_id *id;
5139 isl_ast_node *node;
5140 struct ppcg_kernel *kernel;
5141 isl_set *host_domain;
5142 isl_union_map *schedule;
5143 isl_union_map *local_sched;
5144 isl_union_map *access;
5145 isl_union_set *domain;
5146 int i;
5148 schedule = isl_ast_build_get_schedule(build);
5150 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5151 read_sizes(gen);
5153 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5155 local_sched = isl_union_map_copy(gen->sched);
5156 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5157 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5158 isl_union_map_copy(gen->prog->may_write));
5159 access = isl_union_map_apply_domain(access,
5160 isl_union_map_copy(local_sched));
5162 gen->tiled_sched = tile_schedule(gen, local_sched);
5163 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5164 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5166 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5167 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5168 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5170 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5171 if (!kernel)
5172 goto error;
5174 kernel->id = gen->kernel_id++;
5175 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5176 kernel->grid_size = extract_grid_size(gen, kernel);
5177 extract_block_size(gen, kernel);
5178 kernel->arrays = isl_union_map_range(access);
5179 kernel->arrays = isl_union_set_apply(kernel->arrays,
5180 isl_union_map_copy(gen->prog->to_outer));
5181 kernel->space = isl_ast_build_get_schedule_space(build);
5183 gen->private_access = NULL;
5184 compute_shared_sched(gen);
5185 gen->privatization = compute_privatization(gen);
5186 check_scalar_live_ranges(gen);
5187 if (group_references(gen) < 0)
5188 schedule = isl_union_map_free(schedule);
5189 compute_private_access(gen);
5190 host_domain = isl_set_from_union_set(isl_union_map_range(
5191 isl_union_map_copy(schedule)));
5192 localize_bounds(gen, kernel, host_domain);
5194 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5195 check_shared_memory_bound(gen);
5196 compute_group_tilings(gen);
5198 kernel->tree = generate_kernel(gen, build, host_domain,
5199 kernel->grid_size);
5200 create_kernel_vars(gen, kernel);
5202 free_local_array_info(gen);
5203 isl_map_free(gen->privatization);
5204 isl_union_map_free(gen->private_access);
5205 isl_union_map_free(gen->local_sched);
5206 isl_union_map_free(gen->tiled_sched);
5207 isl_union_map_free(gen->shared_sched);
5208 isl_union_map_free(gen->shared_proj);
5209 isl_set_free(host_domain);
5210 free(gen->tile_size);
5212 node = construct_launch(build, schedule, kernel);
5214 return node;
5215 error:
5216 isl_union_map_free(schedule);
5217 return NULL;
5220 /* Use isl to generate code for the outer gen->tile_first loops
5221 * of the global schedule in gen->sched, resulting in the host code.
5222 * Within each iteration of this partial schedule, i.e., for each kernel
5223 * launch, create_host_leaf takes care of generating the kernel code.
5225 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5227 isl_ast_build *build;
5228 isl_ast_node *tree;
5229 isl_union_map *sched;
5230 isl_map *proj;
5231 isl_id_list *iterators;
5233 sched = isl_union_map_copy(gen->sched);
5234 proj = projection(isl_union_map_get_space(sched),
5235 gen->untiled_len, gen->tile_first);
5236 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5238 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5239 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5240 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5241 build = isl_ast_build_set_iterators(build, iterators);
5242 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5243 tree = isl_ast_build_ast_from_schedule(build, sched);
5244 isl_ast_build_free(build);
5246 return tree;
5249 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5251 if (!str)
5252 return NULL;
5253 return isl_union_map_read_from_str(ctx, str);
5256 /* Information about the outermost tilable bands in the forest of bands.
5258 * tile_len and n_parallel are only sets on band_info structures
5259 * that correspond to outermost bands. For other bands (in particular,
5260 * ancestors of the outermost bands), n_parallal is set to 0.
5262 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5264 * tile_first is the number of schedule dimensions in prefix.
5266 * suffix is the schedule of the outermost tilable bands and their descendants.
5268 struct band_info {
5269 struct gpu_gen *gen;
5270 int tile_first;
5271 int tile_len;
5272 int n_parallel;
5273 isl_union_map *prefix;
5274 isl_union_map *suffix;
5277 /* Set tile_len and n_parallel of the statement to that of
5278 * their outermost band, recorded in the band_info.
5280 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5282 struct band_info *info = user;
5283 struct gpu_stmt *stmt;
5284 isl_id *id;
5286 id = isl_map_get_tuple_id(map, isl_dim_in);
5287 stmt = find_stmt(info->gen->prog, id);
5288 isl_id_free(id);
5290 stmt->tile_len = info->tile_len;
5291 stmt->n_parallel = info->n_parallel;
5293 isl_map_free(map);
5295 return 0;
5298 static void list_select_outer_band(struct gpu_gen *gen,
5299 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5301 /* Check if this band has any parallel loops. If so, take it as
5302 * the outermost tilable band. If not, continue looking for the
5303 * outermost tilable band in the children of the current band.
5305 static void band_select_outer_band(struct gpu_gen *gen,
5306 __isl_take isl_band *band, int pos, struct band_info *info)
5308 int n = isl_band_n_member(band);
5309 int n_parallel;
5311 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5312 if (!isl_band_member_is_coincident(band, n_parallel))
5313 break;
5315 info->n_parallel = n_parallel;
5316 if (n_parallel) {
5317 gen->any_parallelism = 1;
5318 info->gen = gen;
5319 info->tile_first = pos;
5320 info->tile_len = n;
5321 info->prefix = isl_band_get_prefix_schedule(band);
5322 info->suffix = isl_union_map_flat_range_product(
5323 isl_band_get_partial_schedule(band),
5324 isl_band_get_suffix_schedule(band));
5325 isl_union_map_foreach_map(info->prefix,
5326 &set_stmt_tile_len, info);
5327 } else if (isl_band_has_children(band)) {
5328 isl_band_list *children;
5329 children = isl_band_get_children(band);
5330 list_select_outer_band(gen, children, pos + n, info);
5331 } else {
5332 info->gen = gen;
5333 info->tile_first = pos + n;
5334 info->tile_len = 0;
5335 info->prefix = isl_union_map_flat_range_product(
5336 isl_band_get_prefix_schedule(band),
5337 isl_band_get_partial_schedule(band));
5338 info->suffix = isl_band_get_suffix_schedule(band);
5339 isl_union_map_foreach_map(info->prefix,
5340 &set_stmt_tile_len, info);
5343 isl_band_free(band);
5346 /* Comparison function that returns a non-zero value for band_infos
5347 * with different tile_len fields or different n_parallel fields.
5349 static int cmp_band(const void *p1, const void *p2)
5351 const struct band_info *info1 = p1;
5352 const struct band_info *info2 = p2;
5354 if (info1->tile_len != info2->tile_len)
5355 return info1->tile_len - info2->tile_len;
5357 return info1->n_parallel - info2->n_parallel;
5360 /* Extend "umap" with coordinates with fixed value "val"
5361 * to a total length of "dst_len", assuming the original dimension is "src_len".
5363 static __isl_give isl_union_map *extend_range(
5364 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5366 isl_space *dim;
5367 isl_map *map;
5368 int i;
5370 dim = isl_union_map_get_space(umap);
5371 map = isl_map_reverse(projection(dim, dst_len, src_len));
5372 for (i = src_len; i < dst_len; ++i)
5373 map = isl_map_fix_si(map, isl_dim_out, i, val);
5375 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5377 return umap;
5380 /* Group bands with the same values for tile_len and n_parallel.
5381 * The prefix schedule is then extended with a fixed coordinate that
5382 * is different for each such group.
5383 * Note that the actual values for this coordinate are not important.
5384 * The bands have already been effectively separated at a higher level
5385 * or they are independent and may be executed in parallel.
5386 * The list of band_info has been sorted before this functions is called.
5388 static void separate_bands(struct band_info *info, int n)
5390 int i;
5391 int j = 0;
5393 for (i = 0; i < n; ++i) {
5394 int l = info[i].tile_first;
5396 if (i &&
5397 (info[i].tile_len != info[i - 1].tile_len ||
5398 info[i].n_parallel != info[i - 1].n_parallel))
5399 j++;
5401 info[i].prefix = extend_range(info[i].prefix,
5402 l, l + 1, j);
5403 info[i].tile_first = l + 1;
5407 /* Select the outermost bands in the elements of the list, align
5408 * their prefix schedules, separate bands with different values
5409 * for tile_len and/or n_parallel and then combine the resulting
5410 * prefix and suffix schedules into a single pair of prefix and
5411 * suffix schedules for the entire list.
5413 static void list_select_outer_band(struct gpu_gen *gen,
5414 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5416 isl_band *band;
5417 int i;
5418 int n = isl_band_list_n_band(list);
5419 isl_ctx *ctx = isl_band_list_get_ctx(list);
5420 struct band_info *info;
5421 int max_tile_first;
5422 isl_union_map *prefix;
5423 isl_union_map *suffix;
5425 assert(n >= 1);
5426 info = isl_calloc_array(ctx, struct band_info, n);
5427 assert(info);
5429 max_tile_first = 0;
5430 for (i = 0; i < n; ++i) {
5431 band = isl_band_list_get_band(list, i);
5432 band_select_outer_band(gen, band, pos, &info[i]);
5433 if (info[i].tile_first > max_tile_first)
5434 max_tile_first = info[i].tile_first;
5437 for (i = 0; i < n; ++i) {
5438 if (info[i].tile_first == max_tile_first)
5439 continue;
5440 info[i].prefix = extend_range(info[i].prefix,
5441 info[i].tile_first, max_tile_first, 0);
5442 info[i].tile_first = max_tile_first;
5445 qsort(info, n, sizeof(struct band_info), &cmp_band);
5447 for (i = 0; i < n - 1; ++i)
5448 if (info[i].tile_len != info[i + 1].tile_len ||
5449 info[i].n_parallel != info[i + 1].n_parallel)
5450 break;
5452 if (i < n -1)
5453 separate_bands(info, n);
5455 prefix = info[0].prefix;
5456 suffix = info[0].suffix;
5458 for (i = 1; i < n; ++i) {
5459 prefix = isl_union_map_union(prefix, info[i].prefix);
5460 suffix = isl_union_map_union(suffix, info[i].suffix);
5463 list_info->tile_first = info[0].tile_first;
5464 list_info->tile_len = -1;
5465 list_info->prefix = prefix;
5466 list_info->suffix = suffix;
5468 isl_band_list_free(list);
5469 free(info);
5472 /* Select the outermost tilable band that (by construction)
5473 * has at least one parallel loop.
5474 * The starting position of the aligned band is stored in the pair
5475 * gen->tile_first.
5476 * The sizes and number of parallel loops may be different in different
5477 * parts of the band forest and are therefore stored in the gpu_stmts.
5479 * Return the complete schedule, with the tilable bands aligned
5480 * at gen->tile_first and padded with zero, if needed.
5482 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5483 __isl_keep isl_schedule *schedule)
5485 isl_band_list *list;
5486 struct band_info info;
5488 gen->n_parallel = 0;
5489 gen->tile_len = -1;
5491 list = isl_schedule_get_band_forest(schedule);
5493 if (isl_band_list_n_band(list) == 0) {
5494 isl_band_list_free(list);
5495 return isl_schedule_get_map(schedule);
5498 list_select_outer_band(gen, list, 0, &info);
5500 gen->tile_first = info.tile_first;
5501 info.suffix = align_range(info.suffix);
5503 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5506 /* Set gen->untiled_len to the number of scheduling dimensions
5507 * for the schedule of the first domain.
5508 * We assume here that this number is the same for all domains.
5510 static int set_untiled_len(__isl_take isl_map *map, void *user)
5512 unsigned *untiled_len = user;
5514 *untiled_len = isl_map_dim(map, isl_dim_out);
5516 isl_map_free(map);
5517 return -1;
5520 /* Compute an appropriate schedule based on the accesses in
5521 * gen->read and gen->write.
5523 * We use the dependences in gen->prog->scop to compute
5524 * a schedule that has a parallel loop in each tilable band.
5525 * Finally, we select the outermost tilable band.
5527 * If live range reordering is allowed, then we need to make sure
5528 * that live ranges on arrays are not run in parallel since doing
5529 * so would require array expansion. We therefore add the array
5530 * order dependences to the coincidence dependences. Non-zero array
5531 * order dependences will then prevent a schedule dimension from being
5532 * considered parallel.
5533 * Live ranges derived from scalars are allowed to be run in parallel
5534 * since we force the scalars to be mapped to private memory in
5535 * check_scalar_live_ranges.
5536 * If live range reordering is allowed, then the false dependences
5537 * are not added to the validity constraints as that would prevent
5538 * reordering. Instead, the external false dependences that enforce that reads
5539 * from potentially live-in data precede any later write and
5540 * that writes of potentially live-out data follow any other earlier write
5541 * are added to the validity and the coincidence constraints.
5542 * The false dependences are still added to the proximity constraints
5543 * for consistency with the case where live range reordering is not allowed.
5544 * The coincidence constraints then consist of flow dependences,
5545 * exernal false dependences and array order dependences.
5546 * The independences can be filtered out from the first two sets.
5547 * They have already been filtered out from the array order dependences
5548 * on a per array basis in collect_order_dependences.
5549 * There is no need for a per array handling of the other two sets
5550 * as there should be no flow or external false dependence on local
5551 * variables that can be filtered out.
5553 static void compute_schedule(struct gpu_gen *gen)
5555 isl_union_set *domain;
5556 isl_union_map *dep_raw, *dep;
5557 isl_union_map *validity, *proximity, *coincidence;
5558 isl_union_map *sched;
5559 isl_schedule_constraints *sc;
5560 isl_schedule *schedule;
5562 domain = isl_union_set_copy(gen->prog->scop->domain);
5563 domain = isl_union_set_intersect_params(domain,
5564 isl_set_copy(gen->prog->scop->context));
5565 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5566 if (gen->options->live_range_reordering) {
5567 sc = isl_schedule_constraints_set_conditional_validity(sc,
5568 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5569 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5570 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5571 validity = isl_union_map_copy(proximity);
5572 validity = isl_union_map_union(validity,
5573 isl_union_map_copy(gen->prog->scop->dep_external));
5574 proximity = isl_union_map_union(proximity,
5575 isl_union_map_copy(gen->prog->scop->dep_false));
5576 coincidence = isl_union_map_copy(validity);
5577 coincidence = isl_union_map_subtract(coincidence,
5578 isl_union_map_copy(gen->prog->scop->independence));
5579 coincidence = isl_union_map_union(coincidence,
5580 isl_union_map_copy(gen->prog->array_order));
5581 } else {
5582 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5583 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5584 dep = isl_union_map_union(dep, dep_raw);
5585 dep = isl_union_map_coalesce(dep);
5586 proximity = isl_union_map_copy(dep);
5587 coincidence = isl_union_map_copy(dep);
5588 validity = dep;
5590 sc = isl_schedule_constraints_set_validity(sc, validity);
5591 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5592 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5594 if (gen->options->debug->dump_schedule_constraints)
5595 isl_schedule_constraints_dump(sc);
5596 schedule = isl_schedule_constraints_compute_schedule(sc);
5597 if (gen->options->debug->dump_schedule)
5598 isl_schedule_dump(schedule);
5600 sched = select_outer_tilable_band(gen, schedule);
5602 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5603 sched = isl_union_map_intersect_domain(sched, domain);
5604 gen->sched = sched;
5606 isl_schedule_free(schedule);
5609 /* Compute the sets of outer array elements that need to be copied in and out.
5611 * In particular, for each array that is possibly written anywhere in
5612 * gen->prog and that is visible outside the corresponding scop,
5613 * we copy out its entire extent.
5615 * Any array elements that is read without first being written needs
5616 * to be copied in. Furthermore, if there are any array elements that
5617 * are copied out, but that may not be written inside gen->prog, then
5618 * they also need to be copied in to ensure that the value after execution
5619 * is the same as the value before execution.
5620 * In case the array elements are structures, we need to take into
5621 * account that all members of the structures need to be written
5622 * by gen->prog before we can avoid copying the data structure in.
5624 * While computing the set of array elements that are copied out but
5625 * not necessarily written, we intersect both sets with the context.
5626 * This helps in those cases where the arrays are declared with a fixed size,
5627 * while the accesses are parametric and the context assigns a fixed value
5628 * to the parameters.
5630 * If an element from a local array is read without first being written,
5631 * then there is no point in copying it in since it cannot have been
5632 * written prior to the scop. Warn about the uninitialized read instead.
5634 static void compute_copy_in_and_out(struct gpu_gen *gen)
5636 int i;
5637 isl_union_set *local;
5638 isl_union_set *may_write, *must_write;
5639 isl_union_set *copy_in, *copy_out;
5640 isl_union_set *not_written;
5641 isl_union_map *uninitialized;
5642 isl_union_map *local_uninitialized;
5644 must_write = isl_union_map_range(
5645 isl_union_map_copy(gen->prog->must_write));
5646 must_write = isl_union_set_intersect_params(must_write,
5647 isl_set_copy(gen->prog->context));
5648 may_write = isl_union_map_range(
5649 isl_union_map_copy(gen->prog->may_write));
5650 may_write = isl_union_set_intersect_params(may_write,
5651 isl_set_copy(gen->prog->context));
5652 may_write = isl_union_set_universe(may_write);
5653 may_write = isl_union_set_apply(may_write,
5654 isl_union_map_copy(gen->prog->to_outer));
5655 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5656 local = isl_union_set_copy(copy_out);
5658 for (i = 0; i < gen->prog->n_array; ++i) {
5659 isl_space *space;
5660 isl_set *write_i;
5661 int empty;
5663 space = isl_space_copy(gen->prog->array[i].space);
5665 if (gen->prog->array[i].local) {
5666 isl_set *set;
5668 set = isl_set_universe(space);
5669 local = isl_union_set_add_set(local, set);
5670 continue;
5673 write_i = isl_union_set_extract_set(may_write, space);
5674 empty = isl_set_fast_is_empty(write_i);
5675 isl_set_free(write_i);
5676 if (empty)
5677 continue;
5679 write_i = isl_set_copy(gen->prog->array[i].extent);
5680 copy_out = isl_union_set_add_set(copy_out, write_i);
5682 isl_union_set_free(may_write);
5684 copy_out = isl_union_set_intersect_params(copy_out,
5685 isl_set_copy(gen->prog->context));
5687 gen->prog->copy_out = isl_union_set_copy(copy_out);
5689 copy_out = isl_union_set_apply(copy_out,
5690 isl_union_map_copy(gen->prog->to_inner));
5691 not_written = isl_union_set_subtract(copy_out, must_write);
5693 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5694 local_uninitialized = isl_union_map_copy(uninitialized);
5696 local = isl_union_set_apply(local,
5697 isl_union_map_copy(gen->prog->to_inner));
5698 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5699 local);
5700 if (!isl_union_map_is_empty(local_uninitialized)) {
5701 fprintf(stderr,
5702 "possibly uninitialized reads (not copied in):\n");
5703 isl_union_map_dump(local_uninitialized);
5705 uninitialized = isl_union_map_subtract(uninitialized,
5706 local_uninitialized);
5707 copy_in = isl_union_map_range(uninitialized);
5708 copy_in = isl_union_set_union(copy_in, not_written);
5709 copy_in = isl_union_set_apply(copy_in,
5710 isl_union_map_copy(gen->prog->to_outer));
5712 gen->prog->copy_in = copy_in;
5715 /* Internal data structure for extract_access.
5716 * "next_access" points to the end of a linked list that is extended
5717 * by extract_access.
5718 * "single_expression" is set if the access expressions belong to
5719 * an expression statement (i.e., a statement without internal control).
5721 struct ppcg_extract_access_data {
5722 struct gpu_stmt_access **next_access;
5723 int single_expression;
5726 /* Extract a gpu_stmt_access from "expr", append it to the list
5727 * that ends in *data->next_access and update the end of the list.
5728 * If the access expression performs a write, then it is considered
5729 * exact only if it appears in a single expression statement and
5730 * if its may access relation is equal to its must access relation.
5732 static int extract_access(__isl_keep pet_expr *expr, void *user)
5734 struct ppcg_extract_access_data *data = user;
5735 isl_map *may;
5736 struct gpu_stmt_access *access;
5737 isl_ctx *ctx;
5739 may = pet_expr_access_get_may_access(expr);
5740 ctx = isl_map_get_ctx(may);
5741 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5742 assert(access);
5743 access->next = NULL;
5744 access->read = pet_expr_access_is_read(expr);
5745 access->write = pet_expr_access_is_write(expr);
5746 access->access = may;
5747 access->tagged_access = pet_expr_access_get_tagged_may_access(expr);
5748 if (!access->write) {
5749 access->exact_write = 1;
5750 } else if (!data->single_expression) {
5751 access->exact_write = 0;
5752 } else {
5753 isl_map *must;
5754 must = pet_expr_access_get_must_access(expr);
5755 access->exact_write = isl_map_is_equal(must, access->access);
5756 isl_map_free(must);
5758 access->ref_id = pet_expr_access_get_ref_id(expr);
5759 access->group = -1;
5761 *data->next_access = access;
5762 data->next_access = &(*data->next_access)->next;
5764 return 0;
5767 /* Construct a linked list of gpu_stmt_access objects,
5768 * one for each access expression in the statement body.
5770 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
5772 struct ppcg_extract_access_data data;
5774 stmt->accesses = NULL;
5775 data.next_access = &stmt->accesses;
5776 data.single_expression =
5777 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5778 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5781 /* Return an array of gpu_stmt representing the statements in "scop".
5783 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5784 __isl_keep isl_set *context)
5786 int i;
5787 struct gpu_stmt *stmts;
5789 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
5790 if (!stmts)
5791 return NULL;
5793 for (i = 0; i < scop->n_stmt; ++i) {
5794 struct gpu_stmt *s = &stmts[i];
5796 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
5797 s->stmt = scop->stmts[i];
5798 pet_stmt_extract_accesses(s);
5801 return stmts;
5804 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5806 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5808 struct gpu_gen *gen = user;
5810 return gen->print(p, gen->prog, gen->tree, &gen->types,
5811 gen->print_user);
5814 /* Generate CUDA code for "scop" and print it to "p".
5815 * After generating an AST for the transformed scop as explained below,
5816 * we call "gen->print" to print the AST in the desired output format
5817 * to "p".
5819 * If it turns out that it does not make sense to generate GPU code,
5820 * then we generate CPU code instead.
5822 * The GPU code is generated in a context where at least one
5823 * statement instance is executed. The corresponding guard (if any) is printed
5824 * around the entire generated GPU code, except for the declaration
5825 * of the arrays that are visible outside of the scop and that therefore
5826 * cannot be declared inside the body of any possible guard.
5828 * We first compute a schedule that respects the dependences
5829 * of the original program and select the outermost band
5830 * of tilable dimensions that has at least one parallel loop.
5831 * We then have three blocks of dimensions
5833 * H B G
5835 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5836 * in
5838 * H T P G
5840 * For each iteration of the T loop and for each array, we compute
5841 * the array elements accessed by that iteration, construct a rectangular
5842 * box around it and shift it to the origin. The result is used
5843 * as shared memory for the array.
5845 * We then split off at most 2 parallel loops from the T loops and
5846 * at most 3 parallel loops from the P loops
5848 * H T1 T2 P1 P2 G
5850 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5851 * according to "grid"/"block" sizes.
5853 * H T1T T1P T2 P1T P1P P2 G
5855 * Finally, the T1P and P1P iterators are equated to the block and
5856 * thread dimensions respectively and so are effectively removed.
5857 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5858 * are run on the GPU.
5860 * Code is generated in three stages. We first generate code for the
5861 * host (the H loops), with iterators h%d. Then, for each leaf node
5862 * of the resulting AST, we generate code for the shared loops (up to
5863 * and including T2), with iterators g%d and after equating the H loops
5864 * to h%d parameters and the T1P loops to the block dimensions.
5865 * Finally, we generate code for the remaining loops in a similar fashion.
5867 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5868 struct gpu_gen *gen, struct ppcg_scop *scop,
5869 struct ppcg_options *options)
5871 struct gpu_prog *prog;
5872 isl_ctx *ctx;
5873 isl_set *context, *guard;
5875 if (!scop)
5876 return isl_printer_free(p);
5878 ctx = isl_printer_get_ctx(p);
5879 prog = gpu_prog_alloc(ctx, scop);
5880 if (!prog)
5881 return isl_printer_free(p);
5883 context = isl_set_copy(prog->context);
5884 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5885 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5887 gen->prog = prog;
5888 gen->any_parallelism = 0;
5889 compute_schedule(gen);
5891 if (!gen->any_parallelism) {
5892 isl_set_free(context);
5893 isl_set_free(guard);
5894 p = print_cpu(p, scop, options);
5895 } else {
5896 compute_copy_in_and_out(gen);
5897 gen->tree = generate_host_code(gen);
5898 p = ppcg_print_exposed_declarations(p, prog->scop);
5899 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5900 isl_ast_node_free(gen->tree);
5903 isl_union_map_free(gen->sched);
5905 gpu_prog_free(prog);
5907 return p;
5910 /* Wrapper around generate for use as a ppcg_transform callback.
5912 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5913 struct ppcg_scop *scop, void *user)
5915 struct gpu_gen *gen = user;
5917 return generate(p, gen, scop, gen->options);
5920 /* Transform the code in the file called "input" by replacing
5921 * all scops by corresponding GPU code and write the results to "out".
5923 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5924 struct ppcg_options *options,
5925 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5926 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5927 struct gpu_types *types, void *user), void *user)
5929 struct gpu_gen gen;
5930 int r;
5931 int i;
5933 gen.ctx = ctx;
5934 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5935 gen.options = options;
5936 gen.kernel_id = 0;
5937 gen.print = print;
5938 gen.print_user = user;
5939 gen.types.n = 0;
5940 gen.types.name = NULL;
5942 if (options->debug->dump_sizes) {
5943 isl_space *space = isl_space_params_alloc(ctx, 0);
5944 gen.used_sizes = isl_union_map_empty(space);
5947 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5949 if (options->debug->dump_sizes) {
5950 isl_union_map_dump(gen.used_sizes);
5951 isl_union_map_free(gen.used_sizes);
5954 isl_union_map_free(gen.sizes);
5955 for (i = 0; i < gen.types.n; ++i)
5956 free(gen.types.name[i]);
5957 free(gen.types.name);
5959 return r;
5962 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5964 struct gpu_prog *prog;
5966 if (!scop)
5967 return NULL;
5969 prog = isl_calloc_type(ctx, struct gpu_prog);
5970 assert(prog);
5972 prog->ctx = ctx;
5973 prog->scop = scop;
5974 prog->context = isl_set_copy(scop->context);
5975 prog->n_stmts = scop->n_stmt;
5976 prog->stmts = extract_stmts(ctx, scop, prog->context);
5977 prog->read = isl_union_map_copy(scop->reads);
5978 prog->may_write = isl_union_map_copy(scop->may_writes);
5979 prog->must_write = isl_union_map_copy(scop->must_writes);
5980 prog->to_inner = compute_to_inner(scop);
5981 prog->to_outer = isl_union_map_copy(prog->to_inner);
5982 prog->to_outer = isl_union_map_reverse(prog->to_outer);
5984 if (!prog->stmts)
5985 return gpu_prog_free(prog);
5987 if (collect_array_info(prog) < 0)
5988 return gpu_prog_free(prog);
5990 return prog;
5993 void *gpu_prog_free(struct gpu_prog *prog)
5995 if (!prog)
5996 return NULL;
5997 free_array_info(prog);
5998 free_stmts(prog->stmts, prog->n_stmts);
5999 isl_union_map_free(prog->to_outer);
6000 isl_union_map_free(prog->to_inner);
6001 isl_union_set_free(prog->copy_in);
6002 isl_union_set_free(prog->copy_out);
6003 isl_union_map_free(prog->read);
6004 isl_union_map_free(prog->may_write);
6005 isl_union_map_free(prog->must_write);
6006 isl_union_map_free(prog->array_order);
6007 isl_set_free(prog->context);
6008 free(prog);
6009 return NULL;