update pet for change in access relations interface
[ppcg.git] / gpu.c
blob3854a81bf0757a1719efd68d79180d78ce8cbfa6
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.
98 * slice is set if there is at least one access in the group
99 * that refers to more than one element
101 isl_map *access;
102 int write;
103 int exact_write;
104 int slice;
106 /* The shared memory tile, NULL if none. */
107 struct gpu_array_tile *shared_tile;
109 /* The private memory tile, NULL if none. */
110 struct gpu_array_tile *private_tile;
112 /* References in this group; point to elements of a linked list. */
113 int n_ref;
114 struct gpu_stmt_access **refs;
116 /* Last shared memory tile dimension that affects tile of this group. */
117 int last_shared;
120 struct gpu_gen {
121 isl_ctx *ctx;
122 struct ppcg_options *options;
124 /* Callback for printing of AST in appropriate format. */
125 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
126 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
127 struct gpu_types *types, void *user);
128 void *print_user;
130 struct gpu_prog *prog;
131 /* The generated AST. */
132 isl_ast_node *tree;
134 /* The sequence of types for which a definition has been printed. */
135 struct gpu_types types;
137 /* User specified tile, grid and block sizes for each kernel */
138 isl_union_map *sizes;
140 /* Effectively used tile, grid and block sizes for each kernel */
141 isl_union_map *used_sizes;
143 /* Identifier of current kernel. */
144 int kernel_id;
145 /* Pointer to the current kernel. */
146 struct ppcg_kernel *kernel;
147 /* Does the computed schedule exhibit any parallelism? */
148 int any_parallelism;
150 /* First tile dimension. */
151 int tile_first;
152 /* Number of tile dimensions. */
153 int tile_len;
154 /* Number of initial parallel loops among tile dimensions. */
155 int n_parallel;
157 /* Number of dimensions determining shared memory. */
158 int shared_len;
160 /* Number of rows in the untiled schedule. */
161 int untiled_len;
162 /* Number of rows in the tiled schedule. */
163 int tiled_len;
164 /* Number of rows in schedule after tiling/wrapping over threads. */
165 int thread_tiled_len;
167 /* Global untiled schedule. */
168 isl_union_map *sched;
169 /* Local (per kernel launch) tiled schedule. */
170 isl_union_map *tiled_sched;
171 /* Local schedule per shared memory tile loop iteration. */
172 isl_union_map *local_sched;
174 /* Local tiled schedule projected onto the shared tile loops and
175 * the loops that will be wrapped over the threads,
176 * with all shared tile loops parametrized.
178 isl_union_map *shared_sched;
179 /* Projects out the loops that will be wrapped over the threads
180 * from shared_sched.
182 isl_union_map *shared_proj;
184 /* A map that takes the range of shared_sched as input,
185 * wraps the appropriate loops over the threads and then projects
186 * out these loops.
188 isl_map *privatization;
190 /* A map from the shared memory tile loops and the thread indices
191 * (as parameters) to the set of accessed memory elements that
192 * will be accessed through private copies.
194 isl_union_map *private_access;
196 /* The schedule for the current private/shared access
197 * (within print_private_access or print_shared_access).
199 isl_map *copy_sched;
200 /* The array reference group corresponding to copy_sched. */
201 struct gpu_array_ref_group *copy_group;
203 /* Is any array in the current kernel marked force_private? */
204 int any_force_private;
206 /* First loop to unroll (or -1 if none) in the current part of the
207 * schedule.
209 int first_unroll;
211 int n_grid;
212 int n_block;
213 /* Note: in the input file, the sizes of the grid and the blocks
214 * are specified in the order x, y, z, but internally, the sizes
215 * are stored in reverse order, so that the last element always
216 * refers to the x dimension.
218 int grid_dim[2];
219 int block_dim[3];
220 int *tile_size;
223 /* Print the name of the local copy of a given group of array references.
225 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
226 struct gpu_array_ref_group *group)
228 int global = 0;
230 if (group->private_tile)
231 p = isl_printer_print_str(p, "private_");
232 else if (group->shared_tile)
233 p = isl_printer_print_str(p, "shared_");
234 else
235 global = 1;
236 p = isl_printer_print_str(p, group->array->name);
237 if (!global && group->array->n_group > 1) {
238 p = isl_printer_print_str(p, "_");
239 p = isl_printer_print_int(p, group->nr);
242 return p;
245 /* Collect all references to the given array and store pointers to them
246 * in array->refs.
248 * If the array contains structures, then there is no need to collect
249 * the references since we will not be computing any reference groups.
251 static void collect_references(struct gpu_prog *prog,
252 struct gpu_array_info *array)
254 int i;
255 int n;
257 if (array->has_compound_element)
258 return;
260 n = 0;
261 for (i = 0; i < prog->n_stmts; ++i) {
262 struct gpu_stmt *stmt = &prog->stmts[i];
263 struct gpu_stmt_access *access;
265 for (access = stmt->accesses; access; access = access->next) {
266 const char *name;
267 name = isl_map_get_tuple_name(access->access,
268 isl_dim_out);
269 if (name && !strcmp(array->name, name))
270 n++;
274 array->n_ref = n;
275 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
276 assert(array->refs);
278 n = 0;
279 for (i = 0; i < prog->n_stmts; ++i) {
280 struct gpu_stmt *stmt = &prog->stmts[i];
281 struct gpu_stmt_access *access;
283 for (access = stmt->accesses; access; access = access->next) {
284 const char *name;
285 name = isl_map_get_tuple_name(access->access,
286 isl_dim_out);
287 if (!name || strcmp(array->name, name))
288 continue;
290 array->refs[n++] = access;
295 /* Create a gpu_array_tile for an array of dimension "n_index".
297 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
299 int i;
300 struct gpu_array_tile *tile;
302 tile = isl_calloc_type(ctx, struct gpu_array_tile);
303 assert(tile);
305 tile->n = n_index;
307 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
308 assert(tile->bound);
310 for (i = 0; i < n_index; ++i) {
311 tile->bound[i].size = NULL;
312 tile->bound[i].lb = NULL;
313 tile->bound[i].stride = NULL;
314 tile->bound[i].shift = NULL;
315 tile->bound[i].shift_map = NULL;
318 return tile;
321 static void *free_tile(struct gpu_array_tile *tile)
323 int j;
325 if (!tile)
326 return NULL;
328 for (j = 0; j < tile->n; ++j) {
329 isl_val_free(tile->bound[j].size);
330 isl_val_free(tile->bound[j].stride);
331 isl_aff_free(tile->bound[j].lb);
332 isl_aff_free(tile->bound[j].shift);
333 isl_basic_map_free(tile->bound[j].shift_map);
335 free(tile->bound);
336 isl_multi_aff_free(tile->tiling);
337 free(tile);
339 return NULL;
342 static struct pet_array *find_array(struct ppcg_scop *scop,
343 __isl_keep isl_set *accessed)
345 int i;
346 isl_id *id;
348 id = isl_set_get_tuple_id(accessed);
350 for (i = 0; i < scop->pet->n_array; ++i) {
351 isl_id *id_i;
353 id_i = isl_set_get_tuple_id(scop->pet->arrays[i]->extent);
354 isl_id_free(id_i);
355 if (id == id_i)
356 break;
358 isl_id_free(id);
360 return i < scop->pet->n_array ? scop->pet->arrays[i] : NULL;
363 /* Compute and return the extent of "array", taking into account the set of
364 * accessed elements.
366 * In particular, the extent in the outer dimension is taken
367 * from "accessed", while then extent in the remaing dimensions
368 * are taken from array->extent.
370 * The extent in the outer dimension cannot be taken from array->extent
371 * because that may be unbounded. Furthermore, even if it is bounded,
372 * it may be larger than the piece of the array that is being accessed.
374 static __isl_give isl_set *compute_extent(struct pet_array *array,
375 __isl_keep isl_set *accessed)
377 int n_index;
378 isl_id *id;
379 isl_set *outer;
380 isl_set *extent;
382 extent = isl_set_copy(array->extent);
384 n_index = isl_set_dim(accessed, isl_dim_set);
385 if (n_index == 0)
386 return extent;
388 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
389 outer = isl_set_copy(accessed);
390 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
391 extent = isl_set_flat_product(outer, extent);
392 id = isl_set_get_tuple_id(accessed);
393 extent = isl_set_set_tuple_id(extent, id);
395 return extent;
398 /* Is the array "array" being extracted a read-only scalar?
400 * That is, is "array" a scalar that is never possibly written to.
401 * An array containing structures is never considered to be a scalar.
403 static int is_read_only_scalar(struct gpu_array_info *array,
404 struct gpu_prog *prog)
406 isl_set *space;
407 isl_union_map *write;
408 int empty;
410 if (array->has_compound_element)
411 return 0;
412 if (array->n_index != 0)
413 return 0;
415 write = isl_union_map_copy(prog->may_write);
416 space = isl_set_universe(isl_space_copy(array->space));
417 write = isl_union_map_intersect_range(write,
418 isl_union_set_from_set(space));
419 empty = isl_union_map_is_empty(write);
420 isl_union_map_free(write);
422 return empty;
425 /* Compute bounds on the host arrays based on the accessed elements
426 * and collect all references to the array.
428 * If the array is zero-dimensional and does not contain structures,
429 * i.e., if the array is a scalar, we check whether it is read-only.
431 static int extract_array_info(__isl_take isl_set *array, void *user)
433 int i;
434 struct gpu_prog *prog = (struct gpu_prog *)user;
435 const char *name;
436 int n_index;
437 isl_pw_aff **bounds;
438 struct pet_array *pa;
439 struct gpu_array_info *info;
440 isl_set *extent;
442 info = &prog->array[prog->n_array];
443 prog->n_array++;
445 n_index = isl_set_dim(array, isl_dim_set);
446 name = isl_set_get_tuple_name(array);
447 bounds = isl_alloc_array(isl_set_get_ctx(array),
448 isl_pw_aff *, n_index);
449 if (!bounds)
450 goto error;
452 info->space = isl_set_get_space(array);
453 info->name = strdup(name);
454 info->n_index = n_index;
455 info->bound = bounds;
456 info->linearize = prog->scop->options->linearize_device_arrays;
458 pa = find_array(prog->scop, array);
459 if (!pa)
460 isl_die(isl_set_get_ctx(array), isl_error_internal,
461 "unable to find array in scop", goto error);
463 info->type = strdup(pa->element_type);
464 info->size = pa->element_size;
465 info->local = pa->declared && !pa->exposed;
466 info->has_compound_element = pa->element_is_record;
467 info->read_only_scalar = is_read_only_scalar(info, prog);
469 extent = compute_extent(pa, array);
470 info->extent = extent;
471 for (i = 0; i < n_index; ++i) {
472 isl_set *dom;
473 isl_local_space *ls;
474 isl_aff *one;
475 isl_pw_aff *bound;
477 dom = isl_set_copy(extent);
478 dom = isl_set_project_out(dom, isl_dim_set, i + 1,
479 n_index - (i + 1));
480 dom = isl_set_project_out(dom, isl_dim_set, 0, i);
481 if (!isl_set_dim_has_upper_bound(dom, isl_dim_set, 0)) {
482 fprintf(stderr, "unable to determine extent of '%s' "
483 "in dimension %d\n", info->name, i);
484 dom = isl_set_free(dom);
486 bound = isl_set_dim_max(dom, 0);
487 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
488 ls = isl_local_space_from_space(isl_set_get_space(dom));
489 one = isl_aff_zero_on_domain(ls);
490 one = isl_aff_add_constant_si(one, 1);
491 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
492 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
494 bounds[i] = bound;
495 if (!isl_pw_aff_is_cst(bound))
496 info->linearize = 1;
499 collect_references(prog, info);
501 isl_set_free(array);
502 return 0;
503 error:
504 isl_set_free(array);
505 return -1;
508 /* Remove independence from the order constraints "order" on array "array".
509 * Since the pairs of iterations in the filter relation of an independence
510 * are guaranteed to be completely independent by the user, there is
511 * no need to ensure that live ranges are ordered along thong pairs.
512 * We make an exception for local variables, though, as the independence
513 * guarantee does not apply to those.
515 * The order constraints are used in two places.
516 * Those on scalars are used in check_scalar_live_ranges to check if
517 * we need to force the scalar to be private. Any non-local scalar
518 * should not be forced scalar if it only appears in independent loops.
519 * Those on non-scalars are added to the coincidence constraints
520 * in compute_schedule because we do not support any array expansion.
521 * Accesses to non-local arrays should not prevent a loop from being
522 * considered coincident so we should indeed remove those constraints
523 * from the order constraints.
525 static __isl_give isl_union_map *remove_independences(struct gpu_prog *prog,
526 struct gpu_array_info *array, __isl_take isl_union_map *order)
528 int i;
530 for (i = 0; i < prog->scop->pet->n_independence; ++i) {
531 struct pet_independence *pi = prog->scop->pet->independences[i];
532 if (isl_union_set_contains(pi->local, array->space))
533 continue;
535 order = isl_union_map_subtract(order,
536 isl_union_map_copy(pi->filter));
539 return order;
542 /* For each array in "prog", store the (untagged) order dependences
543 * derived from the array in array->dep_order.
544 * In particular, consider all references that access the given array
545 * and take the order dependences that have one of these references
546 * as source. (Since an order dependence relates two references to
547 * the same array, the target of these order dependences will also
548 * be one of these references.)
549 * Additionally, store the union of these array->dep_order relations
550 * for all non-scalar arrays in prog->array_order.
552 void collect_order_dependences(struct gpu_prog *prog)
554 int i;
555 isl_space *space;
556 isl_union_map *accesses;
558 space = isl_union_map_get_space(prog->read);
559 prog->array_order = isl_union_map_empty(space);
561 accesses = isl_union_map_copy(prog->scop->tagged_reads);
562 accesses = isl_union_map_union(accesses,
563 isl_union_map_copy(prog->scop->tagged_may_writes));
564 accesses = isl_union_map_universe(accesses);
565 accesses = isl_union_map_apply_range(accesses,
566 isl_union_map_copy(prog->to_outer));
568 for (i = 0; i < prog->n_array; ++i) {
569 struct gpu_array_info *array = &prog->array[i];
570 isl_set *set;
571 isl_union_set *uset;
572 isl_union_map *order;
574 set = isl_set_universe(isl_space_copy(array->space));
575 uset = isl_union_set_from_set(set);
576 uset = isl_union_map_domain(
577 isl_union_map_intersect_range(isl_union_map_copy(accesses),
578 uset));
579 order = isl_union_map_copy(prog->scop->tagged_dep_order);
580 order = isl_union_map_intersect_domain(order, uset);
581 order = isl_union_map_zip(order);
582 order = isl_union_set_unwrap(isl_union_map_domain(order));
583 order = remove_independences(prog, array, order);
584 array->dep_order = order;
586 if (gpu_array_is_scalar(array))
587 continue;
589 prog->array_order = isl_union_map_union(prog->array_order,
590 isl_union_map_copy(array->dep_order));
593 isl_union_map_free(accesses);
596 /* Construct a gpu_array_info for each array possibly accessed by "prog" and
597 * collect them in prog->array.
599 * If there are any member accesses involved, then they are first mapped
600 * to the outer arrays of structs.
602 * If we are allowing live range reordering, then also set
603 * the dep_order field. Otherwise leave it NULL.
605 static int collect_array_info(struct gpu_prog *prog)
607 int r;
608 isl_union_set *arrays;
610 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
611 arrays = isl_union_set_union(arrays,
612 isl_union_map_range(isl_union_map_copy(prog->may_write)));
614 arrays = isl_union_set_apply(arrays,
615 isl_union_map_copy(prog->to_outer));
617 arrays = isl_union_set_coalesce(arrays);
619 prog->n_array = isl_union_set_n_set(arrays);
620 prog->array = isl_calloc_array(prog->ctx,
621 struct gpu_array_info, prog->n_array);
622 assert(prog->array);
623 prog->n_array = 0;
624 r = isl_union_set_foreach_set(arrays, &extract_array_info, prog);
625 isl_union_set_free(arrays);
627 if (prog->scop->options->live_range_reordering)
628 collect_order_dependences(prog);
630 return r;
633 static void free_array_info(struct gpu_prog *prog)
635 int i, j;
637 for (i = 0; i < prog->n_array; ++i) {
638 int n_index = prog->array[i].n_index;
639 free(prog->array[i].type);
640 free(prog->array[i].name);
641 for (j = 0; j < n_index; ++j)
642 isl_pw_aff_free(prog->array[i].bound[j]);
643 isl_space_free(prog->array[i].space);
644 isl_set_free(prog->array[i].extent);
645 free(prog->array[i].bound);
646 free(prog->array[i].refs);
647 isl_union_map_free(prog->array[i].dep_order);
649 free(prog->array);
652 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
653 * as an array or through a pointer reference, but as a single data element.
654 * At the moment, scalars are represented as zero-dimensional arrays.
655 * A zero-dimensional array containing structures is not considered
656 * to be a scalar.
658 int gpu_array_is_scalar(struct gpu_array_info *array)
660 return !array->has_compound_element && array->n_index == 0;
663 /* Is "array" a read-only scalar?
665 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
667 return array->read_only_scalar;
670 /* Return the set of parameter values for which the array has a positive
671 * size in all dimensions.
672 * If the sizes are only valid for some parameter values, then those
673 * constraints are also taken into account.
675 __isl_give isl_set *gpu_array_positive_size_guard(struct gpu_array_info *array)
677 int i;
678 isl_space *space;
679 isl_set *guard;
681 space = isl_space_params(isl_space_copy(array->space));
682 guard = isl_set_universe(space);
684 for (i = 0; i < array->n_index; ++i) {
685 isl_pw_aff *bound;
686 isl_set *guard_i, *zero;
688 bound = isl_pw_aff_copy(array->bound[i]);
689 guard_i = isl_pw_aff_nonneg_set(isl_pw_aff_copy(bound));
690 zero = isl_pw_aff_zero_set(bound);
691 guard_i = isl_set_subtract(guard_i, zero);
692 guard = isl_set_intersect(guard, guard_i);
695 return guard;
698 /* Internal data structure for extract_size_of_type.
699 * "type" specifies the name of the space that we want to extract.
700 * "res" is used to store the subset of that space.
702 struct ppcg_extract_size_data {
703 const char *type;
704 isl_set *res;
707 /* This function is called for each set in a union_set.
708 * If the name of the set matches data->type, we store the
709 * set in data->res.
711 static int extract_size_of_type(__isl_take isl_set *size, void *user)
713 struct ppcg_extract_size_data *data = user;
714 const char *name;
716 name = isl_set_get_tuple_name(size);
717 if (name && !strcmp(name, data->type)) {
718 data->res = size;
719 return -1;
722 isl_set_free(size);
723 return 0;
726 /* Given a union map { kernel[i] -> *[...] },
727 * return the range in the space called "type" for the kernel with
728 * sequence number "id".
730 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
731 const char *type, int id)
733 isl_space *space;
734 isl_set *dom;
735 isl_union_set *local_sizes;
736 struct ppcg_extract_size_data data = { type, NULL };
738 if (!sizes)
739 return NULL;
741 space = isl_union_map_get_space(sizes);
742 space = isl_space_set_from_params(space);
743 space = isl_space_add_dims(space, isl_dim_set, 1);
744 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
745 dom = isl_set_universe(space);
746 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
748 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
749 isl_union_map_copy(sizes));
750 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
751 isl_union_set_free(local_sizes);
752 return data.res;
755 /* Given a singleton set, extract the first (at most *len) elements
756 * of the single integer tuple into *sizes and update *len if needed.
758 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
760 int i;
761 int dim;
763 if (!set)
764 return;
766 dim = isl_set_dim(set, isl_dim_set);
767 if (dim < *len)
768 *len = dim;
770 for (i = 0; i < *len; ++i) {
771 isl_val *v;
773 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
774 assert(v);
776 sizes[i] = isl_val_get_num_si(v);
777 isl_val_free(v);
780 isl_set_free(set);
783 /* Add the map { kernel[id] -> type[sizes] } to gen->used_sizes,
784 * if the option debug->dump_sizes is set.
786 static void set_used_sizes(struct gpu_gen *gen, const char *type, int id,
787 int *sizes, int len)
789 int i;
790 isl_space *space;
791 isl_map *map;
793 if (!gen->options->debug->dump_sizes)
794 return;
796 space = isl_union_map_get_space(gen->used_sizes);
797 space = isl_space_set_from_params(space);
798 space = isl_space_add_dims(space, isl_dim_set, 1);
799 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
800 space = isl_space_from_domain(space);
801 space = isl_space_add_dims(space, isl_dim_out, len);
802 space = isl_space_set_tuple_name(space, isl_dim_out, type);
804 map = isl_map_universe(space);
805 map = isl_map_fix_si(map, isl_dim_in, 0, id);
806 for (i = 0; i < len; ++i)
807 map = isl_map_fix_si(map, isl_dim_out, i, sizes[i]);
809 gen->used_sizes = isl_union_map_add_map(gen->used_sizes, map);
812 /* Extract user specified "tile" sizes from the "sizes" command line option,
813 * defaulting to option->tile_size in each dimension.
814 * Add the effectively used sizes to gen->used_sizes.
816 static void read_tile_sizes(struct gpu_gen *gen)
818 int n;
819 isl_set *size;
821 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
822 assert(gen->tile_size);
823 for (n = 0; n < gen->tile_len; ++n)
824 gen->tile_size[n] = gen->options->tile_size;
826 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
827 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
828 set_used_sizes(gen, "tile", gen->kernel_id,
829 gen->tile_size, gen->tile_len);
831 if (gen->n_parallel > gen->tile_len)
832 gen->n_parallel = gen->tile_len;
835 /* Extract user specified "block" sizes from the "sizes" command line option,
836 * after filling in some potentially useful defaults.
837 * Add the effectively used sizes to gen->used_sizes.
839 static void read_block_sizes(struct gpu_gen *gen)
841 int n;
842 isl_set *size;
844 n = gen->n_parallel;
845 gen->n_block = (n <= 3) ? n : 3;
846 switch (gen->n_block) {
847 case 1:
848 gen->block_dim[0] = 512;
849 break;
850 case 2:
851 gen->block_dim[0] = 32;
852 gen->block_dim[1] = 16;
853 break;
854 default:
855 gen->block_dim[0] = 32;
856 gen->block_dim[1] = 4;
857 gen->block_dim[2] = 4;
858 break;
861 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
862 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
863 set_used_sizes(gen, "block", gen->kernel_id,
864 gen->block_dim, gen->n_block);
867 /* Extract user specified "grid" sizes from the "sizes" command line option,
868 * after filling in some potentially useful defaults.
869 * Add the effectively used sizes to gen->used_sizes.
871 static void read_grid_sizes(struct gpu_gen *gen)
873 int n = gen->n_parallel;
874 isl_set *size;
876 gen->n_grid = (n <= 2) ? n : 2;
877 switch (gen->n_grid) {
878 case 1:
879 gen->grid_dim[0] = 32768;
880 break;
881 default:
882 gen->grid_dim[0] = 256;
883 gen->grid_dim[1] = 256;
884 break;
887 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
888 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
889 set_used_sizes(gen, "grid", gen->kernel_id, gen->grid_dim, gen->n_grid);
892 /* Extract user specified sizes from the "sizes" command line option
893 * after filling in some potentially useful defaults.
895 static void read_sizes(struct gpu_gen *gen)
897 read_tile_sizes(gen);
898 read_block_sizes(gen);
899 read_grid_sizes(gen);
902 static void *free_stmts(struct gpu_stmt *stmts, int n)
904 int i;
906 if (!stmts)
907 return NULL;
909 for (i = 0; i < n; ++i) {
910 struct gpu_stmt_access *access, *next;
912 for (access = stmts[i].accesses; access; access = next) {
913 next = access->next;
914 isl_id_free(access->ref_id);
915 isl_map_free(access->access);
916 isl_map_free(access->tagged_access);
917 free(access);
920 isl_id_free(stmts[i].id);
922 free(stmts);
924 return NULL;
927 /* Construct a map from a domain of dimensionality "len"
928 * to a domain of dimensionality "len" + "tile_len" that tiles
929 * the "tile_len" coordinates starting at "first".
930 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
931 * "dim" prescribes the parameters.
933 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
934 int first, int tile_len, int *tile_size)
936 int i;
937 isl_basic_map *bmap;
938 isl_constraint *c;
939 isl_local_space *ls;
941 dim = isl_space_add_dims(dim, isl_dim_in, len);
942 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
943 bmap = isl_basic_map_universe(isl_space_copy(dim));
944 ls = isl_local_space_from_space(dim);
946 for (i = 0; i < len - tile_len; ++i) {
947 int j = i < first ? i : i + tile_len;
948 int k = i < first ? i : i + 2 * tile_len;
950 c = isl_equality_alloc(isl_local_space_copy(ls));
951 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
952 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
953 bmap = isl_basic_map_add_constraint(bmap, c);
956 for (i = 0; i < tile_len; ++i) {
957 c = isl_equality_alloc(isl_local_space_copy(ls));
958 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
959 first + i, -1);
960 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
961 first + i, tile_size[i]);
962 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
963 first + i + tile_len, 1);
964 bmap = isl_basic_map_add_constraint(bmap, c);
966 c = isl_inequality_alloc(isl_local_space_copy(ls));
967 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
968 first + i + tile_len, 1);
969 bmap = isl_basic_map_add_constraint(bmap, c);
971 c = isl_inequality_alloc(isl_local_space_copy(ls));
972 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
973 first + i + tile_len, -1);
974 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
975 bmap = isl_basic_map_add_constraint(bmap, c);
978 isl_local_space_free(ls);
980 return isl_map_from_basic_map(bmap);
983 /* Construct a map from a domain of dimensionality "len"
984 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
985 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
986 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
987 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
988 * that are projected out at the end.
989 * "dim" prescribes the parameters.
991 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
992 int first, int wrap_len, int *wrap_size)
994 int i;
995 isl_basic_map *bmap;
996 isl_constraint *c;
997 isl_local_space *ls;
999 dim = isl_space_add_dims(dim, isl_dim_in, len);
1000 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
1001 bmap = isl_basic_map_universe(isl_space_copy(dim));
1002 ls = isl_local_space_from_space(dim);
1004 for (i = 0; i < len; ++i) {
1005 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
1007 c = isl_equality_alloc(isl_local_space_copy(ls));
1008 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
1009 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
1010 bmap = isl_basic_map_add_constraint(bmap, c);
1013 for (i = 0; i < wrap_len; ++i) {
1014 c = isl_equality_alloc(isl_local_space_copy(ls));
1015 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1016 first + i, -1);
1017 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1018 first + wrap_len + i, 1);
1019 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1020 first + 2 * wrap_len + i, wrap_size[i]);
1021 bmap = isl_basic_map_add_constraint(bmap, c);
1023 c = isl_inequality_alloc(isl_local_space_copy(ls));
1024 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1025 first + wrap_len + i, 1);
1026 bmap = isl_basic_map_add_constraint(bmap, c);
1028 c = isl_inequality_alloc(isl_local_space_copy(ls));
1029 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
1030 first + wrap_len + i, -1);
1031 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
1032 bmap = isl_basic_map_add_constraint(bmap, c);
1035 isl_local_space_free(ls);
1037 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
1038 first + 2 * wrap_len, wrap_len);
1040 return isl_map_from_basic_map(bmap);
1043 /* Add "n" parameters named prefix%d.
1045 static __isl_give isl_set *add_params( __isl_take isl_set *set,
1046 int n, const char *prefix)
1048 int i;
1049 unsigned nparam;
1050 char name[20];
1052 nparam = isl_set_dim(set, isl_dim_param);
1053 set = isl_set_add_dims(set, isl_dim_param, n);
1055 for (i = 0; i < n; ++i) {
1056 snprintf(name, sizeof(name), "%s%d", prefix, i);
1057 set = isl_set_set_dim_name(set, isl_dim_param,
1058 nparam + i, name);
1061 return set;
1064 /* Equate the "n" dimensions of "set" starting at "first" to
1065 * freshly created parameters named prefix%d.
1067 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
1068 int first, int n, const char *prefix)
1070 int i;
1071 unsigned nparam;
1073 nparam = isl_set_dim(set, isl_dim_param);
1075 set = add_params(set, n, prefix);
1077 for (i = 0; i < n; ++i)
1078 set = isl_set_equate(set, isl_dim_param, nparam + i,
1079 isl_dim_set, first + i);
1081 return set;
1084 /* Given a parameter space "space", create a set of dimension "len"
1085 * of which the "n" dimensions starting at "first" are equated to
1086 * freshly created parameters named prefix%d.
1088 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
1089 int len, int first, int n, const char *prefix)
1091 isl_set *set;
1093 space = isl_space_set_from_params(space);
1094 space = isl_space_add_dims(space, isl_dim_set, len);
1095 set = isl_set_universe(space);
1097 return parametrize(set, first, n, prefix);
1100 /* Tile the B loops over the tile sizes and then tile/wrap
1101 * the T1 loops over the blocks.
1103 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
1104 __isl_take isl_union_map *sched)
1106 isl_space *dim;
1107 isl_map *tiling, *block_tiling;
1109 dim = isl_union_map_get_space(sched);
1110 tiling = tile(isl_space_copy(dim), gen->untiled_len,
1111 gen->tile_first, gen->tile_len, gen->tile_size);
1113 if (gen->options->wrap)
1114 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
1115 gen->tile_first, gen->n_grid, gen->grid_dim);
1116 else
1117 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
1118 gen->tile_first, gen->n_grid, gen->grid_dim);
1120 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
1122 tiling = isl_map_apply_range(tiling, block_tiling);
1124 sched = isl_union_map_apply_range(sched,
1125 isl_union_map_from_map(tiling));
1127 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1129 return sched;
1132 /* Equate the "T1P" iterators in the tiled schedule "sched"
1133 * to the block dimensions.
1135 static __isl_give isl_union_map *parametrize_tiled_schedule(
1136 struct gpu_gen *gen, __isl_take isl_union_map *sched)
1138 isl_space *dim;
1139 isl_set *par;
1141 dim = isl_union_map_get_space(sched);
1142 par = parametrization(dim, gen->tiled_len,
1143 gen->tile_first + gen->n_grid, gen->n_grid, "b");
1144 sched = isl_union_map_intersect_range(sched,
1145 isl_union_set_from_set(par));
1147 return sched;
1150 /* Tile/wrap the P1 loops over the threads.
1152 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
1153 __isl_take isl_union_map *sched)
1155 isl_space *dim;
1156 isl_map *tiling;
1157 isl_set *par;
1159 dim = isl_union_map_get_space(sched);
1161 if (gen->options->wrap)
1162 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
1163 gen->shared_len, gen->n_block, gen->block_dim);
1164 else
1165 tiling = tile(isl_space_copy(dim), gen->tiled_len,
1166 gen->shared_len, gen->n_block, gen->block_dim);
1167 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
1169 sched = isl_union_map_apply_range(sched,
1170 isl_union_map_from_map(tiling));
1172 par = parametrization(dim, gen->thread_tiled_len,
1173 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
1174 gen->n_block, "t");
1175 sched = isl_union_map_intersect_range(sched,
1176 isl_union_set_from_set(par));
1178 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
1180 return sched;
1183 /* If the user asked for it, scale the shared memory tile loops
1184 * (T1T and T2) of "sched" by gen->tile_size[i].
1185 * If we are not performing "wrapping", then additionally scale the T1P
1186 * loops by gen->grid_dim[i].
1188 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1189 __isl_take isl_union_map *sched)
1191 int i;
1192 isl_space *dim;
1193 isl_basic_map *scale;
1194 isl_constraint *c;
1195 isl_local_space *ls;
1197 if (!gen->options->scale_tile_loops)
1198 return sched;
1200 dim = isl_union_map_get_space(sched);
1201 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1202 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1203 scale = isl_basic_map_universe(isl_space_copy(dim));
1204 ls = isl_local_space_from_space(dim);
1206 for (i = 0; i < gen->tiled_len; ++i) {
1207 int f = 1;
1209 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1210 f = gen->tile_size[i - gen->tile_first];
1211 if (!gen->options->wrap)
1212 f *= gen->grid_dim[i - gen->tile_first];
1213 } else if (i >= gen->tile_first + gen->n_grid &&
1214 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1215 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1218 c = isl_equality_alloc(isl_local_space_copy(ls));
1219 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1220 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1221 scale = isl_basic_map_add_constraint(scale, c);
1224 isl_local_space_free(ls);
1226 sched = isl_union_map_apply_range(sched,
1227 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1229 return sched;
1232 /* If we are not performing "wrapping" and if the user asked for it,
1233 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1235 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1236 __isl_take isl_union_map *sched)
1238 int i;
1239 isl_space *dim;
1240 isl_basic_map *scale;
1241 isl_constraint *c;
1242 isl_local_space *ls;
1244 if (gen->options->wrap)
1245 return sched;
1246 if (!gen->options->scale_tile_loops)
1247 return sched;
1249 dim = isl_union_map_get_space(sched);
1250 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1251 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1252 scale = isl_basic_map_universe(isl_space_copy(dim));
1253 ls = isl_local_space_from_space(dim);
1255 for (i = 0; i < gen->thread_tiled_len; ++i) {
1256 int f = 1;
1258 if (i >= gen->shared_len &&
1259 i < gen->shared_len + gen->n_block)
1260 f = gen->block_dim[i - gen->shared_len];
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 "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1279 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1280 __isl_take isl_union_map *sched, int len, int first, int n_tile)
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, len);
1295 dim = isl_space_add_dims(dim, isl_dim_out, len);
1296 scale = isl_basic_map_universe(isl_space_copy(dim));
1297 ls = isl_local_space_from_space(dim);
1299 for (i = 0; i < len; ++i) {
1300 int f = 1;
1302 if (i >= first && i < first + n_tile)
1303 f = gen->kernel->block_dim[i - first];
1305 c = isl_equality_alloc(isl_local_space_copy(ls));
1306 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1307 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1308 scale = isl_basic_map_add_constraint(scale, c);
1311 isl_local_space_free(ls);
1313 sched = isl_union_map_apply_range(sched,
1314 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1316 return sched;
1319 /* Add "len" parameters p[i] called prefix%d,
1320 * with bounds to 0 <= p[i] < size[i].
1322 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1323 int len, int *size, const char *prefix)
1325 int i;
1326 unsigned nparam;
1327 isl_space *dim;
1328 isl_basic_set *bset;
1329 isl_constraint *c;
1330 isl_local_space *ls;
1331 char name[20];
1333 nparam = isl_set_dim(set, isl_dim_param);
1334 set = isl_set_add_dims(set, isl_dim_param, len);
1336 for (i = 0; i < len; ++i) {
1337 snprintf(name, sizeof(name), "%s%d", prefix, i);
1338 set = isl_set_set_dim_name(set, isl_dim_param,
1339 nparam + i, name);
1342 dim = isl_set_get_space(set);
1343 bset = isl_basic_set_universe(isl_space_copy(dim));
1344 ls = isl_local_space_from_space(dim);
1346 for (i = 0; i < len; ++i) {
1347 c = isl_inequality_alloc(isl_local_space_copy(ls));
1348 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1349 nparam + i, 1);
1350 bset = isl_basic_set_add_constraint(bset, c);
1352 c = isl_inequality_alloc(isl_local_space_copy(ls));
1353 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1354 nparam + i, -1);
1355 c = isl_constraint_set_constant_si(c, size[i] - 1);
1356 bset = isl_basic_set_add_constraint(bset, c);
1359 isl_local_space_free(ls);
1361 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1364 /* Add "len" parameters p[i] called prefix%d and intersect "set"
1365 * with
1367 * { : 0 <= p[i] < size[i] }
1369 * or an overapproximation.
1371 static __isl_give isl_set *add_bounded_parameters_dynamic(
1372 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1373 const char *prefix)
1375 int i, len;
1376 unsigned nparam;
1377 isl_space *space;
1378 isl_local_space *ls;
1379 char name[20];
1381 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1382 nparam = isl_set_dim(set, isl_dim_param);
1383 set = isl_set_add_dims(set, isl_dim_param, len);
1385 for (i = 0; i < len; ++i) {
1386 snprintf(name, sizeof(name), "%s%d", prefix, i);
1387 set = isl_set_set_dim_name(set, isl_dim_param,
1388 nparam + i, name);
1391 space = isl_space_params(isl_set_get_space(set));
1392 ls = isl_local_space_from_space(space);
1393 for (i = 0; i < len; ++i) {
1394 isl_pw_aff *param, *size_i, *zero;
1395 isl_set *bound;
1397 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1398 isl_dim_param, nparam + i);
1400 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1401 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1402 bound = isl_set_from_basic_set(isl_set_simple_hull(bound));
1403 set = isl_set_intersect_params(set, bound);
1405 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1406 bound = isl_pw_aff_ge_set(param, zero);
1407 set = isl_set_intersect_params(set, bound);
1409 isl_local_space_free(ls);
1411 return set;
1414 /* Construct a map from an access to group->array to the corresponding
1415 * shared/private memory tile.
1416 * The map is of the form
1418 * { [D[i] -> A[a]] -> T[t] }
1420 * where D represents the initial shared_len dimensions
1421 * of the computed schedule.
1423 static __isl_give isl_map *shift_access(struct gpu_array_ref_group *group)
1425 struct gpu_array_tile *tile;
1426 isl_multi_aff *tiling;
1428 tile = group->private_tile;
1429 if (!tile)
1430 tile = group->shared_tile;
1432 tiling = isl_multi_aff_copy(tile->tiling);
1434 return isl_map_from_multi_aff(tiling);
1437 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1439 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1440 unsigned pos)
1442 isl_val *v;
1443 int fixed;
1445 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1446 if (!v)
1447 return -1;
1448 fixed = isl_val_is_int(v);
1449 isl_val_free(v);
1451 return fixed;
1454 /* Given a schedule that iterates over all elements in a piece of an array,
1455 * perform tiling/wrapping over the threads.
1457 * In particular, we tile the final iterators so that the final thread
1458 * dimension runs over the final array dimension.
1459 * However, if those final iterators have only a single iteration,
1460 * we try to tile earlier iterators instead.
1462 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1463 __isl_take isl_map *sched)
1465 isl_space *dim;
1466 isl_union_map *usched;
1467 isl_map *tiling;
1468 isl_set *par;
1469 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1470 int n_tile;
1471 int first;
1473 n_tile = gen->kernel->n_block;
1474 if (n_tile > nvar) {
1475 int i;
1476 sched = isl_map_insert_dims(sched,
1477 isl_dim_out, 0, n_tile - nvar);
1478 for (i = 0; i < n_tile - nvar; ++i)
1479 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1480 nvar = n_tile;
1483 first = nvar - n_tile;
1485 for (; first > 0; first --)
1486 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1487 break;
1489 dim = isl_map_get_space(sched);
1490 dim = isl_space_params(dim);
1491 if (gen->options->wrap)
1492 tiling = wrap(isl_space_copy(dim), nvar, first,
1493 n_tile, gen->kernel->block_dim);
1494 else
1495 tiling = tile(isl_space_copy(dim), nvar, first,
1496 n_tile, gen->kernel->block_dim);
1497 sched = isl_map_apply_range(sched, tiling);
1499 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1500 sched = isl_map_intersect_range(sched, par);
1502 usched = isl_union_map_from_map(sched);
1503 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1504 first, n_tile);
1505 sched = isl_map_from_union_map(usched);
1507 return sched;
1510 /* Return the union of all read (read = 1) and/or write (write = 1)
1511 * access relations in the group.
1513 static __isl_give isl_union_map *group_access_relation(
1514 struct gpu_array_ref_group *group, int read, int write)
1516 int i;
1517 isl_union_map *access;
1519 access = isl_union_map_empty(isl_map_get_space(group->access));
1520 for (i = 0; i < group->n_ref; ++i) {
1521 isl_map *map_i;
1523 if (!((read && group->refs[i]->read) ||
1524 (write && group->refs[i]->write)))
1525 continue;
1526 map_i = isl_map_copy(group->refs[i]->access);
1527 access = isl_union_map_union(access,
1528 isl_union_map_from_map(map_i));
1531 return access;
1534 /* Return the union of all tagged access relations in the group.
1536 static __isl_give isl_union_map *group_tagged_access_relation(
1537 struct gpu_array_ref_group *group)
1539 int i;
1540 isl_union_map *access;
1542 access = isl_union_map_empty(isl_map_get_space(group->access));
1543 for (i = 0; i < group->n_ref; ++i) {
1544 isl_map *map_i;
1546 map_i = isl_map_copy(group->refs[i]->tagged_access);
1547 access = isl_union_map_union(access,
1548 isl_union_map_from_map(map_i));
1551 return access;
1554 /* Return the extent of "array", recomputed from the bounds.
1555 * The recomputed extent may be simpler than the original extent.
1557 static __isl_give isl_set *array_extent(struct gpu_array_info *array)
1559 int i;
1560 isl_id *id;
1561 isl_space *space;
1562 isl_local_space *ls;
1563 isl_set *extent;
1565 id = isl_set_get_tuple_id(array->extent);
1566 space = isl_set_get_space(array->extent);
1567 extent = isl_set_universe(isl_space_copy(space));
1568 ls = isl_local_space_from_space(space);
1569 for (i = 0; i < array->n_index; ++i) {
1570 isl_pw_aff *bound;
1571 isl_aff *aff;
1572 isl_pw_aff *index;
1573 isl_set *lt;
1575 extent = isl_set_lower_bound_si(extent, isl_dim_set, i, 0);
1577 aff = isl_aff_var_on_domain(isl_local_space_copy(ls),
1578 isl_dim_set, i);
1579 index = isl_pw_aff_from_aff(aff);
1580 bound = isl_pw_aff_copy(array->bound[i]);
1581 bound = isl_pw_aff_from_range(bound);
1582 bound = isl_pw_aff_add_dims(bound, isl_dim_in, array->n_index);
1583 bound = isl_pw_aff_set_tuple_id(bound, isl_dim_in,
1584 isl_id_copy(id));
1585 lt = isl_pw_aff_lt_set(index, bound);
1586 extent = isl_set_intersect(extent, lt);
1588 isl_local_space_free(ls);
1589 isl_id_free(id);
1591 return extent;
1594 /* Return a map from the first shared_len dimensions of the computed
1595 * schedule to the array tile in
1596 * global memory that corresponds to the shared memory copy.
1598 * In particular, return a map
1600 * { D[i] -> A[a] }
1602 * with constraints
1604 * tile_offset(i) <= a <= tile_offset(i) + tile_size - 1 (1)
1606 * and
1608 * 0 <= a <= array_size - 1 (2)
1610 * Note that if some stride has been detected (i.e., when
1611 * group->shared_tile->bound[i].shift is set), then a in (1) refers
1612 * to the shifted and scaled down version.
1614 * Constraints (1) are obtained by mapping the size constraints on the
1615 * shared/private memory tile back to the access relation.
1616 * Constraints (2) are obtained from the (recomputed) extent.
1618 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1620 int i;
1621 int n_index = group->array->n_index;
1622 isl_map *tile;
1623 isl_space *space;
1624 isl_set *local;
1625 isl_set *extent;
1627 space = isl_multi_aff_get_space(group->shared_tile->tiling);
1628 space = isl_space_range(space);
1629 local = isl_set_universe(space);
1630 for (i = 0; i < n_index; ++i) {
1631 isl_val *bound;
1633 local = isl_set_lower_bound_si(local, isl_dim_set, i, 0);
1634 bound = isl_val_copy(group->shared_tile->bound[i].size);
1635 bound = isl_val_sub_ui(bound, 1);
1636 local = isl_set_upper_bound_val(local, isl_dim_set, i, bound);
1638 local = isl_set_preimage_multi_aff(local,
1639 isl_multi_aff_copy(group->shared_tile->tiling));
1640 tile = isl_set_unwrap(local);
1641 extent = array_extent(group->array);
1642 tile = isl_map_intersect_range(tile, extent);
1644 return tile;
1647 /* Given a mapping "iterator_map" from the AST schedule to a domain,
1648 * return the corresponding mapping from the AST schedule to
1649 * to the first shared_len dimensions of the schedule computed by PPCG.
1651 static __isl_give isl_pw_multi_aff *compute_sched_to_shared(struct gpu_gen *gen,
1652 __isl_take isl_pw_multi_aff *iterator_map)
1654 isl_union_map *umap;
1655 isl_space *space;
1656 isl_map *map, *sched;;
1658 space = isl_space_range(isl_pw_multi_aff_get_space(iterator_map));
1659 space = isl_space_from_domain(space);
1660 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1662 umap = isl_union_map_copy(gen->shared_sched);
1663 umap = isl_union_map_apply_range(umap,
1664 isl_union_map_copy(gen->shared_proj));
1665 map = isl_union_map_extract_map(umap, space);
1666 isl_union_map_free(umap);
1668 sched = isl_map_preimage_domain_pw_multi_aff(map, iterator_map);
1669 sched = isl_map_detect_equalities(sched);
1671 return isl_pw_multi_aff_from_map(sched);
1674 /* Set unroll[j] if the input dimension j is involved in
1675 * the index expression represented by ma.
1677 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1678 void *user)
1680 int i, j;
1681 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1682 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1683 int *unroll = user;
1685 for (i = 0; i < n_out; ++i) {
1686 isl_aff *aff;
1688 aff = isl_multi_aff_get_aff(ma, i);
1689 for (j = 0; j < n_in; ++j)
1690 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1691 unroll[j] = 1;
1692 isl_aff_free(aff);
1695 isl_set_free(set);
1696 isl_multi_aff_free(ma);
1697 return 0;
1700 /* Given an array pos mapping input dimensions to the corresponding
1701 * output dimension, construct the corresponding map.
1703 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1704 int *pos, int len)
1706 int i;
1707 isl_constraint *c;
1708 isl_basic_map *bmap;
1709 isl_local_space *ls;
1711 dim = isl_space_add_dims(dim, isl_dim_in, len);
1712 dim = isl_space_add_dims(dim, isl_dim_out, len);
1713 bmap = isl_basic_map_universe(isl_space_copy(dim));
1714 ls = isl_local_space_from_space(dim);
1716 for (i = 0; i < len; ++i) {
1717 c = isl_equality_alloc(isl_local_space_copy(ls));
1718 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1719 -1);
1720 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1722 bmap = isl_basic_map_add_constraint(bmap, c);
1724 isl_local_space_free(ls);
1726 return isl_map_from_basic_map(bmap);
1729 /* Remove the private tiles from all array reference groups,
1730 * except for the groups of arrays that are marked force_private.
1732 static void remove_private_tiles(struct gpu_gen *gen)
1734 int i, j;
1736 for (i = 0; i < gen->prog->n_array; ++i) {
1737 struct gpu_array_info *array = &gen->prog->array[i];
1739 if (array->force_private)
1740 continue;
1742 for (j = 0; j < array->n_group; ++j) {
1743 struct gpu_array_ref_group *group = array->groups[j];
1745 group->private_tile = free_tile(group->private_tile);
1750 /* Find all loops involved in any of the index expressions for any of
1751 * the private accesses, move them innermost and then mark them as
1752 * requiring unrolling by setting gen->first_unroll.
1753 * The loops involved should all be parallel because of the checks
1754 * we performed in check_private_group_access. Moving them innermost
1755 * is therefore a valid transformation.
1757 * If any of the arrays are marked force_private, however, then
1758 * those loops may not be parallel with respect to the marked arrays.
1759 * If any of the loops would have to be moved innermost for the
1760 * (non forced) private accesses and if there are any force_private
1761 * arrays, then we revert the decision to map the selected arrays
1762 * to private memory. An alternative solution would be to expand
1763 * the force_private arrays.
1765 * Loops up to gen->shared_len are generated before the mapping to
1766 * threads is applied. They should therefore be ignored.
1768 * We compute the hidden equalities of the schedule first
1769 * since we will need them in our calls to isl_pw_multi_aff_from_map
1770 * and because we want to make sure that the same equalities
1771 * are also available to the code generator.
1773 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1774 __isl_take isl_union_map *sched)
1776 int i, j;
1777 int unroll[gen->thread_tiled_len];
1778 int perm[gen->thread_tiled_len];
1779 isl_space *dim;
1780 isl_map *permute;
1781 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1783 gen->first_unroll = -1;
1785 sched = isl_union_map_detect_equalities(sched);
1786 for (i = 0; i < gen->thread_tiled_len; ++i)
1787 unroll[i] = 0;
1788 for (i = 0; i < gen->prog->n_array; ++i) {
1789 struct gpu_array_info *array = &gen->prog->array[i];
1791 for (j = 0; j < array->n_group; ++j) {
1792 isl_union_map *access;
1793 isl_map *acc;
1794 isl_pw_multi_aff *pma;
1796 if (!array->groups[j]->private_tile)
1797 continue;
1799 access = group_access_relation(array->groups[j], 1, 1);
1800 access = isl_union_map_apply_domain(access,
1801 isl_union_map_copy(sched));
1803 acc = isl_map_from_union_map(access);
1804 pma = isl_pw_multi_aff_from_map(acc);
1805 isl_pw_multi_aff_foreach_piece(pma,
1806 &check_unroll, unroll);
1808 isl_pw_multi_aff_free(pma);
1812 for (i = gen->shared_len; i < len; ++i)
1813 if (unroll[i])
1814 break;
1816 if (i >= len)
1817 return sched;
1819 for (i = len; i < gen->thread_tiled_len; ++i)
1820 if (unroll[i])
1821 return sched;
1823 if (gen->any_force_private) {
1824 remove_private_tiles(gen);
1825 return sched;
1828 j = 0;
1829 for (i = 0; i < gen->shared_len; ++i)
1830 perm[i] = j++;
1831 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1832 if (!unroll[i])
1833 perm[i] = j++;
1834 gen->first_unroll = j - gen->shared_len;
1835 for (i = gen->shared_len; i < len; ++i)
1836 if (unroll[i])
1837 perm[i] = j++;
1839 dim = isl_union_map_get_space(sched);
1840 permute = permutation(dim, perm, gen->thread_tiled_len);
1841 sched = isl_union_map_apply_range(sched,
1842 isl_union_map_from_map(permute));
1844 return sched;
1847 /* Given a constraint
1849 * a(p,i) + j = g f(e)
1851 * or -a(p,i) - j = g f(e) if sign < 0,
1852 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1853 * a(p,i) is assumed to be an expression in only the parameters
1854 * and the input dimensions.
1856 static void extract_stride(__isl_keep isl_constraint *c,
1857 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1859 int i;
1860 isl_val *v;
1861 isl_space *space;
1862 unsigned nparam;
1863 unsigned nvar;
1864 isl_aff *aff;
1866 isl_val_free(bound->stride);
1867 bound->stride = isl_val_copy(stride);
1869 space = isl_constraint_get_space(c);
1870 space = isl_space_domain(space);
1872 nparam = isl_space_dim(space, isl_dim_param);
1873 nvar = isl_space_dim(space, isl_dim_set);
1875 v = isl_constraint_get_constant_val(c);
1876 if (sign < 0)
1877 v = isl_val_neg(v);
1878 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1879 aff = isl_aff_set_constant_val(aff, v);
1881 for (i = 0; i < nparam; ++i) {
1882 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1883 continue;
1884 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1885 if (sign < 0)
1886 v = isl_val_neg(v);
1887 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1890 for (i = 0; i < nvar; ++i) {
1891 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1892 continue;
1893 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1894 if (sign < 0)
1895 v = isl_val_neg(v);
1896 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1899 bound->shift = aff;
1902 /* Given an equality constraint of a map with a single output dimension j,
1903 * check if the constraint is of the form
1905 * a(p,i) + j = g f(e)
1907 * with a(p,i) an expression in the parameters and input dimensions
1908 * and f(e) an expression in the existentially quantified variables.
1909 * If so, and if g is larger than any such g from a previously considered
1910 * constraint, then call extract_stride to record the stride information
1911 * in bound.
1913 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1915 int i;
1916 isl_ctx *ctx;
1917 isl_val *v;
1918 unsigned n_div;
1919 struct gpu_array_bound *bound = user;
1921 ctx = isl_constraint_get_ctx(c);
1922 n_div = isl_constraint_dim(c, isl_dim_div);
1923 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1925 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1926 int s = isl_val_sgn(v);
1927 isl_val *stride = isl_val_zero(ctx);
1929 isl_val_free(v);
1930 for (i = 0; i < n_div; ++i) {
1931 v = isl_constraint_get_coefficient_val(c,
1932 isl_dim_div, i);
1933 stride = isl_val_gcd(stride, v);
1935 if (!isl_val_is_zero(stride) &&
1936 isl_val_gt(stride, bound->stride))
1937 extract_stride(c, bound, stride, s);
1939 isl_val_free(stride);
1940 } else
1941 isl_val_free(v);
1943 isl_constraint_free(c);
1944 return 0;
1947 /* Given contraints on an array index i, check if we can find
1948 * a shift a(p) and a stride g such that
1950 * a(p) + i = 0 mod g
1952 * If so, record the information in bound and apply the mapping
1953 * i -> (i + a(p))/g to the array index in bounds and return
1954 * the new constraints.
1955 * If not, simply return the original constraints.
1957 * If bounds is a subset of the space
1959 * D -> i
1961 * then the bound recorded in bound->shift is of the form
1963 * D -> s(D)
1965 * with s(D) equal to a(p) above.
1966 * The mapping recorded in bound->shift_map is of the form
1968 * [D -> i] -> [D -> (i + S(D))/g]
1970 * This mapping is computed as follows.
1971 * We first introduce "i" in the domain through precomposition
1972 * with [D -> i] -> D obtaining
1974 * [D -> i] -> s(D)
1976 * Adding [D -> i] -> i produces
1978 * [D -> i] -> i + s(D)
1980 * and the domain product with [D -> i] -> D yields
1982 * [D -> i] -> [D -> i + s(D)]
1984 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1986 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1987 __isl_take isl_basic_map *bounds)
1989 isl_space *space;
1990 isl_basic_map *hull;
1991 isl_basic_map *shift, *id, *bmap, *scale;
1992 isl_basic_set *bset;
1993 isl_aff *aff;
1995 bound->stride = NULL;
1997 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1999 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
2001 isl_basic_map_free(hull);
2003 if (!bound->stride)
2004 return bounds;
2006 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
2007 space = isl_basic_map_get_space(bounds);
2008 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
2009 shift = isl_basic_map_apply_range(bmap, shift);
2010 space = isl_basic_map_get_space(bounds);
2011 id = isl_basic_map_range_map(isl_basic_map_universe(space));
2012 shift = isl_basic_map_sum(id, shift);
2013 space = isl_basic_map_get_space(bounds);
2014 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
2015 shift = isl_basic_map_range_product(id, shift);
2017 space = isl_space_domain(isl_basic_map_get_space(bounds));
2018 id = isl_basic_map_identity(isl_space_map_from_set(space));
2019 space = isl_space_range(isl_basic_map_get_space(bounds));
2020 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2021 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
2022 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
2023 scale = isl_basic_map_from_aff(aff);
2024 scale = isl_basic_map_product(id, scale);
2026 bound->shift_map = isl_basic_map_apply_range(shift, scale);
2027 bmap = isl_basic_map_copy(bound->shift_map);
2028 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
2029 bounds = isl_basic_set_unwrap(bset);
2031 return bounds;
2034 /* Data used in compute_array_dim_size and compute_size_in_direction.
2036 * pos is the position of the variable representing the array index,
2037 * i.e., the variable for which want to compute the size. This variable
2038 * is also the last variable in the set.
2040 struct gpu_size_info {
2041 isl_basic_set *bset;
2042 struct gpu_array_bound *bound;
2043 int pos;
2046 /* Given a constraint from the basic set describing the bounds on
2047 * an array index, check if it is a lower bound, say m i >= b(x), and,
2048 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
2049 * upper bound. If so, and if this bound is smaller than any bound
2050 * derived from earlier constraints, set the size to this bound on
2051 * the expression and the lower bound to ceil(b(x)/m).
2053 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
2055 struct gpu_size_info *size = user;
2056 unsigned nparam;
2057 unsigned n_div;
2058 isl_val *v;
2059 isl_aff *aff;
2060 isl_aff *lb;
2062 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
2063 n_div = isl_constraint_dim(c, isl_dim_div);
2065 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
2066 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
2067 isl_constraint_free(c);
2068 return 0;
2071 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2072 aff = isl_aff_ceil(aff);
2074 lb = isl_aff_copy(aff);
2076 aff = isl_aff_neg(aff);
2077 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2079 v = isl_basic_set_max_val(size->bset, aff);
2080 isl_aff_free(aff);
2082 if (isl_val_is_int(v)) {
2083 v = isl_val_add_ui(v, 1);
2084 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
2085 isl_val_free(size->bound->size);
2086 size->bound->size = isl_val_copy(v);
2087 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
2088 isl_aff_free(size->bound->lb);
2089 size->bound->lb = isl_aff_copy(lb);
2092 isl_val_free(v);
2093 isl_aff_free(lb);
2095 isl_constraint_free(c);
2097 return 0;
2100 /* Given a basic map "bounds" that maps parameters and input dimensions
2101 * to a single output dimension, look for an expression in the parameters
2102 * and input dimensions such that the range of the output dimension shifted
2103 * by this expression is a constant.
2105 * In particular, we currently only consider lower bounds on the output
2106 * dimension as candidate expressions.
2108 static int compute_array_dim_size(struct gpu_array_bound *bound,
2109 __isl_take isl_basic_map *bounds)
2111 struct gpu_size_info size;
2113 bounds = isl_basic_map_detect_equalities(bounds);
2114 bounds = check_stride(bound, bounds);
2116 bound->size = NULL;
2117 bound->lb = NULL;
2119 size.bound = bound;
2120 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2121 size.bset = isl_basic_map_wrap(bounds);
2122 size.bset = isl_basic_set_flatten(size.bset);
2123 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2124 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2125 &size);
2126 isl_basic_set_free(size.bset);
2128 return bound->size ? 0 : -1;
2131 /* Check if we can find a memory tile for the given array
2132 * based on the given accesses, and if so, put the results in "tile".
2134 * We project the accesses on each index in turn and look for a parametric
2135 * offset such that the size is constant.
2137 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2139 int i;
2141 for (i = 0; i < tile->n; ++i) {
2142 isl_map *access_i;
2143 isl_basic_map *hull;
2145 access_i = isl_map_copy(access);
2146 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2147 access_i = isl_map_project_out(access_i, isl_dim_out,
2148 1, tile->n - (i + 1));
2149 access_i = isl_map_compute_divs(access_i);
2150 hull = isl_map_simple_hull(access_i);
2151 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2152 return 0;
2155 return 1;
2158 /* Construct a map with input the shared tile loops and the loops that
2159 * will be wrapped around the threads that relates these later loops
2160 * to the thread indices and then projects them out.
2162 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2164 isl_map *priv;
2165 isl_map *tiling;
2166 isl_map *proj;
2167 isl_set *par;
2168 isl_space *dim;
2170 dim = isl_union_map_get_space(gen->shared_sched);
2172 if (gen->options->wrap)
2173 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2174 gen->shared_len, gen->n_block, gen->block_dim);
2175 else
2176 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2177 gen->shared_len, gen->n_block, gen->block_dim);
2179 priv = tiling;
2181 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2182 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2183 gen->n_block, "t");
2185 priv = isl_map_align_params(priv, isl_set_get_space(par));
2186 priv = isl_map_intersect_range(priv, par);
2188 dim = isl_map_get_space(priv);
2189 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2190 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2191 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2192 gen->shared_len);
2194 priv = isl_map_apply_range(priv, proj);
2196 return priv;
2199 /* Construct a map from domain_dim to domain_dim that increments
2200 * the dimension at position "pos" and leaves all other dimensions
2201 * constant.
2203 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2205 int i;
2206 int len = isl_space_dim(domain_dim, isl_dim_set);
2207 isl_space *dim;
2208 isl_basic_map *next;
2209 isl_local_space *ls;
2211 dim = isl_space_map_from_set(domain_dim);
2212 next = isl_basic_map_universe(isl_space_copy(dim));
2213 ls = isl_local_space_from_space(dim);
2215 for (i = 0; i < len; ++i) {
2216 isl_constraint *c;
2218 c = isl_equality_alloc(isl_local_space_copy(ls));
2219 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2220 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2221 if (i == pos)
2222 c = isl_constraint_set_constant_si(c, 1);
2223 next = isl_basic_map_add_constraint(next, c);
2226 isl_local_space_free(ls);
2228 return isl_map_from_basic_map(next);
2231 /* Check if the given access is coalesced.
2232 * That is, check whether incrementing the dimension that will get
2233 * wrapped over the last thread index results in incrementing
2234 * the last array index.
2236 * This function is only called for access relations without reuse.
2238 static int access_is_coalesced(struct gpu_gen *gen,
2239 __isl_keep isl_union_map *access)
2241 isl_space *dim;
2242 isl_map *access_map;
2243 isl_map *next_thread_x;
2244 isl_map *next_element;
2245 isl_map *map;
2246 int coalesced;
2248 access = isl_union_map_copy(access);
2249 access = isl_union_map_apply_domain(access,
2250 isl_union_map_copy(gen->tiled_sched));
2251 access_map = isl_map_from_union_map(access);
2253 dim = isl_map_get_space(access_map);
2254 dim = isl_space_domain(dim);
2255 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2257 dim = isl_map_get_space(access_map);
2258 dim = isl_space_range(dim);
2259 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2261 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2262 map = isl_map_apply_range(map, access_map);
2264 coalesced = isl_map_is_subset(map, next_element);
2266 isl_map_free(next_element);
2267 isl_map_free(map);
2269 return coalesced;
2272 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2273 * dimensions of the computed schedule, check if it is bijective for
2274 * fixed values of the first gen->shared_len dimensions.
2275 * We perform this check by equating these dimensions to parameters.
2277 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2279 int res;
2280 isl_set *par;
2281 isl_space *space;
2283 access = isl_map_copy(access);
2284 space = isl_space_params(isl_map_get_space(access));
2285 par = parametrization(space, gen->shared_len + gen->n_block,
2286 0, gen->shared_len, "s");
2287 access = isl_map_intersect_domain(access, par);
2288 res = isl_map_is_bijective(access);
2289 isl_map_free(access);
2291 return res;
2294 /* Look for the last shared tile loop that affects the offset of "tile"
2295 * and return the result.
2296 * If there is no such loop, then return the index of the loop
2297 * before the first shared tile loop, in particular gen->tile_first - 1.
2299 static int compute_tile_last_shared(struct gpu_gen *gen,
2300 struct gpu_array_tile *tile)
2302 int i, j;
2304 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2305 for (i = 0; i < tile->n; ++i) {
2306 isl_aff *lb;
2307 isl_aff *shift;
2309 lb = tile->bound[i].lb;
2310 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2311 break;
2313 shift = tile->bound[i].shift;
2314 if (!shift)
2315 continue;
2316 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2317 break;
2319 if (i < tile->n)
2320 break;
2323 return j;
2326 /* Look for the last shared tile loop that affects the offset of the
2327 * shared or private tile and store the result in group->last_shared.
2328 * If there is no such loop, then group->last_shared is set to a value
2329 * before the first shared tile loop, in particular gen->tile_first - 1.
2330 * If there is no tile defined on the array reference group,
2331 * then set group->last_shared to gen->shared_len - 1.
2333 static void set_last_shared(struct gpu_gen *gen,
2334 struct gpu_array_ref_group *group)
2336 struct gpu_array_tile *tile;
2338 group->last_shared = gen->shared_len - 1;
2340 tile = group->private_tile;
2341 if (!tile)
2342 tile = group->shared_tile;
2343 if (!tile)
2344 return;
2346 group->last_shared = compute_tile_last_shared(gen, tile);
2349 /* Compute a privatized copy of all access relations from reference groups that
2350 * are mapped to private memory and store the result in gen->privatization.
2352 * Read-only scalars and arrays containing structures are not mapped
2353 * to private memory.
2355 static void compute_private_access(struct gpu_gen *gen)
2357 int i, j;
2358 isl_union_map *private;
2360 if (!gen->options->use_private_memory)
2361 return;
2363 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2365 for (i = 0; i < gen->prog->n_array; ++i) {
2366 struct gpu_array_info *array = &gen->prog->array[i];
2368 if (gpu_array_is_read_only_scalar(array))
2369 continue;
2370 if (array->has_compound_element)
2371 continue;
2373 for (j = 0; j < array->n_group; ++j) {
2374 if (!array->groups[j]->private_tile)
2375 continue;
2377 private = isl_union_map_union(private,
2378 group_access_relation(array->groups[j], 1, 1));
2382 if (isl_union_map_is_empty(private))
2383 isl_union_map_free(private);
2384 else {
2385 isl_union_map *priv;
2387 private = isl_union_map_apply_domain(private,
2388 isl_union_map_copy(gen->shared_sched));
2389 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2390 private = isl_union_map_apply_domain(private, priv);
2391 gen->private_access = private;
2395 /* Compute the size of the tile specified by "tile"
2396 * in number of elements and return the result.
2398 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2400 int i;
2401 isl_val *size;
2403 size = isl_val_one(ctx);
2405 for (i = 0; i < tile->n; ++i)
2406 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2408 return size;
2411 /* If max_shared_memory is not set to infinity (-1), then make
2412 * sure that the total amount of shared memory required by the
2413 * array reference groups mapped to shared memory is no larger
2414 * than this maximum.
2416 * We apply a greedy approach and discard (keep in global memory)
2417 * those groups that would result in a total memory size that
2418 * is larger than the maximum.
2420 * This function should be called after any function that may
2421 * affect the decision on whether to place a reference group
2422 * in private, shared or global memory.
2424 static void check_shared_memory_bound(struct gpu_gen *gen)
2426 int i, j;
2427 isl_val *left, *size;
2429 if (gen->options->max_shared_memory < 0)
2430 return;
2432 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2434 for (i = 0; i < gen->prog->n_array; ++i) {
2435 struct gpu_array_info *array = &gen->prog->array[i];
2437 for (j = 0; j < array->n_group; ++j) {
2438 struct gpu_array_ref_group *group;
2440 group = array->groups[j];
2441 if (group->private_tile)
2442 continue;
2443 if (!group->shared_tile)
2444 continue;
2446 size = tile_size(gen->ctx, group->shared_tile);
2447 size = isl_val_mul_ui(size, array->size);
2449 if (isl_val_le(size, left)) {
2450 left = isl_val_sub(left, size);
2451 continue;
2453 isl_val_free(size);
2455 group->shared_tile = free_tile(group->shared_tile);
2459 isl_val_free(left);
2462 /* Given a description of an array tile "tile" and the "space"
2464 * { D -> A }
2466 * where D represents the first shared_len schedule dimensions
2467 * and A represents the array, construct an isl_multi_aff
2469 * { [D[i] -> A[a]] -> A'[a'] }
2471 * with A' a scaled down copy of A according to the shifts and strides
2472 * in "tile". In particular,
2474 * a' = (a + shift(i))/stride
2476 * "insert_array" represents
2478 * { [D -> A] -> D }
2480 * and is used to insert A into the domain of functions that only
2481 * reference D.
2483 static __isl_give isl_multi_aff *strided_tile(
2484 struct gpu_array_tile *tile, __isl_keep isl_space *space,
2485 __isl_keep isl_multi_aff *insert_array)
2487 int i;
2488 isl_ctx *ctx;
2489 isl_multi_aff *shift;
2490 isl_multi_val *stride;
2491 isl_space *space2;
2492 isl_local_space *ls;
2493 isl_multi_aff *tiling;
2495 ctx = isl_space_get_ctx(space);
2496 space2 = isl_space_domain(isl_space_copy(space));
2497 ls = isl_local_space_from_space(space2);
2498 space2 = isl_space_range(isl_space_copy(space));
2499 stride = isl_multi_val_zero(space2);
2500 shift = isl_multi_aff_zero(isl_space_copy(space));
2502 for (i = 0; i < tile->n; ++i) {
2503 struct gpu_array_bound *bound = &tile->bound[i];
2504 isl_val *stride_i;
2505 isl_aff *shift_i;
2507 if (tile->bound[i].shift) {
2508 stride_i = isl_val_copy(bound->stride);
2509 shift_i = isl_aff_copy(bound->shift);
2510 } else {
2511 stride_i = isl_val_one(ctx);
2512 shift_i = isl_aff_zero_on_domain(
2513 isl_local_space_copy(ls));
2516 stride = isl_multi_val_set_val(stride, i, stride_i);
2517 shift = isl_multi_aff_set_aff(shift, i, shift_i);
2519 isl_local_space_free(ls);
2521 shift = isl_multi_aff_pullback_multi_aff(shift,
2522 isl_multi_aff_copy(insert_array));
2524 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2525 tiling = isl_multi_aff_add(tiling, shift);
2526 tiling = isl_multi_aff_scale_down_multi_val(tiling, stride);
2528 return tiling;
2531 /* Compute a tiling for the array reference group "group".
2533 * The tiling is of the form
2535 * { [D[i] -> A[a]] -> T[t] }
2537 * where D represents the first shared_len schedule dimensions,
2538 * A represents the global array and T represents the shared or
2539 * private memory tile. The name of T is the name of the local
2540 * array.
2542 * If there is any stride in the accesses, then the mapping is
2544 * t = (a + shift(i))/stride - lb(i)
2546 * otherwise, it is simply
2548 * t = a - lb(i)
2550 static void compute_group_tiling(struct gpu_array_ref_group *group)
2552 int i;
2553 struct gpu_array_tile *tile;
2554 struct gpu_array_info *array = group->array;
2555 isl_space *space;
2556 isl_multi_aff *tiling, *lb, *insert_array;
2557 isl_printer *p;
2558 char *local_name;
2560 tile = group->private_tile;
2561 if (!tile)
2562 tile = group->shared_tile;
2563 if (!tile)
2564 return;
2566 space = isl_map_get_space(group->access);
2567 insert_array = isl_multi_aff_domain_map(isl_space_copy(space));
2569 for (i = 0; i < tile->n; ++i)
2570 if (tile->bound[i].shift)
2571 break;
2573 if (i < tile->n)
2574 tiling = strided_tile(tile, space, insert_array);
2575 else
2576 tiling = isl_multi_aff_range_map(isl_space_copy(space));
2578 lb = isl_multi_aff_zero(space);
2579 for (i = 0; i < tile->n; ++i) {
2580 isl_aff *lb_i = isl_aff_copy(tile->bound[i].lb);
2581 lb = isl_multi_aff_set_aff(lb, i, lb_i);
2583 lb = isl_multi_aff_pullback_multi_aff(lb, insert_array);
2585 tiling = isl_multi_aff_sub(tiling, lb);
2587 p = isl_printer_to_str(isl_multi_aff_get_ctx(tiling));
2588 p = print_array_name(p, group);
2589 local_name = isl_printer_get_str(p);
2590 isl_printer_free(p);
2591 tiling = isl_multi_aff_set_tuple_name(tiling, isl_dim_out, local_name);
2592 free(local_name);
2594 tile->tiling = tiling;
2597 /* Compute a tiling for all the array reference groups.
2599 static void compute_group_tilings(struct gpu_gen *gen)
2601 int i, j;
2603 for (i = 0; i < gen->prog->n_array; ++i) {
2604 struct gpu_array_info *array = &gen->prog->array[i];
2606 for (j = 0; j < array->n_group; ++j)
2607 compute_group_tiling(array->groups[j]);
2611 /* Fill up the groups array with singleton groups, i.e., one group
2612 * per reference, initializing the array, access, write, n_ref and refs fields.
2613 * In particular the access field is initialized to the scheduled
2614 * access relation of the array reference.
2616 * Return the number of elements initialized, i.e., the number of
2617 * active references in the current kernel.
2619 static int populate_array_references(struct gpu_array_info *array,
2620 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2622 int i;
2623 int n;
2624 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2626 n = 0;
2627 for (i = 0; i < array->n_ref; ++i) {
2628 isl_union_map *umap;
2629 isl_map *map;
2630 struct gpu_array_ref_group *group;
2631 struct gpu_stmt_access *access = array->refs[i];
2633 map = isl_map_copy(access->access);
2634 umap = isl_union_map_from_map(map);
2635 umap = isl_union_map_apply_domain(umap,
2636 isl_union_map_copy(sched));
2638 if (isl_union_map_is_empty(umap)) {
2639 isl_union_map_free(umap);
2640 continue;
2643 map = isl_map_from_union_map(umap);
2644 map = isl_map_detect_equalities(map);
2646 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2647 assert(group);
2648 group->array = array;
2649 group->access = map;
2650 group->write = access->write;
2651 group->exact_write = access->exact_write;
2652 group->slice = access->n_index < array->n_index;
2653 group->refs = &array->refs[i];
2654 group->n_ref = 1;
2656 groups[n++] = group;
2659 return n;
2662 /* If group->n_ref == 1, then group->refs was set by
2663 * populate_array_references to point directly into
2664 * group->array->refs and should not be freed.
2665 * If group->n_ref > 1, then group->refs was set by join_groups
2666 * to point to a newly allocated array.
2668 static void free_array_ref_group(struct gpu_array_ref_group *group)
2670 if (!group)
2671 return;
2672 free_tile(group->shared_tile);
2673 free_tile(group->private_tile);
2674 isl_map_free(group->access);
2675 if (group->n_ref > 1)
2676 free(group->refs);
2677 free(group);
2680 /* Given a map where the input dimensions represent the tile loops,
2681 * eliminate the innermost of those that have a fixed value
2682 * until we reach one that does not (obviously) have a fixed value.
2684 static __isl_give isl_map *eliminate_fixed_inner_loops(
2685 __isl_take isl_map *access)
2687 int i, n;
2689 n = isl_map_dim(access, isl_dim_in);
2691 for (i = n - 1; i >= 0; --i) {
2692 if (!map_plain_is_fixed(access, isl_dim_in, i))
2693 break;
2694 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2696 return access;
2699 /* Check if the access relations of group1 and group2 overlap within
2700 * the innermost loop. In particular, ignore any inner dimension
2701 * with a fixed value.
2702 * The copying to and from shared memory will be performed within
2703 * the innermost actual loop so we are only allowed to consider
2704 * the dimensions up to that innermost loop while checking whether
2705 * two access relations overlap.
2707 static int accesses_overlap(struct gpu_array_ref_group *group1,
2708 struct gpu_array_ref_group *group2)
2710 int empty;
2711 isl_map *access1, *access2;
2713 access1 = isl_map_copy(group1->access);
2714 access1 = eliminate_fixed_inner_loops(access1);
2715 access2 = isl_map_copy(group2->access);
2716 access2 = eliminate_fixed_inner_loops(access2);
2717 access1 = isl_map_intersect(access1, access2);
2718 empty = isl_map_is_empty(access1);
2719 isl_map_free(access1);
2721 return !empty;
2724 /* Combine the given two groups into a single group, containing
2725 * the references of both groups.
2727 static struct gpu_array_ref_group *join_groups(
2728 struct gpu_array_ref_group *group1,
2729 struct gpu_array_ref_group *group2)
2731 int i;
2732 isl_ctx *ctx;
2733 struct gpu_array_ref_group *group;
2735 ctx = isl_map_get_ctx(group1->access);
2736 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2737 assert(group);
2738 group->array = group1->array;
2739 group->access = isl_map_union(isl_map_copy(group1->access),
2740 isl_map_copy(group2->access));
2741 group->write = group1->write || group2->write;
2742 group->exact_write = group1->exact_write && group2->exact_write;
2743 group->slice = group1->slice || group2->slice;
2744 group->n_ref = group1->n_ref + group2->n_ref;
2745 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2746 group->n_ref);
2747 assert(group->refs);
2748 for (i = 0; i < group1->n_ref; ++i)
2749 group->refs[i] = group1->refs[i];
2750 for (i = 0; i < group2->n_ref; ++i)
2751 group->refs[group1->n_ref + i] = group2->refs[i];
2753 return group;
2756 /* Combine the given two groups into a single group and free
2757 * the original two groups.
2759 static struct gpu_array_ref_group *join_groups_and_free(
2760 struct gpu_array_ref_group *group1,
2761 struct gpu_array_ref_group *group2)
2763 struct gpu_array_ref_group *group;
2765 group = join_groups(group1, group2);
2766 free_array_ref_group(group1);
2767 free_array_ref_group(group2);
2768 return group;
2771 /* Compute the private and/or shared memory tiles for the array
2772 * reference group "group" of array "array".
2773 * Return 0 on success and -1 on error.
2775 * If the array is a read-only scalar or if the user requested
2776 * not to use shared or private memory, then we do not need to do anything.
2778 * If any reference in the reference group accesses more than one element,
2779 * then we would have to make sure that the layout in shared memory
2780 * is the same as that in global memory. Since we do not handle this yet
2781 * (and it may not even be possible), we refuse to map to private or
2782 * shared memory in such cases.
2784 * If the array group involves any may writes (that are not must writes),
2785 * then we would have to make sure that we load the data into shared/private
2786 * memory first in case the data is not written by the kernel
2787 * (but still written back out to global memory).
2788 * Since we don't have any such mechanism at the moment, we don't
2789 * compute shared/private tiles for groups involving may writes.
2791 * We only try to compute a shared memory tile if there is any reuse
2792 * or if the access is not coalesced.
2794 * For computing a private memory tile, we also require that there is
2795 * some reuse. Moreover, we require that the access is private
2796 * to the thread. That is, we check that any given array element
2797 * is only accessed by a single thread.
2798 * We compute an access relation that maps the shared tile loop iterators
2799 * and the shared point loop iterators that will be wrapped over the
2800 * threads to the array elements.
2801 * We actually check that those iterators that will be wrapped
2802 * partition the array space. This check is stricter than necessary
2803 * since several iterations may be mapped onto the same thread
2804 * and then they could be allowed to access the same memory elements,
2805 * but our check does not allow this situation.
2807 * We also check that the index expression only depends on parallel
2808 * loops. That way, we can move those loops innermost and unroll them.
2809 * Again, we use a test that is stricter than necessary.
2810 * We actually check whether the index expression only depends
2811 * on the iterators that are wrapped over the threads.
2812 * These are necessarily parallel, but there may be more parallel loops.
2814 * Combining the injectivity of the first test with the single-valuedness
2815 * of the second test, we simply test for bijectivity.
2817 * If the array is marked force_private, then we bypass all checks
2818 * and assume we can (and should) use registers.
2820 * If it turns out we can (or have to) use registers, we compute
2821 * the private memory tile size using can_tile, after introducing a dependence
2822 * on the thread indices.
2824 static int compute_group_bounds_core(struct gpu_gen *gen,
2825 struct gpu_array_ref_group *group)
2827 isl_ctx *ctx = isl_space_get_ctx(group->array->space);
2828 isl_union_map *access;
2829 int n_index = group->array->n_index;
2830 int no_reuse;
2831 isl_map *acc;
2832 int force_private = group->array->force_private;
2833 int use_shared = gen->options->use_shared_memory;
2834 int use_private = force_private || gen->options->use_private_memory;
2836 if (!use_shared && !use_private)
2837 return 0;
2838 if (gpu_array_is_read_only_scalar(group->array))
2839 return 0;
2840 if (!force_private && !group->exact_write)
2841 return 0;
2842 if (group->slice)
2843 return 0;
2845 access = group_access_relation(group, 1, 1);
2846 no_reuse = isl_union_map_is_injective(access);
2848 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2849 group->shared_tile = create_tile(ctx, group->array->n_index);
2850 if (!can_tile(group->access, group->shared_tile))
2851 group->shared_tile = free_tile(group->shared_tile);
2854 if (!force_private && (!use_private || no_reuse)) {
2855 isl_union_map_free(access);
2856 return 0;
2859 access = isl_union_map_apply_domain(access,
2860 isl_union_map_copy(gen->shared_sched));
2862 acc = isl_map_from_union_map(access);
2864 if (!force_private && !access_is_bijective(gen, acc)) {
2865 isl_map_free(acc);
2866 return 0;
2869 group->private_tile = create_tile(gen->ctx, n_index);
2870 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2871 if (!can_tile(acc, group->private_tile))
2872 group->private_tile = free_tile(group->private_tile);
2874 isl_map_free(acc);
2876 if (force_private && !group->private_tile)
2877 isl_die(ctx, isl_error_internal,
2878 "unable to map array reference group to registers",
2879 return -1);
2881 return 0;
2884 /* Compute the private and/or shared memory tiles for the array
2885 * reference group "group" of array "array" and set last_shared.
2886 * Return 0 on success and -1 on error.
2888 static int compute_group_bounds(struct gpu_gen *gen,
2889 struct gpu_array_ref_group *group)
2891 if (compute_group_bounds_core(gen, group) < 0)
2892 return -1;
2893 set_last_shared(gen, group);
2895 return 0;
2898 /* If two groups have overlapping access relations (as determined by
2899 * the "overlap" function) and if one of them involves a write,
2900 * then merge the two groups into one.
2901 * If "compute_bounds" is set, then call compute_group_bounds
2902 * on the merged groups.
2904 * Return the updated number of groups.
2905 * Return -1 on error.
2907 static int group_writes(struct gpu_gen *gen,
2908 int n, struct gpu_array_ref_group **groups,
2909 int (*overlap)(struct gpu_array_ref_group *group1,
2910 struct gpu_array_ref_group *group2), int compute_bounds)
2912 int i, j;
2914 for (i = 0; i < n; ++i) {
2915 for (j = n - 1; j > i; --j) {
2916 if (!groups[i]->write && !groups[j]->write)
2917 continue;
2919 if (!overlap(groups[i], groups[j]))
2920 continue;
2922 groups[i] = join_groups_and_free(groups[i], groups[j]);
2923 if (compute_bounds &&
2924 compute_group_bounds(gen, groups[i]) < 0)
2925 return -1;
2926 if (j != n - 1)
2927 groups[j] = groups[n - 1];
2928 groups[n - 1] = NULL;
2929 n--;
2933 return n;
2936 /* If two groups have overlapping access relations (within the innermost
2937 * loop) and if one of them involves a write, then merge the two groups
2938 * into one.
2940 * Return the updated number of groups.
2942 static int group_overlapping_writes(struct gpu_gen *gen,
2943 int n, struct gpu_array_ref_group **groups)
2945 return group_writes(gen, n, groups, &accesses_overlap, 0);
2948 /* Check if the access relations of group1 and group2 overlap within
2949 * the outermost min(group1->last_shared, group2->last_shared) loops.
2951 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2952 struct gpu_array_ref_group *group2)
2954 int last_shared;
2955 int dim;
2956 int empty;
2957 isl_map *map_i, *map_j, *map;
2959 last_shared = group1->last_shared;
2960 if (group2->last_shared < last_shared)
2961 last_shared = group2->last_shared;
2962 map_i = isl_map_copy(group1->access);
2963 dim = isl_map_dim(map_i, isl_dim_in);
2964 map_i = isl_map_eliminate(map_i, isl_dim_in,
2965 last_shared + 1, dim - (last_shared + 1));
2966 map_j = isl_map_copy(group2->access);
2967 map_j = isl_map_eliminate(map_j, isl_dim_in,
2968 last_shared + 1, dim - (last_shared + 1));
2969 map = isl_map_intersect(map_i, map_j);
2970 empty = isl_map_is_empty(map);
2971 isl_map_free(map);
2973 return !empty;
2976 /* If two groups have overlapping access relations (within the outer
2977 * last_shared loops) and if one of them involves a write,
2978 * then merge the two groups into one.
2980 * Return the updated number of groups.
2982 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2983 struct gpu_array_ref_group **groups)
2985 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2988 /* Is the size of the tile specified by "tile" smaller than the sum of
2989 * the sizes of the tiles specified by "tile1" and "tile2"?
2991 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2992 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2994 int smaller;
2995 isl_val *size, *size1, *size2;
2997 size = tile_size(ctx, tile);
2998 size1 = tile_size(ctx, tile1);
2999 size2 = tile_size(ctx, tile2);
3001 size = isl_val_sub(size, size1);
3002 size = isl_val_sub(size, size2);
3003 smaller = isl_val_is_neg(size);
3005 isl_val_free(size);
3007 return smaller;
3010 /* Given an initial grouping of array references and shared memory tiles
3011 * for each group that allows for a shared memory tile, merge two groups
3012 * if both have a shared memory tile, the merged group also has
3013 * a shared memory tile and the size of the tile for the merge group
3014 * is smaller than the sum of the tile sizes of the individual groups.
3016 * If merging two groups decreases the "last_shared" dimension of
3017 * one or both of the two groups, then we need to check for overlapping
3018 * writes again.
3020 * Return the number of groups after merging.
3021 * Return -1 on error.
3023 static int group_common_shared_memory_tile(struct gpu_gen *gen,
3024 struct gpu_array_info *array, int n,
3025 struct gpu_array_ref_group **groups)
3027 int i, j;
3028 int recompute_overlap = 0;
3029 isl_ctx *ctx = isl_space_get_ctx(array->space);
3031 for (i = 0; i < n; ++i) {
3032 if (!groups[i]->shared_tile)
3033 continue;
3034 for (j = n - 1; j > i; --j) {
3035 isl_map *map;
3036 int empty;
3037 struct gpu_array_ref_group *group;
3039 if (!groups[j]->shared_tile)
3040 continue;
3042 map = isl_map_intersect(isl_map_copy(groups[i]->access),
3043 isl_map_copy(groups[j]->access));
3044 empty = isl_map_is_empty(map);
3045 isl_map_free(map);
3047 if (empty)
3048 continue;
3050 group = join_groups(groups[i], groups[j]);
3051 if (compute_group_bounds(gen, group) < 0) {
3052 free_array_ref_group(group);
3053 return -1;
3055 if (!group->shared_tile ||
3056 !smaller_tile(ctx, group->shared_tile,
3057 groups[i]->shared_tile,
3058 groups[j]->shared_tile)) {
3059 free_array_ref_group(group);
3060 continue;
3063 if (group->last_shared < groups[i]->last_shared ||
3064 group->last_shared < groups[j]->last_shared)
3065 recompute_overlap = 1;
3066 free_array_ref_group(groups[i]);
3067 free_array_ref_group(groups[j]);
3068 groups[i] = group;
3069 if (j != n - 1)
3070 groups[j] = groups[n - 1];
3071 n--;
3075 if (recompute_overlap)
3076 n = group_last_shared_overlapping_writes(gen, n, groups);
3077 return n;
3080 /* Set array->n_group and array->groups to n and groups.
3082 * Additionally, set the "nr" field of each group
3083 * and the "group" field of each reference in each group.
3085 static void set_array_groups(struct gpu_array_info *array,
3086 int n, struct gpu_array_ref_group **groups)
3088 int i, j;
3090 array->n_group = n;
3091 array->groups = groups;
3093 for (i = 0; i < n; ++i) {
3094 groups[i]->nr = i;
3096 for (j = 0; j < groups[i]->n_ref; ++j)
3097 groups[i]->refs[j]->group = i;
3101 /* Group array references that should be considered together when
3102 * deciding whether to access them from private, shared or global memory.
3103 * Return -1 on error.
3105 * In particular, if two array references overlap and if one of them
3106 * is a write, then the two references are grouped together.
3107 * We first perform an initial grouping based only on the access relation.
3108 * After computing shared and private memory tiles, we check for
3109 * overlapping writes again, but this time taking into account
3110 * the "last_shared" property.
3112 * Furthermore, if two groups admit a shared memory tile and if the
3113 * combination of the two also admits a shared memory tile, we merge
3114 * the two groups.
3116 * If the array contains structures, then there is no need to compute
3117 * reference groups since we do not map such arrays to private or shared
3118 * memory.
3120 static int group_array_references(struct gpu_gen *gen,
3121 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
3123 int i;
3124 int n;
3125 isl_ctx *ctx = isl_union_map_get_ctx(sched);
3126 struct gpu_array_ref_group **groups;
3128 if (array->has_compound_element)
3129 return 0;
3131 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
3132 array->n_ref);
3133 if (!groups)
3134 return -1;
3136 n = populate_array_references(array, sched, groups);
3138 n = group_overlapping_writes(gen, n, groups);
3140 for (i = 0; i < n; ++i)
3141 if (compute_group_bounds(gen, groups[i]) < 0)
3142 n = -1;
3144 n = group_last_shared_overlapping_writes(gen, n, groups);
3146 n = group_common_shared_memory_tile(gen, array, n, groups);
3148 set_array_groups(array, n, groups);
3150 if (n >= 0)
3151 return 0;
3153 for (i = 0; i < array->n_ref; ++i)
3154 free_array_ref_group(groups[i]);
3155 return -1;
3158 /* Take tiled_sched, project it onto the shared tile loops and
3159 * the loops that will be wrapped over the threads and
3160 * store the result in gen->shared_sched.
3161 * Also compute a projection that projects out the loops that will be
3162 * wrapped over the threads and store this projection in gen->shared_proj.
3164 static void compute_shared_sched(struct gpu_gen *gen)
3166 isl_space *dim;
3167 isl_map *proj;
3168 isl_set *par;
3169 isl_union_map *sched;
3171 sched = isl_union_map_copy(gen->tiled_sched);
3173 dim = isl_union_map_get_space(sched);
3174 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
3175 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3177 dim = isl_union_map_get_space(sched);
3178 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
3180 gen->shared_sched = sched;
3181 gen->shared_proj = isl_union_map_from_map(proj);
3184 /* For each scalar in the input program, check if there are any
3185 * order dependences active inside the current kernel, within
3186 * the same iteration of the host schedule.
3187 * If so, mark the scalar as force_private so that it will be
3188 * mapped to a register.
3190 static void check_scalar_live_ranges(struct gpu_gen *gen)
3192 int i;
3193 isl_map *proj;
3194 isl_union_map *sched;
3195 isl_union_set *domain;
3196 isl_union_map *same_host_iteration;
3198 gen->any_force_private = 0;
3200 if (!gen->options->live_range_reordering)
3201 return;
3203 sched = gen->shared_sched;
3204 sched = isl_union_map_universe(isl_union_map_copy(sched));
3205 domain = isl_union_map_domain(sched);
3207 sched = isl_union_map_copy(gen->sched);
3208 proj = projection(isl_union_map_get_space(sched),
3209 gen->untiled_len, gen->tile_first);
3210 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
3211 same_host_iteration = isl_union_map_apply_range(sched,
3212 isl_union_map_reverse(isl_union_map_copy(sched)));
3214 for (i = 0; i < gen->prog->n_array; ++i) {
3215 struct gpu_array_info *array = &gen->prog->array[i];
3216 isl_union_map *order;
3218 array->force_private = 0;
3219 if (array->n_index != 0)
3220 continue;
3221 order = isl_union_map_copy(array->dep_order);
3222 order = isl_union_map_intersect_domain(order,
3223 isl_union_set_copy(domain));
3224 order = isl_union_map_intersect_range(order,
3225 isl_union_set_copy(domain));
3226 order = isl_union_map_intersect(order,
3227 isl_union_map_copy(same_host_iteration));
3228 if (!isl_union_map_is_empty(order)) {
3229 array->force_private = 1;
3230 gen->any_force_private = 1;
3232 isl_union_map_free(order);
3235 isl_union_map_free(same_host_iteration);
3236 isl_union_set_free(domain);
3239 /* Group references of all arrays in the program.
3241 static int group_references(struct gpu_gen *gen)
3243 int i;
3244 int r = 0;
3245 isl_union_map *sched;
3247 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3248 isl_union_map_copy(gen->shared_proj));
3250 for (i = 0; i < gen->prog->n_array; ++i) {
3251 r = group_array_references(gen, &gen->prog->array[i], sched);
3252 if (r < 0)
3253 break;
3256 isl_union_map_free(sched);
3258 return r;
3261 /* Free all array information that is local to the current kernel.
3263 static void free_local_array_info(struct gpu_gen *gen)
3265 int i, j;
3267 for (i = 0; i < gen->prog->n_array; ++i) {
3268 struct gpu_array_info *array = &gen->prog->array[i];
3270 for (j = 0; j < array->n_group; ++j)
3271 free_array_ref_group(array->groups[j]);
3272 free(array->groups);
3276 /* Compute the size of a bounding box around the origin and "set",
3277 * where "set" is assumed to contain only non-negative elements.
3278 * In particular, compute the maximal value of "set" in each direction
3279 * and add one.
3281 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
3282 __isl_keep isl_set *context)
3284 int i, n;
3285 isl_multi_pw_aff *mpa;
3287 n = isl_set_dim(set, isl_dim_set);
3288 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
3289 for (i = 0; i < n; ++i) {
3290 isl_space *space;
3291 isl_aff *one;
3292 isl_pw_aff *bound;
3294 bound = isl_set_dim_max(isl_set_copy(set), i);
3295 bound = isl_pw_aff_coalesce(bound);
3296 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
3298 space = isl_pw_aff_get_domain_space(bound);
3299 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
3300 one = isl_aff_add_constant_si(one, 1);
3301 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
3302 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
3304 isl_set_free(set);
3306 return mpa;
3309 /* Compute the effective grid size as a list of the sizes in each dimension.
3311 * The grid size specified by the user or set by default
3312 * in read_grid_sizes() and applied in tile_schedule(),
3313 * may be too large for the given code in the sense that
3314 * it may contain blocks that don't need to execute anything.
3315 * We therefore don't return this grid size, but instead the
3316 * smallest grid size that ensures that all blocks that actually
3317 * execute code are included in the grid.
3319 * We first extract a description of the grid, i.e., the possible values
3320 * of the block ids, from gen->tiled_sched.
3321 * The block ids are parameters in gen->tiled_sched.
3322 * We simply need to change them into set dimensions.
3324 * Then, for each block dimension, we compute the maximal value of the block id
3325 * and add one.
3327 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
3328 struct ppcg_kernel *kernel)
3330 int i;
3331 isl_set *grid;
3333 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
3334 grid = isl_set_from_params(grid);
3335 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
3336 for (i = 0; i < gen->n_grid; ++i) {
3337 int pos;
3338 char name[20];
3340 snprintf(name, sizeof(name), "b%d", i);
3341 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
3342 assert(pos >= 0);
3343 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
3344 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
3347 return extract_size(grid, kernel->context);
3350 /* Compute the size of a fixed bounding box around the origin and "set",
3351 * where "set" is assumed to contain only non-negative elements,
3352 * and store the results in "size".
3353 * In particular, compute the maximal value of "set" in each direction
3354 * and add one.
3356 static void extract_fixed_size(__isl_take isl_set *set, int *size)
3358 int i, n;
3359 isl_local_space *ls;
3360 isl_aff *obj;
3362 n = isl_set_dim(set, isl_dim_set);
3363 ls = isl_local_space_from_space(isl_set_get_space(set));
3364 obj = isl_aff_zero_on_domain(ls);
3365 for (i = 0; i < n; ++i) {
3366 isl_val *max;
3368 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
3369 max = isl_set_max_val(set, obj);
3370 size[i] = isl_val_get_num_si(max) + 1;
3371 isl_val_free(max);
3372 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
3374 isl_aff_free(obj);
3375 isl_set_free(set);
3378 /* Compute the effective block size as a list of the sizes in each dimension
3379 * and store the sizes in kernel->block_dim.
3381 * The block size specified by the user or set by default
3382 * in read_block_sizes() and applied in thread_tile_schedule(),
3383 * may be too large for the given code in the sense that
3384 * it may contain threads that don't need to execute anything.
3385 * We therefore don't store this block size in kernel->block_dim,
3386 * but instead the smallest block size that ensures that all threads
3387 * that actually execute code are included in the block.
3389 * The current implementation eliminates all parameters, ensuring
3390 * that the size is a fixed constant in each dimension.
3391 * In principle we could also compute parametric sizes.
3392 * We would have to make sure to project out all b%d and t%d parameters,
3393 * however.
3395 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3397 int i;
3398 int nparam;
3399 isl_set *block;
3400 isl_multi_pw_aff *mpa;
3402 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3403 block = isl_set_from_params(block);
3404 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3405 kernel->n_block = gen->n_block;
3406 for (i = 0; i < gen->n_block; ++i) {
3407 int pos;
3408 char name[20];
3410 snprintf(name, sizeof(name), "t%d", i);
3411 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3412 assert(pos >= 0);
3413 block = isl_set_equate(block, isl_dim_param, pos,
3414 isl_dim_set, i);
3416 nparam = isl_set_dim(block, isl_dim_param);
3417 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3419 extract_fixed_size(block, kernel->block_dim);
3422 void ppcg_kernel_free(void *user)
3424 struct ppcg_kernel *kernel = user;
3425 int i;
3427 if (!kernel)
3428 return;
3430 isl_multi_pw_aff_free(kernel->grid_size);
3431 isl_set_free(kernel->context);
3432 isl_union_set_free(kernel->arrays);
3433 isl_space_free(kernel->space);
3434 isl_ast_node_free(kernel->tree);
3436 for (i = 0; i < kernel->n_array; ++i)
3437 isl_pw_aff_list_free(kernel->array[i].bound);
3438 free(kernel->array);
3440 for (i = 0; i < kernel->n_var; ++i) {
3441 free(kernel->var[i].name);
3442 isl_vec_free(kernel->var[i].size);
3444 free(kernel->var);
3446 free(kernel);
3449 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3450 struct ppcg_kernel_var *var)
3452 int j;
3453 struct gpu_array_tile *tile;
3454 isl_printer *p;
3455 char *name;
3457 var->array = group->array;
3459 tile = group->private_tile;
3460 var->type = ppcg_access_private;
3461 if (!tile) {
3462 tile = group->shared_tile;
3463 var->type = ppcg_access_shared;
3466 p = isl_printer_to_str(ctx);
3467 p = print_array_name(p, group);
3468 var->name = isl_printer_get_str(p);
3469 isl_printer_free(p);
3471 var->size = isl_vec_alloc(ctx, group->array->n_index);
3473 for (j = 0; j < group->array->n_index; ++j)
3474 var->size = isl_vec_set_element_val(var->size, j,
3475 isl_val_copy(tile->bound[j].size));
3478 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3480 int i, j, n;
3482 n = 0;
3483 for (i = 0; i < gen->prog->n_array; ++i) {
3484 struct gpu_array_info *array = &gen->prog->array[i];
3486 for (j = 0; j < array->n_group; ++j) {
3487 struct gpu_array_ref_group *group = array->groups[j];
3488 if (group->private_tile || group->shared_tile)
3489 ++n;
3493 kernel->n_var = n;
3494 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3495 assert(kernel->var);
3497 n = 0;
3498 for (i = 0; i < gen->prog->n_array; ++i) {
3499 struct gpu_array_info *array = &gen->prog->array[i];
3501 for (j = 0; j < array->n_group; ++j) {
3502 struct gpu_array_ref_group *group = array->groups[j];
3503 if (!group->private_tile && !group->shared_tile)
3504 continue;
3505 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3506 ++n;
3511 /* The sizes of the arrays on the host that have been computed by
3512 * extract_array_info may depend on the parameters. Use the extra
3513 * constraints on the parameters that are valid at "host_domain"
3514 * to simplify these expressions and store the results in kernel->array.
3516 * We only need these localized bounds for arrays that are accessed
3517 * by the current kernel. If we have found at least one reference group
3518 * then the array is accessed by the kernel. If the array has compound
3519 * elements then we skipped the construction of array reference groups.
3521 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3522 __isl_keep isl_set *host_domain)
3524 int i, j;
3525 isl_set *context;
3527 kernel->array = isl_calloc_array(gen->ctx,
3528 struct gpu_local_array_info, gen->prog->n_array);
3529 assert(kernel->array);
3530 kernel->n_array = gen->prog->n_array;
3532 context = isl_set_copy(host_domain);
3533 context = isl_set_params(context);
3535 for (i = 0; i < gen->prog->n_array; ++i) {
3536 struct gpu_array_info *array = &gen->prog->array[i];
3537 isl_pw_aff_list *local;
3539 if (array->n_group == 0 && !array->has_compound_element)
3540 continue;
3542 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3544 for (j = 0; j < array->n_index; ++j) {
3545 isl_pw_aff *pwaff;
3547 pwaff = isl_pw_aff_copy(array->bound[j]);
3548 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3549 local = isl_pw_aff_list_add(local, pwaff);
3552 kernel->array[i].n_index = array->n_index;
3553 kernel->array[i].bound = local;
3555 isl_set_free(context);
3558 /* Find the element in gen->stmt that has the given "id".
3559 * Return NULL if no such gpu_stmt can be found.
3561 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3563 int i;
3565 for (i = 0; i < prog->n_stmts; ++i) {
3566 if (id == prog->stmts[i].id)
3567 break;
3570 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3573 /* Set gen->tile_len and gen->n_parallel to those of the statement
3574 * affected by the first map (part of the schedule)
3575 * on which this function is called.
3576 * Because of the way the schedule is constructed, the other statements
3577 * in the list, if any, should have the same values for these properties.
3579 static int extract_tile_len(__isl_take isl_map *map, void *user)
3581 struct gpu_gen *gen = (struct gpu_gen *) user;
3582 isl_id *id;
3583 struct gpu_stmt *stmt;
3585 id = isl_map_get_tuple_id(map, isl_dim_in);
3586 stmt = find_stmt(gen->prog, id);
3587 isl_id_free(id);
3589 isl_map_free(map);
3591 if (!stmt)
3592 isl_die(gen->ctx, isl_error_unknown,
3593 "statement not found", return -1);
3595 gen->tile_len = stmt->tile_len;
3596 gen->n_parallel = stmt->n_parallel;
3598 return -1;
3601 void ppcg_kernel_stmt_free(void *user)
3603 int i;
3604 struct ppcg_kernel_stmt *stmt = user;
3606 if (!stmt)
3607 return;
3609 switch (stmt->type) {
3610 case ppcg_kernel_copy:
3611 isl_ast_expr_free(stmt->u.c.index);
3612 isl_ast_expr_free(stmt->u.c.local_index);
3613 break;
3614 case ppcg_kernel_domain:
3615 isl_id_to_ast_expr_free(stmt->u.d.ref2expr);
3616 break;
3617 case ppcg_kernel_sync:
3618 break;
3621 free(stmt);
3624 /* Set the options of "context" to
3626 * { space -> [x] : x >= first }
3628 static __isl_give isl_ast_build *set_unroll(
3629 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3630 int first)
3632 isl_ctx *ctx;
3633 isl_map *unroll;
3634 isl_union_map *opt;
3636 ctx = isl_ast_build_get_ctx(build);
3638 space = isl_space_from_domain(space);
3639 space = isl_space_add_dims(space, isl_dim_out, 1);
3640 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3641 unroll = isl_map_universe(space);
3642 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3643 opt = isl_union_map_from_map(unroll);
3645 build = isl_ast_build_set_options(build, opt);
3647 return build;
3650 /* Return a list of isl_ids of the form "prefix%d".
3652 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3653 int n, const char *prefix)
3655 int i;
3656 char name[10];
3657 isl_id_list *names;
3659 names = isl_id_list_alloc(ctx, n);
3660 for (i = 0; i < n; ++i) {
3661 isl_id *id;
3663 snprintf(name, sizeof(name), "%s%d", prefix, i);
3664 id = isl_id_alloc(ctx, name, NULL);
3665 names = isl_id_list_add(names, id);
3668 return names;
3671 /* Extend the schedule "schedule" with the part of "extension"
3672 * starting at "first" up to "len".
3674 static __isl_give isl_union_map *extend_schedule(
3675 __isl_take isl_union_map *schedule,
3676 __isl_take isl_union_map *extension, int first, int len)
3678 isl_space *space;
3679 isl_map *proj;
3680 isl_union_map *umap;
3681 isl_set *set;
3683 space = isl_union_map_get_space(schedule);
3684 space = isl_space_set_from_params(space);
3685 space = isl_space_add_dims(space, isl_dim_set, len);
3686 proj = isl_set_identity(isl_set_universe(space));
3687 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3688 extension = isl_union_map_apply_range(extension,
3689 isl_union_map_from_map(proj));
3691 schedule = isl_union_map_range_product(schedule, extension);
3693 return schedule;
3696 /* Return the gpu_stmt_access in the list "accesses" that corresponds
3697 * to "ref_id".
3699 static struct gpu_stmt_access *find_access(struct gpu_stmt_access *accesses,
3700 __isl_keep isl_id *ref_id)
3702 struct gpu_stmt_access *access;
3704 for (access = accesses; access; access = access->next)
3705 if (access->ref_id == ref_id)
3706 return access;
3708 return NULL;
3711 /* Return the index of the array called "name" in the list of arrays.
3713 static int find_array_index(struct gpu_gen *gen, const char *name)
3715 int i;
3717 for (i = 0; i < gen->prog->n_array; ++i)
3718 if (!strcmp(name, gen->prog->array[i].name))
3719 return i;
3721 return -1;
3724 /* Internal data structure for the index and AST expression transformation
3725 * callbacks for pet_stmt_build_ast_exprs.
3727 * "accesses" is the list of gpu_stmt_access in the statement.
3728 * "iterator_map" expresses the statement iterators in terms of
3729 * the AST loop iterators.
3730 * "sched2shared" expresses the first shared_len dimensions of
3731 * the computed schedule in terms of the AST loop iterators.
3733 * The following fields are set in transform_index and used in transform_expr.
3734 * "array" is the array that is being accessed.
3735 * "global" is set if the global array is accessed (rather than
3736 * shared/private memory).
3737 * "local_array" refers to information on the array specialized
3738 * to the current kernel.
3740 struct ppcg_transform_data {
3741 struct gpu_gen *gen;
3742 struct gpu_stmt_access *accesses;
3743 isl_pw_multi_aff *iterator_map;
3744 isl_pw_multi_aff *sched2shared;
3746 struct gpu_array_info *array;
3747 int global;
3748 struct gpu_local_array_info *local_array;
3751 /* Return the name of the outer array (of structs) accessed by "access".
3753 static const char *get_outer_array_name(__isl_keep isl_map *access)
3755 isl_space *space;
3756 const char *name;
3758 space = isl_space_range(isl_map_get_space(access));
3759 while (space && isl_space_is_wrapping(space))
3760 space = isl_space_domain(isl_space_unwrap(space));
3761 name = isl_space_get_tuple_name(space, isl_dim_set);
3762 isl_space_free(space);
3764 return name;
3767 /* Index transformation callback for pet_stmt_build_ast_exprs.
3769 * "index" expresses the array indices in terms of statement iterators
3771 * We first reformulate "index" in terms of the AST loop iterators.
3772 * Then we check if we are accessing the global array or
3773 * a shared/private copy. In the former case, we simply return
3774 * the updated index. If "index" is an affine expression rather
3775 * than an array access, then we also return the updated index here.
3777 * If no reference groups have been computed for the array,
3778 * then we can only be accessing the global array.
3780 * Otherwise, we apply the tiling to the index.
3781 * This tiling is of the form
3783 * [D -> A] -> T
3785 * The index is of the form
3787 * L -> A
3789 * We update the tiling to refer to the AST loop iteratos
3791 * [L -> A] -> T
3793 * and modify index to keep track of those iterators
3795 * L -> [L -> A]
3797 * Combining these two yields a tiled index expression in terms
3798 * of the AST loop iterators
3800 * L -> T
3802 static __isl_give isl_multi_pw_aff *transform_index(
3803 __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *ref_id,
3804 void *user)
3806 struct ppcg_transform_data *data = user;
3807 struct gpu_stmt_access *access;
3808 struct gpu_array_ref_group *group;
3809 struct gpu_array_tile *tile;
3810 isl_pw_multi_aff *iterator_map;
3811 int i;
3812 const char *name;
3813 isl_space *space;
3814 isl_multi_pw_aff *tiling;
3815 isl_pw_multi_aff *pma;
3816 isl_multi_pw_aff *mpa;
3818 data->array = NULL;
3820 iterator_map = isl_pw_multi_aff_copy(data->iterator_map);
3821 index = isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map);
3823 access = find_access(data->accesses, ref_id);
3824 if (!access)
3825 return index;
3826 if (!isl_map_has_tuple_name(access->access, isl_dim_out))
3827 return index;
3829 name = get_outer_array_name(access->access);
3830 i = find_array_index(data->gen, name);
3831 if (i < 0)
3832 isl_die(isl_multi_pw_aff_get_ctx(index), isl_error_internal,
3833 "cannot find array",
3834 return isl_multi_pw_aff_free(index));
3835 data->array = &data->gen->prog->array[i];
3836 data->local_array = &data->gen->kernel->array[i];
3838 if (access->group < 0) {
3839 data->global = 1;
3840 return index;
3843 group = data->array->groups[access->group];
3844 tile = group->private_tile;
3845 if (!tile)
3846 tile = group->shared_tile;
3847 data->global = !tile;
3848 if (!tile)
3849 return index;
3851 space = isl_space_range(isl_multi_pw_aff_get_space(index));
3852 space = isl_space_map_from_set(space);
3853 pma = isl_pw_multi_aff_identity(space);
3854 pma = isl_pw_multi_aff_product(
3855 isl_pw_multi_aff_copy(data->sched2shared), pma);
3856 tiling = isl_multi_pw_aff_from_multi_aff(
3857 isl_multi_aff_copy(tile->tiling));
3858 tiling = isl_multi_pw_aff_pullback_pw_multi_aff(tiling, pma);
3860 space = isl_space_domain(isl_multi_pw_aff_get_space(index));
3861 space = isl_space_map_from_set(space);
3862 mpa = isl_multi_pw_aff_identity(space);
3863 index = isl_multi_pw_aff_range_product(mpa, index);
3864 index = isl_multi_pw_aff_pullback_multi_pw_aff(tiling, index);
3866 return index;
3869 /* Dereference "expr" by adding an index [0].
3870 * The original "expr" is assumed not to have any indices.
3872 * If "expr" is a member access, then the dereferencing needs
3873 * to be applied to the structure argument of this member access.
3875 static __isl_give isl_ast_expr *dereference(__isl_take isl_ast_expr *expr)
3877 isl_ctx *ctx;
3878 isl_ast_expr *res;
3879 isl_ast_expr_list *list;
3881 if (isl_ast_expr_get_op_type(expr) == isl_ast_op_member) {
3882 isl_ast_expr *arg;
3884 arg = isl_ast_expr_get_op_arg(expr, 0);
3885 arg = dereference(arg);
3886 expr = isl_ast_expr_set_op_arg(expr, 0, arg);
3888 return expr;
3891 ctx = isl_ast_expr_get_ctx(expr);
3892 res = isl_ast_expr_from_val(isl_val_zero(ctx));
3893 list = isl_ast_expr_list_from_ast_expr(res);
3894 res = isl_ast_expr_get_op_arg(expr, 0);
3895 res = isl_ast_expr_access(res, list);
3896 isl_ast_expr_free(expr);
3898 return res;
3901 /* Linearize the index expression "expr" based on the array bounds
3902 * of "array".
3904 * That is, transform expression
3906 * A[i_0][i_1]...[i_n]
3908 * to
3910 * A[(..((i_0 * b_1 + i_1) ... ) * b_n + i_n]
3912 * where b_0, b_1, ..., b_n are the bounds on the array.
3914 * If the base of "expr" is a member access, then the linearization needs
3915 * to be applied to the structure argument of this member access.
3917 * In the base case, if "expr" has no arguments (other than the name of
3918 * the array), then we are passing an entire array to a function.
3919 * In this case, there is nothing to linearize.
3920 * Note that at this point an expression with no arguments can
3921 * only be an entire array because the scalar case and
3922 * the case of single struct are handled by the caller.
3924 * If the number of specified index expressions in "expr"
3925 * is smaller than the dimension of the accessed array,
3926 * then the missing i_j also do not appear in the linearized expression.
3927 * Furthermore, since such an expression does not refer to a single
3928 * element while the default linearized expression would refer to
3929 * a single element, we return the expression
3931 * A + (..((i_0 * b_1 + i_1) ... ) * b_n]
3933 * instead. Note that because of the special case handling above,
3934 * we can assume here that here that there is at least one index expression.
3936 __isl_give isl_ast_expr *gpu_local_array_info_linearize_index(
3937 struct gpu_local_array_info *array, __isl_take isl_ast_expr *expr)
3939 int i, n;
3940 isl_ctx *ctx;
3941 isl_set *context;
3942 isl_ast_expr *arg0;
3943 isl_ast_expr *res;
3944 isl_ast_expr_list *list;
3945 isl_ast_build *build;
3947 arg0 = isl_ast_expr_get_op_arg(expr, 0);
3948 if (isl_ast_expr_get_type(arg0) == isl_ast_expr_op &&
3949 isl_ast_expr_get_op_type(arg0) == isl_ast_op_member) {
3950 isl_ast_expr *arg;
3952 arg = isl_ast_expr_get_op_arg(arg0, 0);
3953 arg = gpu_local_array_info_linearize_index(array, arg);
3954 arg0 = isl_ast_expr_set_op_arg(arg0, 0, arg);
3955 expr = isl_ast_expr_set_op_arg(expr, 0, arg0);
3957 return expr;
3959 isl_ast_expr_free(arg0);
3961 if (isl_ast_expr_get_op_n_arg(expr) == 1)
3962 return expr;
3964 ctx = isl_ast_expr_get_ctx(expr);
3965 context = isl_set_universe(isl_space_params_alloc(ctx, 0));
3966 build = isl_ast_build_from_context(context);
3968 n = isl_ast_expr_get_op_n_arg(expr);
3969 res = isl_ast_expr_get_op_arg(expr, 1);
3970 for (i = 1; i < array->n_index; ++i) {
3971 isl_pw_aff *bound_i;
3972 isl_ast_expr *expr_i;
3974 bound_i = isl_pw_aff_list_get_pw_aff(array->bound, i);
3975 expr_i = isl_ast_build_expr_from_pw_aff(build, bound_i);
3976 res = isl_ast_expr_mul(res, expr_i);
3978 if (i + 1 >= n)
3979 continue;
3980 expr_i = isl_ast_expr_get_op_arg(expr, i + 1);
3981 res = isl_ast_expr_add(res, expr_i);
3984 isl_ast_build_free(build);
3986 if (1 + array->n_index > n) {
3987 res = isl_ast_expr_add(isl_ast_expr_get_op_arg(expr, 0), res);
3988 } else {
3989 list = isl_ast_expr_list_from_ast_expr(res);
3990 res = isl_ast_expr_get_op_arg(expr, 0);
3991 res = isl_ast_expr_access(res, list);
3994 isl_ast_expr_free(expr);
3996 return res;
3999 /* AST expression transformation callback for pet_stmt_build_ast_exprs.
4001 * If the AST expression refers to a global scalar that is not
4002 * a read-only scalar, then its address was passed to the kernel and
4003 * we need to dereference it.
4005 * If the AST expression refers to an access to a global array,
4006 * then we linearize the access exploiting the bounds in data->local_array.
4008 static __isl_give isl_ast_expr *transform_expr(__isl_take isl_ast_expr *expr,
4009 __isl_keep isl_id *id, void *user)
4011 struct ppcg_transform_data *data = user;
4013 if (!data->array)
4014 return expr;
4015 if (gpu_array_is_read_only_scalar(data->array))
4016 return expr;
4017 if (!data->global)
4018 return expr;
4019 if (data->array->n_index == 0)
4020 return dereference(expr);
4021 if (!data->array->linearize)
4022 return expr;
4024 return gpu_local_array_info_linearize_index(data->local_array, expr);
4027 /* This function is called for each instance of a user statement
4028 * in the kernel.
4030 * We attach a struct ppcg_kernel_stmt to the "node", containing
4031 * a computed AST expression for each access.
4032 * These AST expressions are computed from iterator_map,
4033 * which expresses the domain
4034 * elements in terms of the generated loops, and sched2shared,
4035 * which expresses the first shared_len dimensions of the schedule
4036 * computed by PPCG in terms of the generated loops.
4038 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
4039 __isl_keep isl_ast_build *build, void *user)
4041 struct ppcg_transform_data data;
4042 struct gpu_gen *gen = (struct gpu_gen *) user;
4043 struct ppcg_kernel_stmt *stmt;
4044 isl_id *id;
4045 isl_pw_multi_aff *sched2shared;
4046 isl_map *map;
4047 isl_pw_multi_aff *iterator_map;
4048 isl_ast_expr *expr, *arg;
4049 isl_union_map *schedule;
4050 int i, n;
4052 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4053 if (!stmt)
4054 return isl_ast_node_free(node);
4056 expr = isl_ast_node_user_get_expr(node);
4057 arg = isl_ast_expr_get_op_arg(expr, 0);
4058 id = isl_ast_expr_get_id(arg);
4060 schedule = isl_ast_build_get_schedule(build);
4061 map = isl_map_reverse(isl_map_from_union_map(schedule));
4062 iterator_map = isl_pw_multi_aff_from_map(map);
4063 sched2shared = compute_sched_to_shared(gen,
4064 isl_pw_multi_aff_copy(iterator_map));
4066 stmt->type = ppcg_kernel_domain;
4067 stmt->u.d.stmt = find_stmt(gen->prog, id);
4068 if (!stmt->u.d.stmt)
4069 goto error;
4071 data.gen = gen;
4072 data.accesses = stmt->u.d.stmt->accesses;
4073 data.iterator_map = iterator_map;
4074 data.sched2shared = sched2shared;
4075 stmt->u.d.ref2expr = pet_stmt_build_ast_exprs(stmt->u.d.stmt->stmt,
4076 build, &transform_index, &data,
4077 &transform_expr, &data);
4079 isl_id_free(id);
4080 isl_pw_multi_aff_free(iterator_map);
4081 isl_pw_multi_aff_free(sched2shared);
4082 isl_ast_expr_free(arg);
4083 isl_ast_expr_free(expr);
4085 id = isl_id_alloc(gen->ctx, NULL, stmt);
4086 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4087 return isl_ast_node_set_annotation(node, id);
4088 error:
4089 isl_id_free(id);
4090 isl_pw_multi_aff_free(iterator_map);
4091 ppcg_kernel_stmt_free(stmt);
4092 isl_pw_multi_aff_free(sched2shared);
4093 return isl_ast_node_free(node);
4096 /* This function is called when code has been generated for the shared
4097 * tile loops. The "schedule" refers only to the original statements.
4099 * We extend the schedule with that part of gen->local_sched that hasn't
4100 * been taken into account yet. This introduces parameters referring
4101 * to thread ids in the schedule, so we add them (with the appropriate
4102 * bounds to the context as well).
4103 * Finally, we set the appropriate unrolling options
4104 * if gen->first_unroll is set.
4106 static __isl_give isl_ast_node *create_domain_leaf(
4107 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
4108 void *user)
4110 struct gpu_gen *gen = (struct gpu_gen *) user;
4111 isl_space *space;
4112 isl_union_map *sched;
4113 isl_ast_node *tree;
4114 isl_set *set;
4115 isl_id_list *iterators;
4116 int n;
4118 schedule = extend_schedule(schedule,
4119 isl_union_map_copy(gen->local_sched),
4120 gen->shared_len, gen->thread_tiled_len);
4122 space = isl_ast_build_get_schedule_space(build);
4123 set = isl_set_universe(space);
4124 set = add_bounded_parameters(set, gen->kernel->n_block,
4125 gen->kernel->block_dim, "t");
4126 build = isl_ast_build_restrict(build, set);
4128 n = gen->thread_tiled_len - gen->shared_len;
4130 if (gen->first_unroll >= 0) {
4131 space = isl_space_set_alloc(gen->ctx, 0, n);
4132 build = set_unroll(build, space, gen->first_unroll);
4134 iterators = generate_names(gen->ctx, n, "c");
4135 build = isl_ast_build_set_iterators(build, iterators);
4136 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
4137 tree = isl_ast_build_ast_from_schedule(build, schedule);
4138 isl_ast_build_free(build);
4140 return tree;
4143 /* This function is called for each statement node in the AST of the code
4144 * for copying to or from shared/private memory.
4145 * Attach a pointer to a ppcg_kernel_stmt representing the copy
4146 * statement to the node.
4147 * The statement name is "read" or "write", depending on whether we are
4148 * reading from global memory or writing to global memory.
4149 * The name of the T space is {shared,private}_<array>.
4151 * The schedule is of the form
4153 * type[A -> T] -> L
4155 * where A refers to a piece of an array and T to the corresponding
4156 * shifted tile. We split this schedule into mappings L -> A and L -> T
4157 * and store the corresponding expressions in stmt->index and stmt->local_index,
4158 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
4160 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
4161 __isl_keep isl_ast_build *build, void *user)
4163 struct gpu_gen *gen = (struct gpu_gen *) user;
4164 struct ppcg_kernel_stmt *stmt;
4165 isl_id *id;
4166 isl_ast_expr *expr;
4167 isl_space *space;
4168 isl_map *access, *local_access, *map;
4169 isl_pw_multi_aff *pma;
4170 const char *type;
4171 int array_index;
4173 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4174 if (!stmt)
4175 return isl_ast_node_free(node);
4177 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
4178 type = isl_map_get_tuple_name(access, isl_dim_in);
4179 stmt->u.c.read = !strcmp(type, "read");
4180 access = isl_map_reverse(access);
4181 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
4182 local_access = isl_map_copy(access);
4184 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
4185 id = isl_map_get_tuple_id(access, isl_dim_out);
4186 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4187 access = isl_map_apply_range(access, map);
4188 pma = isl_pw_multi_aff_from_map(access);
4189 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4190 stmt->u.c.index = expr;
4192 map = isl_map_range_map(isl_map_universe(space));
4193 id = isl_map_get_tuple_id(local_access, isl_dim_out);
4194 map = isl_map_set_tuple_id(map, isl_dim_in, id);
4195 local_access = isl_map_apply_range(local_access, map);
4196 pma = isl_pw_multi_aff_from_map(local_access);
4197 expr = isl_ast_build_access_from_pw_multi_aff(build, pma);
4198 stmt->u.c.local_index = expr;
4200 stmt->u.c.array = gen->copy_group->array;
4201 array_index = stmt->u.c.array - gen->prog->array;
4202 stmt->u.c.local_array = &gen->kernel->array[array_index];
4203 stmt->type = ppcg_kernel_copy;
4205 id = isl_id_alloc(gen->ctx, NULL, stmt);
4206 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4207 return isl_ast_node_set_annotation(node, id);
4210 /* Given a schedule of the form
4212 * [S -> A] -> L
4214 * (with S the first shared_len dimensions of the computed schedule,
4215 * A the array and L the schedule correponding to the generated loops),
4216 * indicating where to copy the array elements that need to be copied,
4217 * construct code for performing the copying.
4219 * "group" is the array reference group that is being copied
4220 * "type" is either "read" or "write"
4221 * private is set if copying needs to be performed to/from registers
4223 * We first construct a mapping to a shifted tile of the array,
4225 * [S -> A] -> T(S,A) (1)
4227 * If private is set, then we also use this mapping as a schedule
4228 * (which is already thread-specific and will be completely unrolled).
4229 * Otherwise, we wrap/tile the range over the threads.
4230 * The result is
4232 * [S -> A] -> T'(S,A)
4234 * Combined with the given schedule, we have
4236 * [S -> A] -> [L -> T'(S,A)] (2)
4238 * From the shifted tile mapping, we construct a mapping
4240 * [S -> A] -> [A -> T(S,A)]
4242 * and apply it to the schedule (2), obtaining
4244 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
4246 * Note that we can project out S because it is uniquely defined by L.
4248 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
4249 __isl_take isl_map *sched,
4250 const char *type, struct gpu_array_ref_group *group,
4251 __isl_take isl_ast_build *build, int private)
4253 isl_space *space;
4254 isl_ast_node *tree;
4255 isl_map *schedule, *shift, *map;
4256 isl_set *set;
4257 isl_id_list *iterators;
4258 int n;
4260 shift = shift_access(group);
4262 schedule = isl_map_copy(shift);
4263 schedule = isl_map_reset_tuple_id(schedule, isl_dim_out);
4264 if (!private)
4265 schedule = tile_access_schedule(gen, schedule);
4267 n = isl_map_dim(schedule, isl_dim_out);
4268 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
4269 set = add_bounded_parameters(set, gen->kernel->n_block,
4270 gen->kernel->block_dim, "t");
4272 schedule = isl_map_range_product(sched, schedule);
4274 space = isl_space_domain(isl_map_get_space(shift));
4275 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
4276 map = isl_map_range_product(map, shift);
4278 schedule = isl_map_apply_domain(schedule, map);
4280 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, type);
4282 build = isl_ast_build_restrict(build, set);
4284 gen->copy_group = group;
4286 if (private) {
4287 space = isl_space_range(isl_map_get_space(schedule));
4288 space = isl_space_range(isl_space_unwrap(space));
4289 build = set_unroll(build, space, 0);
4291 iterators = generate_names(gen->ctx, n, "c");
4292 build = isl_ast_build_set_iterators(build, iterators);
4293 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
4294 tree = isl_ast_build_ast_from_schedule(build,
4295 isl_union_map_from_map(schedule));
4296 isl_ast_build_free(build);
4298 return tree;
4301 /* Return code for reading into or writing from shared memory
4302 * the given array reference group.
4304 * If we are performing a read from global memory to shared memory and
4305 * if the array involved is not a scalar, then we copy
4306 * the entire tile to shared memory. This may result in some extra
4307 * elements getting copied, but it should lead to simpler code
4308 * (which means that fewer registers may be needed) and less divergence.
4310 * Otherwise, we only copy the elements that will be read or have been written
4311 * in the kernel.
4314 * The input "sched" is of the form.
4316 * type[S -> A] -> L
4318 * with S the first shared_len dimensions of the computed schedule,
4319 * A the array and L the schedule correponding to the generated loops.
4321 * We first drop "type",
4323 * [S -> A] -> L
4325 * If the above conditions are satisfied, we project out A,
4326 * resulting in
4328 * S -> L
4330 * and then introduce the group tile [S -> T], resulting in
4332 * [S -> T] -> L
4334 static __isl_give isl_ast_node *copy_group_shared_accesses(
4335 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4336 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4338 const char *type;
4339 int read;
4340 isl_union_map *access;
4342 type = isl_map_get_tuple_name(sched, isl_dim_in);
4343 read = !strcmp(type, "read");
4345 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4347 if (read && !gpu_array_is_scalar(group->array)) {
4348 isl_space *space;
4349 isl_map *map;
4351 space = isl_space_domain(isl_map_get_space(sched));
4352 space = isl_space_unwrap(space);
4353 map = isl_map_domain_map(isl_map_universe(space));
4354 sched = isl_map_apply_domain(sched, map);
4356 map = group_tile(group);
4357 map = isl_map_reverse(isl_map_domain_map(map));
4358 sched = isl_map_apply_domain(sched, map);
4361 return copy_access(gen, sched, type, group, build, 0);
4364 /* Return code for reading into or writing from private memory
4365 * the given array reference group.
4367 * Let S be the first shared_len dimensions of the computed schedule,
4368 * D the iteration domains, A the array and L the schedule correponding
4369 * to the generated loops.
4370 * "sched" is of the form
4372 * type[S -> A] -> L
4374 * where type is either "read" or "write".
4375 * We apply the privatization D -> S(t), with t the thread ids,
4376 * to the access relation D -> A to obtain the privatized access relation
4378 * S(t) -> A
4380 * We drop the type from "sched" and intersect with the privatized access
4381 * relation to obtain
4383 * [S(t) -> A] -> L
4385 static __isl_give isl_ast_node *copy_group_private_accesses(
4386 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4387 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4389 const char *type;
4390 int read;
4391 isl_union_map *priv;
4392 isl_union_map *access;
4393 isl_map *access_map;
4395 type = isl_map_get_tuple_name(sched, isl_dim_in);
4396 read = !strcmp(type, "read");
4398 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4399 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4400 priv);
4402 access = group_access_relation(group, read, !read);
4403 access = isl_union_map_apply_domain(access, priv);
4404 access_map = isl_map_from_union_map(access);
4406 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4407 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4409 return copy_access(gen, sched, type, group, build, 1);
4412 /* Return code for reading into or writing from shared or private memory.
4414 * "schedule" is of the form
4416 * type[S -> A] -> L
4418 * with S be the first shared_len dimensions of the computed schedule,
4419 * A the array and L the schedule correponding to the generated loops.
4420 * The array reference group is attached to "type".
4422 static __isl_give isl_ast_node *create_access_leaf(
4423 struct gpu_gen *gen, __isl_take isl_map *schedule,
4424 __isl_take isl_ast_build *build)
4426 struct gpu_array_ref_group *group;
4427 isl_id *id;
4429 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4430 group = isl_id_get_user(id);
4431 isl_id_free(id);
4433 if (group->private_tile)
4434 return copy_group_private_accesses(gen, group, schedule,
4435 build);
4436 else
4437 return copy_group_shared_accesses(gen, group, schedule,
4438 build);
4441 /* Create a domain node representing a synchronization.
4443 static __isl_give isl_ast_node *create_sync_leaf(
4444 struct gpu_gen *gen, __isl_take isl_map *schedule,
4445 __isl_take isl_ast_build *build)
4447 struct ppcg_kernel_stmt *stmt;
4448 isl_id *id;
4449 isl_space *space;
4450 isl_ast_node *node;
4451 isl_ast_expr *expr;
4453 isl_map_free(schedule);
4455 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4456 if (!stmt)
4457 return NULL;
4459 stmt->type = ppcg_kernel_sync;
4461 space = isl_ast_build_get_schedule_space(build);
4462 space = isl_space_from_domain(space);
4463 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4464 expr = isl_ast_build_call_from_pw_multi_aff(build,
4465 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4466 node = isl_ast_node_alloc_user(expr);
4467 isl_ast_build_free(build);
4469 id = isl_id_alloc(gen->ctx, NULL, stmt);
4470 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4471 return isl_ast_node_set_annotation(node, id);
4474 /* This function is called during the code generation at the point
4475 * where the schedule domain element is completely determined by
4476 * the generated code. The input schedule contains the original
4477 * statements as well as synchronization and copy "statements".
4478 * The latter are scheduled at different points than any of the original
4479 * statements, so they will only arrive here in isolation.
4481 * If the current schedule only refers to a single statement,
4482 * we check if it is a copy or synchronization statement and
4483 * call the appropriate functions.
4484 * Otherwise, we assume we are dealing with the original statements
4485 * and we call create_domain_leaf.
4487 static __isl_give isl_ast_node *create_kernel_leaf(
4488 __isl_take isl_ast_build *build, void *user)
4490 struct gpu_gen *gen = (struct gpu_gen *) user;
4491 isl_map *map;
4492 isl_union_map *schedule;
4493 const char *name;
4495 schedule = isl_ast_build_get_schedule(build);
4497 if (isl_union_map_n_map(schedule) != 1)
4498 return create_domain_leaf(schedule, build, user);
4500 map = isl_map_from_union_map(schedule);
4501 name = isl_map_get_tuple_name(map, isl_dim_in);
4502 if (!strcmp(name, "read") || !strcmp(name, "write"))
4503 return create_access_leaf(gen, map, build);
4504 if (!strcmp(name, "sync"))
4505 return create_sync_leaf(gen, map, build);
4507 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4510 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4511 * have value 0) and all even schedule dimensions as "unroll".
4513 * That is, the options look as follows
4515 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4516 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4518 * The even positions are used to be able to schedule copying blocks
4519 * and synchronization before or after each level of the shared memory
4520 * tile loops and we want to make sure that code for these is generated
4521 * separately (within each level).
4523 static __isl_give isl_ast_build *set_atomic_and_unroll(
4524 __isl_take isl_ast_build *build,
4525 __isl_take isl_space *space, int sched_len)
4527 isl_ctx *ctx;
4528 isl_map *map;
4529 isl_constraint *c;
4530 isl_union_map *opt;
4531 isl_local_space *ls;
4532 int i, n;
4534 ctx = isl_ast_build_get_ctx(build);
4536 space = isl_space_params(space);
4537 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4538 space = isl_space_from_domain(space);
4539 space = isl_space_add_dims(space, isl_dim_out, 2);
4540 map = isl_map_universe(isl_space_copy(space));
4541 for (i = 0; i < sched_len; i += 2)
4542 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4543 ls = isl_local_space_from_space(isl_map_get_space(map));
4544 c = isl_equality_alloc(ls);
4545 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4546 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4547 c = isl_constraint_set_constant_si(c, 1);
4548 map = isl_map_add_constraint(map, c);
4549 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4550 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4551 opt = isl_union_map_from_map(map);
4553 map = isl_map_universe(space);
4554 ls = isl_local_space_from_space(isl_map_get_space(map));
4555 c = isl_equality_alloc(ls);
4556 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4557 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4558 map = isl_map_add_constraint(map, c);
4559 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4560 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4561 opt = isl_union_map_add_map(opt, map);
4563 build = isl_ast_build_set_options(build, opt);
4565 return build;
4568 /* Return a map that maps a space of dimension gen->shared_len
4569 * to its last dimensions starting at gen->tile_first.
4570 * The range is of dimension
4572 * 2 * (gen->shared_len - gen->tile_first) + 1
4574 * The input dimensions are mapped to the odd dimensions in the output,
4575 * while the even dimensions (except 2*pos) are fixed to 0.
4576 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4577 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4578 * are mapped to the output. The remaining input dimensions are projected
4579 * out and the corresponding output dimensions are fixed to 0.
4581 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4582 __isl_take isl_space *space, int pos, int val)
4584 int i, n;
4585 isl_map *proj;
4587 space = isl_space_set_from_params(space);
4588 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4589 space = isl_space_map_from_set(space);
4590 proj = isl_map_identity(space);
4591 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4592 n = gen->shared_len - gen->tile_first;
4593 for (i = 0; i <= n; ++i) {
4594 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4595 if (i == pos)
4596 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4597 else
4598 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4601 if (pos < 0)
4602 return proj;
4604 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4605 gen->shared_len - (gen->tile_first + pos));
4606 for (i = pos; i < n; ++i)
4607 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4609 return proj;
4612 /* Given the AST context schedule "schedule" and the mapping from
4613 * domains to the shared tile loops "shared_sched", add a schedule
4614 * for a synchronization operation at position "val" of loop level "pos".
4616 * schedule is of the form
4618 * D -> L
4620 * (with D the iteration domains and L the already generated loops),
4621 * while shared_sched is of the form
4623 * D -> S
4625 * We combine them into
4627 * L -> S
4629 * apply a mapping
4631 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4633 * and use the result as a schedule for "sync".
4635 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4636 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4637 __isl_keep isl_union_map *shared_sched, int pos, int val)
4639 isl_space *space;
4640 isl_map *proj, *map;
4642 shared_sched = isl_union_map_copy(shared_sched);
4643 schedule = isl_union_map_copy(schedule);
4645 space = isl_union_map_get_space(shared_sched);
4646 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4647 map = isl_map_from_union_map(schedule);
4649 proj = insert_even(gen, space, pos, val);
4650 map = isl_map_apply_range(map, proj);
4651 map = isl_map_from_range(isl_map_wrap(map));
4652 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4654 res = isl_union_map_add_map(res, map);
4656 return res;
4659 /* Given a set of wrapped references "ref", return the corresponding
4660 * access relations based on the tagged access relations "tagged".
4662 * The elements of "ref" are of the form
4664 * [D -> R]
4666 * with D an iteration domains and R a reference.
4667 * The elements of "tagged" are of the form
4669 * [D -> R] -> A
4671 * with A an array.
4673 * Extend "tagged" to include the iteration domain in the range, i.e.,
4675 * [D -> R] -> [D -> A]
4677 * apply the result to "ref" and then unwrap the resulting set
4678 * to obtain relations of the form
4680 * D -> A
4682 static __isl_give isl_union_map *wrapped_reference_to_access(
4683 __isl_take isl_union_set *ref, __isl_take isl_union_map *tagged)
4685 isl_union_map *tag2access;
4687 tag2access = isl_union_map_copy(tagged);
4688 tag2access = isl_union_map_universe(tag2access);
4689 tag2access = isl_union_set_unwrap(isl_union_map_domain(tag2access));
4690 tag2access = isl_union_map_domain_map(tag2access);
4691 tag2access = isl_union_map_range_product(tag2access, tagged);
4693 ref = isl_union_set_coalesce(ref);
4694 ref = isl_union_set_apply(ref, tag2access);
4696 return isl_union_set_unwrap(ref);
4699 /* Given an access relation "access" from "group", remove those reads
4700 * if ("read" is 1) or writes (if "read" is 0) that are only needed to
4701 * communicate data within the same iteration of the last_shared dimension
4702 * of the group.
4704 * If the access is a read then it is necessarily an element of
4706 * live_in union (range flow)
4708 * where live_in and flow may be overapproximations.
4709 * If the access is a write then it is necessarily an element of
4711 * live_out union (domain flow)
4713 * In both cases, the access relation is also a subset of
4714 * the group access relation.
4716 * Essentially, we compute the intersection of "access" with either
4718 * live_in union (range non-local-flow)
4720 * or
4722 * live_out union (domain non-local-flow)
4724 * We first construct a relation "local"
4726 * [[D -> R] -> [D' -> R']]
4728 * of pairs of domain iterations accessing the reference group
4729 * and references in the group that are scheduled to the same iteration
4730 * of the last_shared dimension.
4732 * If this relation does not intersect the dataflow dependences,
4733 * then there is nothing we can possibly remove and we simply
4734 * return the input.
4736 * Otherwise, we remove the "local" dataflow dependences from
4737 * the set of all dataflow dependences.
4738 * Note that if the potential dataflow dependences are an overapproximation
4739 * of the actual dataflow dependences, then the result remains an
4740 * overapproximation of the non-local dataflow dependences.
4741 * Copying to/from global memory is only needed for the references
4742 * in the domain/range of the result or for accesses that are live out/in
4743 * for the entire scop.
4745 * We therefore map the domain/range of the "external" relation
4746 * to the corresponding access relation and take the union with
4747 * the live out/in relation.
4749 static __isl_give isl_union_map *remove_local_accesses(struct gpu_gen *gen,
4750 struct gpu_array_ref_group *group, __isl_take isl_union_map *access,
4751 int read)
4753 int empty;
4754 isl_union_map *tagger;
4755 isl_union_set *domain;
4756 isl_space *space;
4757 isl_union_map *sched, *local, *tagged, *external;
4758 isl_union_set *tag_set;
4759 isl_map *proj;
4761 if (isl_union_map_is_empty(access))
4762 return access;
4764 tagged = group_tagged_access_relation(group);
4766 sched = isl_union_map_copy(gen->sched);
4768 space = isl_union_map_get_space(sched);
4769 proj = projection(space, gen->untiled_len, group->last_shared + 1);
4770 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4772 tagger = isl_union_map_copy(gen->prog->scop->tagger);
4773 domain = isl_union_map_domain(isl_union_map_copy(tagged));
4774 tagger = isl_union_map_intersect_range(tagger, domain);
4775 sched = isl_union_map_apply_domain(sched, tagger);
4777 local = isl_union_map_apply_range(sched,
4778 isl_union_map_reverse(isl_union_map_copy(sched)));
4779 local = isl_union_map_intersect(local,
4780 isl_union_map_copy(gen->prog->scop->tagged_dep_flow));
4782 empty = isl_union_map_is_empty(local);
4783 if (empty < 0 || empty) {
4784 isl_union_map_free(tagged);
4785 isl_union_map_free(local);
4786 if (empty < 0)
4787 return isl_union_map_free(access);
4788 return access;
4791 external = isl_union_map_copy(gen->prog->scop->tagged_dep_flow);
4792 external = isl_union_map_intersect_params(external,
4793 isl_set_copy(gen->prog->scop->context));
4794 external = isl_union_map_subtract(external, local);
4796 if (read) {
4797 tag_set = isl_union_map_range(external);
4798 external = wrapped_reference_to_access(tag_set, tagged);
4799 external = isl_union_map_union(external,
4800 isl_union_map_copy(gen->prog->scop->live_in));
4801 } else {
4802 tag_set = isl_union_map_domain(external);
4803 external = wrapped_reference_to_access(tag_set, tagged);
4804 external = isl_union_map_union(external,
4805 isl_union_map_copy(gen->prog->scop->live_out));
4808 access = isl_union_map_intersect(access, external);
4810 return access;
4813 /* Given the AST context schedule "schedule" and the mapping from
4814 * domains to the shared tile loops "shared_sched", add a schedule
4815 * for copying an array reference group to/from shared/private memory.
4816 * "read" is set if data should be copied from global memory
4817 * to shared/private memory.
4818 * "k" represents the current group
4819 * "s" is the total number of groups
4821 * We schedule an operation before or after the innermost loop
4822 * of "shared_sched" that affects the tile of the array reference group.
4824 * schedule is of the form
4826 * D -> L
4828 * (with D the iteration domains and L the already generated loops),
4829 * while shared_sched is of the form
4831 * D -> S
4833 * We first compute the access relation for the reference group
4835 * D -> A
4837 * and remove from this access relation those reads or writes
4838 * that only needed to communicate data within the same iteration
4839 * of the last_shared dimension of the group.
4840 * We then combine what is left with shared_sched into
4842 * D -> [S -> A]
4844 * If this results in an empty relation, no copying needs to be performed
4845 * at this point.
4846 * Otherwise, we invert the relation and combine it with "schedule" into
4848 * [S -> A] -> L
4850 * The actual additional piece of the schedule is obtained from combining
4852 * [S -> A] -> S
4854 * with a mapping
4856 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4858 * The position of "val" corresponds to the innermost loop that affects
4859 * the tile and the value indicates where the copying is scheduled
4860 * with respect to the actual kernel code (at value 0).
4861 * Reads are schedule before the code, writes to global memory from
4862 * private memory are scheduled at values 1 to s, writes to global
4863 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4865 * If we are scheduling a read from global memory to shared memory,
4866 * we insert a synchronization before the kernel code (at the innermost
4867 * level).
4868 * If we are scheduling a write to global memory, then we add
4869 * a synchronization after all writes (at value 2 *s + 2).
4870 * However, there is no need for a synchronization after the outermost loop.
4871 * A write to global memory from private memory at the innermost level
4872 * does not require a synchronization, because it is covered by
4873 * the synchronization after the kernel inserted by body_schedule.
4875 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4876 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4877 __isl_keep isl_union_map *shared_sched,
4878 struct gpu_array_ref_group *group, int read, int k, int s)
4880 int n;
4881 int pos, val;
4882 isl_space *space;
4883 isl_union_map *access;
4884 isl_map *map, *proj, *access_map;
4885 isl_id *id;
4887 access = group_access_relation(group, read, !read);
4888 access = remove_local_accesses(gen, group, access, read);
4889 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4890 access);
4892 if (isl_union_map_is_empty(access)) {
4893 isl_union_map_free(access);
4894 return res;
4897 access = isl_union_map_reverse(access);
4898 access = isl_union_map_apply_range(access,
4899 isl_union_map_copy(schedule));
4900 access_map = isl_map_from_union_map(access);
4902 space = isl_space_copy(group->array->space);
4903 space = isl_space_from_range(space);
4904 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4905 map = isl_map_domain_map(isl_map_universe(space));
4907 space = isl_union_map_get_space(schedule);
4908 pos = group->last_shared + 1 - gen->tile_first;
4909 assert(pos >= 0);
4910 if (read)
4911 val = -2 - k;
4912 else if (group->private_tile)
4913 val = 1 + k;
4914 else
4915 val = 1 + s + 1 + k;
4916 proj = insert_even(gen, space, pos, val);
4917 map = isl_map_apply_range(map, proj);
4919 access_map = isl_map_range_product(access_map, map);
4921 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4922 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4924 res = isl_union_map_add_map(res, access_map);
4926 n = gen->shared_len - gen->tile_first;
4927 if (read) {
4928 if (!group->private_tile)
4929 res = add_sync_schedule(gen, res, schedule,
4930 shared_sched, n, -1);
4931 } else {
4932 if (pos == 0)
4933 return res;
4934 if (pos == n && group->private_tile)
4935 return res;
4936 res = add_sync_schedule(gen, res, schedule, shared_sched,
4937 pos, 2 * s + 2);
4940 return res;
4943 /* Return a schedule for the shared tile loops based on the current
4944 * AST context schedule.
4946 * We create a "shared_sched" that maps the domains to the first
4947 * shared_len dimensions of the computed schedule, project out the
4948 * first tile_first dimensions (as these are already covered by
4949 * the host code) and insert "statement-level" dimensions at even
4950 * positions so that we can schedule copy blocks and synchronization
4951 * before/after each level.
4953 * In particular, copy blocks are inserted inside the innermost
4954 * level that affect the tile. For the copying to global memory,
4955 * those from private memory are scheduled before those from shared
4956 * memory such that synchronization can be inserted between the two
4957 * at the innermost level.
4958 * Synchronization is inserted at the innermost level before the
4959 * actual kernel code if there is any copying from global memory
4960 * to shared memory. It is inserted unconditionally at the innermost
4961 * level after the actual kernel code and the copying to global memory
4962 * from private memory (if any). Finally, it is inserted after
4963 * any copying to global memory, except at the outermost level
4964 * and at the innermost level if there is no copying from shared
4965 * memory. The copying from private memory is covered by the unconditional
4966 * synchronization at the innermost level.
4968 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4969 __isl_take isl_union_map *schedule)
4971 isl_space *space;
4972 isl_union_map *res;
4973 isl_union_map *shared_sched;
4974 isl_union_map *sched;
4975 isl_map *proj, *map;
4976 int i, j, k, s;
4978 shared_sched = isl_union_map_copy(gen->tiled_sched);
4979 proj = projection(isl_union_map_get_space(shared_sched),
4980 gen->tiled_len, gen->shared_len);
4981 shared_sched = isl_union_map_apply_range(shared_sched,
4982 isl_union_map_from_map(proj));
4983 space = isl_union_map_get_space(shared_sched);
4984 proj = insert_even(gen, space, -1, 0);
4985 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4986 isl_union_map_from_map(proj));
4988 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4990 s = 0;
4991 for (i = 0; i < gen->prog->n_array; ++i)
4992 s += gen->prog->array[i].n_group;
4994 k = 0;
4995 for (i = 0; i < gen->prog->n_array; ++i) {
4996 struct gpu_array_info *array = &gen->prog->array[i];
4998 for (j = 0; j < array->n_group; ++j) {
4999 struct gpu_array_ref_group *group;
5001 group = array->groups[j];
5002 if (!group->private_tile && !group->shared_tile)
5003 continue;
5004 res = add_group_schedule(gen, res, schedule,
5005 shared_sched, group, 0, k, s);
5006 res = add_group_schedule(gen, res, schedule,
5007 shared_sched, group, 1, k, s);
5008 ++k;
5012 res = add_sync_schedule(gen, res, schedule, shared_sched,
5013 gen->shared_len - gen->tile_first, 1 + s);
5015 isl_union_map_free(shared_sched);
5016 isl_union_map_free(schedule);
5018 return res;
5021 /* Generate code for "kernel" in the given "context".
5023 * We first generate code for the shared tile loops (T1T, T1P and T2)
5024 * in a context that includes the block ids.
5025 * Within each iteration of these loops an additional code generation
5026 * is performed (within create_kernel_leaf) for the rest of the schedule
5027 * in a context that includes the thread ids.
5029 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
5030 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
5031 __isl_keep isl_multi_pw_aff *grid_size)
5033 isl_space *space;
5034 isl_set *set;
5035 isl_id_list *iterators;
5036 isl_union_map *schedule;
5037 isl_ast_node *tree;
5038 int sched_len;
5040 schedule = isl_ast_build_get_schedule(build);
5042 build = isl_ast_build_copy(build);
5043 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
5044 space = isl_ast_build_get_schedule_space(build);
5045 set = isl_set_universe(isl_space_copy(space));
5046 set = add_bounded_parameters_dynamic(set, grid_size, "b");
5047 build = isl_ast_build_restrict(build, set);
5049 schedule = body_schedule(gen, schedule);
5051 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
5053 build = set_atomic_and_unroll(build, space, sched_len);
5054 iterators = generate_names(gen->ctx, sched_len, "g");
5055 build = isl_ast_build_set_iterators(build, iterators);
5056 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
5057 tree = isl_ast_build_ast_from_schedule(build, schedule);
5058 isl_ast_build_free(build);
5060 return tree;
5063 /* Attach "id" to the given node.
5065 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
5066 __isl_keep isl_ast_build *build, void *user)
5068 isl_id *id = user;
5070 node = isl_ast_node_set_annotation(node, id);
5072 return node;
5075 /* Construct an AST node for performing a kernel launch and attach
5076 * the information about the kernel to that node.
5078 * The kernel AST has been constructed in the context of the range
5079 * of "schedule". In particular, the grid size has been computed
5080 * in the context. We therefore still need to make sure that these
5081 * constraints are expressed in the code. We do this by creating a schedule
5083 * kernel[] -> [S -> []]
5085 * where S is the schedule domain, i.e., the range of "schedule".
5086 * The AST generation will then create a single call surrounded by
5087 * all the condition in "S" that have not been expressed yet.
5089 * The kernel information is attached to this node in attach_id.
5091 static __isl_give isl_ast_node *construct_launch(
5092 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
5093 __isl_take struct ppcg_kernel *kernel)
5095 isl_id *id;
5096 isl_ctx *ctx;
5097 isl_union_set *domain;
5098 isl_set *set;
5099 isl_map *map;
5100 isl_ast_node *node;
5102 ctx = isl_ast_build_get_ctx(build);
5104 id = isl_id_alloc(ctx, NULL, kernel);
5105 id = isl_id_set_free_user(id, &ppcg_kernel_free);
5107 domain = isl_union_map_range(schedule);
5108 set = isl_set_from_union_set(domain);
5109 map = isl_map_from_domain(set);
5110 map = isl_map_from_range(isl_map_wrap(map));
5111 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
5112 schedule = isl_union_map_from_map(map);
5114 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
5115 node = isl_ast_build_ast_from_schedule(build, schedule);
5116 isl_ast_build_free(build);
5118 return node;
5121 /* This function is called for each leaf in the AST of the host code.
5122 * We first specialize the schedule to the site of the leaf, compute
5123 * the size of shared memory and then construct the body of the host code
5124 * and the associated kernel.
5126 * The necessary information for printing the kernel launch is
5127 * stored in a struct ppcg_kernel and attached to the leaf node
5128 * created to represent the launch.
5130 static __isl_give isl_ast_node *create_host_leaf(
5131 __isl_take isl_ast_build *build, void *user)
5133 struct gpu_gen *gen = (struct gpu_gen *) user;
5134 isl_id *id;
5135 isl_ast_node *node;
5136 struct ppcg_kernel *kernel;
5137 isl_set *host_domain;
5138 isl_union_map *schedule;
5139 isl_union_map *local_sched;
5140 isl_union_map *access;
5141 isl_union_set *domain;
5142 int i;
5144 schedule = isl_ast_build_get_schedule(build);
5146 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
5147 read_sizes(gen);
5149 domain = isl_union_map_domain(isl_union_map_copy(schedule));
5151 local_sched = isl_union_map_copy(gen->sched);
5152 local_sched = isl_union_map_intersect_domain(local_sched, domain);
5153 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
5154 isl_union_map_copy(gen->prog->may_write));
5155 access = isl_union_map_apply_domain(access,
5156 isl_union_map_copy(local_sched));
5158 gen->tiled_sched = tile_schedule(gen, local_sched);
5159 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
5160 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
5162 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
5163 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
5164 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
5166 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
5167 if (!kernel)
5168 goto error;
5170 kernel->id = gen->kernel_id++;
5171 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
5172 kernel->grid_size = extract_grid_size(gen, kernel);
5173 extract_block_size(gen, kernel);
5174 kernel->arrays = isl_union_map_range(access);
5175 kernel->arrays = isl_union_set_apply(kernel->arrays,
5176 isl_union_map_copy(gen->prog->to_outer));
5177 kernel->space = isl_ast_build_get_schedule_space(build);
5179 gen->private_access = NULL;
5180 compute_shared_sched(gen);
5181 gen->privatization = compute_privatization(gen);
5182 check_scalar_live_ranges(gen);
5183 if (group_references(gen) < 0)
5184 schedule = isl_union_map_free(schedule);
5185 compute_private_access(gen);
5186 host_domain = isl_set_from_union_set(isl_union_map_range(
5187 isl_union_map_copy(schedule)));
5188 localize_bounds(gen, kernel, host_domain);
5190 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
5191 check_shared_memory_bound(gen);
5192 compute_group_tilings(gen);
5194 kernel->tree = generate_kernel(gen, build, host_domain,
5195 kernel->grid_size);
5196 create_kernel_vars(gen, kernel);
5198 free_local_array_info(gen);
5199 isl_map_free(gen->privatization);
5200 isl_union_map_free(gen->private_access);
5201 isl_union_map_free(gen->local_sched);
5202 isl_union_map_free(gen->tiled_sched);
5203 isl_union_map_free(gen->shared_sched);
5204 isl_union_map_free(gen->shared_proj);
5205 isl_set_free(host_domain);
5206 free(gen->tile_size);
5208 node = construct_launch(build, schedule, kernel);
5210 return node;
5211 error:
5212 isl_union_map_free(schedule);
5213 return NULL;
5216 /* Use isl to generate code for the outer gen->tile_first loops
5217 * of the global schedule in gen->sched, resulting in the host code.
5218 * Within each iteration of this partial schedule, i.e., for each kernel
5219 * launch, create_host_leaf takes care of generating the kernel code.
5221 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
5223 isl_ast_build *build;
5224 isl_ast_node *tree;
5225 isl_union_map *sched;
5226 isl_map *proj;
5227 isl_id_list *iterators;
5229 sched = isl_union_map_copy(gen->sched);
5230 proj = projection(isl_union_map_get_space(sched),
5231 gen->untiled_len, gen->tile_first);
5232 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5234 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5235 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
5236 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5237 build = isl_ast_build_set_iterators(build, iterators);
5238 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5239 tree = isl_ast_build_ast_from_schedule(build, sched);
5240 isl_ast_build_free(build);
5242 return tree;
5245 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5247 if (!str)
5248 return NULL;
5249 return isl_union_map_read_from_str(ctx, str);
5252 /* Information about the outermost tilable bands in the forest of bands.
5254 * tile_len and n_parallel are only sets on band_info structures
5255 * that correspond to outermost bands. For other bands (in particular,
5256 * ancestors of the outermost bands), n_parallal is set to 0.
5258 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5260 * tile_first is the number of schedule dimensions in prefix.
5262 * suffix is the schedule of the outermost tilable bands and their descendants.
5264 struct band_info {
5265 struct gpu_gen *gen;
5266 int tile_first;
5267 int tile_len;
5268 int n_parallel;
5269 isl_union_map *prefix;
5270 isl_union_map *suffix;
5273 /* Set tile_len and n_parallel of the statement to that of
5274 * their outermost band, recorded in the band_info.
5276 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5278 struct band_info *info = user;
5279 struct gpu_stmt *stmt;
5280 isl_id *id;
5282 id = isl_map_get_tuple_id(map, isl_dim_in);
5283 stmt = find_stmt(info->gen->prog, id);
5284 isl_id_free(id);
5286 stmt->tile_len = info->tile_len;
5287 stmt->n_parallel = info->n_parallel;
5289 isl_map_free(map);
5291 return 0;
5294 static void list_select_outer_band(struct gpu_gen *gen,
5295 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5297 /* Check if this band has any parallel loops. If so, take it as
5298 * the outermost tilable band. If not, continue looking for the
5299 * outermost tilable band in the children of the current band.
5301 static void band_select_outer_band(struct gpu_gen *gen,
5302 __isl_take isl_band *band, int pos, struct band_info *info)
5304 int n = isl_band_n_member(band);
5305 int n_parallel;
5307 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5308 if (!isl_band_member_is_coincident(band, n_parallel))
5309 break;
5311 info->n_parallel = n_parallel;
5312 if (n_parallel) {
5313 gen->any_parallelism = 1;
5314 info->gen = gen;
5315 info->tile_first = pos;
5316 info->tile_len = n;
5317 info->prefix = isl_band_get_prefix_schedule(band);
5318 info->suffix = isl_union_map_flat_range_product(
5319 isl_band_get_partial_schedule(band),
5320 isl_band_get_suffix_schedule(band));
5321 isl_union_map_foreach_map(info->prefix,
5322 &set_stmt_tile_len, info);
5323 } else if (isl_band_has_children(band)) {
5324 isl_band_list *children;
5325 children = isl_band_get_children(band);
5326 list_select_outer_band(gen, children, pos + n, info);
5327 } else {
5328 info->gen = gen;
5329 info->tile_first = pos + n;
5330 info->tile_len = 0;
5331 info->prefix = isl_union_map_flat_range_product(
5332 isl_band_get_prefix_schedule(band),
5333 isl_band_get_partial_schedule(band));
5334 info->suffix = isl_band_get_suffix_schedule(band);
5335 isl_union_map_foreach_map(info->prefix,
5336 &set_stmt_tile_len, info);
5339 isl_band_free(band);
5342 /* Comparison function that returns a non-zero value for band_infos
5343 * with different tile_len fields or different n_parallel fields.
5345 static int cmp_band(const void *p1, const void *p2)
5347 const struct band_info *info1 = p1;
5348 const struct band_info *info2 = p2;
5350 if (info1->tile_len != info2->tile_len)
5351 return info1->tile_len - info2->tile_len;
5353 return info1->n_parallel - info2->n_parallel;
5356 /* Extend "umap" with coordinates with fixed value "val"
5357 * to a total length of "dst_len", assuming the original dimension is "src_len".
5359 static __isl_give isl_union_map *extend_range(
5360 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5362 isl_space *dim;
5363 isl_map *map;
5364 int i;
5366 dim = isl_union_map_get_space(umap);
5367 map = isl_map_reverse(projection(dim, dst_len, src_len));
5368 for (i = src_len; i < dst_len; ++i)
5369 map = isl_map_fix_si(map, isl_dim_out, i, val);
5371 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5373 return umap;
5376 /* Group bands with the same values for tile_len and n_parallel.
5377 * The prefix schedule is then extended with a fixed coordinate that
5378 * is different for each such group.
5379 * Note that the actual values for this coordinate are not important.
5380 * The bands have already been effectively separated at a higher level
5381 * or they are independent and may be executed in parallel.
5382 * The list of band_info has been sorted before this functions is called.
5384 static void separate_bands(struct band_info *info, int n)
5386 int i;
5387 int j = 0;
5389 for (i = 0; i < n; ++i) {
5390 int l = info[i].tile_first;
5392 if (i &&
5393 (info[i].tile_len != info[i - 1].tile_len ||
5394 info[i].n_parallel != info[i - 1].n_parallel))
5395 j++;
5397 info[i].prefix = extend_range(info[i].prefix,
5398 l, l + 1, j);
5399 info[i].tile_first = l + 1;
5403 /* Select the outermost bands in the elements of the list, align
5404 * their prefix schedules, separate bands with different values
5405 * for tile_len and/or n_parallel and then combine the resulting
5406 * prefix and suffix schedules into a single pair of prefix and
5407 * suffix schedules for the entire list.
5409 static void list_select_outer_band(struct gpu_gen *gen,
5410 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5412 isl_band *band;
5413 int i;
5414 int n = isl_band_list_n_band(list);
5415 isl_ctx *ctx = isl_band_list_get_ctx(list);
5416 struct band_info *info;
5417 int max_tile_first;
5418 isl_union_map *prefix;
5419 isl_union_map *suffix;
5421 assert(n >= 1);
5422 info = isl_calloc_array(ctx, struct band_info, n);
5423 assert(info);
5425 max_tile_first = 0;
5426 for (i = 0; i < n; ++i) {
5427 band = isl_band_list_get_band(list, i);
5428 band_select_outer_band(gen, band, pos, &info[i]);
5429 if (info[i].tile_first > max_tile_first)
5430 max_tile_first = info[i].tile_first;
5433 for (i = 0; i < n; ++i) {
5434 if (info[i].tile_first == max_tile_first)
5435 continue;
5436 info[i].prefix = extend_range(info[i].prefix,
5437 info[i].tile_first, max_tile_first, 0);
5438 info[i].tile_first = max_tile_first;
5441 qsort(info, n, sizeof(struct band_info), &cmp_band);
5443 for (i = 0; i < n - 1; ++i)
5444 if (info[i].tile_len != info[i + 1].tile_len ||
5445 info[i].n_parallel != info[i + 1].n_parallel)
5446 break;
5448 if (i < n -1)
5449 separate_bands(info, n);
5451 prefix = info[0].prefix;
5452 suffix = info[0].suffix;
5454 for (i = 1; i < n; ++i) {
5455 prefix = isl_union_map_union(prefix, info[i].prefix);
5456 suffix = isl_union_map_union(suffix, info[i].suffix);
5459 list_info->tile_first = info[0].tile_first;
5460 list_info->tile_len = -1;
5461 list_info->prefix = prefix;
5462 list_info->suffix = suffix;
5464 isl_band_list_free(list);
5465 free(info);
5468 /* Select the outermost tilable band that (by construction)
5469 * has at least one parallel loop.
5470 * The starting position of the aligned band is stored in the pair
5471 * gen->tile_first.
5472 * The sizes and number of parallel loops may be different in different
5473 * parts of the band forest and are therefore stored in the gpu_stmts.
5475 * Return the complete schedule, with the tilable bands aligned
5476 * at gen->tile_first and padded with zero, if needed.
5478 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5479 __isl_keep isl_schedule *schedule)
5481 isl_band_list *list;
5482 struct band_info info;
5484 gen->n_parallel = 0;
5485 gen->tile_len = -1;
5487 list = isl_schedule_get_band_forest(schedule);
5489 if (isl_band_list_n_band(list) == 0) {
5490 isl_band_list_free(list);
5491 return isl_schedule_get_map(schedule);
5494 list_select_outer_band(gen, list, 0, &info);
5496 gen->tile_first = info.tile_first;
5497 info.suffix = align_range(info.suffix);
5499 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5502 /* Set gen->untiled_len to the number of scheduling dimensions
5503 * for the schedule of the first domain.
5504 * We assume here that this number is the same for all domains.
5506 static int set_untiled_len(__isl_take isl_map *map, void *user)
5508 unsigned *untiled_len = user;
5510 *untiled_len = isl_map_dim(map, isl_dim_out);
5512 isl_map_free(map);
5513 return -1;
5516 /* Compute an appropriate schedule based on the accesses in
5517 * gen->read and gen->write.
5519 * We use the dependences in gen->prog->scop to compute
5520 * a schedule that has a parallel loop in each tilable band.
5521 * Finally, we select the outermost tilable band.
5523 * If live range reordering is allowed, then we need to make sure
5524 * that live ranges on arrays are not run in parallel since doing
5525 * so would require array expansion. We therefore add the array
5526 * order dependences to the coincidence dependences. Non-zero array
5527 * order dependences will then prevent a schedule dimension from being
5528 * considered parallel.
5529 * Live ranges derived from scalars are allowed to be run in parallel
5530 * since we force the scalars to be mapped to private memory in
5531 * check_scalar_live_ranges.
5532 * If live range reordering is allowed, then the false dependences
5533 * are not added to the validity constraints as that would prevent
5534 * reordering. Instead, the external false dependences that enforce that reads
5535 * from potentially live-in data precede any later write and
5536 * that writes of potentially live-out data follow any other earlier write
5537 * are added to the validity and the coincidence constraints.
5538 * The false dependences are still added to the proximity constraints
5539 * for consistency with the case where live range reordering is not allowed.
5540 * The coincidence constraints then consist of flow dependences,
5541 * exernal false dependences and array order dependences.
5542 * The independences can be filtered out from the first two sets.
5543 * They have already been filtered out from the array order dependences
5544 * on a per array basis in collect_order_dependences.
5545 * There is no need for a per array handling of the other two sets
5546 * as there should be no flow or external false dependence on local
5547 * variables that can be filtered out.
5549 static void compute_schedule(struct gpu_gen *gen)
5551 isl_union_set *domain;
5552 isl_union_map *dep_raw, *dep;
5553 isl_union_map *validity, *proximity, *coincidence;
5554 isl_union_map *sched;
5555 isl_schedule_constraints *sc;
5556 isl_schedule *schedule;
5558 domain = isl_union_set_copy(gen->prog->scop->domain);
5559 domain = isl_union_set_intersect_params(domain,
5560 isl_set_copy(gen->prog->scop->context));
5561 sc = isl_schedule_constraints_on_domain(isl_union_set_copy(domain));
5562 if (gen->options->live_range_reordering) {
5563 sc = isl_schedule_constraints_set_conditional_validity(sc,
5564 isl_union_map_copy(gen->prog->scop->tagged_dep_flow),
5565 isl_union_map_copy(gen->prog->scop->tagged_dep_order));
5566 proximity = isl_union_map_copy(gen->prog->scop->dep_flow);
5567 validity = isl_union_map_copy(proximity);
5568 validity = isl_union_map_union(validity,
5569 isl_union_map_copy(gen->prog->scop->dep_external));
5570 proximity = isl_union_map_union(proximity,
5571 isl_union_map_copy(gen->prog->scop->dep_false));
5572 coincidence = isl_union_map_copy(validity);
5573 coincidence = isl_union_map_subtract(coincidence,
5574 isl_union_map_copy(gen->prog->scop->independence));
5575 coincidence = isl_union_map_union(coincidence,
5576 isl_union_map_copy(gen->prog->array_order));
5577 } else {
5578 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
5579 dep = isl_union_map_copy(gen->prog->scop->dep_false);
5580 dep = isl_union_map_union(dep, dep_raw);
5581 dep = isl_union_map_coalesce(dep);
5582 proximity = isl_union_map_copy(dep);
5583 coincidence = isl_union_map_copy(dep);
5584 validity = dep;
5586 sc = isl_schedule_constraints_set_validity(sc, validity);
5587 sc = isl_schedule_constraints_set_coincidence(sc, coincidence);
5588 sc = isl_schedule_constraints_set_proximity(sc, proximity);
5590 if (gen->options->debug->dump_schedule_constraints)
5591 isl_schedule_constraints_dump(sc);
5592 schedule = isl_schedule_constraints_compute_schedule(sc);
5593 if (gen->options->debug->dump_schedule)
5594 isl_schedule_dump(schedule);
5596 sched = select_outer_tilable_band(gen, schedule);
5598 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5599 sched = isl_union_map_intersect_domain(sched, domain);
5600 gen->sched = sched;
5602 isl_schedule_free(schedule);
5605 /* Compute the sets of outer array elements that need to be copied in and out.
5607 * In particular, for each array that is possibly written anywhere in
5608 * gen->prog and that is visible outside the corresponding scop,
5609 * we copy out its entire extent.
5611 * Any array elements that is read without first being written needs
5612 * to be copied in. Furthermore, if there are any array elements that
5613 * are copied out, but that may not be written inside gen->prog, then
5614 * they also need to be copied in to ensure that the value after execution
5615 * is the same as the value before execution.
5616 * In case the array elements are structures, we need to take into
5617 * account that all members of the structures need to be written
5618 * by gen->prog before we can avoid copying the data structure in.
5620 * While computing the set of array elements that are copied out but
5621 * not necessarily written, we intersect both sets with the context.
5622 * This helps in those cases where the arrays are declared with a fixed size,
5623 * while the accesses are parametric and the context assigns a fixed value
5624 * to the parameters.
5626 * If an element from a local array is read without first being written,
5627 * then there is no point in copying it in since it cannot have been
5628 * written prior to the scop. Warn about the uninitialized read instead.
5630 static void compute_copy_in_and_out(struct gpu_gen *gen)
5632 int i;
5633 isl_union_set *local;
5634 isl_union_set *may_write, *must_write;
5635 isl_union_set *copy_in, *copy_out;
5636 isl_union_set *not_written;
5637 isl_union_map *uninitialized;
5638 isl_union_map *local_uninitialized;
5640 must_write = isl_union_map_range(
5641 isl_union_map_copy(gen->prog->must_write));
5642 must_write = isl_union_set_intersect_params(must_write,
5643 isl_set_copy(gen->prog->context));
5644 may_write = isl_union_map_range(
5645 isl_union_map_copy(gen->prog->may_write));
5646 may_write = isl_union_set_intersect_params(may_write,
5647 isl_set_copy(gen->prog->context));
5648 may_write = isl_union_set_universe(may_write);
5649 may_write = isl_union_set_apply(may_write,
5650 isl_union_map_copy(gen->prog->to_outer));
5651 copy_out = isl_union_set_empty(isl_union_set_get_space(may_write));
5652 local = isl_union_set_copy(copy_out);
5654 for (i = 0; i < gen->prog->n_array; ++i) {
5655 isl_space *space;
5656 isl_set *write_i;
5657 int empty;
5659 space = isl_space_copy(gen->prog->array[i].space);
5661 if (gen->prog->array[i].local) {
5662 isl_set *set;
5664 set = isl_set_universe(space);
5665 local = isl_union_set_add_set(local, set);
5666 continue;
5669 write_i = isl_union_set_extract_set(may_write, space);
5670 empty = isl_set_plain_is_empty(write_i);
5671 isl_set_free(write_i);
5672 if (empty)
5673 continue;
5675 write_i = isl_set_copy(gen->prog->array[i].extent);
5676 copy_out = isl_union_set_add_set(copy_out, write_i);
5678 isl_union_set_free(may_write);
5680 copy_out = isl_union_set_intersect_params(copy_out,
5681 isl_set_copy(gen->prog->context));
5683 gen->prog->copy_out = isl_union_set_copy(copy_out);
5685 copy_out = isl_union_set_apply(copy_out,
5686 isl_union_map_copy(gen->prog->to_inner));
5687 not_written = isl_union_set_subtract(copy_out, must_write);
5689 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
5690 local_uninitialized = isl_union_map_copy(uninitialized);
5692 local = isl_union_set_apply(local,
5693 isl_union_map_copy(gen->prog->to_inner));
5694 local_uninitialized = isl_union_map_intersect_range(local_uninitialized,
5695 local);
5696 if (!isl_union_map_is_empty(local_uninitialized)) {
5697 fprintf(stderr,
5698 "possibly uninitialized reads (not copied in):\n");
5699 isl_union_map_dump(local_uninitialized);
5701 uninitialized = isl_union_map_subtract(uninitialized,
5702 local_uninitialized);
5703 copy_in = isl_union_map_range(uninitialized);
5704 copy_in = isl_union_set_union(copy_in, not_written);
5705 copy_in = isl_union_set_apply(copy_in,
5706 isl_union_map_copy(gen->prog->to_outer));
5708 gen->prog->copy_in = copy_in;
5711 /* Internal data structure for extract_access.
5712 * "next_access" points to the end of a linked list that is extended
5713 * by extract_access.
5714 * "single_expression" is set if the access expressions belong to
5715 * an expression statement (i.e., a statement without internal control).
5716 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5718 struct ppcg_extract_access_data {
5719 struct gpu_stmt_access **next_access;
5720 int single_expression;
5721 isl_union_map *any_to_outer;
5724 /* Extract a gpu_stmt_access from "expr", append it to the list
5725 * that ends in *data->next_access and update the end of the list.
5726 * If the access expression performs a write, then it is considered
5727 * exact only if it appears in a single expression statement and
5728 * if its may access relation is equal to its must access relation.
5730 * The combined set of may accesses may be union if member accesses
5731 * are involved, but the entire set is derived from a single reference and
5732 * therefore from a single index expression. These accesses therefore
5733 * all map to the same outer array.
5735 static int extract_access(__isl_keep pet_expr *expr, void *user)
5737 struct ppcg_extract_access_data *data = user;
5738 isl_union_map *may, *tagged;
5739 struct gpu_stmt_access *access;
5740 isl_ctx *ctx;
5741 isl_multi_pw_aff *index;
5743 may = pet_expr_access_get_may_read(expr);
5744 may = isl_union_map_union(may, pet_expr_access_get_may_write(expr));
5745 may = isl_union_map_apply_range(may,
5746 isl_union_map_copy(data->any_to_outer));
5747 ctx = isl_union_map_get_ctx(may);
5748 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5749 assert(access);
5750 access->next = NULL;
5751 access->read = pet_expr_access_is_read(expr);
5752 access->write = pet_expr_access_is_write(expr);
5753 tagged = pet_expr_access_get_tagged_may_read(expr);
5754 tagged = isl_union_map_union(tagged,
5755 pet_expr_access_get_tagged_may_write(expr));
5756 tagged = isl_union_map_apply_range(tagged,
5757 isl_union_map_copy(data->any_to_outer));
5758 access->tagged_access = isl_map_from_union_map(tagged);
5759 if (!access->write) {
5760 access->exact_write = 1;
5761 } else if (!data->single_expression) {
5762 access->exact_write = 0;
5763 } else {
5764 isl_union_map *must;
5765 must = pet_expr_access_get_must_write(expr);
5766 access->exact_write = isl_union_map_is_equal(must, may);
5767 isl_union_map_free(must);
5769 access->access = isl_map_from_union_map(may);
5770 index = pet_expr_access_get_index(expr);
5771 access->n_index = isl_multi_pw_aff_dim(index, isl_dim_out);
5772 isl_multi_pw_aff_free(index);
5773 access->ref_id = pet_expr_access_get_ref_id(expr);
5774 access->group = -1;
5776 *data->next_access = access;
5777 data->next_access = &(*data->next_access)->next;
5779 return 0;
5782 /* Construct a linked list of gpu_stmt_access objects,
5783 * one for each access expression in the statement body.
5784 * "any_to_outer" maps all intermediate arrays to their outer arrays.
5786 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt,
5787 __isl_keep isl_union_map *any_to_outer)
5789 struct ppcg_extract_access_data data;
5791 stmt->accesses = NULL;
5792 data.next_access = &stmt->accesses;
5793 data.single_expression =
5794 pet_tree_get_type(stmt->stmt->body) == pet_tree_expr;
5795 data.any_to_outer = any_to_outer;
5796 pet_tree_foreach_access_expr(stmt->stmt->body, &extract_access, &data);
5799 /* Return an array of gpu_stmt representing the statements in "scop".
5801 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
5802 __isl_keep isl_set *context, __isl_keep isl_union_map *any_to_outer)
5804 int i;
5805 struct gpu_stmt *stmts;
5807 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->pet->n_stmt);
5808 if (!stmts)
5809 return NULL;
5811 for (i = 0; i < scop->pet->n_stmt; ++i) {
5812 struct gpu_stmt *s = &stmts[i];
5814 s->id = isl_set_get_tuple_id(scop->pet->stmts[i]->domain);
5815 s->stmt = scop->pet->stmts[i];
5816 pet_stmt_extract_accesses(s, any_to_outer);
5819 return stmts;
5822 /* Callback for ppcg_print_guarded that calls the callback for generate_gpu.
5824 static __isl_give isl_printer *print_gpu(__isl_take isl_printer *p, void *user)
5826 struct gpu_gen *gen = user;
5828 return gen->print(p, gen->prog, gen->tree, &gen->types,
5829 gen->print_user);
5832 /* Generate CUDA code for "scop" and print it to "p".
5833 * After generating an AST for the transformed scop as explained below,
5834 * we call "gen->print" to print the AST in the desired output format
5835 * to "p".
5837 * If it turns out that it does not make sense to generate GPU code,
5838 * then we generate CPU code instead.
5840 * The GPU code is generated in a context where at least one
5841 * statement instance is executed. The corresponding guard (if any) is printed
5842 * around the entire generated GPU code, except for the declaration
5843 * of the arrays that are visible outside of the scop and that therefore
5844 * cannot be declared inside the body of any possible guard.
5846 * We first compute a schedule that respects the dependences
5847 * of the original program and select the outermost band
5848 * of tilable dimensions that has at least one parallel loop.
5849 * We then have three blocks of dimensions
5851 * H B G
5853 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5854 * in
5856 * H T P G
5858 * For each iteration of the T loop and for each array, we compute
5859 * the array elements accessed by that iteration, construct a rectangular
5860 * box around it and shift it to the origin. The result is used
5861 * as shared memory for the array.
5863 * We then split off at most 2 parallel loops from the T loops and
5864 * at most 3 parallel loops from the P loops
5866 * H T1 T2 P1 P2 G
5868 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5869 * according to "grid"/"block" sizes.
5871 * H T1T T1P T2 P1T P1P P2 G
5873 * Finally, the T1P and P1P iterators are equated to the block and
5874 * thread dimensions respectively and so are effectively removed.
5875 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5876 * are run on the GPU.
5878 * Code is generated in three stages. We first generate code for the
5879 * host (the H loops), with iterators h%d. Then, for each leaf node
5880 * of the resulting AST, we generate code for the shared loops (up to
5881 * and including T2), with iterators g%d and after equating the H loops
5882 * to h%d parameters and the T1P loops to the block dimensions.
5883 * Finally, we generate code for the remaining loops in a similar fashion.
5885 static __isl_give isl_printer *generate(__isl_take isl_printer *p,
5886 struct gpu_gen *gen, struct ppcg_scop *scop,
5887 struct ppcg_options *options)
5889 struct gpu_prog *prog;
5890 isl_ctx *ctx;
5891 isl_set *context, *guard;
5893 if (!scop)
5894 return isl_printer_free(p);
5896 ctx = isl_printer_get_ctx(p);
5897 prog = gpu_prog_alloc(ctx, scop);
5898 if (!prog)
5899 return isl_printer_free(p);
5901 context = isl_set_copy(prog->context);
5902 guard = isl_union_set_params(isl_union_set_copy(prog->scop->domain));
5903 prog->context = isl_set_intersect(prog->context, isl_set_copy(guard));
5905 gen->prog = prog;
5906 gen->any_parallelism = 0;
5907 compute_schedule(gen);
5909 if (!gen->any_parallelism) {
5910 isl_set_free(context);
5911 isl_set_free(guard);
5912 p = print_cpu(p, scop, options);
5913 } else {
5914 compute_copy_in_and_out(gen);
5915 gen->tree = generate_host_code(gen);
5916 p = ppcg_print_exposed_declarations(p, prog->scop);
5917 p = ppcg_print_guarded(p, guard, context, &print_gpu, gen);
5918 isl_ast_node_free(gen->tree);
5921 isl_union_map_free(gen->sched);
5923 gpu_prog_free(prog);
5925 return p;
5928 /* Wrapper around generate for use as a ppcg_transform callback.
5930 static __isl_give isl_printer *generate_wrap(__isl_take isl_printer *p,
5931 struct ppcg_scop *scop, void *user)
5933 struct gpu_gen *gen = user;
5935 return generate(p, gen, scop, gen->options);
5938 /* Transform the code in the file called "input" by replacing
5939 * all scops by corresponding GPU code and write the results to "out".
5941 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
5942 struct ppcg_options *options,
5943 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
5944 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
5945 struct gpu_types *types, void *user), void *user)
5947 struct gpu_gen gen;
5948 int r;
5949 int i;
5951 gen.ctx = ctx;
5952 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5953 gen.options = options;
5954 gen.kernel_id = 0;
5955 gen.print = print;
5956 gen.print_user = user;
5957 gen.types.n = 0;
5958 gen.types.name = NULL;
5960 if (options->debug->dump_sizes) {
5961 isl_space *space = isl_space_params_alloc(ctx, 0);
5962 gen.used_sizes = isl_union_map_empty(space);
5965 r = ppcg_transform(ctx, input, out, options, &generate_wrap, &gen);
5967 if (options->debug->dump_sizes) {
5968 isl_union_map_dump(gen.used_sizes);
5969 isl_union_map_free(gen.used_sizes);
5972 isl_union_map_free(gen.sizes);
5973 for (i = 0; i < gen.types.n; ++i)
5974 free(gen.types.name[i]);
5975 free(gen.types.name);
5977 return r;
5980 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5982 struct gpu_prog *prog;
5983 isl_space *space;
5984 isl_map *id;
5986 if (!scop)
5987 return NULL;
5989 prog = isl_calloc_type(ctx, struct gpu_prog);
5990 assert(prog);
5992 prog->ctx = ctx;
5993 prog->scop = scop;
5994 prog->context = isl_set_copy(scop->context);
5995 prog->n_stmts = scop->pet->n_stmt;
5996 prog->any_to_outer = pet_scop_compute_outer_to_any(scop->pet);
5997 prog->any_to_outer = isl_union_map_reverse(prog->any_to_outer);
5998 space = isl_union_map_get_space(prog->any_to_outer);
5999 space = isl_space_set_from_params(space);
6000 space = isl_space_add_dims(space, isl_dim_set, 1);
6001 space = isl_space_map_from_set(space);
6002 id = isl_map_identity(space);
6003 prog->any_to_outer = isl_union_map_add_map(prog->any_to_outer, id);
6004 prog->stmts = extract_stmts(ctx, scop,
6005 prog->context, prog->any_to_outer);
6006 prog->read = isl_union_map_copy(scop->reads);
6007 prog->may_write = isl_union_map_copy(scop->may_writes);
6008 prog->must_write = isl_union_map_copy(scop->must_writes);
6009 prog->to_inner = pet_scop_compute_outer_to_inner(scop->pet);
6010 prog->to_outer = isl_union_map_copy(prog->to_inner);
6011 prog->to_outer = isl_union_map_reverse(prog->to_outer);
6013 if (!prog->stmts)
6014 return gpu_prog_free(prog);
6016 if (collect_array_info(prog) < 0)
6017 return gpu_prog_free(prog);
6019 return prog;
6022 void *gpu_prog_free(struct gpu_prog *prog)
6024 if (!prog)
6025 return NULL;
6026 free_array_info(prog);
6027 free_stmts(prog->stmts, prog->n_stmts);
6028 isl_union_map_free(prog->any_to_outer);
6029 isl_union_map_free(prog->to_outer);
6030 isl_union_map_free(prog->to_inner);
6031 isl_union_set_free(prog->copy_in);
6032 isl_union_set_free(prog->copy_out);
6033 isl_union_map_free(prog->read);
6034 isl_union_map_free(prog->may_write);
6035 isl_union_map_free(prog->must_write);
6036 isl_union_map_free(prog->array_order);
6037 isl_set_free(prog->context);
6038 free(prog);
6039 return NULL;