cuda.c: copy_arrays_from_device: do not copy local arrays back to host
[ppcg.git] / gpu.c
blobb672a959c0ccc40baa6dc918a3dbae1f93a52efd
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012 Ecole Normale Superieure
5 * Use of this software is governed by the GNU LGPLv2.1 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>
16 #include <isl/polynomial.h>
17 #include <isl/union_set.h>
18 #include <isl/aff.h>
19 #include <isl/ilp.h>
20 #include <isl/flow.h>
21 #include <isl/band.h>
22 #include <isl/schedule.h>
23 #include <isl/options.h>
24 #include <isl/ast_build.h>
26 #include "gpu.h"
27 #include "schedule.h"
28 #include "ppcg_options.h"
30 /* The fields stride, shift and shift_map only contain valid information
31 * if shift != NULL.
32 * If so, they express that current index is such that if you add shift,
33 * then the result is always a multiple of stride.
34 * shift_map contains the mapping
36 * i -> (i + shift)/stride
38 * Let D represent the initial shared_len dimensions of the computed schedule.
39 * The spaces of "lb" and "shift" are of the form
41 * D -> [b]
43 * "shift_map" is of the form
45 * [D -> i] -> [D -> (i + shift(D))/stride]
47 struct gpu_array_bound {
48 isl_int size;
49 isl_aff *lb;
51 isl_int stride;
52 isl_aff *shift;
53 isl_basic_map *shift_map;
56 struct gpu_array_info;
58 /* A group of array references in a kernel that should be handled together.
59 * If private_bound is not NULL, then it is mapped to registers.
60 * Otherwise, if shared_bound is not NULL, it is mapped to shared memory.
61 * Otherwise, it is accessed from global memory.
63 struct gpu_array_ref_group {
64 /* The references in this group access this array. */
65 struct gpu_array_info *array;
66 /* Position of this group in the list of reference groups of array. */
67 int nr;
69 /* The following fields are use during the construction of the groups.
70 * access is the combined access relation relative to the shared
71 * memory tiling. In particular, the domain of the map corresponds
72 * to the first shared_len dimensions of the computed schedule.
73 * write is set if any access in the group is a write.
75 isl_map *access;
76 int write;
78 /* For each index, size and offset of piece in shared memory. */
79 struct gpu_array_bound *shared_bound;
81 /* For each index, size and offset of piece in private memory. */
82 struct gpu_array_bound *private_bound;
84 /* References in this group; point to elements of a linked list. */
85 int n_ref;
86 struct gpu_stmt_access **refs;
88 /* Last shared memory tile dimension that affects tile of this group. */
89 int last_shared;
92 struct gpu_gen {
93 isl_ctx *ctx;
94 struct ppcg_options *options;
96 struct gpu_prog *prog;
98 /* tile, grid and block sizes for each kernel */
99 isl_union_map *sizes;
101 /* Identifier of current kernel. */
102 int kernel_id;
103 /* Pointer to the current kernel. */
104 struct ppcg_kernel *kernel;
106 /* First tile dimension. */
107 int tile_first;
108 /* Number of tile dimensions. */
109 int tile_len;
110 /* Number of initial parallel loops among tile dimensions. */
111 int n_parallel;
113 /* Number of dimensions determining shared memory. */
114 int shared_len;
116 /* Number of rows in the untiled schedule. */
117 int untiled_len;
118 /* Number of rows in the tiled schedule. */
119 int tiled_len;
120 /* Number of rows in schedule after tiling/wrapping over threads. */
121 int thread_tiled_len;
123 /* Global untiled schedule. */
124 isl_union_map *sched;
125 /* Local (per kernel launch) tiled schedule. */
126 isl_union_map *tiled_sched;
127 /* Local schedule per shared memory tile loop iteration. */
128 isl_union_map *local_sched;
130 /* Local tiled schedule projected onto the shared tile loops and
131 * the loops that will be wrapped over the threads,
132 * with all shared tile loops parametrized.
134 isl_union_map *shared_sched;
135 /* Projects out the loops that will be wrapped over the threads
136 * from shared_sched.
138 isl_union_map *shared_proj;
140 /* A map that takes the range of shared_sched as input,
141 * wraps the appropriate loops over the threads and then projects
142 * out these loops.
144 isl_map *privatization;
146 /* A map from the shared memory tile loops and the thread indices
147 * (as parameters) to the set of accessed memory elements that
148 * will be accessed through private copies.
150 isl_union_map *private_access;
152 /* The schedule for the current private/shared access
153 * (within print_private_access or print_shared_access).
155 isl_map *copy_sched;
156 /* The array reference group corresponding to copy_sched. */
157 struct gpu_array_ref_group *copy_group;
158 /* copy_group->private_bound or copy_group->shared_bound */
159 struct gpu_array_bound *copy_bound;
161 /* First loop to unroll (or -1 if none) in the current part of the
162 * schedule.
164 int first_unroll;
166 int n_grid;
167 int n_block;
168 /* Note: in the input file, the sizes of the grid and the blocks
169 * are specified in the order x, y, z, but internally, the sizes
170 * are stored in reverse order, so that the last element always
171 * refers to the x dimension.
173 int grid_dim[2];
174 int block_dim[3];
175 int *tile_size;
178 /* Print the name of the local copy of a given group of array references.
180 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
181 struct gpu_array_ref_group *group)
183 int global = 0;
185 if (group->private_bound)
186 p = isl_printer_print_str(p, "private_");
187 else if (group->shared_bound)
188 p = isl_printer_print_str(p, "shared_");
189 else
190 global = 1;
191 p = isl_printer_print_str(p, group->array->name);
192 if (!global && group->array->n_group > 1) {
193 p = isl_printer_print_str(p, "_");
194 p = isl_printer_print_int(p, group->nr);
197 return p;
200 /* Collect all references to the given array and store pointers to them
201 * in array->refs.
203 static void collect_references(struct gpu_prog *prog,
204 struct gpu_array_info *array)
206 int i;
207 int n;
209 n = 0;
210 for (i = 0; i < prog->n_stmts; ++i) {
211 struct gpu_stmt *stmt = &prog->stmts[i];
212 struct gpu_stmt_access *access;
214 for (access = stmt->accesses; access; access = access->next) {
215 const char *name;
216 name = isl_map_get_tuple_name(access->access,
217 isl_dim_out);
218 if (name && !strcmp(array->name, name))
219 n++;
223 array->n_ref = n;
224 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
225 assert(array->refs);
227 n = 0;
228 for (i = 0; i < prog->n_stmts; ++i) {
229 struct gpu_stmt *stmt = &prog->stmts[i];
230 struct gpu_stmt_access *access;
232 for (access = stmt->accesses; access; access = access->next) {
233 const char *name;
234 name = isl_map_get_tuple_name(access->access,
235 isl_dim_out);
236 if (!name || strcmp(array->name, name))
237 continue;
239 array->refs[n++] = access;
244 static struct gpu_array_bound *create_bound_list(isl_ctx *ctx, int n_index)
246 int i;
247 struct gpu_array_bound *bound;
249 bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
250 assert(bound);
252 for (i = 0; i < n_index; ++i) {
253 isl_int_init(bound[i].size);
254 bound[i].lb = NULL;
255 isl_int_init(bound[i].stride);
256 bound[i].shift = NULL;
257 bound[i].shift_map = NULL;
260 return bound;
263 static void free_bound_list(struct gpu_array_bound *bound, int n_index)
265 int j;
267 if (!bound)
268 return;
270 for (j = 0; j < n_index; ++j) {
271 isl_int_clear(bound[j].size);
272 isl_int_clear(bound[j].stride);
273 isl_aff_free(bound[j].lb);
274 isl_aff_free(bound[j].shift);
275 isl_basic_map_free(bound[j].shift_map);
277 free(bound);
280 static struct pet_array *find_array(struct ppcg_scop *scop,
281 __isl_keep isl_set *accessed)
283 int i;
284 isl_id *id;
286 id = isl_set_get_tuple_id(accessed);
288 for (i = 0; i < scop->n_array; ++i) {
289 isl_id *id_i;
291 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
292 isl_id_free(id_i);
293 if (id == id_i)
294 break;
296 isl_id_free(id);
298 return i < scop->n_array ? scop->arrays[i] : NULL;
301 /* Compute bounds on the host arrays based on the accessed elements
302 * and collect all references to the array.
304 * If the array is zero-dimensional, i.e., a scalar, we check
305 * whether it is read-only.
307 static int extract_array_info(__isl_take isl_set *array, void *user)
309 int i;
310 struct gpu_prog *prog = (struct gpu_prog *)user;
311 const char *name;
312 int n_index;
313 isl_pw_aff **bounds;
314 struct pet_array *pa;
316 n_index = isl_set_dim(array, isl_dim_set);
317 name = isl_set_get_tuple_name(array);
318 bounds = isl_alloc_array(isl_set_get_ctx(array),
319 isl_pw_aff *, n_index);
320 assert(bounds);
321 prog->array[prog->n_array].dim = isl_set_get_space(array);
322 prog->array[prog->n_array].name = strdup(name);
323 prog->array[prog->n_array].n_index = n_index;
324 prog->array[prog->n_array].bound = bounds;
326 pa = find_array(prog->scop, array);
327 assert(pa);
329 prog->array[prog->n_array].type = strdup(pa->element_type);
330 prog->array[prog->n_array].size = pa->element_size;
331 prog->array[prog->n_array].local = pa->declared && !pa->exposed;
333 if (n_index == 0) {
334 isl_set *space;
335 isl_union_map *write;
336 int empty;
338 write = isl_union_map_copy(prog->write);
339 space = isl_set_universe(isl_set_get_space(array));
340 write = isl_union_map_intersect_range(write,
341 isl_union_set_from_set(space));
342 empty = isl_union_map_is_empty(write);
343 isl_union_map_free(write);
345 prog->array[prog->n_array].read_only = empty;
348 for (i = 0; i < n_index; ++i) {
349 isl_set *dom;
350 isl_local_space *ls;
351 isl_aff *one;
352 isl_pw_aff *bound;
353 isl_set *size = i == 0 ? array : pa->extent;
355 bound = isl_set_dim_max(isl_set_copy(size), i);
356 assert(bound);
357 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
358 ls = isl_local_space_from_space(isl_set_get_space(dom));
359 one = isl_aff_zero_on_domain(ls);
360 one = isl_aff_add_constant_si(one, 1);
361 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
362 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
364 bounds[i] = bound;
367 collect_references(prog, &prog->array[prog->n_array]);
369 prog->n_array++;
371 isl_set_free(array);
372 return 0;
375 void collect_array_info(struct gpu_prog *prog)
377 isl_union_set *arrays;
379 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
380 arrays = isl_union_set_union(arrays,
381 isl_union_map_range(isl_union_map_copy(prog->write)));
382 arrays = isl_union_set_coalesce(arrays);
384 prog->n_array = isl_union_set_n_set(arrays);
385 prog->array = isl_alloc_array(prog->ctx,
386 struct gpu_array_info, prog->n_array);
387 assert(prog->array);
388 prog->n_array = 0;
389 isl_union_set_foreach_set(arrays, &extract_array_info, prog);
390 isl_union_set_free(arrays);
393 static void free_array_info(struct gpu_prog *prog)
395 int i, j;
397 for (i = 0; i < prog->n_array; ++i) {
398 int n_index = prog->array[i].n_index;
399 free(prog->array[i].type);
400 free(prog->array[i].name);
401 for (j = 0; j < n_index; ++j)
402 isl_pw_aff_free(prog->array[i].bound[j]);
403 isl_space_free(prog->array[i].dim);
404 free(prog->array[i].bound);
405 free(prog->array[i].refs);
407 free(prog->array);
410 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
411 * as an array or through a pointer reference, but as single data element. At
412 * the moment, scalars are represented as zero dimensional arrays.
414 int gpu_array_is_scalar(struct gpu_array_info *array)
416 return (array->n_index == 0);
419 /* Is "array" a read-only scalar?
421 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
423 return gpu_array_is_scalar(array) && array->read_only;
426 /* Internal data structure for extract_size_of_type.
427 * "type" specifies the name of the space that we want to extract.
428 * "res" is used to store the subset of that space.
430 struct ppcg_extract_size_data {
431 const char *type;
432 isl_set *res;
435 /* This function is called for each set in a union_set.
436 * If the name of the set matches data->type, we store the
437 * set in data->res.
439 static int extract_size_of_type(__isl_take isl_set *size, void *user)
441 struct ppcg_extract_size_data *data = user;
442 const char *name;
444 name = isl_set_get_tuple_name(size);
445 if (name && !strcmp(name, data->type)) {
446 data->res = size;
447 return -1;
450 isl_set_free(size);
451 return 0;
454 /* Given a union map { kernel[i] -> *[...] },
455 * return the range in the space called "type" for the kernel with
456 * sequence number "id".
458 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
459 const char *type, int id)
461 isl_space *space;
462 isl_set *dom;
463 isl_union_set *local_sizes;
464 struct ppcg_extract_size_data data = { type, NULL };
466 if (!sizes)
467 return NULL;
469 space = isl_union_map_get_space(sizes);
470 space = isl_space_set_from_params(space);
471 space = isl_space_add_dims(space, isl_dim_set, 1);
472 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
473 dom = isl_set_universe(space);
474 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
476 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
477 isl_union_map_copy(sizes));
478 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
479 isl_union_set_free(local_sizes);
480 return data.res;
483 /* Given a singleton set, extract the first (at most *len) elements
484 * of the single integer tuple into *sizes and update *len if needed.
486 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
488 int i;
489 int dim;
490 isl_int v;
492 if (!set)
493 return;
495 dim = isl_set_dim(set, isl_dim_set);
496 if (dim < *len)
497 *len = dim;
499 isl_int_init(v);
501 for (i = 0; i < *len; ++i) {
502 int ok;
504 ok = isl_set_plain_is_fixed(set, isl_dim_set, i, &v);
505 assert(ok);
507 sizes[i] = isl_int_get_si(v);
510 isl_int_clear(v);
512 isl_set_free(set);
515 /* Extract user specified "tile" sizes from the "sizes" command line option,
516 * defaulting to option->tile_size in each dimension.
518 static void read_tile_sizes(struct gpu_gen *gen)
520 int n;
521 isl_set *size;
523 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
524 assert(gen->tile_size);
525 for (n = 0; n < gen->tile_len; ++n)
526 gen->tile_size[n] = gen->options->tile_size;
528 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
529 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
531 if (gen->n_parallel > gen->tile_len)
532 gen->n_parallel = gen->tile_len;
535 /* Extract user specified "block" sizes from the "sizes" command line option,
536 * after filling in some potentially useful defaults.
538 static void read_block_sizes(struct gpu_gen *gen)
540 int n;
541 isl_set *size;
543 n = gen->n_parallel;
544 gen->n_block = (n <= 3) ? n : 3;
545 switch (gen->n_block) {
546 case 1:
547 gen->block_dim[0] = 512;
548 break;
549 case 2:
550 gen->block_dim[0] = 32;
551 gen->block_dim[1] = 16;
552 break;
553 default:
554 gen->block_dim[0] = 32;
555 gen->block_dim[1] = 4;
556 gen->block_dim[2] = 4;
557 break;
560 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
561 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
564 /* Extract user specified "grid" sizes from the "sizes" command line option,
565 * after filling in some potentially useful defaults.
567 static void read_grid_sizes(struct gpu_gen *gen)
569 int n = gen->n_parallel;
570 isl_set *size;
572 gen->n_grid = (n <= 2) ? n : 2;
573 switch (gen->n_grid) {
574 case 1:
575 gen->grid_dim[0] = 32768;
576 break;
577 default:
578 gen->grid_dim[0] = 256;
579 gen->grid_dim[1] = 256;
580 break;
583 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
584 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
587 /* Extract user specified sizes from the "sizes" command line option
588 * after filling in some potentially useful defaults.
590 static void read_sizes(struct gpu_gen *gen)
592 read_tile_sizes(gen);
593 read_block_sizes(gen);
594 read_grid_sizes(gen);
597 static void free_stmts(struct gpu_stmt *stmts, int n)
599 int i;
601 for (i = 0; i < n; ++i) {
602 struct gpu_stmt_access *access, *next;
604 for (access = stmts[i].accesses; access; access = next) {
605 next = access->next;
606 isl_map_free(access->access);
607 free(access);
610 isl_id_free(stmts[i].id);
612 free(stmts);
615 void clear_gpu_gen(struct gpu_gen *gen)
617 isl_union_map_free(gen->sizes);
618 isl_union_map_free(gen->sched);
621 /* Construct a map from a domain of dimensionality "len"
622 * to a domain of dimensionality "len" + "tile_len" that tiles
623 * the "tile_len" coordinates starting at "first".
624 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
625 * "dim" prescribes the parameters.
627 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
628 int first, int tile_len, int *tile_size)
630 int i;
631 isl_int v;
632 isl_basic_map *bmap;
633 isl_constraint *c;
634 isl_local_space *ls;
636 isl_int_init(v);
638 dim = isl_space_add_dims(dim, isl_dim_in, len);
639 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
640 bmap = isl_basic_map_universe(isl_space_copy(dim));
641 ls = isl_local_space_from_space(dim);
643 for (i = 0; i < len - tile_len; ++i) {
644 int j = i < first ? i : i + tile_len;
645 int k = i < first ? i : i + 2 * tile_len;
647 c = isl_equality_alloc(isl_local_space_copy(ls));
648 isl_int_set_si(v, -1);
649 isl_constraint_set_coefficient(c, isl_dim_in, j, v);
650 isl_int_set_si(v, 1);
651 isl_constraint_set_coefficient(c, isl_dim_out, k, v);
652 bmap = isl_basic_map_add_constraint(bmap, c);
655 for (i = 0; i < tile_len; ++i) {
656 c = isl_equality_alloc(isl_local_space_copy(ls));
657 isl_int_set_si(v, -1);
658 isl_constraint_set_coefficient(c, isl_dim_in, first + i, v);
659 isl_int_set_si(v, tile_size[i]);
660 isl_constraint_set_coefficient(c, isl_dim_out, first + i, v);
661 isl_int_set_si(v, 1);
662 isl_constraint_set_coefficient(c, isl_dim_out,
663 first + i + tile_len, v);
664 bmap = isl_basic_map_add_constraint(bmap, c);
666 c = isl_inequality_alloc(isl_local_space_copy(ls));
667 isl_int_set_si(v, 1);
668 isl_constraint_set_coefficient(c, isl_dim_out,
669 first + i + tile_len, v);
670 bmap = isl_basic_map_add_constraint(bmap, c);
672 c = isl_inequality_alloc(isl_local_space_copy(ls));
673 isl_int_set_si(v, -1);
674 isl_constraint_set_coefficient(c, isl_dim_out,
675 first + i + tile_len, v);
676 isl_int_set_si(v, tile_size[i] - 1);
677 isl_constraint_set_constant(c, v);
678 bmap = isl_basic_map_add_constraint(bmap, c);
681 isl_local_space_free(ls);
682 isl_int_clear(v);
684 return isl_map_from_basic_map(bmap);
687 /* Construct a map from a domain of dimensionality "len"
688 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
689 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
690 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
691 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
692 * that are projected out at the end.
693 * "dim" prescribes the parameters.
695 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
696 int first, int wrap_len, int *wrap_size)
698 int i;
699 isl_basic_map *bmap;
700 isl_constraint *c;
701 isl_local_space *ls;
703 dim = isl_space_add_dims(dim, isl_dim_in, len);
704 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
705 bmap = isl_basic_map_universe(isl_space_copy(dim));
706 ls = isl_local_space_from_space(dim);
708 for (i = 0; i < len; ++i) {
709 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
711 c = isl_equality_alloc(isl_local_space_copy(ls));
712 isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
713 isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
714 bmap = isl_basic_map_add_constraint(bmap, c);
717 for (i = 0; i < wrap_len; ++i) {
718 c = isl_equality_alloc(isl_local_space_copy(ls));
719 isl_constraint_set_coefficient_si(c, isl_dim_out,
720 first + i, -1);
721 isl_constraint_set_coefficient_si(c, isl_dim_out,
722 first + wrap_len + i, 1);
723 isl_constraint_set_coefficient_si(c, isl_dim_out,
724 first + 2 * wrap_len + i, wrap_size[i]);
725 bmap = isl_basic_map_add_constraint(bmap, c);
727 c = isl_inequality_alloc(isl_local_space_copy(ls));
728 isl_constraint_set_coefficient_si(c, isl_dim_out,
729 first + wrap_len + i, 1);
730 bmap = isl_basic_map_add_constraint(bmap, c);
732 c = isl_inequality_alloc(isl_local_space_copy(ls));
733 isl_constraint_set_coefficient_si(c, isl_dim_out,
734 first + wrap_len + i, -1);
735 isl_constraint_set_constant_si(c, wrap_size[i] - 1);
736 bmap = isl_basic_map_add_constraint(bmap, c);
739 isl_local_space_free(ls);
741 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
742 first + 2 * wrap_len, wrap_len);
744 return isl_map_from_basic_map(bmap);
747 /* Add "n" parameters named prefix%d.
749 static __isl_give isl_set *add_params( __isl_take isl_set *set,
750 int n, const char *prefix)
752 int i;
753 unsigned nparam;
754 char name[20];
756 nparam = isl_set_dim(set, isl_dim_param);
757 set = isl_set_add_dims(set, isl_dim_param, n);
759 for (i = 0; i < n; ++i) {
760 snprintf(name, sizeof(name), "%s%d", prefix, i);
761 set = isl_set_set_dim_name(set, isl_dim_param,
762 nparam + i, name);
765 return set;
768 /* Equate the "n" dimensions of "set" starting at "first" to
769 * freshly created parameters named prefix%d.
771 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
772 int first, int n, const char *prefix)
774 int i;
775 unsigned nparam;
776 isl_int v;
777 isl_space *dim;
778 isl_basic_set *bset;
779 isl_constraint *c;
780 isl_local_space *ls;
782 nparam = isl_set_dim(set, isl_dim_param);
784 set = add_params(set, n, prefix);
786 dim = isl_set_get_space(set);
787 bset = isl_basic_set_universe(isl_space_copy(dim));
788 ls = isl_local_space_from_space(dim);
790 isl_int_init(v);
792 for (i = 0; i < n; ++i) {
793 c = isl_equality_alloc(isl_local_space_copy(ls));
794 isl_int_set_si(v, -1);
795 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
796 isl_int_set_si(v, 1);
797 isl_constraint_set_coefficient(c, isl_dim_set, first + i, v);
798 bset = isl_basic_set_add_constraint(bset, c);
801 isl_int_clear(v);
802 isl_local_space_free(ls);
804 return isl_set_intersect(set, isl_set_from_basic_set(bset));
807 /* Given a parameter space "space", create a set of dimension "len"
808 * of which the "n" dimensions starting at "first" are equated to
809 * freshly created parameters named prefix%d.
811 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
812 int len, int first, int n, const char *prefix)
814 isl_set *set;
816 space = isl_space_set_from_params(space);
817 space = isl_space_add_dims(space, isl_dim_set, len);
818 set = isl_set_universe(space);
820 return parametrize(set, first, n, prefix);
823 /* Tile the B loops over the tile sizes and then tile/wrap
824 * the T1 loops over the blocks.
826 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
827 __isl_take isl_union_map *sched)
829 isl_space *dim;
830 isl_map *tiling, *block_tiling;
832 dim = isl_union_map_get_space(sched);
833 tiling = tile(isl_space_copy(dim), gen->untiled_len,
834 gen->tile_first, gen->tile_len, gen->tile_size);
836 if (gen->options->wrap)
837 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
838 gen->tile_first, gen->n_grid, gen->grid_dim);
839 else
840 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
841 gen->tile_first, gen->n_grid, gen->grid_dim);
843 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
845 tiling = isl_map_apply_range(tiling, block_tiling);
847 sched = isl_union_map_apply_range(sched,
848 isl_union_map_from_map(tiling));
850 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
852 return sched;
855 /* Equate the "T1P" iterators in the tiled schedule "sched"
856 * to the block dimensions.
858 static __isl_give isl_union_map *parametrize_tiled_schedule(
859 struct gpu_gen *gen, __isl_take isl_union_map *sched)
861 isl_space *dim;
862 isl_set *par;
864 dim = isl_union_map_get_space(sched);
865 par = parametrization(dim, gen->tiled_len,
866 gen->tile_first + gen->n_grid, gen->n_grid, "b");
867 sched = isl_union_map_intersect_range(sched,
868 isl_union_set_from_set(par));
870 return sched;
873 /* Tile/wrap the P1 loops over the threads.
875 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
876 __isl_take isl_union_map *sched)
878 isl_space *dim;
879 isl_map *tiling;
880 isl_set *par;
882 dim = isl_union_map_get_space(sched);
884 if (gen->options->wrap)
885 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
886 gen->shared_len, gen->n_block, gen->block_dim);
887 else
888 tiling = tile(isl_space_copy(dim), gen->tiled_len,
889 gen->shared_len, gen->n_block, gen->block_dim);
890 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
892 sched = isl_union_map_apply_range(sched,
893 isl_union_map_from_map(tiling));
895 par = parametrization(dim, gen->thread_tiled_len,
896 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
897 gen->n_block, "t");
898 sched = isl_union_map_intersect_range(sched,
899 isl_union_set_from_set(par));
901 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
903 return sched;
906 /* If the user asked for it, scale the shared memory tile loops
907 * (T1T and T2) of "sched" by gen->tile_size[i].
908 * If we are not performing "wrapping", then additionally scale the T1P
909 * loops by gen->grid_dim[i].
911 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
912 __isl_take isl_union_map *sched)
914 int i;
915 isl_space *dim;
916 isl_basic_map *scale;
917 isl_constraint *c;
918 isl_local_space *ls;
920 if (!gen->options->scale_tile_loops)
921 return sched;
923 dim = isl_union_map_get_space(sched);
924 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
925 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
926 scale = isl_basic_map_universe(isl_space_copy(dim));
927 ls = isl_local_space_from_space(dim);
929 for (i = 0; i < gen->tiled_len; ++i) {
930 int f = 1;
932 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
933 f = gen->tile_size[i - gen->tile_first];
934 if (!gen->options->wrap)
935 f *= gen->grid_dim[i - gen->tile_first];
936 } else if (i >= gen->tile_first + gen->n_grid &&
937 i < gen->tile_first + gen->n_grid + gen->tile_len) {
938 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
941 c = isl_equality_alloc(isl_local_space_copy(ls));
942 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
943 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
944 scale = isl_basic_map_add_constraint(scale, c);
947 isl_local_space_free(ls);
949 sched = isl_union_map_apply_range(sched,
950 isl_union_map_from_map(isl_map_from_basic_map(scale)));
952 return sched;
955 /* If we are not performing "wrapping" and if the user asked for it,
956 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
958 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
959 __isl_take isl_union_map *sched)
961 int i;
962 isl_space *dim;
963 isl_basic_map *scale;
964 isl_constraint *c;
965 isl_local_space *ls;
967 if (gen->options->wrap)
968 return sched;
969 if (!gen->options->scale_tile_loops)
970 return sched;
972 dim = isl_union_map_get_space(sched);
973 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
974 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
975 scale = isl_basic_map_universe(isl_space_copy(dim));
976 ls = isl_local_space_from_space(dim);
978 for (i = 0; i < gen->thread_tiled_len; ++i) {
979 int f = 1;
981 if (i >= gen->shared_len &&
982 i < gen->shared_len + gen->n_block)
983 f = gen->block_dim[i - gen->shared_len];
985 c = isl_equality_alloc(isl_local_space_copy(ls));
986 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
987 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
988 scale = isl_basic_map_add_constraint(scale, c);
991 isl_local_space_free(ls);
993 sched = isl_union_map_apply_range(sched,
994 isl_union_map_from_map(isl_map_from_basic_map(scale)));
996 return sched;
999 /* If we are not performing "wrapping" and if the user asked for it,
1000 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1002 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1003 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1005 int i;
1006 isl_space *dim;
1007 isl_basic_map *scale;
1008 isl_constraint *c;
1009 isl_local_space *ls;
1011 if (gen->options->wrap)
1012 return sched;
1013 if (!gen->options->scale_tile_loops)
1014 return sched;
1016 dim = isl_union_map_get_space(sched);
1017 dim = isl_space_add_dims(dim, isl_dim_in, len);
1018 dim = isl_space_add_dims(dim, isl_dim_out, len);
1019 scale = isl_basic_map_universe(isl_space_copy(dim));
1020 ls = isl_local_space_from_space(dim);
1022 for (i = 0; i < len; ++i) {
1023 int f = 1;
1025 if (i >= first && i < first + n_tile)
1026 f = gen->block_dim[i - first];
1028 c = isl_equality_alloc(isl_local_space_copy(ls));
1029 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1030 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1031 scale = isl_basic_map_add_constraint(scale, c);
1034 isl_local_space_free(ls);
1036 sched = isl_union_map_apply_range(sched,
1037 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1039 return sched;
1042 /* Add "len" parameters p[i] called prefix%d,
1043 * with bounds to 0 <= p[i] < size[i].
1045 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1046 int len, int *size, const char *prefix)
1048 int i;
1049 unsigned nparam;
1050 isl_int v;
1051 isl_space *dim;
1052 isl_basic_set *bset;
1053 isl_constraint *c;
1054 isl_local_space *ls;
1055 char name[20];
1057 nparam = isl_set_dim(set, isl_dim_param);
1058 set = isl_set_add_dims(set, isl_dim_param, len);
1060 for (i = 0; i < len; ++i) {
1061 snprintf(name, sizeof(name), "%s%d", prefix, i);
1062 set = isl_set_set_dim_name(set, isl_dim_param,
1063 nparam + i, name);
1066 dim = isl_set_get_space(set);
1067 bset = isl_basic_set_universe(isl_space_copy(dim));
1068 ls = isl_local_space_from_space(dim);
1070 isl_int_init(v);
1072 for (i = 0; i < len; ++i) {
1073 c = isl_inequality_alloc(isl_local_space_copy(ls));
1074 isl_int_set_si(v, 1);
1075 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
1076 bset = isl_basic_set_add_constraint(bset, c);
1078 c = isl_inequality_alloc(isl_local_space_copy(ls));
1079 isl_int_set_si(v, -1);
1080 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
1081 isl_int_set_si(v, size[i] - 1);
1082 isl_constraint_set_constant(c, v);
1083 bset = isl_basic_set_add_constraint(bset, c);
1086 isl_int_clear(v);
1087 isl_local_space_free(ls);
1089 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1092 /* Add "len" parameters p[i] called prefix%d,
1093 * with bounds to 0 <= p[i] < size[i].
1095 static __isl_give isl_set *add_bounded_parameters_dynamic(
1096 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1097 const char *prefix)
1099 int i, len;
1100 unsigned nparam;
1101 isl_space *space;
1102 isl_local_space *ls;
1103 char name[20];
1105 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1106 nparam = isl_set_dim(set, isl_dim_param);
1107 set = isl_set_add_dims(set, isl_dim_param, len);
1109 for (i = 0; i < len; ++i) {
1110 snprintf(name, sizeof(name), "%s%d", prefix, i);
1111 set = isl_set_set_dim_name(set, isl_dim_param,
1112 nparam + i, name);
1115 space = isl_space_params(isl_set_get_space(set));
1116 ls = isl_local_space_from_space(space);
1117 for (i = 0; i < len; ++i) {
1118 isl_pw_aff *param, *size_i, *zero;
1119 isl_set *bound;
1121 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1122 isl_dim_param, nparam + i);
1124 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1125 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1126 set = isl_set_intersect_params(set, bound);
1128 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1129 bound = isl_pw_aff_ge_set(param, zero);
1130 set = isl_set_intersect_params(set, bound);
1132 isl_local_space_free(ls);
1134 return set;
1137 /* Given a mapping "sched" of the form
1139 * [D -> A] -> [D -> T(A)]
1141 * apply the mapping encoded in bounds[i].shift_map to the range of "sched".
1142 * The mappings in bounds[i].shift_map are of the form
1144 * [D -> a] -> [D -> s(D,a)]
1146 * We first compose them with a mapping
1148 * [D -> v] -> v
1150 * (If bounds[i].shift_map is not set, then it is assumed to be
1151 * an identity mapping and then we use this second mapping instead.)
1152 * This results in
1154 * [D -> a] -> s(D,a)
1156 * We precompose them with a projection on the i th dimension to obtain
1158 * [D -> T] -> s(D,T)
1160 * and collect these into
1162 * [D -> T] -> S(D,T)
1164 * Introducing D in the range yields
1166 * [D -> T] -> [D -> S(D,T)]
1168 * and application to "sched" yields
1170 * [D -> A] -> [D -> S(D,T(A))]
1172 static __isl_give isl_map *pre_shift(__isl_take isl_map *sched,
1173 int n_index, struct gpu_array_bound *bounds)
1175 int i;
1176 isl_ctx *ctx = isl_map_get_ctx(sched);
1177 isl_space *space, *space2;
1178 isl_basic_map *def;
1179 isl_map *map, *id, *pre_shift;
1181 space = isl_space_range(isl_map_get_space(sched));
1182 space2 = isl_space_from_domain(isl_space_copy(space));
1183 pre_shift = isl_map_universe(space2);
1184 space = isl_space_domain(isl_space_unwrap(space));
1185 id = isl_map_identity(isl_space_map_from_set(isl_space_copy(space)));
1186 space = isl_space_from_domain(space);
1187 space = isl_space_add_dims(space, isl_dim_out, 1);
1188 def = isl_basic_map_range_map(isl_basic_map_universe(space));
1190 for (i = 0; i < n_index; ++i) {
1191 isl_basic_map *bmap, *drop;
1192 isl_map *proj;
1194 space = isl_space_alloc(ctx, 0, n_index, n_index);
1195 proj = isl_map_identity(space);
1196 proj = isl_map_project_out(proj, isl_dim_out,
1197 i + 1, n_index - (i + 1));
1198 proj = isl_map_project_out(proj, isl_dim_out, 0, i);
1199 proj = isl_map_product(isl_map_copy(id), proj);
1201 if (!bounds[i].shift_map)
1202 bmap = isl_basic_map_copy(def);
1203 else {
1204 bmap = isl_basic_map_copy(bounds[i].shift_map);
1205 bmap = isl_basic_map_apply_range(bmap,
1206 isl_basic_map_copy(def));
1209 map = isl_map_from_basic_map(bmap);
1210 map = isl_map_apply_range(proj, map);
1211 pre_shift = isl_map_flat_range_product(pre_shift, map);
1214 isl_map_free(id);
1215 isl_basic_map_free(def);
1217 space = isl_space_domain(isl_map_get_space(pre_shift));
1218 map = isl_map_domain_map(isl_map_universe(isl_space_unwrap(space)));
1219 pre_shift = isl_map_range_product(map, pre_shift);
1221 sched = isl_map_apply_range(sched, pre_shift);
1223 return sched;
1226 /* Given an access relation to a tile of an array, construct a map that
1227 * maps each element in the space of the access relation
1228 * to a copy of the tile shifted to the origin
1229 * (based on the lower bounds in group->private_bound or group->shared_bound).
1230 * If any of the indices is strided, then {private,shared}_bound[i].shift_map
1231 * is applied to the index first.
1232 * The domain space of the resulting map is that of access "access",
1233 * while the range space is anonymous.
1234 * The resulting map only encodes the mapping to the shift tile and
1235 * not the constraints of "access".
1237 * Let the space of the access relation be
1239 * D -> A
1241 * We first construct an identity relation on a wrapped copy of this space,
1242 * except that it strips off the name of array
1244 * [D -> A] -> [D -> T(A)] (1)
1246 * The bounds in bounds[i].lb are of the form
1248 * D -> b(D)
1250 * We collect them into
1252 * D -> B(D)
1254 * and then transform them into
1256 * [D -> T] -> T - B(D) (2)
1258 * Combining those two mappings (1) and (2) yields
1260 * [D -> A] -> T(A) - B(D)
1262 * If there are any strides, then (1) is first transformed into (1')
1264 * [D -> A] -> [D -> T'(A)] (1')
1266 * by a call to pre_shift.
1268 static __isl_give isl_map *shift_access(__isl_take isl_map *access,
1269 struct gpu_array_ref_group *group)
1271 int i;
1272 isl_space *space;
1273 isl_map *id1, *id2;
1274 isl_map *map;
1275 isl_map *shift;
1276 isl_map *sched;
1277 struct gpu_array_bound *bounds;
1278 int n_index = group->array->n_index;
1280 bounds = group->private_bound;
1281 if (!bounds)
1282 bounds = group->shared_bound;
1284 space = isl_space_domain(isl_map_get_space(access));
1285 space = isl_space_map_from_set(space);
1286 id1 = isl_map_identity(space);
1287 space = isl_space_range(isl_map_get_space(access));
1288 space = isl_space_map_from_set(space);
1289 space = isl_space_set_tuple_name(space, isl_dim_out, NULL);
1290 id2 = isl_map_identity(space);
1291 sched = isl_map_product(id1, id2);
1293 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1294 space = isl_space_from_domain(isl_space_domain(space));
1295 shift = isl_map_universe(space);
1296 for (i = 0; i < n_index; ++i) {
1297 map = isl_map_from_aff(isl_aff_copy(bounds[i].lb));
1298 shift = isl_map_flat_range_product(shift, map);
1301 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1302 map = isl_map_universe(space);
1303 id1 = isl_map_range_map(isl_map_copy(map));
1304 map = isl_map_domain_map(map);
1305 shift = isl_map_neg(shift);
1306 shift = isl_map_apply_range(map, shift);
1307 shift = isl_map_sum(id1, shift);
1309 for (i = 0; i < n_index; ++i)
1310 if (bounds[i].shift_map)
1311 break;
1313 if (i < n_index)
1314 sched = pre_shift(sched, n_index, bounds);
1316 sched = isl_map_apply_range(sched, shift);
1318 isl_map_free(access);
1320 return sched;
1323 /* Given a schedule that iterates over all elements in a piece of an array,
1324 * perform tiling/wrapping over the threads.
1326 * In particular, we tile the final iterators so that the final thread
1327 * dimension runs over the final array dimension.
1328 * However, if those final iterators have only a single iteration,
1329 * we try to tile earlier iterators instead.
1331 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1332 __isl_take isl_map *sched)
1334 isl_space *dim;
1335 isl_union_map *usched;
1336 isl_map *tiling;
1337 isl_set *par;
1338 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1339 int n_tile;
1340 int first;
1342 n_tile = gen->n_block;
1343 if (n_tile > nvar) {
1344 int i;
1345 sched = isl_map_insert_dims(sched,
1346 isl_dim_out, 0, n_tile - nvar);
1347 for (i = 0; i < n_tile - nvar; ++i)
1348 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1349 nvar = n_tile;
1352 first = nvar - n_tile;
1354 for (; first > 0; first --)
1355 if (!isl_map_plain_is_fixed(sched, isl_dim_out,
1356 first + n_tile - 1, NULL))
1357 break;
1359 dim = isl_map_get_space(sched);
1360 dim = isl_space_params(dim);
1361 if (gen->options->wrap)
1362 tiling = wrap(isl_space_copy(dim), nvar, first,
1363 n_tile, gen->block_dim);
1364 else
1365 tiling = tile(isl_space_copy(dim), nvar, first,
1366 n_tile, gen->block_dim);
1367 sched = isl_map_apply_range(sched, tiling);
1369 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1370 sched = isl_map_intersect_range(sched, par);
1372 usched = isl_union_map_from_map(sched);
1373 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1374 first, n_tile);
1375 sched = isl_map_from_union_map(usched);
1377 return sched;
1380 /* Given an index expression "pa" into a tile of an array, adjust the expression
1381 * to a shift of the tile to the origin
1382 * (based on the lower bounds in "bound".
1383 * If the index is strided, then we first add
1384 * bound->shift and divide by bound->stride.
1385 * In the end, we compute the gist with respect to "domain".
1387 * All of the input expression "pa", the set "domain" and
1388 * the output are expressed in terms of the AST schedule domain.
1389 * The expressions in "bound" are expressed
1390 * in terms of the first shared_len dimensions of the schedule computed by PPCG.
1391 * The mapping "sched2shared" maps the former domain to the latter domain.
1393 static __isl_give isl_pw_aff *shift_index(__isl_take isl_pw_aff *pa,
1394 struct gpu_array_info *array,
1395 struct gpu_array_bound *bound, __isl_take isl_set *domain,
1396 __isl_take isl_map *sched2shared)
1398 isl_map *map;
1399 isl_pw_aff *tmp;
1400 isl_pw_multi_aff *pma;
1402 if (bound->shift) {
1403 map = isl_map_from_aff(isl_aff_copy(bound->shift));
1404 map = isl_map_apply_range(isl_map_copy(sched2shared), map);
1405 pma = isl_pw_multi_aff_from_map(map);
1406 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1407 isl_pw_multi_aff_free(pma);
1408 pa = isl_pw_aff_add(pa, tmp);
1409 pa = isl_pw_aff_scale_down(pa, bound->stride);
1413 map = isl_map_from_aff(isl_aff_copy(bound->lb));
1414 map = isl_map_apply_range(sched2shared, map);
1415 pma = isl_pw_multi_aff_from_map(map);
1416 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1417 isl_pw_multi_aff_free(pma);
1418 pa = isl_pw_aff_sub(pa, tmp);
1419 pa = isl_pw_aff_coalesce(pa);
1420 pa = isl_pw_aff_gist(pa, domain);
1422 return pa;
1425 /* Return the union of all read (read = 1) and/or write (write = 1)
1426 * access relations in the group.
1428 static __isl_give isl_union_map *group_access_relation(
1429 struct gpu_array_ref_group *group, int read, int write)
1431 int i;
1432 isl_union_map *access;
1434 access = isl_union_map_empty(isl_map_get_space(group->access));
1435 for (i = 0; i < group->n_ref; ++i) {
1436 isl_map *map_i;
1438 if (!((read && group->refs[i]->read) ||
1439 (write && group->refs[i]->write)))
1440 continue;
1441 map_i = isl_map_copy(group->refs[i]->access);
1442 access = isl_union_map_union(access,
1443 isl_union_map_from_map(map_i));
1446 return access;
1449 /* Return a map from the first shared_len dimensions of the computed
1450 * schedule to the values of the given index "i"
1451 * of the elements in the array tile in global memory that corresponds
1452 * to the shared memory copy.
1453 * In particular, if a is the index, then the range of the map
1455 * { D -> [a] }
1457 * is constrained as follows
1459 * tile_offset(D) <= a <= tile_offset(D) + tile_size - 1 (1)
1461 * and
1463 * 0 <= a <= array_size - 1 (2)
1466 * Note that if some stride has been detected (i.e., when
1467 * group->shared_bound[i].shift is set), then offset and size (i.e.,
1468 * constraints (1)) apply to the shifted and scaled down copy of the tile.
1469 * These constraints therefore have to be mapped back to the original
1470 * array space using the inverse of the shift_map.
1472 static __isl_give isl_map *group_tile_dim(struct gpu_array_ref_group *group,
1473 int i)
1475 isl_aff *aff;
1476 isl_space *space;
1477 isl_map *map, *tile, *gt;
1478 isl_set *bound;
1480 map = isl_map_from_aff(isl_aff_copy(group->shared_bound[i].lb));
1481 space = isl_space_range(isl_map_get_space(map));
1482 map = isl_map_apply_range(map, isl_map_lex_le(isl_space_copy(space)));
1483 tile = map;
1485 aff = isl_aff_copy(group->shared_bound[i].lb);
1486 aff = isl_aff_add_constant(aff, group->shared_bound[i].size);
1487 map = isl_map_from_aff(aff);
1488 gt = isl_map_lex_gt(space);
1489 map = isl_map_apply_range(map, isl_map_copy(gt));
1490 tile = isl_map_intersect(tile, map);
1492 if (group->shared_bound[i].shift) {
1493 isl_basic_map *shift;
1494 shift = isl_basic_map_copy(group->shared_bound[i].shift_map);
1495 shift = isl_basic_map_reverse(shift);
1496 tile = isl_set_unwrap(isl_set_apply(isl_map_wrap(tile),
1497 isl_map_from_basic_map(shift)));
1500 tile = isl_map_lower_bound_si(tile, isl_dim_out, 0, 0);
1502 bound = isl_set_from_pw_aff(isl_pw_aff_copy(group->array->bound[i]));
1503 bound = isl_set_apply(bound, gt);
1504 tile = isl_map_intersect_range(tile, bound);
1506 return tile;
1509 /* Return a map from the first shared_len dimensions of the computed
1510 * schedule to the array tile in
1511 * global memory that corresponds to the shared memory copy.
1513 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1515 int i;
1516 int n_index = group->array->n_index;
1517 isl_map *tile;
1519 tile = group_tile_dim(group, 0);
1520 for (i = 1; i < n_index; ++i) {
1521 isl_map *tile_i;
1523 tile_i = group_tile_dim(group, i);
1524 tile = isl_map_flat_range_product(tile, tile_i);
1527 tile = isl_map_set_tuple_name(tile, isl_dim_out, group->array->name);
1529 return tile;
1532 /* Given a mapping "sched" from the AST schedule to a domain,
1533 * return the corresponding mapping from the AST schedule to
1534 * to the first shared_len dimensions of the schedule computed by PPCG.
1536 static __isl_give isl_map *compute_sched_to_shared(struct gpu_gen *gen,
1537 __isl_take isl_map *sched)
1539 isl_union_map *umap;
1540 isl_space *space;
1541 isl_map *map;
1543 space = isl_space_range(isl_map_get_space(sched));
1544 space = isl_space_from_domain(space);
1545 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1547 umap = isl_union_map_copy(gen->shared_sched);
1548 umap = isl_union_map_apply_range(umap,
1549 isl_union_map_copy(gen->shared_proj));
1550 map = isl_union_map_extract_map(umap, space);
1551 isl_union_map_free(umap);
1553 sched = isl_map_apply_range(sched, map);
1554 sched = isl_map_detect_equalities(sched);
1556 return sched;
1559 /* Set unroll[j] if the input dimension j is involved in
1560 * the index expression represented by bmap.
1562 static int check_unroll(__isl_take isl_basic_map *bmap, void *user)
1564 int i, j;
1565 int n_in = isl_basic_map_dim(bmap, isl_dim_in);
1566 int n_out = isl_basic_map_dim(bmap, isl_dim_out);
1567 int *unroll = user;
1569 for (i = 0; i < n_out; ++i) {
1570 isl_constraint *c;
1571 int ok;
1573 ok = isl_basic_map_has_defining_equality(bmap,
1574 isl_dim_out, i, &c);
1575 assert(ok);
1576 for (j = 0; j < n_in; ++j)
1577 if (isl_constraint_involves_dims(c, isl_dim_in, j, 1))
1578 unroll[j] = 1;
1579 isl_constraint_free(c);
1582 isl_basic_map_free(bmap);
1583 return 0;
1586 /* Given an array pos mapping input dimensions to the corresponding
1587 * output dimension, construct the corresponding map.
1589 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1590 int *pos, int len)
1592 int i;
1593 isl_constraint *c;
1594 isl_basic_map *bmap;
1595 isl_local_space *ls;
1597 dim = isl_space_add_dims(dim, isl_dim_in, len);
1598 dim = isl_space_add_dims(dim, isl_dim_out, len);
1599 bmap = isl_basic_map_universe(isl_space_copy(dim));
1600 ls = isl_local_space_from_space(dim);
1602 for (i = 0; i < len; ++i) {
1603 c = isl_equality_alloc(isl_local_space_copy(ls));
1604 isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
1605 isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i], 1);
1606 bmap = isl_basic_map_add_constraint(bmap, c);
1608 isl_local_space_free(ls);
1610 return isl_map_from_basic_map(bmap);
1613 /* Find all loops involved in any of the index expressions for any of
1614 * the private accesses, move them innermost and then mark them as
1615 * requiring unrolling by setting gen->first_unroll.
1616 * The loops involved should all be parallel because of the checks
1617 * we performed in check_private_group_access. Moving them innermost
1618 * is therefore a valid transformation.
1620 * Loops up to gen->shared_len are generated before the mapping to
1621 * threads is applied. They should therefore be ignored.
1623 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1624 __isl_take isl_union_map *sched)
1626 int i, j;
1627 int unroll[gen->thread_tiled_len];
1628 int perm[gen->thread_tiled_len];
1629 isl_space *dim;
1630 isl_map *permute;
1631 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1633 gen->first_unroll = -1;
1635 for (i = 0; i < gen->thread_tiled_len; ++i)
1636 unroll[i] = 0;
1637 for (i = 0; i < gen->prog->n_array; ++i) {
1638 struct gpu_array_info *array = &gen->prog->array[i];
1640 for (j = 0; j < array->n_group; ++j) {
1641 isl_union_map *access;
1642 isl_map *acc;
1644 if (!array->groups[j]->private_bound)
1645 continue;
1647 access = group_access_relation(array->groups[j], 1, 1);
1648 access = isl_union_map_apply_domain(access,
1649 isl_union_map_copy(sched));
1651 acc = isl_map_from_union_map(access);
1652 isl_map_foreach_basic_map(acc, &check_unroll, unroll);
1654 isl_map_free(acc);
1658 for (i = gen->shared_len; i < len; ++i)
1659 if (unroll[i])
1660 break;
1662 if (i >= len)
1663 return sched;
1665 for (i = len; i < gen->thread_tiled_len; ++i)
1666 if (unroll[i])
1667 return sched;
1669 j = 0;
1670 for (i = 0; i < gen->shared_len; ++i)
1671 perm[i] = j++;
1672 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1673 if (!unroll[i])
1674 perm[i] = j++;
1675 gen->first_unroll = j - gen->shared_len;
1676 for (i = gen->shared_len; i < len; ++i)
1677 if (unroll[i])
1678 perm[i] = j++;
1680 dim = isl_union_map_get_space(sched);
1681 permute = permutation(dim, perm, gen->thread_tiled_len);
1682 sched = isl_union_map_apply_range(sched,
1683 isl_union_map_from_map(permute));
1685 return sched;
1688 /* Given a constraint
1690 * a(p,i) + j = g f(e)
1692 * or -a(p,i) - j = g f(e) if sign < 0,
1693 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1694 * a(p,i) is assumed to be an expression in only the parameters
1695 * and the input dimensions.
1697 static void extract_stride(__isl_keep isl_constraint *c,
1698 struct gpu_array_bound *bound, isl_int stride, int sign)
1700 int i;
1701 isl_int v;
1702 isl_space *space;
1703 unsigned nparam;
1704 unsigned nvar;
1705 isl_aff *aff;
1707 isl_int_set(bound->stride, stride);
1709 space = isl_constraint_get_space(c);
1710 space = isl_space_domain(space);
1712 nparam = isl_space_dim(space, isl_dim_param);
1713 nvar = isl_space_dim(space, isl_dim_set);
1715 isl_int_init(v);
1717 isl_constraint_get_constant(c, &v);
1718 if (sign < 0)
1719 isl_int_neg(v, v);
1720 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1721 aff = isl_aff_set_constant(aff, v);
1723 for (i = 0; i < nparam; ++i) {
1724 isl_constraint_get_coefficient(c, isl_dim_param, i, &v);
1725 if (isl_int_is_zero(v))
1726 continue;
1727 if (sign < 0)
1728 isl_int_neg(v, v);
1729 aff = isl_aff_add_coefficient(aff, isl_dim_param, i, v);
1732 for (i = 0; i < nvar; ++i) {
1733 isl_constraint_get_coefficient(c, isl_dim_in, i, &v);
1734 if (isl_int_is_zero(v))
1735 continue;
1736 if (sign < 0)
1737 isl_int_neg(v, v);
1738 aff = isl_aff_add_coefficient(aff, isl_dim_in, i, v);
1741 isl_int_clear(v);
1743 bound->shift = aff;
1746 /* Given an equality constraint of a map with a single output dimension j,
1747 * check if the constraint is of the form
1749 * a(p,i) + j = g f(e)
1751 * with a(p,i) an expression in the parameters and input dimensions
1752 * and f(e) an expression in the existentially quantified variables.
1753 * If so, and if g is larger than any such g from a previously considered
1754 * constraint, then call extract_stride to record the stride information
1755 * in bound.
1757 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1759 int i;
1760 isl_int v, stride;
1761 unsigned n_div;
1762 struct gpu_array_bound *bound = user;
1764 isl_int_init(v);
1765 isl_int_init(stride);
1767 n_div = isl_constraint_dim(c, isl_dim_div);
1768 isl_constraint_get_coefficient(c, isl_dim_out, 0, &v);
1770 if (n_div && (isl_int_is_one(v) || isl_int_is_negone(v))) {
1771 int s = isl_int_sgn(v);
1772 isl_int_set_si(stride, 0);
1773 for (i = 0; i < n_div; ++i) {
1774 isl_constraint_get_coefficient(c, isl_dim_div, i, &v);
1775 isl_int_gcd(stride, stride, v);
1777 if (!isl_int_is_zero(stride) &&
1778 isl_int_gt(stride, bound->stride))
1779 extract_stride(c, bound, stride, s);
1782 isl_int_clear(stride);
1783 isl_int_clear(v);
1785 isl_constraint_free(c);
1786 return 0;
1789 /* Given contraints on an array index i, check if we can find
1790 * a shift a(p) and a stride g such that
1792 * a(p) + i = 0 mod g
1794 * If so, record the information in bound and apply the mapping
1795 * i -> (i + a(p))/g to the array index in bounds and return
1796 * the new constraints.
1797 * If not, simply return the original constraints.
1799 * If bounds is a subset of the space
1801 * D -> i
1803 * then the bound recorded in bound->shift is of the form
1805 * D -> s(D)
1807 * with s(D) equal to a(p) above.
1808 * The mapping recorded in bound->shift_map is of the form
1810 * [D -> i] -> [D -> (i + S(D))/g]
1812 * This mapping is computed as follows.
1813 * We first introduce "i" in the domain through precomposition
1814 * with [D -> i] -> D obtaining
1816 * [D -> i] -> s(D)
1818 * Adding [D -> i] -> i produces
1820 * [D -> i] -> i + s(D)
1822 * and the domain product with [D -> i] -> D yields
1824 * [D -> i] -> [D -> i + s(D)]
1826 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1828 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1829 __isl_take isl_basic_map *bounds)
1831 isl_space *space;
1832 isl_basic_map *hull;
1833 isl_basic_map *shift, *id, *bmap, *scale;
1834 isl_basic_set *bset;
1835 isl_aff *aff;
1837 isl_int_set_si(bound->stride, -1);
1839 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1841 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1843 isl_basic_map_free(hull);
1845 if (isl_int_is_neg(bound->stride))
1846 return bounds;
1848 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1849 space = isl_basic_map_get_space(bounds);
1850 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1851 shift = isl_basic_map_apply_range(bmap, shift);
1852 space = isl_basic_map_get_space(bounds);
1853 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1854 shift = isl_basic_map_sum(id, shift);
1855 space = isl_basic_map_get_space(bounds);
1856 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1857 shift = isl_basic_map_range_product(id, shift);
1859 space = isl_space_domain(isl_basic_map_get_space(bounds));
1860 id = isl_basic_map_identity(isl_space_map_from_set(space));
1861 space = isl_space_range(isl_basic_map_get_space(bounds));
1862 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1863 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1864 aff = isl_aff_scale_down(aff, bound->stride);
1865 scale = isl_basic_map_from_aff(aff);
1866 scale = isl_basic_map_product(id, scale);
1868 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1869 bmap = isl_basic_map_copy(bound->shift_map);
1870 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1871 bounds = isl_basic_set_unwrap(bset);
1873 return bounds;
1876 /* Data used in compute_array_dim_size and compute_size_in_direction.
1878 * pos is the position of the variable representing the array index,
1879 * i.e., the variable for which want to compute the size. This variable
1880 * is also the last variable in the set.
1882 struct gpu_size_info {
1883 isl_basic_set *bset;
1884 struct gpu_array_bound *bound;
1885 int pos;
1888 /* Given a constraint from the basic set describing the bounds on
1889 * an array index, check if it is a lower bound, say m i >= b(x), and,
1890 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1891 * upper bound. If so, and if this bound is smaller than any bound
1892 * derived from earlier constraints, set the size to this bound on
1893 * the expression and the lower bound to ceil(b(x)/m).
1895 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1897 struct gpu_size_info *size = user;
1898 unsigned nparam;
1899 unsigned n_div;
1900 isl_int v;
1902 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1903 n_div = isl_constraint_dim(c, isl_dim_div);
1905 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div)) {
1906 isl_constraint_free(c);
1907 return 0;
1910 isl_int_init(v);
1912 isl_constraint_get_coefficient(c, isl_dim_set, size->pos, &v);
1914 if (isl_int_is_pos(v)) {
1915 isl_aff *aff;
1916 isl_aff *lb;
1917 enum isl_lp_result res;
1919 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1920 aff = isl_aff_ceil(aff);
1922 lb = isl_aff_copy(aff);
1924 aff = isl_aff_neg(aff);
1925 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1927 res = isl_basic_set_max(size->bset, aff, &v);
1928 isl_aff_free(aff);
1930 if (res == isl_lp_ok) {
1931 isl_int_add_ui(v, v, 1);
1932 if (isl_int_is_neg(size->bound->size) ||
1933 isl_int_lt(v, size->bound->size)) {
1934 isl_int_set(size->bound->size, v);
1935 lb = isl_aff_drop_dims(lb, isl_dim_in,
1936 size->pos, 1);
1937 isl_aff_free(size->bound->lb);
1938 size->bound->lb = isl_aff_copy(lb);
1941 isl_aff_free(lb);
1944 isl_int_clear(v);
1945 isl_constraint_free(c);
1947 return 0;
1950 /* Given a basic map "bounds" that maps parameters and input dimensions
1951 * to a single output dimension, look for an expression in the parameters
1952 * and input dimensions such that the range of the output dimension shifted
1953 * by this expression is a constant.
1955 * In particular, we currently only consider lower bounds on the output
1956 * dimension as candidate expressions.
1958 static int compute_array_dim_size(struct gpu_array_bound *bound,
1959 __isl_take isl_basic_map *bounds)
1961 struct gpu_size_info size;
1963 bounds = isl_basic_map_detect_equalities(bounds);
1964 bounds = check_stride(bound, bounds);
1966 isl_int_set_si(bound->size, -1);
1967 bound->lb = NULL;
1969 size.bound = bound;
1970 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
1971 size.bset = isl_basic_map_wrap(bounds);
1972 size.bset = isl_basic_set_flatten(size.bset);
1973 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
1974 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
1975 &size);
1976 isl_basic_set_free(size.bset);
1978 return isl_int_is_nonneg(bound->size) ? 0 : -1;
1981 /* Check if we can find a shared memory tile for the given array
1982 * based on the given accesses, and if so, put the results
1983 * in array->shared_bound.
1985 * We project the accesses on each index in turn and look for a parametric
1986 * offset such that the size is constant.
1988 static int can_tile_for_shared_memory(struct gpu_array_info *array,
1989 __isl_keep isl_map *access, struct gpu_array_bound *bounds)
1991 int i;
1993 for (i = 0; i < array->n_index; ++i) {
1994 isl_map *access_i;
1995 isl_basic_map *hull;
1997 access_i = isl_map_copy(access);
1998 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
1999 access_i = isl_map_project_out(access_i, isl_dim_out,
2000 1, array->n_index - (i + 1));
2001 access_i = isl_map_compute_divs(access_i);
2002 hull = isl_map_simple_hull(access_i);
2003 if (compute_array_dim_size(&bounds[i], hull) < 0)
2004 return 0;
2007 return 1;
2010 /* Construct a map with input the shared tile loops and the loops that
2011 * will be wrapped around the threads that relates these later loops
2012 * to the thread indices and then projects them out.
2014 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2016 isl_map *priv;
2017 isl_map *tiling;
2018 isl_map *proj;
2019 isl_set *par;
2020 isl_space *dim;
2022 dim = isl_union_map_get_space(gen->shared_sched);
2024 if (gen->options->wrap)
2025 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2026 gen->shared_len, gen->n_block, gen->block_dim);
2027 else
2028 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2029 gen->shared_len, gen->n_block, gen->block_dim);
2031 priv = tiling;
2033 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2034 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2035 gen->n_block, "t");
2037 priv = isl_map_align_params(priv, isl_set_get_space(par));
2038 priv = isl_map_intersect_range(priv, par);
2040 dim = isl_map_get_space(priv);
2041 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2042 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2043 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2044 gen->shared_len);
2046 priv = isl_map_apply_range(priv, proj);
2048 return priv;
2051 /* Construct a map from domain_dim to domain_dim that increments
2052 * the dimension at position "pos" and leaves all other dimensions
2053 * constant.
2055 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2057 int i;
2058 int len = isl_space_dim(domain_dim, isl_dim_set);
2059 isl_space *dim;
2060 isl_basic_map *next;
2061 isl_local_space *ls;
2063 dim = isl_space_map_from_set(domain_dim);
2064 next = isl_basic_map_universe(isl_space_copy(dim));
2065 ls = isl_local_space_from_space(dim);
2067 for (i = 0; i < len; ++i) {
2068 isl_constraint *c;
2070 c = isl_equality_alloc(isl_local_space_copy(ls));
2071 isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2072 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2073 if (i == pos)
2074 isl_constraint_set_constant_si(c, 1);
2075 next = isl_basic_map_add_constraint(next, c);
2078 isl_local_space_free(ls);
2080 return isl_map_from_basic_map(next);
2083 /* Check if the given access is coalesced.
2084 * That is, check whether incrementing the dimension that will get
2085 * wrapped over the last thread index results in incrementing
2086 * the last array index.
2088 * This function is only called for access relations without reuse.
2090 static int access_is_coalesced(struct gpu_gen *gen,
2091 __isl_keep isl_union_map *access)
2093 isl_space *dim;
2094 isl_map *access_map;
2095 isl_map *next_thread_x;
2096 isl_map *next_element;
2097 isl_map *map;
2098 int coalesced;
2100 access = isl_union_map_copy(access);
2101 access = isl_union_map_apply_domain(access,
2102 isl_union_map_copy(gen->tiled_sched));
2103 access_map = isl_map_from_union_map(access);
2105 dim = isl_map_get_space(access_map);
2106 dim = isl_space_domain(dim);
2107 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2109 dim = isl_map_get_space(access_map);
2110 dim = isl_space_range(dim);
2111 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2113 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2114 map = isl_map_apply_range(map, access_map);
2116 coalesced = isl_map_is_subset(map, next_element);
2118 isl_map_free(next_element);
2119 isl_map_free(map);
2121 return coalesced;
2124 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2125 * dimensions of the computed schedule, check if it is bijective for
2126 * fixed values of the first gen->shared_len dimensions.
2127 * We perform this check by equating these dimensions to parameters.
2129 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2131 int res;
2132 isl_set *par;
2133 isl_space *space;
2135 access = isl_map_copy(access);
2136 space = isl_space_params(isl_map_get_space(access));
2137 par = parametrization(space, gen->shared_len + gen->n_block,
2138 0, gen->shared_len, "s");
2139 access = isl_map_intersect_domain(access, par);
2140 res = isl_map_is_bijective(access);
2141 isl_map_free(access);
2143 return res;
2146 /* For the given array reference group, check whether the access is private
2147 * to the thread. That is, check that any given array element
2148 * is only accessed by a single thread.
2149 * We compute an access relation that maps the shared tile loop iterators
2150 * and the shared point loop iterators that will be wrapped over the
2151 * threads to the array elements.
2152 * We actually check that those iterators that will be wrapped
2153 * partition the array space. This check is stricter than necessary
2154 * since several iterations may be mapped onto the same thread
2155 * and then they could be allowed to access the same memory elements,
2156 * but our check does not allow this situation.
2158 * We also check that the index expression only depends on parallel
2159 * loops. That way, we can move those loops innermost and unroll them.
2160 * Again, we use a test that is stricter than necessary.
2161 * We actually check whether the index expression only depends
2162 * on the iterators that are wrapped over the threads.
2163 * These are necessarily parallel, but there may be more parallel loops.
2165 * Combining the injectivity of the first test with the single-valuedness
2166 * of the second test, we simply test for bijectivity.
2168 * If it turns out we can use registers, we compute the private memory
2169 * tile size using can_tile_for_shared_memory, after introducing a dependence
2170 * on the thread indices.
2172 * Before performing any of the above computations, we first check
2173 * if there is any reuse on the reference group. If not, we simply
2174 * return. If, moreover, the access is coalesced then we also remove
2175 * the shared memory tiling since we should just use global memory instead.
2177 static void check_private_group_access(struct gpu_gen *gen,
2178 struct gpu_array_ref_group *group)
2180 isl_map *acc;
2181 isl_union_map *access;
2182 int n_index = group->array->n_index;
2184 access = group_access_relation(group, 1, 1);
2185 if (isl_union_map_is_injective(access)) {
2186 if (group->shared_bound && access_is_coalesced(gen, access)) {
2187 free_bound_list(group->shared_bound, n_index);
2188 group->shared_bound = NULL;
2190 isl_union_map_free(access);
2191 return;
2193 access = isl_union_map_apply_domain(access,
2194 isl_union_map_copy(gen->shared_sched));
2196 acc = isl_map_from_union_map(access);
2198 if (!access_is_bijective(gen, acc)) {
2199 isl_map_free(acc);
2200 return;
2203 group->private_bound = create_bound_list(gen->ctx, n_index);
2204 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2205 if (!can_tile_for_shared_memory(group->array, acc,
2206 group->private_bound)) {
2207 free_bound_list(group->private_bound, n_index);
2208 group->private_bound = NULL;
2211 isl_map_free(acc);
2214 /* Look for the last shared tile loop that affects the offset of the
2215 * shared or private tile and store the result in array->last_shared.
2216 * If there is no such loop, then array->last_shared is set to a value
2217 * before the first shared tile loop, in particular gen->tile_first - 1.
2219 static void set_last_shared(struct gpu_gen *gen,
2220 struct gpu_array_ref_group *group)
2222 int i, j;
2223 struct gpu_array_bound *bounds;
2224 int n_index = group->array->n_index;
2226 bounds = group->private_bound;
2227 if (!bounds)
2228 bounds = group->shared_bound;
2229 if (!bounds)
2230 return;
2232 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2233 for (i = 0; i < n_index; ++i) {
2234 isl_aff *lb;
2235 isl_aff *shift;
2237 lb = bounds[i].lb;
2238 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2239 break;
2241 shift = bounds[i].shift;
2242 if (!shift)
2243 continue;
2244 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2245 break;
2247 if (i < n_index)
2248 break;
2250 group->last_shared = j;
2253 /* Compute the sizes of all private arrays for the current kernel,
2254 * as well as the offsets of the private pieces in the original arrays.
2255 * If we cannot or don't want to privatize a given array group,
2256 * we use the shared memory tile sizes computed in
2257 * compute_group_shared_bound instead.
2259 * If we have been able to find a private or shared tile,
2260 * we also look for the last shared tile loop that affects the offset
2261 * (and therefore the group tile) and store the result in group->last_shared.
2263 * A privatized copy of all access relations from reference groups that
2264 * are mapped to private memory is stored in gen->privatization.
2266 static void compute_private_size(struct gpu_gen *gen)
2268 int i, j;
2269 isl_union_map *private;
2271 if (!gen->options->use_private_memory)
2272 return;
2274 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2276 for (i = 0; i < gen->prog->n_array; ++i) {
2277 struct gpu_array_info *array = &gen->prog->array[i];
2279 if (gpu_array_is_read_only_scalar(array))
2280 continue;
2282 for (j = 0; j < array->n_group; ++j) {
2283 check_private_group_access(gen, array->groups[j]);
2285 if (!array->groups[j]->private_bound)
2286 continue;
2288 private = isl_union_map_union(private,
2289 group_access_relation(array->groups[j], 1, 1));
2292 for (j = 0; j < array->n_group; ++j) {
2293 array->groups[j]->last_shared = gen->shared_len - 1;
2294 set_last_shared(gen, array->groups[j]);
2298 if (isl_union_map_is_empty(private))
2299 isl_union_map_free(private);
2300 else {
2301 isl_union_map *priv;
2303 private = isl_union_map_apply_domain(private,
2304 isl_union_map_copy(gen->shared_sched));
2305 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2306 private = isl_union_map_apply_domain(private, priv);
2307 gen->private_access = private;
2311 /* Compute the size of the tile specified by the list "bound" of n_index
2312 * gpu_array_bounds in number of elements and put the result in *size.
2314 static void tile_size(unsigned n_index, struct gpu_array_bound *bound,
2315 isl_int *size)
2317 int i;
2319 isl_int_set_si(*size, 1);
2321 for (i = 0; i < n_index; ++i)
2322 isl_int_mul(*size, *size, bound[i].size);
2325 /* If max_shared_memory is not set to infinity (-1), then make
2326 * sure that the total amount of shared memory required by the
2327 * array reference groups mapped to shared memory is no larger
2328 * than this maximum.
2330 * We apply a greedy approach and discard (keep in global memory)
2331 * those groups that would result in a total memory size that
2332 * is larger than the maximum.
2334 static void check_shared_memory_bound(struct gpu_gen *gen)
2336 int i, j;
2337 isl_int left, size;
2339 if (gen->options->max_shared_memory < 0)
2340 return;
2342 isl_int_init(left);
2343 isl_int_init(size);
2344 isl_int_set_si(left, gen->options->max_shared_memory);
2346 for (i = 0; i < gen->prog->n_array; ++i) {
2347 struct gpu_array_info *array = &gen->prog->array[i];
2349 for (j = 0; j < array->n_group; ++j) {
2350 struct gpu_array_ref_group *group;
2352 group = array->groups[j];
2353 if (!group->shared_bound)
2354 continue;
2356 tile_size(array->n_index, group->shared_bound, &size);
2357 isl_int_mul_ui(size, size, array->size);
2359 if (isl_int_le(size, left)) {
2360 isl_int_sub(left, left, size);
2361 continue;
2364 free_bound_list(group->shared_bound, array->n_index);
2365 group->shared_bound = NULL;
2369 isl_int_clear(size);
2370 isl_int_clear(left);
2373 /* Fill up the groups array with singleton groups, i.e., one group
2374 * per reference, initializing the array, access, write and refs fields.
2375 * In particular the access field is initialized to the scheduled
2376 * access relation of the array reference.
2378 * Return the number of elements initialized, i.e., the number of
2379 * active references in the current kernel.
2381 static int populate_array_references(struct gpu_array_info *array,
2382 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2384 int i;
2385 int n;
2386 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2388 n = 0;
2389 for (i = 0; i < array->n_ref; ++i) {
2390 isl_union_map *umap;
2391 isl_map *map;
2392 struct gpu_array_ref_group *group;
2393 struct gpu_stmt_access *access = array->refs[i];
2395 map = isl_map_copy(access->access);
2396 umap = isl_union_map_from_map(map);
2397 umap = isl_union_map_apply_domain(umap,
2398 isl_union_map_copy(sched));
2400 if (isl_union_map_is_empty(umap)) {
2401 isl_union_map_free(umap);
2402 continue;
2405 map = isl_map_from_union_map(umap);
2406 map = isl_map_detect_equalities(map);
2408 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2409 assert(group);
2410 group->array = array;
2411 group->access = map;
2412 group->write = access->write;
2413 group->refs = &array->refs[i];
2415 groups[n++] = group;
2418 return n;
2421 static void free_array_ref_group(struct gpu_array_ref_group *group,
2422 int n_index)
2424 if (!group)
2425 return;
2426 free_bound_list(group->shared_bound, n_index);
2427 free_bound_list(group->private_bound, n_index);
2428 isl_map_free(group->access);
2429 free(group->refs);
2430 free(group);
2433 /* Given a map where the input dimensions represent the tile loops,
2434 * eliminate the innermost of those that have a fixed value
2435 * until we reach one that does not (obviously) have a fixed value.
2437 static __isl_give isl_map *eliminate_fixed_inner_loops(
2438 __isl_take isl_map *access)
2440 int i, n;
2442 n = isl_map_dim(access, isl_dim_in);
2444 for (i = n - 1; i >= 0; --i) {
2445 if (!isl_map_plain_is_fixed(access, isl_dim_in, i, NULL))
2446 break;
2447 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2449 return access;
2452 /* Check if the access relations of group1 and group2 overlap within
2453 * the innermost loop. In particular, ignore any inner dimension
2454 * with a fixed value.
2455 * The copying to and from shared memory will be performed within
2456 * the innermost actual loop so we are only allowed to consider
2457 * the dimensions up to that innermost loop while checking whether
2458 * two access relations overlap.
2460 static int accesses_overlap(struct gpu_array_ref_group *group1,
2461 struct gpu_array_ref_group *group2)
2463 int empty;
2464 isl_map *access1, *access2;
2466 access1 = isl_map_copy(group1->access);
2467 access1 = eliminate_fixed_inner_loops(access1);
2468 access2 = isl_map_copy(group2->access);
2469 access2 = eliminate_fixed_inner_loops(access2);
2470 access1 = isl_map_intersect(access1, access2);
2471 empty = isl_map_is_empty(access1);
2472 isl_map_free(access1);
2474 return !empty;
2477 /* If two groups have overlapping access relations (within the innermost
2478 * loop) and if one of them involves a write, then merge the two groups
2479 * into one.
2481 * We keep track of the grouping in "leader". leader[j] points to
2482 * an earlier group array element that belongs to the same group,
2483 * or the array element j itself if this element is the first in the group.
2485 * Return the number of group leaders.
2487 static int group_overlapping_writes(int n,
2488 struct gpu_array_ref_group **groups, int *leader)
2490 int i, j;
2491 int n_group = n;
2493 for (i = 0; i < n; ++i) {
2494 int l = i;
2495 groups[l]->n_ref = 1;
2496 for (j = i - 1; j >= 0; --j) {
2497 if (leader[j] != j)
2498 continue;
2499 if (!groups[l]->write && !groups[j]->write)
2500 continue;
2502 if (!accesses_overlap(groups[l], groups[j]))
2503 continue;
2505 groups[j]->access = isl_map_union(groups[j]->access,
2506 groups[l]->access);
2507 groups[j]->write = 1;
2508 groups[l]->access = NULL;
2509 groups[j]->n_ref += groups[l]->n_ref;
2510 l = leader[l] = j;
2511 n_group--;
2513 leader[i] = l;
2516 return n_group;
2519 /* Compute the size of the shared array corresponding to the given
2520 * array reference group, based on the accesses from the current kernel,
2521 * as well as the offset of the shared piece in the original array.
2523 static void compute_group_shared_bound(struct gpu_gen *gen,
2524 struct gpu_array_info *array, struct gpu_array_ref_group *group)
2526 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2528 if (!gen->options->use_shared_memory)
2529 return;
2530 if (gpu_array_is_read_only_scalar(array))
2531 return;
2533 group->shared_bound = create_bound_list(ctx, array->n_index);
2534 if (!can_tile_for_shared_memory(array, group->access,
2535 group->shared_bound)) {
2536 free_bound_list(group->shared_bound, array->n_index);
2537 group->shared_bound = NULL;
2541 /* Is the size of the tile specified by "bound" smaller than the sum of
2542 * the sizes of the tiles specified by "bound1" and "bound2"?
2544 static int smaller_tile(unsigned n_index, struct gpu_array_bound *bound,
2545 struct gpu_array_bound *bound1, struct gpu_array_bound *bound2)
2547 int smaller;
2548 isl_int size, size1, size2;
2550 isl_int_init(size);
2551 isl_int_init(size1);
2552 isl_int_init(size2);
2554 tile_size(n_index, bound, &size);
2555 tile_size(n_index, bound1, &size1);
2556 tile_size(n_index, bound2, &size2);
2558 isl_int_sub(size, size, size1);
2559 isl_int_sub(size, size, size2);
2560 smaller = isl_int_is_neg(size);
2562 isl_int_clear(size2);
2563 isl_int_clear(size1);
2564 isl_int_clear(size);
2566 return smaller;
2569 /* Given an initial grouping of array references and shared memory tiles
2570 * for each group that allows for a shared memory tile, merge two groups
2571 * if both have a shared memory tile, the merged group also has
2572 * a shared memory tile and the size of the tile for the merge group
2573 * is smaller than the sum of the tile sizes of the individual groups.
2575 * Return the number of group leaders after merging.
2577 static int group_common_shared_memory_tile(struct gpu_array_info *array, int n,
2578 struct gpu_array_ref_group **groups, int *leader, int n_group)
2580 int i, j;
2581 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2583 for (i = 0; n_group > 1 && i < n; ++i) {
2584 int l = i;
2585 if (leader[i] != i)
2586 continue;
2587 if (!groups[i]->shared_bound)
2588 continue;
2589 for (j = i - 1; j >= 0; --j) {
2590 isl_map *map;
2591 int empty;
2592 struct gpu_array_bound *shared_bound;
2594 if (leader[j] != j)
2595 continue;
2596 if (!groups[j]->shared_bound)
2597 continue;
2599 map = isl_map_intersect(isl_map_copy(groups[l]->access),
2600 isl_map_copy(groups[j]->access));
2601 empty = isl_map_is_empty(map);
2602 isl_map_free(map);
2604 if (empty)
2605 continue;
2607 map = isl_map_union(isl_map_copy(groups[l]->access),
2608 isl_map_copy(groups[j]->access));
2609 shared_bound = create_bound_list(ctx, array->n_index);
2610 if (!can_tile_for_shared_memory(array, map,
2611 shared_bound) ||
2612 !smaller_tile(array->n_index, shared_bound,
2613 groups[l]->shared_bound,
2614 groups[j]->shared_bound)) {
2615 isl_map_free(map);
2616 free_bound_list(shared_bound, array->n_index);
2617 continue;
2620 free_bound_list(groups[j]->shared_bound,
2621 array->n_index);
2622 groups[j]->shared_bound = shared_bound;
2623 isl_map_free(groups[j]->access);
2624 groups[j]->access = map;
2625 groups[j]->n_ref += groups[l]->n_ref;
2626 l = leader[l] = j;
2627 n_group--;
2631 return n_group;
2634 /* Extract an array of array reference groups from the array of references
2635 * and the grouping information in "leader".
2637 * Store the results in array->n_group and array->groups.
2639 static void extract_array_groups(isl_ctx *ctx, struct gpu_array_info *array,
2640 int n, struct gpu_array_ref_group **groups, int *leader, int n_group)
2642 int i, j;
2644 for (i = 2; i < n; ++i)
2645 leader[i] = leader[leader[i]];
2647 array->n_group = n_group;
2648 array->groups = isl_alloc_array(ctx, struct gpu_array_ref_group *,
2649 n_group);
2650 assert(array->groups);
2652 j = 0;
2653 for (i = 0; i < n; ++i) {
2654 int k, l;
2655 struct gpu_stmt_access **refs;
2657 if (leader[i] != i) {
2658 groups[i]->refs = NULL;
2659 free_array_ref_group(groups[i], array->n_index);
2660 continue;
2663 refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2664 groups[i]->n_ref);
2665 assert(refs);
2666 l = 0;
2667 for (k = i; k < n; ++k)
2668 if (leader[k] == i) {
2669 refs[l++] = *groups[k]->refs;
2670 (*groups[k]->refs)->group = j;
2673 groups[i]->refs = refs;
2674 groups[i]->nr = j;
2675 array->groups[j++] = groups[i];
2679 /* Group array references that should be considered together when
2680 * deciding whether to access them from private, shared or global memory.
2682 * In particular, if two array references overlap and if one of them
2683 * is a write, then the two references are grouped together.
2684 * Furthermore, if two groups admit a shared memory tile and if the
2685 * combination of the two also admits a shared memory tile, we merge
2686 * the two groups.
2688 * During the construction the group->refs field points to a single
2689 * array reference inside the array of array references, while
2690 * group->n_ref contains the number of element in leader that
2691 * (directly or indirectly) point to this group, provided the group
2692 * is a leader.
2694 static void group_array_references(struct gpu_gen *gen,
2695 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2697 int i;
2698 int n, n_group;
2699 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2700 struct gpu_array_ref_group **groups;
2701 int *leader;
2703 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2704 array->n_ref);
2705 assert(groups);
2707 n = populate_array_references(array, sched, groups);
2709 leader = isl_alloc_array(ctx, int, n);
2710 assert(leader);
2712 n_group = group_overlapping_writes(n, groups, leader);
2714 for (i = 0; i < n; ++i)
2715 if (leader[i] == i)
2716 compute_group_shared_bound(gen, array, groups[i]);
2718 n_group = group_common_shared_memory_tile(array, n, groups,
2719 leader, n_group);
2721 extract_array_groups(ctx, array, n, groups, leader, n_group);
2723 free(leader);
2724 free(groups);
2727 /* Take tiled_sched, project it onto the shared tile loops and
2728 * the loops that will be wrapped over the threads and
2729 * store the result in gen->shared_sched.
2730 * Also compute a projection that projects out the loops that will be
2731 * wrapped over the threads and store this projection in gen->shared_proj.
2733 static void compute_shared_sched(struct gpu_gen *gen)
2735 isl_space *dim;
2736 isl_map *proj;
2737 isl_set *par;
2738 isl_union_map *sched;
2740 sched = isl_union_map_copy(gen->tiled_sched);
2742 dim = isl_union_map_get_space(sched);
2743 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2744 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2746 dim = isl_union_map_get_space(sched);
2747 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2749 gen->shared_sched = sched;
2750 gen->shared_proj = isl_union_map_from_map(proj);
2753 /* Group references of all arrays in the program.
2755 static void group_references(struct gpu_gen *gen)
2757 int i;
2758 isl_union_map *sched;
2760 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2761 isl_union_map_copy(gen->shared_proj));
2763 for (i = 0; i < gen->prog->n_array; ++i)
2764 group_array_references(gen, &gen->prog->array[i], sched);
2766 isl_union_map_free(sched);
2769 /* Free all array information that is local to the current kernel.
2771 static void free_local_array_info(struct gpu_gen *gen)
2773 int i, j;
2775 for (i = 0; i < gen->prog->n_array; ++i) {
2776 struct gpu_array_info *array = &gen->prog->array[i];
2778 for (j = 0; j < array->n_group; ++j)
2779 free_array_ref_group(array->groups[j], array->n_index);
2780 free(array->groups);
2784 /* Compute the effective grid size as a list of the sizes in each dimension.
2786 * The grid size specified by the user or set by default
2787 * in read_grid_sizes() and applied in tile_schedule(),
2788 * may be too large for the given code in the sense that
2789 * it may contain blocks that don't need to execute anything.
2790 * We therefore don't return this grid size, but instead the
2791 * smallest grid size that ensures that all blocks that actually
2792 * execute code are included in the grid.
2794 * We first extract a description of the grid, i.e., the possible values
2795 * of the block ids, from gen->tiled_sched.
2796 * The block ids are parameters in gen->tiled_sched.
2797 * We simply need to change them into set dimensions.
2799 * Then, for each block dimension, we compute the maximal value of the block id
2800 * and add one.
2802 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2803 struct ppcg_kernel *kernel)
2805 int i;
2806 isl_set *grid;
2807 isl_multi_pw_aff *mpa;
2809 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2810 grid = isl_set_from_params(grid);
2811 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2812 for (i = 0; i < gen->n_grid; ++i) {
2813 int pos;
2814 char name[20];
2816 snprintf(name, sizeof(name), "b%d", i);
2817 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2818 assert(pos >= 0);
2819 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2820 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2823 mpa = isl_multi_pw_aff_zero(isl_set_get_space(grid));
2824 for (i = 0; i < gen->n_grid; ++i) {
2825 isl_space *space;
2826 isl_aff *one;
2827 isl_pw_aff *bound;
2829 bound = isl_set_dim_max(isl_set_copy(grid), i);
2830 bound = isl_pw_aff_coalesce(bound);
2831 bound = isl_pw_aff_gist(bound, isl_set_copy(kernel->context));
2833 space = isl_pw_aff_get_domain_space(bound);
2834 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2835 one = isl_aff_add_constant_si(one, 1);
2836 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2837 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2839 isl_set_free(grid);
2841 return mpa;
2844 void ppcg_kernel_free(void *user)
2846 struct ppcg_kernel *kernel = user;
2847 int i;
2849 if (!kernel)
2850 return;
2852 isl_multi_pw_aff_free(kernel->grid_size);
2853 isl_set_free(kernel->context);
2854 isl_union_set_free(kernel->arrays);
2855 isl_space_free(kernel->space);
2856 isl_ast_node_free(kernel->tree);
2858 for (i = 0; i < kernel->n_array; ++i)
2859 isl_pw_aff_list_free(kernel->array[i].bound);
2860 free(kernel->array);
2862 for (i = 0; i < kernel->n_var; ++i) {
2863 free(kernel->var[i].name);
2864 isl_vec_free(kernel->var[i].size);
2866 free(kernel->var);
2868 free(kernel);
2871 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
2872 struct ppcg_kernel_var *var)
2874 int j;
2875 struct gpu_array_bound *bounds;
2876 isl_printer *p;
2877 char *name;
2879 var->array = group->array;
2881 bounds = group->private_bound;
2882 var->type = ppcg_access_private;
2883 if (!bounds) {
2884 bounds = group->shared_bound;
2885 var->type = ppcg_access_shared;
2888 p = isl_printer_to_str(ctx);
2889 p = print_array_name(p, group);
2890 var->name = isl_printer_get_str(p);
2891 isl_printer_free(p);
2893 var->size = isl_vec_alloc(ctx, group->array->n_index);
2895 for (j = 0; j < group->array->n_index; ++j)
2896 var->size = isl_vec_set_element(var->size, j, bounds[j].size);
2899 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
2901 int i, j, n;
2903 n = 0;
2904 for (i = 0; i < gen->prog->n_array; ++i) {
2905 struct gpu_array_info *array = &gen->prog->array[i];
2907 for (j = 0; j < array->n_group; ++j) {
2908 struct gpu_array_ref_group *group = array->groups[j];
2909 if (group->private_bound || group->shared_bound)
2910 ++n;
2914 kernel->n_var = n;
2915 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
2916 assert(kernel->var);
2918 n = 0;
2919 for (i = 0; i < gen->prog->n_array; ++i) {
2920 struct gpu_array_info *array = &gen->prog->array[i];
2922 for (j = 0; j < array->n_group; ++j) {
2923 struct gpu_array_ref_group *group = array->groups[j];
2924 if (!group->private_bound && !group->shared_bound)
2925 continue;
2926 create_kernel_var(gen->ctx, group, &kernel->var[n]);
2927 ++n;
2932 /* The sizes of the arrays on the host that have been computed by
2933 * extract_array_info may depend on the parameters. Use the extra
2934 * constraints on the parameters that are valid at "host_domain"
2935 * to simplify these expressions and store the results in kernel->array.
2937 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
2938 __isl_keep isl_set *host_domain)
2940 int i, j;
2941 isl_set *context;
2943 kernel->array = isl_calloc_array(gen->ctx,
2944 struct gpu_local_array_info, gen->prog->n_array);
2945 assert(kernel->array);
2946 kernel->n_array = gen->prog->n_array;
2948 context = isl_set_copy(host_domain);
2949 context = isl_set_params(context);
2951 for (i = 0; i < gen->prog->n_array; ++i) {
2952 struct gpu_array_info *array = &gen->prog->array[i];
2953 isl_pw_aff_list *local;
2955 if (array->n_group == 0)
2956 continue;
2958 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
2960 for (j = 0; j < array->n_index; ++j) {
2961 isl_pw_aff *pwaff;
2963 pwaff = isl_pw_aff_copy(array->bound[j]);
2964 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
2965 local = isl_pw_aff_list_add(local, pwaff);
2968 kernel->array[i].bound = local;
2970 isl_set_free(context);
2973 /* Find the element in gen->stmt that has the given "id".
2974 * Return NULL if no such gpu_stmt can be found.
2976 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
2978 int i;
2980 for (i = 0; i < prog->n_stmts; ++i) {
2981 if (id == prog->stmts[i].id)
2982 break;
2985 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
2988 /* Set gen->tile_len and gen->n_parallel to those of the statement
2989 * affected by the first map (part of the schedule)
2990 * on which this function is called.
2991 * Because of the way the schedule is constructed, the other statements
2992 * in the list, if any, should have the same values for these properties.
2994 static int extract_tile_len(__isl_take isl_map *map, void *user)
2996 struct gpu_gen *gen = (struct gpu_gen *) user;
2997 isl_id *id;
2998 struct gpu_stmt *stmt;
3000 id = isl_map_get_tuple_id(map, isl_dim_in);
3001 stmt = find_stmt(gen->prog, id);
3002 isl_id_free(id);
3004 isl_map_free(map);
3006 if (!stmt)
3007 isl_die(gen->ctx, isl_error_unknown,
3008 "statement not found", return -1);
3010 gen->tile_len = stmt->tile_len;
3011 gen->n_parallel = stmt->n_parallel;
3013 return -1;
3016 void ppcg_kernel_stmt_free(void *user)
3018 int i;
3019 struct ppcg_kernel_stmt *stmt = user;
3021 if (!stmt)
3022 return;
3024 switch (stmt->type) {
3025 case ppcg_kernel_copy:
3026 isl_ast_expr_free(stmt->u.c.index);
3027 isl_ast_expr_free(stmt->u.c.local_index);
3028 break;
3029 case ppcg_kernel_domain:
3030 for (i = 0; i < stmt->u.d.n_access; ++i) {
3031 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3032 free(stmt->u.d.access[i].local_name);
3034 free(stmt->u.d.access);
3035 break;
3036 case ppcg_kernel_sync:
3037 break;
3040 free(stmt);
3043 /* Set the options of "context" to
3045 * { space -> [x] : x >= first }
3047 static __isl_give isl_ast_build *set_unroll(
3048 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3049 int first)
3051 isl_ctx *ctx;
3052 isl_map *unroll;
3053 isl_union_map *opt;
3055 ctx = isl_ast_build_get_ctx(build);
3057 space = isl_space_from_domain(space);
3058 space = isl_space_add_dims(space, isl_dim_out, 1);
3059 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3060 unroll = isl_map_universe(space);
3061 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3062 opt = isl_union_map_from_map(unroll);
3064 build = isl_ast_build_set_options(build, opt);
3066 return build;
3069 /* Return a list of isl_ids of the form "prefix%d".
3071 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3072 int n, const char *prefix)
3074 int i;
3075 char name[10];
3076 isl_id_list *names;
3078 names = isl_id_list_alloc(ctx, n);
3079 for (i = 0; i < n; ++i) {
3080 isl_id *id;
3082 snprintf(name, sizeof(name), "%s%d", prefix, i);
3083 id = isl_id_alloc(ctx, name, NULL);
3084 names = isl_id_list_add(names, id);
3087 return names;
3090 /* Extend the schedule "schedule" with the part of "extension"
3091 * starting at "first" up to "len".
3093 static __isl_give isl_union_map *extend_schedule(
3094 __isl_take isl_union_map *schedule,
3095 __isl_take isl_union_map *extension, int first, int len)
3097 isl_space *space;
3098 isl_map *proj;
3099 isl_union_map *umap;
3100 isl_set *set;
3102 space = isl_union_map_get_space(schedule);
3103 space = isl_space_set_from_params(space);
3104 space = isl_space_add_dims(space, isl_dim_set, len);
3105 proj = isl_set_identity(isl_set_universe(space));
3106 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3107 extension = isl_union_map_apply_range(extension,
3108 isl_union_map_from_map(proj));
3110 schedule = isl_union_map_range_product(schedule, extension);
3112 return schedule;
3115 /* This function is called for each access to an array in each instance
3116 * in the kernel of some statement in the original code.
3117 * Replace that access by an access to global, shared or private memory
3118 * and store the results in *kernel_access.
3120 * Since the array in shared or private memory is just
3121 * a shifted copy of part of the original array, we simply need
3122 * to subtract the lower bound, which was computed
3123 * in can_tile_for_shared_memory.
3124 * If any of the indices is strided, then we first add
3125 * shared_bound[i].shift and divide by shared_bound[i].stride.
3127 * If the given array is accessed directly from global memory,
3128 * we don't need to perform any shifting and simply simplify
3129 * the expression in the context of the domain instead.
3131 * If the array space (range of access) has no name, then we are
3132 * accessing an iterator in the original program.
3134 * The input stmt_access->access relation maps the iteration domain
3135 * of the current statement to an array element.
3136 * The first step is to reformulate
3137 * this access relation in terms of the loop iterators of the generated
3138 * code through precomposition with gen->stmt_it.
3140 * The expressions in "bounds" are formulated in terms of the first
3141 * gen->shared_len dimensions of the computed schedule using the mapping
3142 * sched2shared which maps the loop iterators to these dimensions.
3144 static void compute_index_expression(struct gpu_gen *gen,
3145 struct ppcg_kernel_access *kernel_access,
3146 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3147 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3149 isl_map *access;
3150 isl_pw_multi_aff *pma;
3151 int i;
3152 unsigned n_index;
3153 struct gpu_array_bound *bounds = NULL;
3155 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3156 int i;
3157 const char *name;
3158 struct gpu_array_ref_group *group;
3159 isl_printer *p;
3161 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3163 for (i = 0; i < gen->prog->n_array; ++i) {
3164 if (strcmp(name, gen->prog->array[i].name))
3165 continue;
3166 kernel_access->array = &gen->prog->array[i];
3167 kernel_access->local_array = &gen->kernel->array[i];
3169 assert(kernel_access->array);
3170 group = kernel_access->array->groups[stmt_access->group];
3171 p = isl_printer_to_str(gen->ctx);
3172 p = print_array_name(p, group);
3173 kernel_access->local_name = isl_printer_get_str(p);
3174 isl_printer_free(p);
3175 bounds = group->private_bound;
3176 kernel_access->type = ppcg_access_private;
3177 if (!bounds) {
3178 bounds = group->shared_bound;
3179 kernel_access->type = ppcg_access_shared;
3182 if (!bounds)
3183 kernel_access->type = ppcg_access_global;
3185 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3186 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3188 if (n_index == 0)
3189 return;
3191 access = isl_map_copy(stmt_access->access);
3192 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3193 pma = isl_pw_multi_aff_from_map(access);
3194 pma = isl_pw_multi_aff_coalesce(pma);
3196 for (i = 0; i < n_index; ++i) {
3197 isl_set *domain;
3198 isl_pw_aff *index;
3199 isl_ast_expr *expr;
3201 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3203 if (!kernel_access->array) {
3204 } else if (!bounds) {
3205 domain = isl_map_domain(isl_map_copy(stmt_it));
3206 index = isl_pw_aff_coalesce(index);
3207 index = isl_pw_aff_gist(index, domain);
3208 } else {
3209 domain = isl_map_domain(isl_map_copy(stmt_it));
3210 index = shift_index(index, kernel_access->array,
3211 &bounds[i], domain, isl_map_copy(sched2shared));
3214 expr = isl_ast_build_expr_from_pw_aff(build, index);
3216 kernel_access->index = isl_ast_expr_list_add(
3217 kernel_access->index, expr);
3220 isl_pw_multi_aff_free(pma);
3223 /* This function is called for each instance of a user statement
3224 * in the kernel.
3226 * We attach a struct ppcg_kernel_stmt to the "node", containing
3227 * local information about the accesses.
3228 * This information is computed from stmt_it, which expresses the domain
3229 * elements in terms of the generated loops, and sched2shared,
3230 * which expresses the first shared_len dimensions of the schedule
3231 * computed by PPCG in terms of the generated loops.
3233 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3234 __isl_keep isl_ast_build *build, void *user)
3236 struct gpu_gen *gen = (struct gpu_gen *) user;
3237 struct ppcg_kernel_stmt *stmt;
3238 isl_id *id;
3239 isl_map *stmt_it, *sched2shared;
3240 isl_ast_expr *expr, *arg;
3241 isl_union_map *schedule;
3242 int i, n;
3243 struct gpu_stmt_access *access;
3245 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3246 if (!stmt)
3247 return isl_ast_node_free(node);
3249 expr = isl_ast_node_user_get_expr(node);
3250 arg = isl_ast_expr_get_op_arg(expr, 0);
3251 id = isl_ast_expr_get_id(arg);
3253 schedule = isl_ast_build_get_schedule(build);
3254 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3255 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3257 stmt->type = ppcg_kernel_domain;
3258 stmt->u.d.stmt = find_stmt(gen->prog, id);
3259 if (!stmt->u.d.stmt)
3260 goto error;
3262 n = 0;
3263 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3264 ++n;
3266 stmt->u.d.access = isl_calloc_array(gen->ctx,
3267 struct ppcg_kernel_access, n);
3268 if (!stmt->u.d.access)
3269 goto error;
3271 stmt->u.d.n_access = n;
3273 access = stmt->u.d.stmt->accesses;
3274 for (i = 0; i < n; ++i, access = access->next) {
3275 compute_index_expression(gen, &stmt->u.d.access[i], access,
3276 stmt_it, sched2shared, build);
3279 isl_id_free(id);
3280 isl_map_free(stmt_it);
3281 isl_map_free(sched2shared);
3282 isl_ast_expr_free(arg);
3283 isl_ast_expr_free(expr);
3285 id = isl_id_alloc(gen->ctx, NULL, stmt);
3286 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3287 return isl_ast_node_set_annotation(node, id);
3288 error:
3289 isl_id_free(id);
3290 isl_map_free(stmt_it);
3291 ppcg_kernel_stmt_free(stmt);
3292 isl_map_free(sched2shared);
3293 return isl_ast_node_free(node);
3296 /* This function is called when code has been generated for the shared
3297 * tile loops. The "schedule" refers only to the original statements.
3299 * We extend the schedule with that part of gen->local_sched that hasn't
3300 * been taken into account yet. This introduces parameters referring
3301 * to thread ids in the schedule, so we add them (with the appropriate
3302 * bounds to the context as well).
3303 * Finally, we set the appropriate unrolling options
3304 * if gen->first_unroll is set.
3306 static __isl_give isl_ast_node *create_domain_leaf(
3307 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3308 void *user)
3310 struct gpu_gen *gen = (struct gpu_gen *) user;
3311 isl_space *space;
3312 isl_union_map *sched;
3313 isl_ast_node *tree;
3314 isl_set *set;
3315 isl_id_list *iterators;
3316 int n;
3318 schedule = extend_schedule(schedule,
3319 isl_union_map_copy(gen->local_sched),
3320 gen->shared_len, gen->thread_tiled_len);
3322 space = isl_ast_build_get_schedule_space(build);
3323 set = isl_set_universe(space);
3324 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3325 build = isl_ast_build_restrict(build, set);
3327 n = gen->thread_tiled_len - gen->shared_len;
3329 if (gen->first_unroll >= 0) {
3330 space = isl_space_set_alloc(gen->ctx, 0, n);
3331 build = set_unroll(build, space, gen->first_unroll);
3333 iterators = generate_names(gen->ctx, n, "c");
3334 build = isl_ast_build_set_iterators(build, iterators);
3335 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3336 tree = isl_ast_build_ast_from_schedule(build, schedule);
3337 isl_ast_build_free(build);
3339 return tree;
3342 /* This function is called for each leaf in the AST of the code
3343 * for copying to or from shared/private memory.
3344 * The statement name is {read,write}_{shared,private}_<array>.
3346 * The schedule is of the form
3348 * [A -> T] -> L
3350 * where A refers to a piece of an array and T to the corresponding
3351 * shifted tile. We split this schedule into mappings L -> A and L -> T
3352 * and store the corresponding expressions in stmt->index and stmt->local_index,
3353 * where stmt represents the copy statement.
3355 static __isl_give isl_ast_node *create_copy_leaf(
3356 __isl_take isl_ast_build *build, void *user)
3358 struct gpu_gen *gen = (struct gpu_gen *) user;
3359 struct ppcg_kernel_stmt *stmt;
3360 isl_id *id;
3361 isl_ast_expr *expr;
3362 isl_ast_node *node;
3363 isl_space *space;
3364 isl_map *access, *local_access, *map;
3365 isl_pw_multi_aff *pma;
3366 const char *name;
3367 int array_index;
3369 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3370 if (!stmt)
3371 return isl_ast_build_free(build);
3373 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3374 name = isl_map_get_tuple_name(access, isl_dim_in);
3375 stmt->u.c.read = !strncmp(name, "read", 4);
3376 access = isl_map_reverse(access);
3377 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3378 local_access = isl_map_copy(access);
3380 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3381 id = isl_map_get_tuple_id(access, isl_dim_out);
3382 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3383 access = isl_map_apply_range(access, map);
3384 pma = isl_pw_multi_aff_from_map(access);
3385 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3386 stmt->u.c.index = expr;
3388 map = isl_map_range_map(isl_map_universe(space));
3389 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3390 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3391 local_access = isl_map_apply_range(local_access, map);
3392 pma = isl_pw_multi_aff_from_map(local_access);
3393 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3394 stmt->u.c.local_index = expr;
3396 stmt->u.c.array = gen->copy_group->array;
3397 array_index = stmt->u.c.array - gen->prog->array;
3398 stmt->u.c.local_array = &gen->kernel->array[array_index];
3399 stmt->type = ppcg_kernel_copy;
3401 space = isl_ast_build_get_schedule_space(build);
3402 space = isl_space_from_domain(space);
3403 space = isl_space_set_tuple_name(space, isl_dim_out, name);
3404 expr = isl_ast_build_call_from_pw_multi_aff(build,
3405 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3406 node = isl_ast_node_alloc_user(expr);
3407 isl_ast_build_free(build);
3409 id = isl_id_alloc(gen->ctx, NULL, stmt);
3410 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3411 return isl_ast_node_set_annotation(node, id);
3414 /* Given a schedule of the form
3416 * [S -> A] -> L
3418 * (with S the first shared_len dimensions of the computed schedule,
3419 * A the array and L the schedule correponding to the generated loops),
3420 * indicating where the copying the array elements that need to be copied,
3421 * construct code for performing the copying.
3423 * "group" is the array reference group that is being copied
3424 * "type" is either "read" or "write"
3425 * private is set if copying needs to be performed to/from registers
3427 * We first construct a mapping to a shifted tile of the array,
3429 * [S -> A] -> T(S,A) (1)
3431 * If private is set, then we also use this mapping as a schedule
3432 * (which is already thread-specific and will be completely unrolled).
3433 * Otherwise, we wrap/tile the range over the threads.
3434 * The result is
3436 * [S -> A] -> T'(S,A)
3438 * Combined with the given schedule, we have
3440 * [S -> A] -> [L -> T'(S,A)] (2)
3442 * From the shifted tile mapping, we construct a mapping
3444 * [S -> A] -> [A -> T(S,A)]
3446 * and apply it to the schedule (2), obtaining
3448 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3450 * Note that we can project out S because it is uniquely defined by L.
3452 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3453 __isl_take isl_map *sched,
3454 const char *type, struct gpu_array_ref_group *group,
3455 __isl_take isl_ast_build *build, int private)
3457 const char *array_name;
3458 const char *mem = private ? "private" : "shared";
3459 char *name;
3460 isl_space *space;
3461 isl_ast_node *tree;
3462 isl_map *schedule, *shift, *map;
3463 isl_set *set;
3464 isl_id_list *iterators;
3465 int n;
3467 shift = isl_set_unwrap(isl_map_domain(isl_map_copy(sched)));
3468 array_name = isl_map_get_tuple_name(shift, isl_dim_out);
3469 shift = shift_access(shift, group);
3471 schedule = isl_map_copy(shift);
3472 if (!private)
3473 schedule = tile_access_schedule(gen, schedule);
3475 n = isl_map_dim(schedule, isl_dim_out);
3476 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3477 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3479 schedule = isl_map_range_product(sched, schedule);
3481 assert(array_name);
3482 name = isl_alloc_array(gen->ctx, char,
3483 strlen(type) + sizeof("_private_") + strlen(array_name) + 20);
3484 if (group->array->n_group > 1)
3485 sprintf(name, "%s_%s_%s_%d", type, mem, array_name, group->nr);
3486 else
3487 sprintf(name, "%s_%s_%s", type, mem, array_name);
3488 shift = isl_map_set_tuple_name(shift,
3489 isl_dim_out, name + strlen(type) + 1);
3491 space = isl_space_domain(isl_map_get_space(shift));
3492 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3493 map = isl_map_range_product(map, shift);
3495 schedule = isl_map_apply_domain(schedule, map);
3497 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, name);
3498 free(name);
3500 build = isl_ast_build_restrict(build, set);
3502 gen->copy_group = group;
3503 gen->copy_bound = group->shared_bound;
3505 if (private) {
3506 space = isl_space_range(isl_map_get_space(schedule));
3507 space = isl_space_range(isl_space_unwrap(space));
3508 build = set_unroll(build, space, 0);
3510 iterators = generate_names(gen->ctx, n, "c");
3511 build = isl_ast_build_set_iterators(build, iterators);
3512 build = isl_ast_build_set_create_leaf(build, &create_copy_leaf, gen);
3513 tree = isl_ast_build_ast_from_schedule(build,
3514 isl_union_map_from_map(schedule));
3515 isl_ast_build_free(build);
3517 return tree;
3520 /* Return code for reading into or writing from shared memory
3521 * the given array reference group.
3523 * If we are performing a read from global memory to shared memory and
3524 * if the array involved is not a scalar, then we copy
3525 * the entire tile to shared memory. This may result in some extra
3526 * elements getting copied, but it should lead to simpler code
3527 * (which means that fewer registers may be needed) and less divergence.
3529 * Otherwise, we only copy the elements that will be read or have been written
3530 * in the kernel.
3533 * The input "sched" is of the form.
3535 * type[S -> A] -> L
3537 * with S the first shared_len dimensions of the computed schedule,
3538 * A the array and L the schedule correponding to the generated loops.
3540 * We first drop "type",
3542 * [S -> A] -> L
3544 * If the above conditions are satisfied, we project out A,
3545 * resulting in
3547 * S -> L
3549 * and then introduce the group tile [S -> T], resulting in
3551 * [S -> T] -> L
3553 static __isl_give isl_ast_node *copy_group_shared_accesses(
3554 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3555 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3557 const char *type;
3558 int read;
3559 isl_union_map *access;
3561 type = isl_map_get_tuple_name(sched, isl_dim_in);
3562 read = !strcmp(type, "read");
3564 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3566 if (read && group->array->n_index > 0) {
3567 isl_space *space;
3568 isl_map *map;
3570 space = isl_space_domain(isl_map_get_space(sched));
3571 space = isl_space_unwrap(space);
3572 map = isl_map_domain_map(isl_map_universe(space));
3573 sched = isl_map_apply_domain(sched, map);
3575 map = group_tile(group);
3576 map = isl_map_reverse(isl_map_domain_map(map));
3577 sched = isl_map_apply_domain(sched, map);
3580 return copy_access(gen, sched, type, group, build, 0);
3583 /* Return code for reading into or writing from private memory
3584 * the given array reference group.
3586 * Let S be the first shared_len dimensions of the computed schedule,
3587 * D the iteration domains, A the array and L the schedule correponding
3588 * to the generated loops.
3589 * "sched" is of the form
3591 * type[S -> A] -> L
3593 * where type is either "read" or "write".
3594 * We apply the privatization D -> S(t), with t the thread ids,
3595 * to the access relation D -> A to obtain the privatized access relation
3597 * S(t) -> A
3599 * We drop the type from "sched" and intersect with the privatized access
3600 * relation to obtain
3602 * [S(t) -> A] -> L
3604 static __isl_give isl_ast_node *copy_group_private_accesses(
3605 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3606 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3608 const char *type;
3609 int read;
3610 isl_union_map *priv;
3611 isl_union_map *access;
3612 isl_map *access_map;
3614 type = isl_map_get_tuple_name(sched, isl_dim_in);
3615 read = !strcmp(type, "read");
3617 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3618 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3619 priv);
3621 access = group_access_relation(group, read, !read);
3622 access = isl_union_map_apply_domain(access, priv);
3623 access_map = isl_map_from_union_map(access);
3625 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3626 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3628 return copy_access(gen, sched, type, group, build, 1);
3631 /* Return code for reading into or writing from shared or private memory.
3633 * "schedule" is of the form
3635 * type[S -> A] -> L
3637 * with S be the first shared_len dimensions of the computed schedule,
3638 * A the array and L the schedule correponding to the generated loops.
3639 * The array reference group is attached to "type".
3641 static __isl_give isl_ast_node *create_access_leaf(
3642 struct gpu_gen *gen, __isl_take isl_map *schedule,
3643 __isl_take isl_ast_build *build)
3645 struct gpu_array_ref_group *group;
3646 isl_id *id;
3648 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3649 group = isl_id_get_user(id);
3650 isl_id_free(id);
3652 if (group->private_bound)
3653 return copy_group_private_accesses(gen, group, schedule,
3654 build);
3655 else
3656 return copy_group_shared_accesses(gen, group, schedule,
3657 build);
3660 /* Create a domain node representing a synchronization.
3662 static __isl_give isl_ast_node *create_sync_leaf(
3663 struct gpu_gen *gen, __isl_take isl_map *schedule,
3664 __isl_take isl_ast_build *build)
3666 struct ppcg_kernel_stmt *stmt;
3667 isl_id *id;
3668 isl_space *space;
3669 isl_ast_node *node;
3670 isl_ast_expr *expr;
3672 isl_map_free(schedule);
3674 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3675 if (!stmt)
3676 return NULL;
3678 stmt->type = ppcg_kernel_sync;
3680 space = isl_ast_build_get_schedule_space(build);
3681 space = isl_space_from_domain(space);
3682 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3683 expr = isl_ast_build_call_from_pw_multi_aff(build,
3684 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3685 node = isl_ast_node_alloc_user(expr);
3686 isl_ast_build_free(build);
3688 id = isl_id_alloc(gen->ctx, NULL, stmt);
3689 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3690 return isl_ast_node_set_annotation(node, id);
3693 /* This function is called during the code generation at the point
3694 * where the schedule domain element is completely determined by
3695 * the generated code. The input schedule contains the original
3696 * statements as well as synchronization and copy "statements".
3697 * The latter are scheduled at different points than any of the original
3698 * statements, so they will only arrive here in isolation.
3700 * If the current schedule only refers to a single statement,
3701 * we check if it is a copy or synchronization statement and
3702 * call the appropriate functions.
3703 * Otherwise, we assume we are dealing with the original statements
3704 * and we call create_domain_leaf.
3706 static __isl_give isl_ast_node *create_kernel_leaf(
3707 __isl_take isl_ast_build *build, void *user)
3709 struct gpu_gen *gen = (struct gpu_gen *) user;
3710 isl_map *map;
3711 isl_union_map *schedule;
3712 const char *name;
3714 schedule = isl_ast_build_get_schedule(build);
3716 if (isl_union_map_n_map(schedule) != 1)
3717 return create_domain_leaf(schedule, build, user);
3719 map = isl_map_from_union_map(schedule);
3720 name = isl_map_get_tuple_name(map, isl_dim_in);
3721 if (!strcmp(name, "read") || !strcmp(name, "write"))
3722 return create_access_leaf(gen, map, build);
3723 if (!strcmp(name, "sync"))
3724 return create_sync_leaf(gen, map, build);
3726 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3729 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3730 * have value 0) and all even schedule dimensions as "unroll".
3732 * That is, the options look as follows
3734 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
3735 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
3737 * The even positions are used to be able to schedule copying blocks
3738 * and synchronization before or after each level of the shared memory
3739 * tile loops and we want to make sure that code for these is generated
3740 * separately (within each level).
3742 static __isl_give isl_ast_build *set_atomic_and_unroll(
3743 __isl_take isl_ast_build *build,
3744 __isl_take isl_space *space, int sched_len)
3746 isl_ctx *ctx;
3747 isl_map *map;
3748 isl_constraint *c;
3749 isl_union_map *opt;
3750 isl_local_space *ls;
3751 int i, n;
3753 ctx = isl_ast_build_get_ctx(build);
3755 space = isl_space_params(space);
3756 space = isl_space_add_dims(space, isl_dim_set, sched_len);
3757 space = isl_space_from_domain(space);
3758 space = isl_space_add_dims(space, isl_dim_out, 2);
3759 map = isl_map_universe(isl_space_copy(space));
3760 for (i = 0; i < sched_len; i += 2)
3761 map = isl_map_fix_si(map, isl_dim_in, i, 0);
3762 ls = isl_local_space_from_space(isl_map_get_space(map));
3763 c = isl_equality_alloc(ls);
3764 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3765 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3766 c = isl_constraint_set_constant_si(c, 1);
3767 map = isl_map_add_constraint(map, c);
3768 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3769 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
3770 opt = isl_union_map_from_map(map);
3772 map = isl_map_universe(space);
3773 ls = isl_local_space_from_space(isl_map_get_space(map));
3774 c = isl_equality_alloc(ls);
3775 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3776 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3777 map = isl_map_add_constraint(map, c);
3778 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3779 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
3780 opt = isl_union_map_add_map(opt, map);
3782 build = isl_ast_build_set_options(build, opt);
3784 return build;
3787 /* Return a map that maps a space of dimension gen->shared_len
3788 * to its last dimensions starting at gen->tile_first.
3789 * The range is of dimension
3791 * 2 * (gen->shared_len - gen->tile_first) + 1
3793 * The input dimensions are mapped to the odd dimensions in the output,
3794 * while the even dimensions (except 2*pos) are fixed to 0.
3795 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
3796 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
3797 * are mapped to the output. The remaining input dimensions are projected
3798 * out and the corresponding output dimensions are fixed to 0.
3800 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
3801 __isl_take isl_space *space, int pos, int val)
3803 int i, n;
3804 isl_map *proj;
3806 space = isl_space_set_from_params(space);
3807 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
3808 space = isl_space_map_from_set(space);
3809 proj = isl_map_identity(space);
3810 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
3811 n = gen->shared_len - gen->tile_first;
3812 for (i = 0; i <= n; ++i) {
3813 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
3814 if (i == pos)
3815 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
3816 else
3817 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
3820 if (pos < 0)
3821 return proj;
3823 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
3824 gen->shared_len - (gen->tile_first + pos));
3825 for (i = pos; i < n; ++i)
3826 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
3828 return proj;
3831 /* Given the AST context schedule "schedule" and the mapping from
3832 * domains to the shared tile loops "shared_sched", add a schedule
3833 * for a synchronization operation at position "val" of loop level "pos".
3835 * schedule is of the form
3837 * D -> L
3839 * (with D the iteration domains and L the already generated loops),
3840 * while shared_sched is of the form
3842 * D -> S
3844 * We combine them into
3846 * L -> S
3848 * apply a mapping
3850 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3852 * and use the result as a schedule for "sync".
3854 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
3855 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3856 __isl_keep isl_union_map *shared_sched, int pos, int val)
3858 isl_space *space;
3859 isl_map *proj, *map;
3861 shared_sched = isl_union_map_copy(shared_sched);
3862 schedule = isl_union_map_copy(schedule);
3864 space = isl_union_map_get_space(shared_sched);
3865 schedule = isl_union_map_apply_domain(shared_sched, schedule);
3866 map = isl_map_from_union_map(schedule);
3868 proj = insert_even(gen, space, pos, val);
3869 map = isl_map_apply_range(map, proj);
3870 map = isl_map_from_range(isl_map_wrap(map));
3871 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
3873 res = isl_union_map_add_map(res, map);
3875 return res;
3878 /* Given the AST context schedule "schedule" and the mapping from
3879 * domains to the shared tile loops "shared_sched", add a schedule
3880 * for copying an array reference group to/from shared/private memory.
3881 * "read" is set if data should be copied from global memory
3882 * to shared/private memory.
3883 * "k" represents the current group
3884 * "s" is the total number of groups
3886 * We schedule an operation before or after the innermost loop
3887 * of "shared_sched" that affects the tile of the array reference group.
3889 * schedule is of the form
3891 * D -> L
3893 * (with D the iteration domains and L the already generated loops),
3894 * while shared_sched is of the form
3896 * D -> S
3898 * We first compute the access relation for the reference group
3900 * D -> A
3902 * and combine it with shared_sched into
3904 * D -> [S -> A]
3906 * If this results in an empty relation, no copying needs to be performed
3907 * at this point.
3908 * Otherwise, we invert the relation and combine it with "schedule" into
3910 * [S -> A] -> L
3912 * The actual additional piece of the schedule is obtained from combining
3914 * [S -> A] -> S
3916 * with a mapping
3918 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
3920 * The position of "val" corresponds to the innermost loop that affects
3921 * the tile and the value indicates where the copying is scheduled
3922 * with respect to the actual kernel code (at value 0).
3923 * Reads are schedule before the code, writes to global memory from
3924 * private memory are scheduled at values 1 to s, writes to global
3925 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
3927 * If we are scheduling a read from global memory to shared memory,
3928 * we insert a synchronization before the kernel code (at the innermost
3929 * level).
3930 * If we are scheduling a write to global memory, then we add
3931 * a synchronization after all writes (at value 2 *s + 2).
3932 * However, there is no need for a synchronization after the outermost loop.
3933 * A write to global memory from private memory at the innermost level
3934 * does not require a synchronization, because it is covered by
3935 * the synchronization after the kernel inserted by body_schedule.
3937 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
3938 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
3939 __isl_keep isl_union_map *shared_sched,
3940 struct gpu_array_ref_group *group, int read, int k, int s)
3942 int n;
3943 int pos, val;
3944 isl_space *space;
3945 isl_union_map *access;
3946 isl_map *map, *proj, *access_map;
3947 isl_id *id;
3949 access = group_access_relation(group, read, !read);
3950 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
3951 access);
3953 if (isl_union_map_is_empty(access)) {
3954 isl_union_map_free(access);
3955 return res;
3958 access = isl_union_map_reverse(access);
3959 access = isl_union_map_apply_range(access,
3960 isl_union_map_copy(schedule));
3961 access_map = isl_map_from_union_map(access);
3963 space = isl_space_copy(group->array->dim);
3964 space = isl_space_from_range(space);
3965 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
3966 map = isl_map_domain_map(isl_map_universe(space));
3968 space = isl_union_map_get_space(schedule);
3969 pos = group->last_shared + 1 - gen->tile_first;
3970 if (read)
3971 val = -2 - k;
3972 else if (group->private_bound)
3973 val = 1 + k;
3974 else
3975 val = 1 + s + 1 + k;
3976 proj = insert_even(gen, space, pos, val);
3977 map = isl_map_apply_range(map, proj);
3979 access_map = isl_map_range_product(access_map, map);
3981 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
3982 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
3984 res = isl_union_map_add_map(res, access_map);
3986 n = gen->shared_len - gen->tile_first;
3987 if (read) {
3988 if (!group->private_bound)
3989 res = add_sync_schedule(gen, res, schedule,
3990 shared_sched, n, -1);
3991 } else {
3992 if (pos == 0)
3993 return res;
3994 if (pos == n && group->private_bound)
3995 return res;
3996 res = add_sync_schedule(gen, res, schedule, shared_sched,
3997 pos, 2 * s + 2);
4000 return res;
4003 /* Return a schedule for the shared tile loops based on the current
4004 * AST context schedule.
4006 * We create a "shared_sched" that maps the domains to the first
4007 * shared_len dimensions of the computed schedule, project out the
4008 * first tile_first dimensions (as these are already covered by
4009 * the host code) and insert "statement-level" dimensions at even
4010 * positions so that we can schedule copy blocks and synchronization
4011 * before/after each level.
4013 * In particular, copy blocks are inserted inside the innermost
4014 * level that affect the tile. For the copying to global memory,
4015 * those from private memory are scheduled before those from shared
4016 * memory such that synchronization can be inserted between the two
4017 * at the innermost level.
4018 * Synchronization is inserted at the innermost level before the
4019 * actual kernel code if there is any copying from global memory
4020 * to shared memory. It is inserted unconditionally at the innermost
4021 * level after the actual kernel code and the copying to global memory
4022 * from private memory (if any). Finally, it is inserted after
4023 * any copying to global memory, except at the outermost level
4024 * and at the innermost level if there is no copying from shared
4025 * memory. The copying from private memory is covered by the unconditional
4026 * synchronization at the innermost level.
4028 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4029 __isl_take isl_union_map *schedule)
4031 isl_space *space;
4032 isl_union_map *res;
4033 isl_union_map *shared_sched;
4034 isl_union_map *sched;
4035 isl_map *proj, *map;
4036 int i, j, k, s;
4038 shared_sched = isl_union_map_copy(gen->tiled_sched);
4039 proj = projection(isl_union_map_get_space(shared_sched),
4040 gen->tiled_len, gen->shared_len);
4041 shared_sched = isl_union_map_apply_range(shared_sched,
4042 isl_union_map_from_map(proj));
4043 space = isl_union_map_get_space(shared_sched);
4044 proj = insert_even(gen, space, -1, 0);
4045 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4046 isl_union_map_from_map(proj));
4048 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4050 s = 0;
4051 for (i = 0; i < gen->prog->n_array; ++i)
4052 s += gen->prog->array[i].n_group;
4054 k = 0;
4055 for (i = 0; i < gen->prog->n_array; ++i) {
4056 struct gpu_array_info *array = &gen->prog->array[i];
4058 for (j = 0; j < array->n_group; ++j) {
4059 struct gpu_array_ref_group *group;
4061 group = array->groups[j];
4062 if (!group->private_bound && !group->shared_bound)
4063 continue;
4064 res = add_group_schedule(gen, res, schedule,
4065 shared_sched, group, 0, k, s);
4066 res = add_group_schedule(gen, res, schedule,
4067 shared_sched, group, 1, k, s);
4068 ++k;
4072 res = add_sync_schedule(gen, res, schedule, shared_sched,
4073 gen->shared_len - gen->tile_first, 1 + s);
4075 isl_union_map_free(shared_sched);
4076 isl_union_map_free(schedule);
4078 return res;
4081 /* Generate code for "kernel" in the given "context".
4083 * We first generate code for the shared tile loops (T1T, T1P and T2)
4084 * in a context that includes the block ids.
4085 * Within each iteration of these loops an additional code generation
4086 * is performed (within create_kernel_leaf) for the rest of the schedule
4087 * in a context that includes the thread ids.
4089 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4090 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4091 __isl_keep isl_multi_pw_aff *grid_size)
4093 isl_space *space;
4094 isl_set *set;
4095 isl_id_list *iterators;
4096 isl_union_map *schedule;
4097 isl_ast_node *tree;
4098 int sched_len;
4100 schedule = isl_ast_build_get_schedule(build);
4102 build = isl_ast_build_copy(build);
4103 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4104 space = isl_ast_build_get_schedule_space(build);
4105 set = isl_set_universe(isl_space_copy(space));
4106 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4107 build = isl_ast_build_restrict(build, set);
4109 schedule = body_schedule(gen, schedule);
4111 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4113 build = set_atomic_and_unroll(build, space, sched_len);
4114 iterators = generate_names(gen->ctx, sched_len, "g");
4115 build = isl_ast_build_set_iterators(build, iterators);
4116 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4117 tree = isl_ast_build_ast_from_schedule(build, schedule);
4118 isl_ast_build_free(build);
4120 return tree;
4123 /* Attach "id" to the given node.
4125 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4126 __isl_keep isl_ast_build *build, void *user)
4128 isl_id *id = user;
4130 node = isl_ast_node_set_annotation(node, id);
4132 return node;
4135 /* Construct an AST node for performing a kernel launch and attach
4136 * the information about the kernel to that node.
4138 * The kernel AST has been constructed in the context of the range
4139 * of "schedule". In particular, the grid size has been computed
4140 * in the context. We therefore still need to make sure that these
4141 * constraints are expressed in the code. We do this by creating a schedule
4143 * kernel[] -> [S -> []]
4145 * where S is the schedule domain, i.e., the range of "schedule".
4146 * The AST generation will then create a single call surrounded by
4147 * all the condition in "S" that have not been expressed yet.
4149 * The kernel information is attached to this node in attach_id.
4151 static __isl_give isl_ast_node *construct_launch(
4152 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4153 __isl_take struct ppcg_kernel *kernel)
4155 isl_id *id;
4156 isl_ctx *ctx;
4157 isl_union_set *domain;
4158 isl_set *set;
4159 isl_map *map;
4160 isl_ast_node *node;
4162 ctx = isl_ast_build_get_ctx(build);
4164 id = isl_id_alloc(ctx, NULL, kernel);
4165 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4167 domain = isl_union_map_range(schedule);
4168 set = isl_set_from_union_set(domain);
4169 map = isl_map_from_domain(set);
4170 map = isl_map_from_range(isl_map_wrap(map));
4171 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4172 schedule = isl_union_map_from_map(map);
4174 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4175 node = isl_ast_build_ast_from_schedule(build, schedule);
4176 isl_ast_build_free(build);
4178 return node;
4181 /* This function is called for each leaf in the AST of the host code.
4182 * We first specialize the schedule to the site of the leaf, compute
4183 * the size of shared memory and then construct the body of host code
4184 * and the associated kernel.
4186 * The necessary information for printing the kernel launch is
4187 * stored in a struct ppcg_kernel and attached to the leaf node
4188 * created to represent the launch.
4190 static __isl_give isl_ast_node *create_host_leaf(
4191 __isl_take isl_ast_build *build, void *user)
4193 struct gpu_gen *gen = (struct gpu_gen *) user;
4194 isl_id *id;
4195 isl_ast_node *node;
4196 struct ppcg_kernel *kernel;
4197 isl_set *host_domain;
4198 isl_union_map *schedule;
4199 isl_union_map *local_sched;
4200 isl_union_map *access;
4201 isl_union_set *domain;
4202 int i;
4204 schedule = isl_ast_build_get_schedule(build);
4206 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4207 read_sizes(gen);
4209 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4211 local_sched = isl_union_map_copy(gen->sched);
4212 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4213 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4214 isl_union_map_copy(gen->prog->write));
4215 access = isl_union_map_apply_domain(access,
4216 isl_union_map_copy(local_sched));
4218 gen->tiled_sched = tile_schedule(gen, local_sched);
4219 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4220 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4222 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4223 if (!kernel)
4224 goto error;
4226 kernel->id = gen->kernel_id++;
4227 kernel->n_block = gen->n_block;
4228 for (i = 0; i < gen->n_block; ++i)
4229 kernel->block_dim[i] = gen->block_dim[i];
4230 kernel->n_grid = gen->n_grid;
4231 for (i = 0; i < gen->n_grid; ++i)
4232 kernel->grid_dim[i] = gen->grid_dim[i];
4233 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4234 kernel->grid_size = extract_grid_size(gen, kernel);
4235 kernel->arrays = isl_union_map_range(access);
4236 kernel->space = isl_ast_build_get_schedule_space(build);
4238 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4240 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4241 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4243 gen->private_access = NULL;
4244 compute_shared_sched(gen);
4245 gen->privatization = compute_privatization(gen);
4246 group_references(gen);
4247 compute_private_size(gen);
4248 check_shared_memory_bound(gen);
4249 host_domain = isl_set_from_union_set(isl_union_map_range(
4250 isl_union_map_copy(schedule)));
4251 localize_bounds(gen, kernel, host_domain);
4253 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4255 kernel->tree = generate_kernel(gen, build, host_domain,
4256 kernel->grid_size);
4257 create_kernel_vars(gen, kernel);
4259 free_local_array_info(gen);
4260 isl_map_free(gen->privatization);
4261 isl_union_map_free(gen->private_access);
4262 isl_union_map_free(gen->local_sched);
4263 isl_union_map_free(gen->tiled_sched);
4264 isl_union_map_free(gen->shared_sched);
4265 isl_union_map_free(gen->shared_proj);
4266 isl_set_free(host_domain);
4267 free(gen->tile_size);
4269 node = construct_launch(build, schedule, kernel);
4271 return node;
4272 error:
4273 isl_union_map_free(schedule);
4274 return NULL;
4277 /* Use isl to generate code for the outer gen->tile_first loops
4278 * of the global schedule in gen->sched, resulting in the host code.
4279 * Within each iteration of this partial schedule, i.e., for each kernel
4280 * launch, create_host_leaf takes care of generating the kernel code.
4282 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4284 isl_ast_build *build;
4285 isl_ast_node *tree;
4286 isl_union_map *sched;
4287 isl_map *proj;
4288 isl_id_list *iterators;
4290 sched = isl_union_map_copy(gen->sched);
4291 proj = projection(isl_union_map_get_space(sched),
4292 gen->untiled_len, gen->tile_first);
4293 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4295 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4296 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4297 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4298 build = isl_ast_build_set_iterators(build, iterators);
4299 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4300 tree = isl_ast_build_ast_from_schedule(build, sched);
4301 isl_ast_build_free(build);
4303 return tree;
4306 __isl_give isl_set *add_context_from_str(__isl_take isl_set *set,
4307 const char *str)
4309 isl_ctx *ctx;
4310 isl_set *context;
4312 if (!str)
4313 return set;
4315 ctx = isl_set_get_ctx(set);
4316 context = isl_set_read_from_str(ctx, str);
4317 context = isl_set_align_params(context, isl_set_get_space(set));
4318 set = isl_set_intersect(set, context);
4320 return set;
4323 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4325 if (!str)
4326 return NULL;
4327 return isl_union_map_read_from_str(ctx, str);
4330 /* Information about the outermost tilable bands in the forest of bands.
4332 * tile_len and n_parallel are only sets on band_info structures
4333 * that correspond to outermost bands. For other bands (in particular,
4334 * ancestors of the outermost bands), n_parallal is set to 0.
4336 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4338 * tile_first is the number of schedule dimensions in prefix.
4340 * suffix is the schedule of the outermost tilable bands and their descendants.
4342 struct band_info {
4343 struct gpu_gen *gen;
4344 int tile_first;
4345 int tile_len;
4346 int n_parallel;
4347 isl_union_map *prefix;
4348 isl_union_map *suffix;
4351 /* Set tile_len and n_parallel of the statement to that of
4352 * their outermost band, recorded in the band_info.
4354 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4356 struct band_info *info = user;
4357 struct gpu_stmt *stmt;
4358 isl_id *id;
4360 id = isl_map_get_tuple_id(map, isl_dim_in);
4361 stmt = find_stmt(info->gen->prog, id);
4362 isl_id_free(id);
4364 stmt->tile_len = info->tile_len;
4365 stmt->n_parallel = info->n_parallel;
4367 isl_map_free(map);
4369 return 0;
4372 static void list_select_outer_band(struct gpu_gen *gen,
4373 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4375 /* Check if this band has any parallel loops. If so, take it as
4376 * the outermost tilable band. If not, continue looking for the
4377 * outermost tilable band in the children of the current band.
4379 static void band_select_outer_band(struct gpu_gen *gen,
4380 __isl_take isl_band *band, int pos, struct band_info *info)
4382 int n = isl_band_n_member(band);
4383 int n_parallel;
4385 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4386 if (!isl_band_member_is_zero_distance(band, n_parallel))
4387 break;
4389 info->n_parallel = n_parallel;
4390 if (n_parallel) {
4391 info->gen = gen;
4392 info->tile_first = pos;
4393 info->tile_len = n;
4394 info->prefix = isl_band_get_prefix_schedule(band);
4395 info->suffix = isl_union_map_flat_range_product(
4396 isl_band_get_partial_schedule(band),
4397 isl_band_get_suffix_schedule(band));
4398 isl_union_map_foreach_map(info->prefix,
4399 &set_stmt_tile_len, info);
4400 } else if (isl_band_has_children(band)) {
4401 isl_band_list *children;
4402 children = isl_band_get_children(band);
4403 list_select_outer_band(gen, children, pos + n, info);
4404 } else {
4405 info->gen = gen;
4406 info->tile_first = pos + n;
4407 info->tile_len = 0;
4408 info->prefix = isl_union_map_flat_range_product(
4409 isl_band_get_prefix_schedule(band),
4410 isl_band_get_partial_schedule(band));
4411 info->suffix = isl_band_get_suffix_schedule(band);
4412 isl_union_map_foreach_map(info->prefix,
4413 &set_stmt_tile_len, info);
4416 isl_band_free(band);
4419 /* Comparison function that returns a non-zero value for band_infos
4420 * with different tile_len fields or different n_parallel fields.
4422 static int cmp_band(const void *p1, const void *p2)
4424 const struct band_info *info1 = p1;
4425 const struct band_info *info2 = p2;
4427 if (info1->tile_len != info2->tile_len)
4428 return info1->tile_len - info2->tile_len;
4430 return info1->n_parallel - info2->n_parallel;
4433 /* Extend "umap" with coordinates with fixed value "val"
4434 * to a total length of "dst_len", assuming the original dimension is "src_len".
4436 static __isl_give isl_union_map *extend_range(
4437 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4439 isl_space *dim;
4440 isl_map *map;
4441 int i;
4443 dim = isl_union_map_get_space(umap);
4444 map = isl_map_reverse(projection(dim, dst_len, src_len));
4445 for (i = src_len; i < dst_len; ++i)
4446 map = isl_map_fix_si(map, isl_dim_out, i, val);
4448 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4450 return umap;
4453 /* Group bands with the same values for tile_len and n_parallel.
4454 * The prefix schedule is then extended with a fixed coordinate that
4455 * is different for each such group.
4456 * Note that the actual values for this coordinate are not important.
4457 * The bands have already been effectively separated at a higher level
4458 * or they are independent and may be executed in parallel.
4459 * The list of band_info has been sorted before this functions is called.
4461 static void separate_bands(struct band_info *info, int n)
4463 int i;
4464 int j = 0;
4466 for (i = 0; i < n; ++i) {
4467 int l = info[i].tile_first;
4469 if (i &&
4470 (info[i].tile_len != info[i - 1].tile_len ||
4471 info[i].n_parallel != info[i - 1].n_parallel))
4472 j++;
4474 info[i].prefix = extend_range(info[i].prefix,
4475 l, l + 1, j);
4476 info[i].tile_first = l + 1;
4480 /* Select the outermost bands in the elements of the list, align
4481 * their prefix schedules, separate bands with different values
4482 * for tile_len and/or n_parallel and then combine the resulting
4483 * prefix and suffix schedules into a single pair of prefix and
4484 * suffix schedules for the entire list.
4486 static void list_select_outer_band(struct gpu_gen *gen,
4487 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4489 isl_band *band;
4490 int i;
4491 int n = isl_band_list_n_band(list);
4492 isl_ctx *ctx = isl_band_list_get_ctx(list);
4493 struct band_info *info;
4494 int max_tile_first;
4495 isl_union_map *prefix;
4496 isl_union_map *suffix;
4498 assert(n >= 1);
4499 info = isl_calloc_array(ctx, struct band_info, n);
4500 assert(info);
4502 max_tile_first = 0;
4503 for (i = 0; i < n; ++i) {
4504 band = isl_band_list_get_band(list, i);
4505 band_select_outer_band(gen, band, pos, &info[i]);
4506 if (info[i].tile_first > max_tile_first)
4507 max_tile_first = info[i].tile_first;
4510 for (i = 0; i < n; ++i) {
4511 if (info[i].tile_first == max_tile_first)
4512 continue;
4513 info[i].prefix = extend_range(info[i].prefix,
4514 info[i].tile_first, max_tile_first, 0);
4515 info[i].tile_first = max_tile_first;
4518 qsort(info, n, sizeof(struct band_info), &cmp_band);
4520 for (i = 0; i < n - 1; ++i)
4521 if (info[i].tile_len != info[i + 1].tile_len ||
4522 info[i].n_parallel != info[i + 1].n_parallel)
4523 break;
4525 if (i < n -1)
4526 separate_bands(info, n);
4528 prefix = info[0].prefix;
4529 suffix = info[0].suffix;
4531 for (i = 1; i < n; ++i) {
4532 prefix = isl_union_map_union(prefix, info[i].prefix);
4533 suffix = isl_union_map_union(suffix, info[i].suffix);
4536 list_info->tile_first = info[0].tile_first;
4537 list_info->tile_len = -1;
4538 list_info->prefix = prefix;
4539 list_info->suffix = suffix;
4541 isl_band_list_free(list);
4542 free(info);
4545 /* Select the outermost tilable band that (by construction)
4546 * has at least one parallel loop.
4547 * The starting position of the aligned band is stored in the pair
4548 * gen->tile_first.
4549 * The sizes and number of parallel loops may be different in different
4550 * parts of the band forest and are therefore stored in the gpu_stmts.
4552 * Return the complete schedule, with the tilable bands aligned
4553 * at gen->tile_first and padded with zero, if needed.
4555 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4556 __isl_keep isl_schedule *schedule)
4558 isl_band_list *list;
4559 struct band_info info;
4561 gen->n_parallel = 0;
4562 gen->tile_len = -1;
4564 list = isl_schedule_get_band_forest(schedule);
4566 list_select_outer_band(gen, list, 0, &info);
4568 gen->tile_first = info.tile_first;
4569 info.suffix = align_range(info.suffix);
4571 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4574 /* Set gen->untiled_len to the number of scheduling dimensions
4575 * for the schedule of the first domain.
4576 * We assume here that this number is the same for all domains.
4578 static int set_untiled_len(__isl_take isl_map *map, void *user)
4580 unsigned *untiled_len = user;
4582 *untiled_len = isl_map_dim(map, isl_dim_out);
4584 isl_map_free(map);
4585 return -1;
4588 /* Compute an appropriate schedule based on the accesses in
4589 * gen->read and gen->write.
4591 * We first compute dependences and then use those to compute
4592 * a schedule that has a parallel loop in each tilable band.
4593 * Finally, we select the outermost tilable band.
4595 static void compute_schedule(struct gpu_gen *gen,
4596 __isl_take isl_union_map *sched)
4598 isl_union_set *domain;
4599 isl_union_map *empty;
4600 isl_union_map *dep_raw, *dep2, *dep3, *dep;
4601 isl_union_map *uninitialized;
4602 isl_schedule *schedule;
4604 empty = isl_union_map_empty(isl_union_map_get_space(sched));
4606 isl_union_map_compute_flow(isl_union_map_copy(gen->prog->read),
4607 isl_union_map_copy(gen->prog->write), empty,
4608 isl_union_map_copy(sched),
4609 &dep_raw, NULL, &uninitialized, NULL);
4610 isl_union_map_compute_flow(isl_union_map_copy(gen->prog->write),
4611 isl_union_map_copy(gen->prog->write),
4612 isl_union_map_copy(gen->prog->read),
4613 isl_union_map_copy(sched),
4614 &dep2, &dep3, NULL, NULL);
4615 isl_union_map_free(sched);
4617 gen->prog->copy_in = isl_union_map_range(uninitialized);
4619 dep = isl_union_map_union(dep2, dep3);
4620 dep = isl_union_map_union(dep, dep_raw);
4621 dep = isl_union_map_coalesce(dep);
4623 domain = isl_union_set_copy(gen->prog->scop->domain);
4624 domain = isl_union_set_intersect_params(domain,
4625 isl_set_copy(gen->prog->scop->context));
4626 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4627 isl_union_map_copy(dep), dep);
4629 sched = select_outer_tilable_band(gen, schedule);
4631 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4632 sched = isl_union_map_intersect_domain(sched, domain);
4633 gen->sched = sched;
4635 isl_schedule_free(schedule);
4638 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4639 struct gpu_stmt_access **next_access)
4641 struct gpu_stmt_access *access;
4642 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4644 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4645 assert(access);
4646 access->next = NULL;
4647 access->read = expr->acc.read;
4648 access->write = expr->acc.write;
4649 access->access = isl_map_copy(expr->acc.access);
4651 *next_access = access;
4652 next_access = &(*next_access)->next;
4653 return next_access;
4656 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4657 struct gpu_stmt_access **next_access)
4659 int i;
4661 for (i = 0; i < expr->n_arg; ++i)
4662 next_access = expr_extract_accesses(expr->args[i],
4663 next_access);
4665 if (expr->type == pet_expr_access)
4666 next_access = expr_extract_access(expr, next_access);
4668 return next_access;
4671 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4673 struct gpu_stmt_access **next_access = &stmt->accesses;
4675 stmt->accesses = NULL;
4676 expr_extract_accesses(stmt->body, next_access);
4679 /* Return an array of gpu_stmt representing the statements in "scop".
4681 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4682 __isl_keep isl_set *context)
4684 int i;
4685 struct gpu_stmt *stmts;
4687 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4688 assert(stmts);
4690 for (i = 0; i < scop->n_stmt; ++i) {
4691 struct gpu_stmt *s = &stmts[i];
4693 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4694 s->body = scop->stmts[i]->body;
4695 pet_stmt_extract_accesses(s);
4698 return stmts;
4701 /* Replace the scop in the "input" file by equivalent code
4702 * that uses the GPU. "scop" is assumed to correspond to this scop.
4704 * We first compute a schedule that respects the dependences
4705 * of the original program and select the outermost band
4706 * of tilable dimensions that has at least one parallel loop.
4707 * We then have three blocks of dimensions
4709 * H B G
4711 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4712 * in
4714 * H T P G
4716 * For each iteration of the T loop and for each array, we compute
4717 * the array elements accessed by that iteration, construct a rectangular
4718 * box around it and shift it to the origin. The result is used
4719 * as shared memory for the array.
4721 * We then split off at most 2 parallel loops from the T loops and
4722 * at most 3 parallel loops from the P loops
4724 * H T1 T2 P1 P2 G
4726 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4727 * according to "grid"/"block" sizes.
4729 * H T1T T1P T2 P1T P1P P2 G
4731 * Finally, the T1P and P1P iterators are equated to the block and
4732 * thread dimensions respectively and so are effectively removed.
4733 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4734 * are run on the GPU.
4736 * Code is generated in three stages. We first generate code for the
4737 * host (the H loops), with iterators h%d. Then, for each leaf node
4738 * of the resulting AST, we generate code for the shared loops (up to
4739 * and including T2), with iterators g%d and after equating the H loops
4740 * to h%d parameters and the T1P loops to the block dimensions.
4741 * Finally, we generate code for the remaining loops in a similar fashion.
4743 __isl_give isl_ast_node *generate_gpu(isl_ctx *ctx, struct gpu_prog *prog,
4744 struct ppcg_options *options)
4746 isl_union_map *sched;
4747 struct gpu_gen gen;
4748 isl_ast_node *tree;
4750 if (!prog)
4751 return NULL;
4753 gen.ctx = ctx;
4754 gen.prog = prog;
4755 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4756 gen.options = options;
4758 sched = isl_union_map_copy(prog->scop->schedule);
4760 compute_schedule(&gen, sched);
4762 gen.kernel_id = 0;
4763 tree = generate_host_code(&gen);
4765 clear_gpu_gen(&gen);
4767 return tree;
4770 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
4772 struct gpu_prog *prog;
4774 if (!scop)
4775 return NULL;
4777 prog = isl_calloc_type(ctx, struct gpu_prog);
4778 assert(prog);
4780 prog->ctx = ctx;
4781 prog->scop = scop;
4782 prog->context = isl_set_copy(scop->context);
4783 prog->n_stmts = scop->n_stmt;
4784 prog->stmts = extract_stmts(ctx, scop, prog->context);
4785 prog->read = isl_union_map_copy(scop->reads);
4786 prog->write = isl_union_map_copy(scop->writes);
4788 collect_array_info(prog);
4790 return prog;
4793 void gpu_prog_free(struct gpu_prog *prog)
4795 if (!prog)
4796 return;
4797 free_array_info(prog);
4798 free_stmts(prog->stmts, prog->n_stmts);
4799 isl_union_set_free(prog->copy_in);
4800 isl_union_map_free(prog->read);
4801 isl_union_map_free(prog->write);
4802 isl_set_free(prog->context);
4803 free(prog);