cpu.c: extract out print_cpu, printing the entire CPU code to an isl_printer
[ppcg.git] / gpu.c
blob025dfa1889c5ac9728af88c45dfa0fadb271a0b0
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012 Ecole Normale Superieure
5 * Use of this software is governed by the MIT license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
15 #include <string.h>
17 #include <isl/polynomial.h>
18 #include <isl/union_set.h>
19 #include <isl/aff.h>
20 #include <isl/ilp.h>
21 #include <isl/flow.h>
22 #include <isl/band.h>
23 #include <isl/schedule.h>
24 #include <isl/options.h>
25 #include <isl/ast_build.h>
27 #include "gpu.h"
28 #include "schedule.h"
29 #include "ppcg_options.h"
30 #include "print.h"
31 #include "rewrite.h"
33 /* The fields stride, shift and shift_map only contain valid information
34 * if shift != NULL.
35 * If so, they express that current index is such that if you add shift,
36 * then the result is always a multiple of stride.
37 * shift_map contains the mapping
39 * i -> (i + shift)/stride
41 * Let D represent the initial shared_len dimensions of the computed schedule.
42 * The spaces of "lb" and "shift" are of the form
44 * D -> [b]
46 * "shift_map" is of the form
48 * [D -> i] -> [D -> (i + shift(D))/stride]
50 struct gpu_array_bound {
51 isl_val *size;
52 isl_aff *lb;
54 isl_val *stride;
55 isl_aff *shift;
56 isl_basic_map *shift_map;
59 /* A tile of an array.
61 * n is the dimension of the array.
62 * bound is an array of size "n" representing the lower bound
63 * and size for each index.
65 struct gpu_array_tile {
66 int n;
67 struct gpu_array_bound *bound;
70 struct gpu_array_info;
72 /* A group of array references in a kernel that should be handled together.
73 * If private_tile is not NULL, then it is mapped to registers.
74 * Otherwise, if shared_tile is not NULL, it is mapped to shared memory.
75 * Otherwise, it is accessed from global memory.
77 struct gpu_array_ref_group {
78 /* The references in this group access this array. */
79 struct gpu_array_info *array;
80 /* Position of this group in the list of reference groups of array. */
81 int nr;
83 /* The following fields are use during the construction of the groups.
84 * access is the combined access relation relative to the shared
85 * memory tiling. In particular, the domain of the map corresponds
86 * to the first shared_len dimensions of the computed schedule.
87 * write is set if any access in the group is a write.
89 isl_map *access;
90 int write;
92 /* The shared memory tile, NULL if none. */
93 struct gpu_array_tile *shared_tile;
95 /* The private memory tile, NULL if none. */
96 struct gpu_array_tile *private_tile;
98 /* References in this group; point to elements of a linked list. */
99 int n_ref;
100 struct gpu_stmt_access **refs;
102 /* Last shared memory tile dimension that affects tile of this group. */
103 int last_shared;
106 struct gpu_gen {
107 isl_ctx *ctx;
108 struct ppcg_options *options;
110 struct gpu_prog *prog;
112 /* tile, grid and block sizes for each kernel */
113 isl_union_map *sizes;
115 /* Identifier of current kernel. */
116 int kernel_id;
117 /* Pointer to the current kernel. */
118 struct ppcg_kernel *kernel;
120 /* First tile dimension. */
121 int tile_first;
122 /* Number of tile dimensions. */
123 int tile_len;
124 /* Number of initial parallel loops among tile dimensions. */
125 int n_parallel;
127 /* Number of dimensions determining shared memory. */
128 int shared_len;
130 /* Number of rows in the untiled schedule. */
131 int untiled_len;
132 /* Number of rows in the tiled schedule. */
133 int tiled_len;
134 /* Number of rows in schedule after tiling/wrapping over threads. */
135 int thread_tiled_len;
137 /* Global untiled schedule. */
138 isl_union_map *sched;
139 /* Local (per kernel launch) tiled schedule. */
140 isl_union_map *tiled_sched;
141 /* Local schedule per shared memory tile loop iteration. */
142 isl_union_map *local_sched;
144 /* Local tiled schedule projected onto the shared tile loops and
145 * the loops that will be wrapped over the threads,
146 * with all shared tile loops parametrized.
148 isl_union_map *shared_sched;
149 /* Projects out the loops that will be wrapped over the threads
150 * from shared_sched.
152 isl_union_map *shared_proj;
154 /* A map that takes the range of shared_sched as input,
155 * wraps the appropriate loops over the threads and then projects
156 * out these loops.
158 isl_map *privatization;
160 /* A map from the shared memory tile loops and the thread indices
161 * (as parameters) to the set of accessed memory elements that
162 * will be accessed through private copies.
164 isl_union_map *private_access;
166 /* The schedule for the current private/shared access
167 * (within print_private_access or print_shared_access).
169 isl_map *copy_sched;
170 /* The array reference group corresponding to copy_sched. */
171 struct gpu_array_ref_group *copy_group;
173 /* First loop to unroll (or -1 if none) in the current part of the
174 * schedule.
176 int first_unroll;
178 int n_grid;
179 int n_block;
180 /* Note: in the input file, the sizes of the grid and the blocks
181 * are specified in the order x, y, z, but internally, the sizes
182 * are stored in reverse order, so that the last element always
183 * refers to the x dimension.
185 int grid_dim[2];
186 int block_dim[3];
187 int *tile_size;
190 /* Print the name of the local copy of a given group of array references.
192 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
193 struct gpu_array_ref_group *group)
195 int global = 0;
197 if (group->private_tile)
198 p = isl_printer_print_str(p, "private_");
199 else if (group->shared_tile)
200 p = isl_printer_print_str(p, "shared_");
201 else
202 global = 1;
203 p = isl_printer_print_str(p, group->array->name);
204 if (!global && group->array->n_group > 1) {
205 p = isl_printer_print_str(p, "_");
206 p = isl_printer_print_int(p, group->nr);
209 return p;
212 /* Collect all references to the given array and store pointers to them
213 * in array->refs.
215 static void collect_references(struct gpu_prog *prog,
216 struct gpu_array_info *array)
218 int i;
219 int n;
221 n = 0;
222 for (i = 0; i < prog->n_stmts; ++i) {
223 struct gpu_stmt *stmt = &prog->stmts[i];
224 struct gpu_stmt_access *access;
226 for (access = stmt->accesses; access; access = access->next) {
227 const char *name;
228 name = isl_map_get_tuple_name(access->access,
229 isl_dim_out);
230 if (name && !strcmp(array->name, name))
231 n++;
235 array->n_ref = n;
236 array->refs = isl_alloc_array(prog->ctx, struct gpu_stmt_access *, n);
237 assert(array->refs);
239 n = 0;
240 for (i = 0; i < prog->n_stmts; ++i) {
241 struct gpu_stmt *stmt = &prog->stmts[i];
242 struct gpu_stmt_access *access;
244 for (access = stmt->accesses; access; access = access->next) {
245 const char *name;
246 name = isl_map_get_tuple_name(access->access,
247 isl_dim_out);
248 if (!name || strcmp(array->name, name))
249 continue;
251 array->refs[n++] = access;
256 /* Create a gpu_array_tile for an array of dimension "n_index".
258 static struct gpu_array_tile *create_tile(isl_ctx *ctx, int n_index)
260 int i;
261 struct gpu_array_tile *tile;
263 tile = isl_calloc_type(ctx, struct gpu_array_tile);
264 assert(tile);
266 tile->n = n_index;
268 tile->bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
269 assert(tile->bound);
271 for (i = 0; i < n_index; ++i) {
272 tile->bound[i].size = NULL;
273 tile->bound[i].lb = NULL;
274 tile->bound[i].stride = NULL;
275 tile->bound[i].shift = NULL;
276 tile->bound[i].shift_map = NULL;
279 return tile;
282 static void *free_tile(struct gpu_array_tile *tile)
284 int j;
286 if (!tile)
287 return NULL;
289 for (j = 0; j < tile->n; ++j) {
290 isl_val_free(tile->bound[j].size);
291 isl_val_free(tile->bound[j].stride);
292 isl_aff_free(tile->bound[j].lb);
293 isl_aff_free(tile->bound[j].shift);
294 isl_basic_map_free(tile->bound[j].shift_map);
296 free(tile->bound);
297 free(tile);
299 return NULL;
302 static struct pet_array *find_array(struct ppcg_scop *scop,
303 __isl_keep isl_set *accessed)
305 int i;
306 isl_id *id;
308 id = isl_set_get_tuple_id(accessed);
310 for (i = 0; i < scop->n_array; ++i) {
311 isl_id *id_i;
313 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
314 isl_id_free(id_i);
315 if (id == id_i)
316 break;
318 isl_id_free(id);
320 return i < scop->n_array ? scop->arrays[i] : NULL;
323 /* Compute and return the extent of "array", taking into account the set of
324 * accessed elements.
326 * In particular, the extent in the outer dimension is taken
327 * from "accessed", while then extent in the remaing dimensions
328 * are taken from array->extent.
330 * The extent in the outer dimension cannot be taken from array->extent
331 * because that may be unbounded. Furthermore, even if it is bounded,
332 * it may be larger than the piece of the array that is being accessed.
334 static __isl_give isl_set *compute_extent(struct pet_array *array,
335 __isl_keep isl_set *accessed)
337 int n_index;
338 isl_id *id;
339 isl_set *outer;
340 isl_set *extent;
342 extent = isl_set_copy(array->extent);
344 n_index = isl_set_dim(accessed, isl_dim_set);
345 if (n_index == 0)
346 return extent;
348 extent = isl_set_project_out(extent, isl_dim_set, 0, 1);
349 outer = isl_set_copy(accessed);
350 outer = isl_set_project_out(outer, isl_dim_set, 1, n_index - 1);
351 extent = isl_set_flat_product(outer, extent);
352 id = isl_set_get_tuple_id(accessed);
353 extent = isl_set_set_tuple_id(extent, id);
355 return extent;
358 /* Compute bounds on the host arrays based on the accessed elements
359 * and collect all references to the array.
361 * If the array is zero-dimensional, i.e., a scalar, we check
362 * whether it is read-only.
364 static int extract_array_info(__isl_take isl_set *array, void *user)
366 int i;
367 struct gpu_prog *prog = (struct gpu_prog *)user;
368 const char *name;
369 int n_index;
370 isl_pw_aff **bounds;
371 struct pet_array *pa;
372 isl_set *extent;
374 n_index = isl_set_dim(array, isl_dim_set);
375 name = isl_set_get_tuple_name(array);
376 bounds = isl_alloc_array(isl_set_get_ctx(array),
377 isl_pw_aff *, n_index);
378 assert(bounds);
379 prog->array[prog->n_array].dim = isl_set_get_space(array);
380 prog->array[prog->n_array].name = strdup(name);
381 prog->array[prog->n_array].n_index = n_index;
382 prog->array[prog->n_array].bound = bounds;
384 pa = find_array(prog->scop, array);
385 assert(pa);
387 prog->array[prog->n_array].type = strdup(pa->element_type);
388 prog->array[prog->n_array].size = pa->element_size;
389 prog->array[prog->n_array].local = pa->declared && !pa->exposed;
391 if (n_index == 0) {
392 isl_set *space;
393 isl_union_map *write;
394 int empty;
396 write = isl_union_map_copy(prog->write);
397 space = isl_set_universe(isl_set_get_space(array));
398 write = isl_union_map_intersect_range(write,
399 isl_union_set_from_set(space));
400 empty = isl_union_map_is_empty(write);
401 isl_union_map_free(write);
403 prog->array[prog->n_array].read_only = empty;
406 extent = compute_extent(pa, array);
407 for (i = 0; i < n_index; ++i) {
408 isl_set *dom;
409 isl_local_space *ls;
410 isl_aff *one;
411 isl_pw_aff *bound;
413 bound = isl_set_dim_max(isl_set_copy(extent), i);
414 assert(bound);
415 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
416 ls = isl_local_space_from_space(isl_set_get_space(dom));
417 one = isl_aff_zero_on_domain(ls);
418 one = isl_aff_add_constant_si(one, 1);
419 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
420 bound = isl_pw_aff_gist(bound, isl_set_copy(prog->context));
422 bounds[i] = bound;
424 prog->array[prog->n_array].extent = extent;
426 collect_references(prog, &prog->array[prog->n_array]);
428 prog->n_array++;
430 isl_set_free(array);
431 return 0;
434 void collect_array_info(struct gpu_prog *prog)
436 isl_union_set *arrays;
438 arrays = isl_union_map_range(isl_union_map_copy(prog->read));
439 arrays = isl_union_set_union(arrays,
440 isl_union_map_range(isl_union_map_copy(prog->write)));
441 arrays = isl_union_set_coalesce(arrays);
443 prog->n_array = isl_union_set_n_set(arrays);
444 prog->array = isl_alloc_array(prog->ctx,
445 struct gpu_array_info, prog->n_array);
446 assert(prog->array);
447 prog->n_array = 0;
448 isl_union_set_foreach_set(arrays, &extract_array_info, prog);
449 isl_union_set_free(arrays);
452 static void free_array_info(struct gpu_prog *prog)
454 int i, j;
456 for (i = 0; i < prog->n_array; ++i) {
457 int n_index = prog->array[i].n_index;
458 free(prog->array[i].type);
459 free(prog->array[i].name);
460 for (j = 0; j < n_index; ++j)
461 isl_pw_aff_free(prog->array[i].bound[j]);
462 isl_space_free(prog->array[i].dim);
463 isl_set_free(prog->array[i].extent);
464 free(prog->array[i].bound);
465 free(prog->array[i].refs);
467 free(prog->array);
470 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
471 * as an array or through a pointer reference, but as single data element. At
472 * the moment, scalars are represented as zero dimensional arrays.
474 int gpu_array_is_scalar(struct gpu_array_info *array)
476 return (array->n_index == 0);
479 /* Is "array" a read-only scalar?
481 int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
483 return gpu_array_is_scalar(array) && array->read_only;
486 /* Internal data structure for extract_size_of_type.
487 * "type" specifies the name of the space that we want to extract.
488 * "res" is used to store the subset of that space.
490 struct ppcg_extract_size_data {
491 const char *type;
492 isl_set *res;
495 /* This function is called for each set in a union_set.
496 * If the name of the set matches data->type, we store the
497 * set in data->res.
499 static int extract_size_of_type(__isl_take isl_set *size, void *user)
501 struct ppcg_extract_size_data *data = user;
502 const char *name;
504 name = isl_set_get_tuple_name(size);
505 if (name && !strcmp(name, data->type)) {
506 data->res = size;
507 return -1;
510 isl_set_free(size);
511 return 0;
514 /* Given a union map { kernel[i] -> *[...] },
515 * return the range in the space called "type" for the kernel with
516 * sequence number "id".
518 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
519 const char *type, int id)
521 isl_space *space;
522 isl_set *dom;
523 isl_union_set *local_sizes;
524 struct ppcg_extract_size_data data = { type, NULL };
526 if (!sizes)
527 return NULL;
529 space = isl_union_map_get_space(sizes);
530 space = isl_space_set_from_params(space);
531 space = isl_space_add_dims(space, isl_dim_set, 1);
532 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
533 dom = isl_set_universe(space);
534 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
536 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
537 isl_union_map_copy(sizes));
538 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
539 isl_union_set_free(local_sizes);
540 return data.res;
543 /* Given a singleton set, extract the first (at most *len) elements
544 * of the single integer tuple into *sizes and update *len if needed.
546 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
548 int i;
549 int dim;
551 if (!set)
552 return;
554 dim = isl_set_dim(set, isl_dim_set);
555 if (dim < *len)
556 *len = dim;
558 for (i = 0; i < *len; ++i) {
559 isl_val *v;
561 v = isl_set_plain_get_val_if_fixed(set, isl_dim_set, i);
562 assert(v);
564 sizes[i] = isl_val_get_num_si(v);
565 isl_val_free(v);
568 isl_set_free(set);
571 /* Extract user specified "tile" sizes from the "sizes" command line option,
572 * defaulting to option->tile_size in each dimension.
574 static void read_tile_sizes(struct gpu_gen *gen)
576 int n;
577 isl_set *size;
579 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
580 assert(gen->tile_size);
581 for (n = 0; n < gen->tile_len; ++n)
582 gen->tile_size[n] = gen->options->tile_size;
584 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
585 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
587 if (gen->n_parallel > gen->tile_len)
588 gen->n_parallel = gen->tile_len;
591 /* Extract user specified "block" sizes from the "sizes" command line option,
592 * after filling in some potentially useful defaults.
594 static void read_block_sizes(struct gpu_gen *gen)
596 int n;
597 isl_set *size;
599 n = gen->n_parallel;
600 gen->n_block = (n <= 3) ? n : 3;
601 switch (gen->n_block) {
602 case 1:
603 gen->block_dim[0] = 512;
604 break;
605 case 2:
606 gen->block_dim[0] = 32;
607 gen->block_dim[1] = 16;
608 break;
609 default:
610 gen->block_dim[0] = 32;
611 gen->block_dim[1] = 4;
612 gen->block_dim[2] = 4;
613 break;
616 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
617 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
620 /* Extract user specified "grid" sizes from the "sizes" command line option,
621 * after filling in some potentially useful defaults.
623 static void read_grid_sizes(struct gpu_gen *gen)
625 int n = gen->n_parallel;
626 isl_set *size;
628 gen->n_grid = (n <= 2) ? n : 2;
629 switch (gen->n_grid) {
630 case 1:
631 gen->grid_dim[0] = 32768;
632 break;
633 default:
634 gen->grid_dim[0] = 256;
635 gen->grid_dim[1] = 256;
636 break;
639 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
640 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
643 /* Extract user specified sizes from the "sizes" command line option
644 * after filling in some potentially useful defaults.
646 static void read_sizes(struct gpu_gen *gen)
648 read_tile_sizes(gen);
649 read_block_sizes(gen);
650 read_grid_sizes(gen);
653 static void *free_stmts(struct gpu_stmt *stmts, int n)
655 int i;
657 if (!stmts)
658 return NULL;
660 for (i = 0; i < n; ++i) {
661 struct gpu_stmt_access *access, *next;
663 for (access = stmts[i].accesses; access; access = next) {
664 next = access->next;
665 isl_map_free(access->access);
666 free(access);
669 isl_id_free(stmts[i].id);
671 free(stmts);
673 return NULL;
676 void clear_gpu_gen(struct gpu_gen *gen)
678 isl_union_map_free(gen->sizes);
679 isl_union_map_free(gen->sched);
682 /* Construct a map from a domain of dimensionality "len"
683 * to a domain of dimensionality "len" + "tile_len" that tiles
684 * the "tile_len" coordinates starting at "first".
685 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
686 * "dim" prescribes the parameters.
688 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
689 int first, int tile_len, int *tile_size)
691 int i;
692 isl_basic_map *bmap;
693 isl_constraint *c;
694 isl_local_space *ls;
696 dim = isl_space_add_dims(dim, isl_dim_in, len);
697 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
698 bmap = isl_basic_map_universe(isl_space_copy(dim));
699 ls = isl_local_space_from_space(dim);
701 for (i = 0; i < len - tile_len; ++i) {
702 int j = i < first ? i : i + tile_len;
703 int k = i < first ? i : i + 2 * tile_len;
705 c = isl_equality_alloc(isl_local_space_copy(ls));
706 c = isl_constraint_set_coefficient_si(c, isl_dim_in, j, -1);
707 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
708 bmap = isl_basic_map_add_constraint(bmap, c);
711 for (i = 0; i < tile_len; ++i) {
712 c = isl_equality_alloc(isl_local_space_copy(ls));
713 c = isl_constraint_set_coefficient_si(c, isl_dim_in,
714 first + i, -1);
715 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
716 first + i, tile_size[i]);
717 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
718 first + i + tile_len, 1);
719 bmap = isl_basic_map_add_constraint(bmap, c);
721 c = isl_inequality_alloc(isl_local_space_copy(ls));
722 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
723 first + i + tile_len, 1);
724 bmap = isl_basic_map_add_constraint(bmap, c);
726 c = isl_inequality_alloc(isl_local_space_copy(ls));
727 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
728 first + i + tile_len, -1);
729 c = isl_constraint_set_constant_si(c, tile_size[i] - 1);
730 bmap = isl_basic_map_add_constraint(bmap, c);
733 isl_local_space_free(ls);
735 return isl_map_from_basic_map(bmap);
738 /* Construct a map from a domain of dimensionality "len"
739 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
740 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
741 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
742 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
743 * that are projected out at the end.
744 * "dim" prescribes the parameters.
746 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
747 int first, int wrap_len, int *wrap_size)
749 int i;
750 isl_basic_map *bmap;
751 isl_constraint *c;
752 isl_local_space *ls;
754 dim = isl_space_add_dims(dim, isl_dim_in, len);
755 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
756 bmap = isl_basic_map_universe(isl_space_copy(dim));
757 ls = isl_local_space_from_space(dim);
759 for (i = 0; i < len; ++i) {
760 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
762 c = isl_equality_alloc(isl_local_space_copy(ls));
763 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
764 c = isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
765 bmap = isl_basic_map_add_constraint(bmap, c);
768 for (i = 0; i < wrap_len; ++i) {
769 c = isl_equality_alloc(isl_local_space_copy(ls));
770 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
771 first + i, -1);
772 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
773 first + wrap_len + i, 1);
774 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
775 first + 2 * wrap_len + i, wrap_size[i]);
776 bmap = isl_basic_map_add_constraint(bmap, c);
778 c = isl_inequality_alloc(isl_local_space_copy(ls));
779 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
780 first + wrap_len + i, 1);
781 bmap = isl_basic_map_add_constraint(bmap, c);
783 c = isl_inequality_alloc(isl_local_space_copy(ls));
784 c = isl_constraint_set_coefficient_si(c, isl_dim_out,
785 first + wrap_len + i, -1);
786 c = isl_constraint_set_constant_si(c, wrap_size[i] - 1);
787 bmap = isl_basic_map_add_constraint(bmap, c);
790 isl_local_space_free(ls);
792 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
793 first + 2 * wrap_len, wrap_len);
795 return isl_map_from_basic_map(bmap);
798 /* Add "n" parameters named prefix%d.
800 static __isl_give isl_set *add_params( __isl_take isl_set *set,
801 int n, const char *prefix)
803 int i;
804 unsigned nparam;
805 char name[20];
807 nparam = isl_set_dim(set, isl_dim_param);
808 set = isl_set_add_dims(set, isl_dim_param, n);
810 for (i = 0; i < n; ++i) {
811 snprintf(name, sizeof(name), "%s%d", prefix, i);
812 set = isl_set_set_dim_name(set, isl_dim_param,
813 nparam + i, name);
816 return set;
819 /* Equate the "n" dimensions of "set" starting at "first" to
820 * freshly created parameters named prefix%d.
822 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
823 int first, int n, const char *prefix)
825 int i;
826 unsigned nparam;
828 nparam = isl_set_dim(set, isl_dim_param);
830 set = add_params(set, n, prefix);
832 for (i = 0; i < n; ++i)
833 set = isl_set_equate(set, isl_dim_param, nparam + i,
834 isl_dim_set, first + i);
836 return set;
839 /* Given a parameter space "space", create a set of dimension "len"
840 * of which the "n" dimensions starting at "first" are equated to
841 * freshly created parameters named prefix%d.
843 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
844 int len, int first, int n, const char *prefix)
846 isl_set *set;
848 space = isl_space_set_from_params(space);
849 space = isl_space_add_dims(space, isl_dim_set, len);
850 set = isl_set_universe(space);
852 return parametrize(set, first, n, prefix);
855 /* Tile the B loops over the tile sizes and then tile/wrap
856 * the T1 loops over the blocks.
858 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
859 __isl_take isl_union_map *sched)
861 isl_space *dim;
862 isl_map *tiling, *block_tiling;
864 dim = isl_union_map_get_space(sched);
865 tiling = tile(isl_space_copy(dim), gen->untiled_len,
866 gen->tile_first, gen->tile_len, gen->tile_size);
868 if (gen->options->wrap)
869 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
870 gen->tile_first, gen->n_grid, gen->grid_dim);
871 else
872 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
873 gen->tile_first, gen->n_grid, gen->grid_dim);
875 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
877 tiling = isl_map_apply_range(tiling, block_tiling);
879 sched = isl_union_map_apply_range(sched,
880 isl_union_map_from_map(tiling));
882 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
884 return sched;
887 /* Equate the "T1P" iterators in the tiled schedule "sched"
888 * to the block dimensions.
890 static __isl_give isl_union_map *parametrize_tiled_schedule(
891 struct gpu_gen *gen, __isl_take isl_union_map *sched)
893 isl_space *dim;
894 isl_set *par;
896 dim = isl_union_map_get_space(sched);
897 par = parametrization(dim, gen->tiled_len,
898 gen->tile_first + gen->n_grid, gen->n_grid, "b");
899 sched = isl_union_map_intersect_range(sched,
900 isl_union_set_from_set(par));
902 return sched;
905 /* Tile/wrap the P1 loops over the threads.
907 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
908 __isl_take isl_union_map *sched)
910 isl_space *dim;
911 isl_map *tiling;
912 isl_set *par;
914 dim = isl_union_map_get_space(sched);
916 if (gen->options->wrap)
917 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
918 gen->shared_len, gen->n_block, gen->block_dim);
919 else
920 tiling = tile(isl_space_copy(dim), gen->tiled_len,
921 gen->shared_len, gen->n_block, gen->block_dim);
922 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
924 sched = isl_union_map_apply_range(sched,
925 isl_union_map_from_map(tiling));
927 par = parametrization(dim, gen->thread_tiled_len,
928 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
929 gen->n_block, "t");
930 sched = isl_union_map_intersect_range(sched,
931 isl_union_set_from_set(par));
933 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
935 return sched;
938 /* If the user asked for it, scale the shared memory tile loops
939 * (T1T and T2) of "sched" by gen->tile_size[i].
940 * If we are not performing "wrapping", then additionally scale the T1P
941 * loops by gen->grid_dim[i].
943 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
944 __isl_take isl_union_map *sched)
946 int i;
947 isl_space *dim;
948 isl_basic_map *scale;
949 isl_constraint *c;
950 isl_local_space *ls;
952 if (!gen->options->scale_tile_loops)
953 return sched;
955 dim = isl_union_map_get_space(sched);
956 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
957 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
958 scale = isl_basic_map_universe(isl_space_copy(dim));
959 ls = isl_local_space_from_space(dim);
961 for (i = 0; i < gen->tiled_len; ++i) {
962 int f = 1;
964 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
965 f = gen->tile_size[i - gen->tile_first];
966 if (!gen->options->wrap)
967 f *= gen->grid_dim[i - gen->tile_first];
968 } else if (i >= gen->tile_first + gen->n_grid &&
969 i < gen->tile_first + gen->n_grid + gen->tile_len) {
970 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
973 c = isl_equality_alloc(isl_local_space_copy(ls));
974 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
975 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
976 scale = isl_basic_map_add_constraint(scale, c);
979 isl_local_space_free(ls);
981 sched = isl_union_map_apply_range(sched,
982 isl_union_map_from_map(isl_map_from_basic_map(scale)));
984 return sched;
987 /* If we are not performing "wrapping" and if the user asked for it,
988 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
990 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
991 __isl_take isl_union_map *sched)
993 int i;
994 isl_space *dim;
995 isl_basic_map *scale;
996 isl_constraint *c;
997 isl_local_space *ls;
999 if (gen->options->wrap)
1000 return sched;
1001 if (!gen->options->scale_tile_loops)
1002 return sched;
1004 dim = isl_union_map_get_space(sched);
1005 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1006 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1007 scale = isl_basic_map_universe(isl_space_copy(dim));
1008 ls = isl_local_space_from_space(dim);
1010 for (i = 0; i < gen->thread_tiled_len; ++i) {
1011 int f = 1;
1013 if (i >= gen->shared_len &&
1014 i < gen->shared_len + gen->n_block)
1015 f = gen->block_dim[i - gen->shared_len];
1017 c = isl_equality_alloc(isl_local_space_copy(ls));
1018 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1019 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1020 scale = isl_basic_map_add_constraint(scale, c);
1023 isl_local_space_free(ls);
1025 sched = isl_union_map_apply_range(sched,
1026 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1028 return sched;
1031 /* If we are not performing "wrapping" and if the user asked for it,
1032 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1034 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1035 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1037 int i;
1038 isl_space *dim;
1039 isl_basic_map *scale;
1040 isl_constraint *c;
1041 isl_local_space *ls;
1043 if (gen->options->wrap)
1044 return sched;
1045 if (!gen->options->scale_tile_loops)
1046 return sched;
1048 dim = isl_union_map_get_space(sched);
1049 dim = isl_space_add_dims(dim, isl_dim_in, len);
1050 dim = isl_space_add_dims(dim, isl_dim_out, len);
1051 scale = isl_basic_map_universe(isl_space_copy(dim));
1052 ls = isl_local_space_from_space(dim);
1054 for (i = 0; i < len; ++i) {
1055 int f = 1;
1057 if (i >= first && i < first + n_tile)
1058 f = gen->kernel->block_dim[i - first];
1060 c = isl_equality_alloc(isl_local_space_copy(ls));
1061 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1062 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1063 scale = isl_basic_map_add_constraint(scale, c);
1066 isl_local_space_free(ls);
1068 sched = isl_union_map_apply_range(sched,
1069 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1071 return sched;
1074 /* Add "len" parameters p[i] called prefix%d,
1075 * with bounds to 0 <= p[i] < size[i].
1077 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1078 int len, int *size, const char *prefix)
1080 int i;
1081 unsigned nparam;
1082 isl_space *dim;
1083 isl_basic_set *bset;
1084 isl_constraint *c;
1085 isl_local_space *ls;
1086 char name[20];
1088 nparam = isl_set_dim(set, isl_dim_param);
1089 set = isl_set_add_dims(set, isl_dim_param, len);
1091 for (i = 0; i < len; ++i) {
1092 snprintf(name, sizeof(name), "%s%d", prefix, i);
1093 set = isl_set_set_dim_name(set, isl_dim_param,
1094 nparam + i, name);
1097 dim = isl_set_get_space(set);
1098 bset = isl_basic_set_universe(isl_space_copy(dim));
1099 ls = isl_local_space_from_space(dim);
1101 for (i = 0; i < len; ++i) {
1102 c = isl_inequality_alloc(isl_local_space_copy(ls));
1103 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1104 nparam + i, 1);
1105 bset = isl_basic_set_add_constraint(bset, c);
1107 c = isl_inequality_alloc(isl_local_space_copy(ls));
1108 c = isl_constraint_set_coefficient_si(c, isl_dim_param,
1109 nparam + i, -1);
1110 c = isl_constraint_set_constant_si(c, size[i] - 1);
1111 bset = isl_basic_set_add_constraint(bset, c);
1114 isl_local_space_free(ls);
1116 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1119 /* Add "len" parameters p[i] called prefix%d,
1120 * with bounds to 0 <= p[i] < size[i].
1122 static __isl_give isl_set *add_bounded_parameters_dynamic(
1123 __isl_take isl_set *set, __isl_keep isl_multi_pw_aff *size,
1124 const char *prefix)
1126 int i, len;
1127 unsigned nparam;
1128 isl_space *space;
1129 isl_local_space *ls;
1130 char name[20];
1132 len = isl_multi_pw_aff_dim(size, isl_dim_out);
1133 nparam = isl_set_dim(set, isl_dim_param);
1134 set = isl_set_add_dims(set, isl_dim_param, len);
1136 for (i = 0; i < len; ++i) {
1137 snprintf(name, sizeof(name), "%s%d", prefix, i);
1138 set = isl_set_set_dim_name(set, isl_dim_param,
1139 nparam + i, name);
1142 space = isl_space_params(isl_set_get_space(set));
1143 ls = isl_local_space_from_space(space);
1144 for (i = 0; i < len; ++i) {
1145 isl_pw_aff *param, *size_i, *zero;
1146 isl_set *bound;
1148 param = isl_pw_aff_var_on_domain(isl_local_space_copy(ls),
1149 isl_dim_param, nparam + i);
1151 size_i = isl_multi_pw_aff_get_pw_aff(size, i);
1152 bound = isl_pw_aff_lt_set(isl_pw_aff_copy(param), size_i);
1153 set = isl_set_intersect_params(set, bound);
1155 zero = isl_pw_aff_zero_on_domain(isl_local_space_copy(ls));
1156 bound = isl_pw_aff_ge_set(param, zero);
1157 set = isl_set_intersect_params(set, bound);
1159 isl_local_space_free(ls);
1161 return set;
1164 /* Given a mapping "sched" of the form
1166 * [D -> A] -> [D -> T(A)]
1168 * apply the mapping encoded in tile->bound[i].shift_map
1169 * to the range of "sched".
1170 * The mappings in tile->bound[i].shift_map are of the form
1172 * [D -> a] -> [D -> s(D,a)]
1174 * We first compose them with a mapping
1176 * [D -> v] -> v
1178 * (If tile->bound[i].shift_map is not set, then it is assumed to be
1179 * an identity mapping and then we use this second mapping instead.)
1180 * This results in
1182 * [D -> a] -> s(D,a)
1184 * We precompose them with a projection on the i th dimension to obtain
1186 * [D -> T] -> s(D,T)
1188 * and collect these into
1190 * [D -> T] -> S(D,T)
1192 * Introducing D in the range yields
1194 * [D -> T] -> [D -> S(D,T)]
1196 * and application to "sched" yields
1198 * [D -> A] -> [D -> S(D,T(A))]
1200 static __isl_give isl_map *pre_shift(__isl_take isl_map *sched,
1201 struct gpu_array_tile *tile)
1203 int i;
1204 isl_ctx *ctx = isl_map_get_ctx(sched);
1205 isl_space *space, *space2;
1206 isl_basic_map *def;
1207 isl_map *map, *id, *pre_shift;
1209 space = isl_space_range(isl_map_get_space(sched));
1210 space2 = isl_space_from_domain(isl_space_copy(space));
1211 pre_shift = isl_map_universe(space2);
1212 space = isl_space_domain(isl_space_unwrap(space));
1213 id = isl_map_identity(isl_space_map_from_set(isl_space_copy(space)));
1214 space = isl_space_from_domain(space);
1215 space = isl_space_add_dims(space, isl_dim_out, 1);
1216 def = isl_basic_map_range_map(isl_basic_map_universe(space));
1218 for (i = 0; i < tile->n; ++i) {
1219 isl_basic_map *bmap, *drop;
1220 isl_map *proj;
1222 space = isl_space_alloc(ctx, 0, tile->n, tile->n);
1223 proj = isl_map_identity(space);
1224 proj = isl_map_project_out(proj, isl_dim_out,
1225 i + 1, tile->n - (i + 1));
1226 proj = isl_map_project_out(proj, isl_dim_out, 0, i);
1227 proj = isl_map_product(isl_map_copy(id), proj);
1229 if (!tile->bound[i].shift_map)
1230 bmap = isl_basic_map_copy(def);
1231 else {
1232 bmap = isl_basic_map_copy(tile->bound[i].shift_map);
1233 bmap = isl_basic_map_apply_range(bmap,
1234 isl_basic_map_copy(def));
1237 map = isl_map_from_basic_map(bmap);
1238 map = isl_map_apply_range(proj, map);
1239 pre_shift = isl_map_flat_range_product(pre_shift, map);
1242 isl_map_free(id);
1243 isl_basic_map_free(def);
1245 space = isl_space_domain(isl_map_get_space(pre_shift));
1246 map = isl_map_domain_map(isl_map_universe(isl_space_unwrap(space)));
1247 pre_shift = isl_map_range_product(map, pre_shift);
1249 sched = isl_map_apply_range(sched, pre_shift);
1251 return sched;
1254 /* Given an access relation to a tile of an array, construct a map that
1255 * maps each element in the space of the access relation
1256 * to a copy of the tile shifted to the origin
1257 * (based on the lower bounds in group->private_tile or group->shared_tile).
1258 * If any of the indices is strided, then
1259 * {private,shared}_tile->bound[i].shift_map is applied to the index first.
1260 * The domain space of the resulting map is that of access "access",
1261 * while the range space is anonymous.
1262 * The resulting map only encodes the mapping to the shift tile and
1263 * not the constraints of "access".
1265 * Let the space of the access relation be
1267 * D -> A
1269 * We first construct an identity relation on a wrapped copy of this space,
1270 * except that it strips off the name of array
1272 * [D -> A] -> [D -> T(A)] (1)
1274 * The bounds in tile->bound[i].lb are of the form
1276 * D -> b(D)
1278 * We collect them into
1280 * D -> B(D)
1282 * and then transform them into
1284 * [D -> T] -> T - B(D) (2)
1286 * Combining those two mappings (1) and (2) yields
1288 * [D -> A] -> T(A) - B(D)
1290 * If there are any strides, then (1) is first transformed into (1')
1292 * [D -> A] -> [D -> T'(A)] (1')
1294 * by a call to pre_shift.
1296 static __isl_give isl_map *shift_access(__isl_take isl_map *access,
1297 struct gpu_array_ref_group *group)
1299 int i;
1300 isl_space *space;
1301 isl_map *id1, *id2;
1302 isl_map *map;
1303 isl_map *shift;
1304 isl_map *sched;
1305 struct gpu_array_tile *tile;
1306 int n_index = group->array->n_index;
1308 tile = group->private_tile;
1309 if (!tile)
1310 tile = group->shared_tile;
1312 space = isl_space_domain(isl_map_get_space(access));
1313 space = isl_space_map_from_set(space);
1314 id1 = isl_map_identity(space);
1315 space = isl_space_range(isl_map_get_space(access));
1316 space = isl_space_map_from_set(space);
1317 space = isl_space_set_tuple_name(space, isl_dim_out, NULL);
1318 id2 = isl_map_identity(space);
1319 sched = isl_map_product(id1, id2);
1321 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1322 space = isl_space_from_domain(isl_space_domain(space));
1323 shift = isl_map_universe(space);
1324 for (i = 0; i < n_index; ++i) {
1325 map = isl_map_from_aff(isl_aff_copy(tile->bound[i].lb));
1326 shift = isl_map_flat_range_product(shift, map);
1329 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1330 map = isl_map_universe(space);
1331 id1 = isl_map_range_map(isl_map_copy(map));
1332 map = isl_map_domain_map(map);
1333 shift = isl_map_neg(shift);
1334 shift = isl_map_apply_range(map, shift);
1335 shift = isl_map_sum(id1, shift);
1337 for (i = 0; i < n_index; ++i)
1338 if (tile->bound[i].shift_map)
1339 break;
1341 if (i < n_index)
1342 sched = pre_shift(sched, tile);
1344 sched = isl_map_apply_range(sched, shift);
1346 isl_map_free(access);
1348 return sched;
1351 /* Does "map" have an obviously fixed value at variable "pos" of "type"?
1353 static int map_plain_is_fixed(isl_map *map, enum isl_dim_type type,
1354 unsigned pos)
1356 isl_val *v;
1357 int fixed;
1359 v = isl_map_plain_get_val_if_fixed(map, type, pos);
1360 if (!v)
1361 return -1;
1362 fixed = isl_val_is_int(v);
1363 isl_val_free(v);
1365 return fixed;
1368 /* Given a schedule that iterates over all elements in a piece of an array,
1369 * perform tiling/wrapping over the threads.
1371 * In particular, we tile the final iterators so that the final thread
1372 * dimension runs over the final array dimension.
1373 * However, if those final iterators have only a single iteration,
1374 * we try to tile earlier iterators instead.
1376 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1377 __isl_take isl_map *sched)
1379 isl_space *dim;
1380 isl_union_map *usched;
1381 isl_map *tiling;
1382 isl_set *par;
1383 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1384 int n_tile;
1385 int first;
1387 n_tile = gen->kernel->n_block;
1388 if (n_tile > nvar) {
1389 int i;
1390 sched = isl_map_insert_dims(sched,
1391 isl_dim_out, 0, n_tile - nvar);
1392 for (i = 0; i < n_tile - nvar; ++i)
1393 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1394 nvar = n_tile;
1397 first = nvar - n_tile;
1399 for (; first > 0; first --)
1400 if (!map_plain_is_fixed(sched, isl_dim_out, first + n_tile - 1))
1401 break;
1403 dim = isl_map_get_space(sched);
1404 dim = isl_space_params(dim);
1405 if (gen->options->wrap)
1406 tiling = wrap(isl_space_copy(dim), nvar, first,
1407 n_tile, gen->kernel->block_dim);
1408 else
1409 tiling = tile(isl_space_copy(dim), nvar, first,
1410 n_tile, gen->kernel->block_dim);
1411 sched = isl_map_apply_range(sched, tiling);
1413 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1414 sched = isl_map_intersect_range(sched, par);
1416 usched = isl_union_map_from_map(sched);
1417 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1418 first, n_tile);
1419 sched = isl_map_from_union_map(usched);
1421 return sched;
1424 /* Given an index expression "pa" into a tile of an array, adjust the expression
1425 * to a shift of the tile to the origin
1426 * (based on the lower bounds in "bound".
1427 * If the index is strided, then we first add
1428 * bound->shift and divide by bound->stride.
1429 * In the end, we compute the gist with respect to "domain".
1431 * All of the input expression "pa", the set "domain" and
1432 * the output are expressed in terms of the AST schedule domain.
1433 * The expressions in "bound" are expressed
1434 * in terms of the first shared_len dimensions of the schedule computed by PPCG.
1435 * The mapping "sched2shared" maps the former domain to the latter domain.
1437 static __isl_give isl_pw_aff *shift_index(__isl_take isl_pw_aff *pa,
1438 struct gpu_array_info *array,
1439 struct gpu_array_bound *bound, __isl_take isl_set *domain,
1440 __isl_take isl_map *sched2shared)
1442 isl_map *map;
1443 isl_pw_aff *tmp;
1444 isl_pw_multi_aff *pma;
1446 if (bound->shift) {
1447 map = isl_map_from_aff(isl_aff_copy(bound->shift));
1448 map = isl_map_apply_range(isl_map_copy(sched2shared), map);
1449 pma = isl_pw_multi_aff_from_map(map);
1450 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1451 isl_pw_multi_aff_free(pma);
1452 pa = isl_pw_aff_add(pa, tmp);
1453 pa = isl_pw_aff_scale_down_val(pa, isl_val_copy(bound->stride));
1457 map = isl_map_from_aff(isl_aff_copy(bound->lb));
1458 map = isl_map_apply_range(sched2shared, map);
1459 pma = isl_pw_multi_aff_from_map(map);
1460 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1461 isl_pw_multi_aff_free(pma);
1462 pa = isl_pw_aff_sub(pa, tmp);
1463 pa = isl_pw_aff_coalesce(pa);
1464 pa = isl_pw_aff_gist(pa, domain);
1466 return pa;
1469 /* Return the union of all read (read = 1) and/or write (write = 1)
1470 * access relations in the group.
1472 static __isl_give isl_union_map *group_access_relation(
1473 struct gpu_array_ref_group *group, int read, int write)
1475 int i;
1476 isl_union_map *access;
1478 access = isl_union_map_empty(isl_map_get_space(group->access));
1479 for (i = 0; i < group->n_ref; ++i) {
1480 isl_map *map_i;
1482 if (!((read && group->refs[i]->read) ||
1483 (write && group->refs[i]->write)))
1484 continue;
1485 map_i = isl_map_copy(group->refs[i]->access);
1486 access = isl_union_map_union(access,
1487 isl_union_map_from_map(map_i));
1490 return access;
1493 /* Return a map from the first shared_len dimensions of the computed
1494 * schedule to the values of the given index "i"
1495 * of the elements in the array tile in global memory that corresponds
1496 * to the shared memory copy.
1497 * In particular, if a is the index, then the range of the map
1499 * { D -> [a] }
1501 * is constrained as follows
1503 * tile_offset(D) <= a <= tile_offset(D) + tile_size - 1 (1)
1505 * and
1507 * 0 <= a <= array_size - 1 (2)
1510 * Note that if some stride has been detected (i.e., when
1511 * group->shared_tile->bound[i].shift is set), then offset and size (i.e.,
1512 * constraints (1)) apply to the shifted and scaled down copy of the tile.
1513 * These constraints therefore have to be mapped back to the original
1514 * array space using the inverse of the shift_map.
1516 static __isl_give isl_map *group_tile_dim(struct gpu_array_ref_group *group,
1517 int i)
1519 isl_aff *aff;
1520 isl_space *space;
1521 isl_map *map, *tile, *gt;
1522 isl_set *bound;
1524 map = isl_map_from_aff(isl_aff_copy(group->shared_tile->bound[i].lb));
1525 space = isl_space_range(isl_map_get_space(map));
1526 map = isl_map_apply_range(map, isl_map_lex_le(isl_space_copy(space)));
1527 tile = map;
1529 aff = isl_aff_copy(group->shared_tile->bound[i].lb);
1530 aff = isl_aff_add_constant_val(aff,
1531 isl_val_copy(group->shared_tile->bound[i].size));
1532 map = isl_map_from_aff(aff);
1533 gt = isl_map_lex_gt(space);
1534 map = isl_map_apply_range(map, isl_map_copy(gt));
1535 tile = isl_map_intersect(tile, map);
1537 if (group->shared_tile->bound[i].shift) {
1538 isl_basic_map *shift;
1539 shift = isl_basic_map_copy(group->shared_tile->bound[i].shift_map);
1540 shift = isl_basic_map_reverse(shift);
1541 tile = isl_set_unwrap(isl_set_apply(isl_map_wrap(tile),
1542 isl_map_from_basic_map(shift)));
1545 tile = isl_map_lower_bound_si(tile, isl_dim_out, 0, 0);
1547 bound = isl_set_from_pw_aff(isl_pw_aff_copy(group->array->bound[i]));
1548 bound = isl_set_apply(bound, gt);
1549 tile = isl_map_intersect_range(tile, bound);
1551 return tile;
1554 /* Return a map from the first shared_len dimensions of the computed
1555 * schedule to the array tile in
1556 * global memory that corresponds to the shared memory copy.
1558 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1560 int i;
1561 int n_index = group->array->n_index;
1562 isl_map *tile;
1564 tile = group_tile_dim(group, 0);
1565 for (i = 1; i < n_index; ++i) {
1566 isl_map *tile_i;
1568 tile_i = group_tile_dim(group, i);
1569 tile = isl_map_flat_range_product(tile, tile_i);
1572 tile = isl_map_set_tuple_name(tile, isl_dim_out, group->array->name);
1574 return tile;
1577 /* Given a mapping "sched" from the AST schedule to a domain,
1578 * return the corresponding mapping from the AST schedule to
1579 * to the first shared_len dimensions of the schedule computed by PPCG.
1581 static __isl_give isl_map *compute_sched_to_shared(struct gpu_gen *gen,
1582 __isl_take isl_map *sched)
1584 isl_union_map *umap;
1585 isl_space *space;
1586 isl_map *map;
1588 space = isl_space_range(isl_map_get_space(sched));
1589 space = isl_space_from_domain(space);
1590 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1592 umap = isl_union_map_copy(gen->shared_sched);
1593 umap = isl_union_map_apply_range(umap,
1594 isl_union_map_copy(gen->shared_proj));
1595 map = isl_union_map_extract_map(umap, space);
1596 isl_union_map_free(umap);
1598 sched = isl_map_apply_range(sched, map);
1599 sched = isl_map_detect_equalities(sched);
1601 return sched;
1604 /* Set unroll[j] if the input dimension j is involved in
1605 * the index expression represented by ma.
1607 static int check_unroll(__isl_take isl_set *set, __isl_take isl_multi_aff *ma,
1608 void *user)
1610 int i, j;
1611 int n_in = isl_multi_aff_dim(ma, isl_dim_in);
1612 int n_out = isl_multi_aff_dim(ma, isl_dim_out);
1613 int *unroll = user;
1615 for (i = 0; i < n_out; ++i) {
1616 isl_aff *aff;
1618 aff = isl_multi_aff_get_aff(ma, i);
1619 for (j = 0; j < n_in; ++j)
1620 if (isl_aff_involves_dims(aff, isl_dim_in, j, 1))
1621 unroll[j] = 1;
1622 isl_aff_free(aff);
1625 isl_set_free(set);
1626 isl_multi_aff_free(ma);
1627 return 0;
1630 /* Given an array pos mapping input dimensions to the corresponding
1631 * output dimension, construct the corresponding map.
1633 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1634 int *pos, int len)
1636 int i;
1637 isl_constraint *c;
1638 isl_basic_map *bmap;
1639 isl_local_space *ls;
1641 dim = isl_space_add_dims(dim, isl_dim_in, len);
1642 dim = isl_space_add_dims(dim, isl_dim_out, len);
1643 bmap = isl_basic_map_universe(isl_space_copy(dim));
1644 ls = isl_local_space_from_space(dim);
1646 for (i = 0; i < len; ++i) {
1647 c = isl_equality_alloc(isl_local_space_copy(ls));
1648 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i,
1649 -1);
1650 c = isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i],
1652 bmap = isl_basic_map_add_constraint(bmap, c);
1654 isl_local_space_free(ls);
1656 return isl_map_from_basic_map(bmap);
1659 /* Find all loops involved in any of the index expressions for any of
1660 * the private accesses, move them innermost and then mark them as
1661 * requiring unrolling by setting gen->first_unroll.
1662 * The loops involved should all be parallel because of the checks
1663 * we performed in check_private_group_access. Moving them innermost
1664 * is therefore a valid transformation.
1666 * Loops up to gen->shared_len are generated before the mapping to
1667 * threads is applied. They should therefore be ignored.
1669 * We compute the hidden equalities of the schedule first
1670 * since we will need them in our calls to isl_pw_multi_aff_from_map
1671 * and because we want to make sure that the same equalities
1672 * are also available to the code generator.
1674 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1675 __isl_take isl_union_map *sched)
1677 int i, j;
1678 int unroll[gen->thread_tiled_len];
1679 int perm[gen->thread_tiled_len];
1680 isl_space *dim;
1681 isl_map *permute;
1682 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1684 gen->first_unroll = -1;
1686 sched = isl_union_map_detect_equalities(sched);
1687 for (i = 0; i < gen->thread_tiled_len; ++i)
1688 unroll[i] = 0;
1689 for (i = 0; i < gen->prog->n_array; ++i) {
1690 struct gpu_array_info *array = &gen->prog->array[i];
1692 for (j = 0; j < array->n_group; ++j) {
1693 isl_union_map *access;
1694 isl_map *acc;
1695 isl_pw_multi_aff *pma;
1697 if (!array->groups[j]->private_tile)
1698 continue;
1700 access = group_access_relation(array->groups[j], 1, 1);
1701 access = isl_union_map_apply_domain(access,
1702 isl_union_map_copy(sched));
1704 acc = isl_map_from_union_map(access);
1705 pma = isl_pw_multi_aff_from_map(acc);
1706 isl_pw_multi_aff_foreach_piece(pma,
1707 &check_unroll, unroll);
1709 isl_pw_multi_aff_free(pma);
1713 for (i = gen->shared_len; i < len; ++i)
1714 if (unroll[i])
1715 break;
1717 if (i >= len)
1718 return sched;
1720 for (i = len; i < gen->thread_tiled_len; ++i)
1721 if (unroll[i])
1722 return sched;
1724 j = 0;
1725 for (i = 0; i < gen->shared_len; ++i)
1726 perm[i] = j++;
1727 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1728 if (!unroll[i])
1729 perm[i] = j++;
1730 gen->first_unroll = j - gen->shared_len;
1731 for (i = gen->shared_len; i < len; ++i)
1732 if (unroll[i])
1733 perm[i] = j++;
1735 dim = isl_union_map_get_space(sched);
1736 permute = permutation(dim, perm, gen->thread_tiled_len);
1737 sched = isl_union_map_apply_range(sched,
1738 isl_union_map_from_map(permute));
1740 return sched;
1743 /* Given a constraint
1745 * a(p,i) + j = g f(e)
1747 * or -a(p,i) - j = g f(e) if sign < 0,
1748 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1749 * a(p,i) is assumed to be an expression in only the parameters
1750 * and the input dimensions.
1752 static void extract_stride(__isl_keep isl_constraint *c,
1753 struct gpu_array_bound *bound, __isl_keep isl_val *stride, int sign)
1755 int i;
1756 isl_val *v;
1757 isl_space *space;
1758 unsigned nparam;
1759 unsigned nvar;
1760 isl_aff *aff;
1762 isl_val_free(bound->stride);
1763 bound->stride = isl_val_copy(stride);
1765 space = isl_constraint_get_space(c);
1766 space = isl_space_domain(space);
1768 nparam = isl_space_dim(space, isl_dim_param);
1769 nvar = isl_space_dim(space, isl_dim_set);
1771 v = isl_constraint_get_constant_val(c);
1772 if (sign < 0)
1773 v = isl_val_neg(v);
1774 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1775 aff = isl_aff_set_constant_val(aff, v);
1777 for (i = 0; i < nparam; ++i) {
1778 if (!isl_constraint_involves_dims(c, isl_dim_param, i, 1))
1779 continue;
1780 v = isl_constraint_get_coefficient_val(c, isl_dim_param, i);
1781 if (sign < 0)
1782 v = isl_val_neg(v);
1783 aff = isl_aff_add_coefficient_val(aff, isl_dim_param, i, v);
1786 for (i = 0; i < nvar; ++i) {
1787 if (!isl_constraint_involves_dims(c, isl_dim_in, i, 1))
1788 continue;
1789 v = isl_constraint_get_coefficient_val(c, isl_dim_in, i);
1790 if (sign < 0)
1791 v = isl_val_neg(v);
1792 aff = isl_aff_add_coefficient_val(aff, isl_dim_in, i, v);
1795 bound->shift = aff;
1798 /* Given an equality constraint of a map with a single output dimension j,
1799 * check if the constraint is of the form
1801 * a(p,i) + j = g f(e)
1803 * with a(p,i) an expression in the parameters and input dimensions
1804 * and f(e) an expression in the existentially quantified variables.
1805 * If so, and if g is larger than any such g from a previously considered
1806 * constraint, then call extract_stride to record the stride information
1807 * in bound.
1809 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1811 int i;
1812 isl_ctx *ctx;
1813 isl_val *v;
1814 unsigned n_div;
1815 struct gpu_array_bound *bound = user;
1817 ctx = isl_constraint_get_ctx(c);
1818 n_div = isl_constraint_dim(c, isl_dim_div);
1819 v = isl_constraint_get_coefficient_val(c, isl_dim_out, 0);
1821 if (n_div && (isl_val_is_one(v) || isl_val_is_negone(v))) {
1822 int s = isl_val_sgn(v);
1823 isl_val *stride = isl_val_zero(ctx);
1825 isl_val_free(v);
1826 for (i = 0; i < n_div; ++i) {
1827 v = isl_constraint_get_coefficient_val(c,
1828 isl_dim_div, i);
1829 stride = isl_val_gcd(stride, v);
1831 if (!isl_val_is_zero(stride) &&
1832 isl_val_gt(stride, bound->stride))
1833 extract_stride(c, bound, stride, s);
1835 isl_val_free(stride);
1836 } else
1837 isl_val_free(v);
1839 isl_constraint_free(c);
1840 return 0;
1843 /* Given contraints on an array index i, check if we can find
1844 * a shift a(p) and a stride g such that
1846 * a(p) + i = 0 mod g
1848 * If so, record the information in bound and apply the mapping
1849 * i -> (i + a(p))/g to the array index in bounds and return
1850 * the new constraints.
1851 * If not, simply return the original constraints.
1853 * If bounds is a subset of the space
1855 * D -> i
1857 * then the bound recorded in bound->shift is of the form
1859 * D -> s(D)
1861 * with s(D) equal to a(p) above.
1862 * The mapping recorded in bound->shift_map is of the form
1864 * [D -> i] -> [D -> (i + S(D))/g]
1866 * This mapping is computed as follows.
1867 * We first introduce "i" in the domain through precomposition
1868 * with [D -> i] -> D obtaining
1870 * [D -> i] -> s(D)
1872 * Adding [D -> i] -> i produces
1874 * [D -> i] -> i + s(D)
1876 * and the domain product with [D -> i] -> D yields
1878 * [D -> i] -> [D -> i + s(D)]
1880 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1882 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1883 __isl_take isl_basic_map *bounds)
1885 isl_space *space;
1886 isl_basic_map *hull;
1887 isl_basic_map *shift, *id, *bmap, *scale;
1888 isl_basic_set *bset;
1889 isl_aff *aff;
1891 bound->stride = NULL;
1893 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1895 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1897 isl_basic_map_free(hull);
1899 if (!bound->stride)
1900 return bounds;
1902 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1903 space = isl_basic_map_get_space(bounds);
1904 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1905 shift = isl_basic_map_apply_range(bmap, shift);
1906 space = isl_basic_map_get_space(bounds);
1907 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1908 shift = isl_basic_map_sum(id, shift);
1909 space = isl_basic_map_get_space(bounds);
1910 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1911 shift = isl_basic_map_range_product(id, shift);
1913 space = isl_space_domain(isl_basic_map_get_space(bounds));
1914 id = isl_basic_map_identity(isl_space_map_from_set(space));
1915 space = isl_space_range(isl_basic_map_get_space(bounds));
1916 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1917 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1918 aff = isl_aff_scale_down_val(aff, isl_val_copy(bound->stride));
1919 scale = isl_basic_map_from_aff(aff);
1920 scale = isl_basic_map_product(id, scale);
1922 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1923 bmap = isl_basic_map_copy(bound->shift_map);
1924 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1925 bounds = isl_basic_set_unwrap(bset);
1927 return bounds;
1930 /* Data used in compute_array_dim_size and compute_size_in_direction.
1932 * pos is the position of the variable representing the array index,
1933 * i.e., the variable for which want to compute the size. This variable
1934 * is also the last variable in the set.
1936 struct gpu_size_info {
1937 isl_basic_set *bset;
1938 struct gpu_array_bound *bound;
1939 int pos;
1942 /* Given a constraint from the basic set describing the bounds on
1943 * an array index, check if it is a lower bound, say m i >= b(x), and,
1944 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1945 * upper bound. If so, and if this bound is smaller than any bound
1946 * derived from earlier constraints, set the size to this bound on
1947 * the expression and the lower bound to ceil(b(x)/m).
1949 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1951 struct gpu_size_info *size = user;
1952 unsigned nparam;
1953 unsigned n_div;
1954 isl_val *v;
1955 isl_aff *aff;
1956 isl_aff *lb;
1958 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1959 n_div = isl_constraint_dim(c, isl_dim_div);
1961 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div) ||
1962 !isl_constraint_is_lower_bound(c, isl_dim_set, size->pos)) {
1963 isl_constraint_free(c);
1964 return 0;
1967 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
1968 aff = isl_aff_ceil(aff);
1970 lb = isl_aff_copy(aff);
1972 aff = isl_aff_neg(aff);
1973 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
1975 v = isl_basic_set_max_val(size->bset, aff);
1976 isl_aff_free(aff);
1978 if (isl_val_is_int(v)) {
1979 v = isl_val_add_ui(v, 1);
1980 if (!size->bound->size || isl_val_lt(v, size->bound->size)) {
1981 isl_val_free(size->bound->size);
1982 size->bound->size = isl_val_copy(v);
1983 lb = isl_aff_drop_dims(lb, isl_dim_in, size->pos, 1);
1984 isl_aff_free(size->bound->lb);
1985 size->bound->lb = isl_aff_copy(lb);
1988 isl_val_free(v);
1989 isl_aff_free(lb);
1991 isl_constraint_free(c);
1993 return 0;
1996 /* Given a basic map "bounds" that maps parameters and input dimensions
1997 * to a single output dimension, look for an expression in the parameters
1998 * and input dimensions such that the range of the output dimension shifted
1999 * by this expression is a constant.
2001 * In particular, we currently only consider lower bounds on the output
2002 * dimension as candidate expressions.
2004 static int compute_array_dim_size(struct gpu_array_bound *bound,
2005 __isl_take isl_basic_map *bounds)
2007 struct gpu_size_info size;
2009 bounds = isl_basic_map_detect_equalities(bounds);
2010 bounds = check_stride(bound, bounds);
2012 bound->size = NULL;
2013 bound->lb = NULL;
2015 size.bound = bound;
2016 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2017 size.bset = isl_basic_map_wrap(bounds);
2018 size.bset = isl_basic_set_flatten(size.bset);
2019 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2020 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2021 &size);
2022 isl_basic_set_free(size.bset);
2024 return bound->size ? 0 : -1;
2027 /* Check if we can find a memory tile for the given array
2028 * based on the given accesses, and if so, put the results in "tile".
2030 * We project the accesses on each index in turn and look for a parametric
2031 * offset such that the size is constant.
2033 static int can_tile(__isl_keep isl_map *access, struct gpu_array_tile *tile)
2035 int i;
2037 for (i = 0; i < tile->n; ++i) {
2038 isl_map *access_i;
2039 isl_basic_map *hull;
2041 access_i = isl_map_copy(access);
2042 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2043 access_i = isl_map_project_out(access_i, isl_dim_out,
2044 1, tile->n - (i + 1));
2045 access_i = isl_map_compute_divs(access_i);
2046 hull = isl_map_simple_hull(access_i);
2047 if (compute_array_dim_size(&tile->bound[i], hull) < 0)
2048 return 0;
2051 return 1;
2054 /* Construct a map with input the shared tile loops and the loops that
2055 * will be wrapped around the threads that relates these later loops
2056 * to the thread indices and then projects them out.
2058 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2060 isl_map *priv;
2061 isl_map *tiling;
2062 isl_map *proj;
2063 isl_set *par;
2064 isl_space *dim;
2066 dim = isl_union_map_get_space(gen->shared_sched);
2068 if (gen->options->wrap)
2069 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2070 gen->shared_len, gen->n_block, gen->block_dim);
2071 else
2072 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2073 gen->shared_len, gen->n_block, gen->block_dim);
2075 priv = tiling;
2077 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2078 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2079 gen->n_block, "t");
2081 priv = isl_map_align_params(priv, isl_set_get_space(par));
2082 priv = isl_map_intersect_range(priv, par);
2084 dim = isl_map_get_space(priv);
2085 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2086 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2087 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2088 gen->shared_len);
2090 priv = isl_map_apply_range(priv, proj);
2092 return priv;
2095 /* Construct a map from domain_dim to domain_dim that increments
2096 * the dimension at position "pos" and leaves all other dimensions
2097 * constant.
2099 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2101 int i;
2102 int len = isl_space_dim(domain_dim, isl_dim_set);
2103 isl_space *dim;
2104 isl_basic_map *next;
2105 isl_local_space *ls;
2107 dim = isl_space_map_from_set(domain_dim);
2108 next = isl_basic_map_universe(isl_space_copy(dim));
2109 ls = isl_local_space_from_space(dim);
2111 for (i = 0; i < len; ++i) {
2112 isl_constraint *c;
2114 c = isl_equality_alloc(isl_local_space_copy(ls));
2115 c = isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2116 c = isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2117 if (i == pos)
2118 c = isl_constraint_set_constant_si(c, 1);
2119 next = isl_basic_map_add_constraint(next, c);
2122 isl_local_space_free(ls);
2124 return isl_map_from_basic_map(next);
2127 /* Check if the given access is coalesced.
2128 * That is, check whether incrementing the dimension that will get
2129 * wrapped over the last thread index results in incrementing
2130 * the last array index.
2132 * This function is only called for access relations without reuse.
2134 static int access_is_coalesced(struct gpu_gen *gen,
2135 __isl_keep isl_union_map *access)
2137 isl_space *dim;
2138 isl_map *access_map;
2139 isl_map *next_thread_x;
2140 isl_map *next_element;
2141 isl_map *map;
2142 int coalesced;
2144 access = isl_union_map_copy(access);
2145 access = isl_union_map_apply_domain(access,
2146 isl_union_map_copy(gen->tiled_sched));
2147 access_map = isl_map_from_union_map(access);
2149 dim = isl_map_get_space(access_map);
2150 dim = isl_space_domain(dim);
2151 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2153 dim = isl_map_get_space(access_map);
2154 dim = isl_space_range(dim);
2155 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2157 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2158 map = isl_map_apply_range(map, access_map);
2160 coalesced = isl_map_is_subset(map, next_element);
2162 isl_map_free(next_element);
2163 isl_map_free(map);
2165 return coalesced;
2168 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2169 * dimensions of the computed schedule, check if it is bijective for
2170 * fixed values of the first gen->shared_len dimensions.
2171 * We perform this check by equating these dimensions to parameters.
2173 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2175 int res;
2176 isl_set *par;
2177 isl_space *space;
2179 access = isl_map_copy(access);
2180 space = isl_space_params(isl_map_get_space(access));
2181 par = parametrization(space, gen->shared_len + gen->n_block,
2182 0, gen->shared_len, "s");
2183 access = isl_map_intersect_domain(access, par);
2184 res = isl_map_is_bijective(access);
2185 isl_map_free(access);
2187 return res;
2190 /* Look for the last shared tile loop that affects the offset of "tile"
2191 * and return the result.
2192 * If there is no such loop, then return the index of the loop
2193 * before the first shared tile loop, in particular gen->tile_first - 1.
2195 static int compute_tile_last_shared(struct gpu_gen *gen,
2196 struct gpu_array_tile *tile)
2198 int i, j;
2200 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2201 for (i = 0; i < tile->n; ++i) {
2202 isl_aff *lb;
2203 isl_aff *shift;
2205 lb = tile->bound[i].lb;
2206 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2207 break;
2209 shift = tile->bound[i].shift;
2210 if (!shift)
2211 continue;
2212 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2213 break;
2215 if (i < tile->n)
2216 break;
2219 return j;
2222 /* Look for the last shared tile loop that affects the offset of the
2223 * shared or private tile and store the result in group->last_shared.
2224 * If there is no such loop, then group->last_shared is set to a value
2225 * before the first shared tile loop, in particular gen->tile_first - 1.
2226 * If there is no tile defined on the array reference group,
2227 * then set group->last_shared to gen->shared_len - 1.
2229 static void set_last_shared(struct gpu_gen *gen,
2230 struct gpu_array_ref_group *group)
2232 struct gpu_array_tile *tile;
2234 group->last_shared = gen->shared_len - 1;
2236 tile = group->private_tile;
2237 if (!tile)
2238 tile = group->shared_tile;
2239 if (!tile)
2240 return;
2242 group->last_shared = compute_tile_last_shared(gen, tile);
2245 /* Compute a privatized copy of all access relations from reference groups that
2246 * are mapped to private memory and store the result in gen->privatization.
2248 static void compute_private_access(struct gpu_gen *gen)
2250 int i, j;
2251 isl_union_map *private;
2253 if (!gen->options->use_private_memory)
2254 return;
2256 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2258 for (i = 0; i < gen->prog->n_array; ++i) {
2259 struct gpu_array_info *array = &gen->prog->array[i];
2261 if (gpu_array_is_read_only_scalar(array))
2262 continue;
2264 for (j = 0; j < array->n_group; ++j) {
2265 if (!array->groups[j]->private_tile)
2266 continue;
2268 private = isl_union_map_union(private,
2269 group_access_relation(array->groups[j], 1, 1));
2273 if (isl_union_map_is_empty(private))
2274 isl_union_map_free(private);
2275 else {
2276 isl_union_map *priv;
2278 private = isl_union_map_apply_domain(private,
2279 isl_union_map_copy(gen->shared_sched));
2280 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2281 private = isl_union_map_apply_domain(private, priv);
2282 gen->private_access = private;
2286 /* Compute the size of the tile specified by "tile"
2287 * in number of elements and return the result.
2289 static __isl_give isl_val *tile_size(isl_ctx *ctx, struct gpu_array_tile *tile)
2291 int i;
2292 isl_val *size;
2294 size = isl_val_one(ctx);
2296 for (i = 0; i < tile->n; ++i)
2297 size = isl_val_mul(size, isl_val_copy(tile->bound[i].size));
2299 return size;
2302 /* If max_shared_memory is not set to infinity (-1), then make
2303 * sure that the total amount of shared memory required by the
2304 * array reference groups mapped to shared memory is no larger
2305 * than this maximum.
2307 * We apply a greedy approach and discard (keep in global memory)
2308 * those groups that would result in a total memory size that
2309 * is larger than the maximum.
2311 static void check_shared_memory_bound(struct gpu_gen *gen)
2313 int i, j;
2314 isl_val *left, *size;
2316 if (gen->options->max_shared_memory < 0)
2317 return;
2319 left = isl_val_int_from_si(gen->ctx, gen->options->max_shared_memory);
2321 for (i = 0; i < gen->prog->n_array; ++i) {
2322 struct gpu_array_info *array = &gen->prog->array[i];
2324 for (j = 0; j < array->n_group; ++j) {
2325 struct gpu_array_ref_group *group;
2327 group = array->groups[j];
2328 if (!group->shared_tile)
2329 continue;
2331 size = tile_size(gen->ctx, group->shared_tile);
2332 size = isl_val_mul_ui(size, array->size);
2334 if (isl_val_le(size, left)) {
2335 left = isl_val_sub(left, size);
2336 continue;
2338 isl_val_free(size);
2340 group->shared_tile = free_tile(group->shared_tile);
2344 isl_val_free(left);
2347 /* Fill up the groups array with singleton groups, i.e., one group
2348 * per reference, initializing the array, access, write, n_ref and refs fields.
2349 * In particular the access field is initialized to the scheduled
2350 * access relation of the array reference.
2352 * Return the number of elements initialized, i.e., the number of
2353 * active references in the current kernel.
2355 static int populate_array_references(struct gpu_array_info *array,
2356 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2358 int i;
2359 int n;
2360 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2362 n = 0;
2363 for (i = 0; i < array->n_ref; ++i) {
2364 isl_union_map *umap;
2365 isl_map *map;
2366 struct gpu_array_ref_group *group;
2367 struct gpu_stmt_access *access = array->refs[i];
2369 map = isl_map_copy(access->access);
2370 umap = isl_union_map_from_map(map);
2371 umap = isl_union_map_apply_domain(umap,
2372 isl_union_map_copy(sched));
2374 if (isl_union_map_is_empty(umap)) {
2375 isl_union_map_free(umap);
2376 continue;
2379 map = isl_map_from_union_map(umap);
2380 map = isl_map_detect_equalities(map);
2382 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2383 assert(group);
2384 group->array = array;
2385 group->access = map;
2386 group->write = access->write;
2387 group->refs = &array->refs[i];
2388 group->n_ref = 1;
2390 groups[n++] = group;
2393 return n;
2396 /* If group->n_ref == 1, then group->refs was set by
2397 * populate_array_references to point directly into
2398 * group->array->refs and should not be freed.
2399 * If group->n_ref > 1, then group->refs was set by join_groups
2400 * to point to a newly allocated array.
2402 static void free_array_ref_group(struct gpu_array_ref_group *group)
2404 if (!group)
2405 return;
2406 free_tile(group->shared_tile);
2407 free_tile(group->private_tile);
2408 isl_map_free(group->access);
2409 if (group->n_ref > 1)
2410 free(group->refs);
2411 free(group);
2414 /* Given a map where the input dimensions represent the tile loops,
2415 * eliminate the innermost of those that have a fixed value
2416 * until we reach one that does not (obviously) have a fixed value.
2418 static __isl_give isl_map *eliminate_fixed_inner_loops(
2419 __isl_take isl_map *access)
2421 int i, n;
2423 n = isl_map_dim(access, isl_dim_in);
2425 for (i = n - 1; i >= 0; --i) {
2426 if (!map_plain_is_fixed(access, isl_dim_in, i))
2427 break;
2428 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2430 return access;
2433 /* Check if the access relations of group1 and group2 overlap within
2434 * the innermost loop. In particular, ignore any inner dimension
2435 * with a fixed value.
2436 * The copying to and from shared memory will be performed within
2437 * the innermost actual loop so we are only allowed to consider
2438 * the dimensions up to that innermost loop while checking whether
2439 * two access relations overlap.
2441 static int accesses_overlap(struct gpu_array_ref_group *group1,
2442 struct gpu_array_ref_group *group2)
2444 int empty;
2445 isl_map *access1, *access2;
2447 access1 = isl_map_copy(group1->access);
2448 access1 = eliminate_fixed_inner_loops(access1);
2449 access2 = isl_map_copy(group2->access);
2450 access2 = eliminate_fixed_inner_loops(access2);
2451 access1 = isl_map_intersect(access1, access2);
2452 empty = isl_map_is_empty(access1);
2453 isl_map_free(access1);
2455 return !empty;
2458 /* Combine the given two groups into a single group, containing
2459 * the references of both groups.
2461 static struct gpu_array_ref_group *join_groups(
2462 struct gpu_array_ref_group *group1,
2463 struct gpu_array_ref_group *group2)
2465 int i;
2466 isl_ctx *ctx;
2467 struct gpu_array_ref_group *group;
2469 ctx = isl_map_get_ctx(group1->access);
2470 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2471 assert(group);
2472 group->array = group1->array;
2473 group->access = isl_map_union(isl_map_copy(group1->access),
2474 isl_map_copy(group2->access));
2475 group->write = group1->write || group2->write;
2476 group->n_ref = group1->n_ref + group2->n_ref;
2477 group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2478 group->n_ref);
2479 assert(group->refs);
2480 for (i = 0; i < group1->n_ref; ++i)
2481 group->refs[i] = group1->refs[i];
2482 for (i = 0; i < group2->n_ref; ++i)
2483 group->refs[group1->n_ref + i] = group2->refs[i];
2485 return group;
2488 /* Combine the given two groups into a single group and free
2489 * the original two groups.
2491 static struct gpu_array_ref_group *join_groups_and_free(
2492 struct gpu_array_ref_group *group1,
2493 struct gpu_array_ref_group *group2)
2495 struct gpu_array_ref_group *group;
2497 group = join_groups(group1, group2);
2498 free_array_ref_group(group1);
2499 free_array_ref_group(group2);
2500 return group;
2503 /* Compute the private and/or shared memory tiles for the array
2504 * reference group "group" of array "array".
2506 * If the array is a read-only scalar or if the user requested
2507 * not to use shared or private memory, then we do not need to do anything.
2509 * We only try to compute a shared memory tile if there is any reuse
2510 * or if the access is not coalesced.
2512 * For computing a private memory tile, we also require that there is
2513 * some reuse. Moreover, we require that the access is private
2514 * to the thread. That is, we check that any given array element
2515 * is only accessed by a single thread.
2516 * We compute an access relation that maps the shared tile loop iterators
2517 * and the shared point loop iterators that will be wrapped over the
2518 * threads to the array elements.
2519 * We actually check that those iterators that will be wrapped
2520 * partition the array space. This check is stricter than necessary
2521 * since several iterations may be mapped onto the same thread
2522 * and then they could be allowed to access the same memory elements,
2523 * but our check does not allow this situation.
2525 * We also check that the index expression only depends on parallel
2526 * loops. That way, we can move those loops innermost and unroll them.
2527 * Again, we use a test that is stricter than necessary.
2528 * We actually check whether the index expression only depends
2529 * on the iterators that are wrapped over the threads.
2530 * These are necessarily parallel, but there may be more parallel loops.
2532 * Combining the injectivity of the first test with the single-valuedness
2533 * of the second test, we simply test for bijectivity.
2535 * If it turns out we can use registers, we compute the private memory
2536 * tile size using can_tile, after introducing a dependence
2537 * on the thread indices.
2539 static void compute_group_bounds_core(struct gpu_gen *gen,
2540 struct gpu_array_ref_group *group)
2542 isl_ctx *ctx = isl_space_get_ctx(group->array->dim);
2543 isl_union_map *access;
2544 int n_index = group->array->n_index;
2545 int no_reuse;
2546 isl_map *acc;
2547 int use_shared = gen->options->use_shared_memory;
2548 int use_private = gen->options->use_private_memory;
2550 if (!use_shared && !use_private)
2551 return;
2552 if (gpu_array_is_read_only_scalar(group->array))
2553 return;
2555 access = group_access_relation(group, 1, 1);
2556 no_reuse = isl_union_map_is_injective(access);
2558 if (use_shared && (!no_reuse || !access_is_coalesced(gen, access))) {
2559 group->shared_tile = create_tile(ctx, group->array->n_index);
2560 if (!can_tile(group->access, group->shared_tile))
2561 group->shared_tile = free_tile(group->shared_tile);
2564 if (!use_private || no_reuse) {
2565 isl_union_map_free(access);
2566 return;
2569 access = isl_union_map_apply_domain(access,
2570 isl_union_map_copy(gen->shared_sched));
2572 acc = isl_map_from_union_map(access);
2574 if (!access_is_bijective(gen, acc)) {
2575 isl_map_free(acc);
2576 return;
2579 group->private_tile = create_tile(gen->ctx, n_index);
2580 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2581 if (!can_tile(acc, group->private_tile))
2582 group->private_tile = free_tile(group->private_tile);
2584 isl_map_free(acc);
2587 /* Compute the private and/or shared memory tiles for the array
2588 * reference group "group" of array "array" and set last_shared.
2590 static void compute_group_bounds(struct gpu_gen *gen,
2591 struct gpu_array_ref_group *group)
2593 compute_group_bounds_core(gen, group);
2594 set_last_shared(gen, group);
2597 /* If two groups have overlapping access relations (as determined by
2598 * the "overlap" function) and if one of them involves a write,
2599 * then merge the two groups into one.
2600 * If "compute_bounds" is set, then call compute_group_bounds
2601 * on the merged groups.
2603 * Return the updated number of groups.
2605 static int group_writes(struct gpu_gen *gen,
2606 int n, struct gpu_array_ref_group **groups,
2607 int (*overlap)(struct gpu_array_ref_group *group1,
2608 struct gpu_array_ref_group *group2), int compute_bounds)
2610 int i, j;
2612 for (i = 0; i < n; ++i) {
2613 for (j = n - 1; j > i; --j) {
2614 if (!groups[i]->write && !groups[j]->write)
2615 continue;
2617 if (!overlap(groups[i], groups[j]))
2618 continue;
2620 groups[i] = join_groups_and_free(groups[i], groups[j]);
2621 if (compute_bounds)
2622 compute_group_bounds(gen, groups[i]);
2623 if (j != n - 1)
2624 groups[j] = groups[n - 1];
2625 n--;
2629 return n;
2632 /* If two groups have overlapping access relations (within the innermost
2633 * loop) and if one of them involves a write, then merge the two groups
2634 * into one.
2636 * Return the updated number of groups.
2638 static int group_overlapping_writes(struct gpu_gen *gen,
2639 int n, struct gpu_array_ref_group **groups)
2641 return group_writes(gen, n, groups, &accesses_overlap, 0);
2644 /* Check if the access relations of group1 and group2 overlap within
2645 * the outermost min(group1->last_shared, group2->last_shared) loops.
2647 static int last_shared_accesses_overlap(struct gpu_array_ref_group *group1,
2648 struct gpu_array_ref_group *group2)
2650 int last_shared;
2651 int dim;
2652 int empty;
2653 isl_map *map_i, *map_j, *map;
2655 last_shared = group1->last_shared;
2656 if (group2->last_shared < last_shared)
2657 last_shared = group2->last_shared;
2658 map_i = isl_map_copy(group1->access);
2659 dim = isl_map_dim(map_i, isl_dim_in);
2660 map_i = isl_map_eliminate(map_i, isl_dim_in,
2661 last_shared + 1, dim - (last_shared + 1));
2662 map_j = isl_map_copy(group2->access);
2663 map_j = isl_map_eliminate(map_j, isl_dim_in,
2664 last_shared + 1, dim - (last_shared + 1));
2665 map = isl_map_intersect(map_i, map_j);
2666 empty = isl_map_is_empty(map);
2667 isl_map_free(map);
2669 return !empty;
2672 /* If two groups have overlapping access relations (within the outer
2673 * last_shared loops) and if one of them involves a write,
2674 * then merge the two groups into one.
2676 * Return the updated number of groups.
2678 static int group_last_shared_overlapping_writes(struct gpu_gen *gen, int n,
2679 struct gpu_array_ref_group **groups)
2681 return group_writes(gen, n, groups, &last_shared_accesses_overlap, 1);
2684 /* Is the size of the tile specified by "tile" smaller than the sum of
2685 * the sizes of the tiles specified by "tile1" and "tile2"?
2687 static int smaller_tile(isl_ctx *ctx, struct gpu_array_tile *tile,
2688 struct gpu_array_tile *tile1, struct gpu_array_tile *tile2)
2690 int smaller;
2691 isl_val *size, *size1, *size2;
2693 size = tile_size(ctx, tile);
2694 size1 = tile_size(ctx, tile1);
2695 size2 = tile_size(ctx, tile2);
2697 size = isl_val_sub(size, size1);
2698 size = isl_val_sub(size, size2);
2699 smaller = isl_val_is_neg(size);
2701 isl_val_free(size);
2703 return smaller;
2706 /* Given an initial grouping of array references and shared memory tiles
2707 * for each group that allows for a shared memory tile, merge two groups
2708 * if both have a shared memory tile, the merged group also has
2709 * a shared memory tile and the size of the tile for the merge group
2710 * is smaller than the sum of the tile sizes of the individual groups.
2712 * If merging two groups decreases the "last_shared" dimension of
2713 * one or both of the two groups, then we need to check for overlapping
2714 * writes again.
2716 * Return the number of groups after merging.
2718 static int group_common_shared_memory_tile(struct gpu_gen *gen,
2719 struct gpu_array_info *array, int n,
2720 struct gpu_array_ref_group **groups)
2722 int i, j;
2723 int recompute_overlap = 0;
2724 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2726 for (i = 0; i < n; ++i) {
2727 if (!groups[i]->shared_tile)
2728 continue;
2729 for (j = n - 1; j > i; --j) {
2730 isl_map *map;
2731 int empty;
2732 struct gpu_array_ref_group *group;
2734 if (!groups[j]->shared_tile)
2735 continue;
2737 map = isl_map_intersect(isl_map_copy(groups[i]->access),
2738 isl_map_copy(groups[j]->access));
2739 empty = isl_map_is_empty(map);
2740 isl_map_free(map);
2742 if (empty)
2743 continue;
2745 group = join_groups(groups[i], groups[j]);
2746 compute_group_bounds(gen, group);
2747 if (!group->shared_tile ||
2748 !smaller_tile(ctx, group->shared_tile,
2749 groups[i]->shared_tile,
2750 groups[j]->shared_tile)) {
2751 free_array_ref_group(group);
2752 continue;
2755 if (group->last_shared < groups[i]->last_shared ||
2756 group->last_shared < groups[j]->last_shared)
2757 recompute_overlap = 1;
2758 free_array_ref_group(groups[i]);
2759 free_array_ref_group(groups[j]);
2760 groups[i] = group;
2761 if (j != n - 1)
2762 groups[j] = groups[n - 1];
2763 n--;
2767 if (recompute_overlap)
2768 n = group_last_shared_overlapping_writes(gen, n, groups);
2769 return n;
2772 /* Set array->n_group and array->groups to n and groups.
2774 * Additionally, set the "nr" field of each group
2775 * and the "group" field of each reference in each group.
2777 static void set_array_groups(struct gpu_array_info *array,
2778 int n, struct gpu_array_ref_group **groups)
2780 int i, j;
2782 array->n_group = n;
2783 array->groups = groups;
2785 for (i = 0; i < n; ++i) {
2786 groups[i]->nr = i;
2788 for (j = 0; j < groups[i]->n_ref; ++j)
2789 groups[i]->refs[j]->group = i;
2793 /* Group array references that should be considered together when
2794 * deciding whether to access them from private, shared or global memory.
2796 * In particular, if two array references overlap and if one of them
2797 * is a write, then the two references are grouped together.
2798 * We first perform an initial grouping based only on the access relation.
2799 * After computing shared and private memory tiles, we check for
2800 * overlapping writes again, but this time taking into account
2801 * the "last_shared" property.
2803 * Furthermore, if two groups admit a shared memory tile and if the
2804 * combination of the two also admits a shared memory tile, we merge
2805 * the two groups.
2807 static void group_array_references(struct gpu_gen *gen,
2808 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2810 int i;
2811 int n;
2812 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2813 struct gpu_array_ref_group **groups;
2815 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2816 array->n_ref);
2817 assert(groups);
2819 n = populate_array_references(array, sched, groups);
2821 n = group_overlapping_writes(gen, n, groups);
2823 for (i = 0; i < n; ++i)
2824 compute_group_bounds(gen, groups[i]);
2826 n = group_last_shared_overlapping_writes(gen, n, groups);
2828 n = group_common_shared_memory_tile(gen, array, n, groups);
2830 set_array_groups(array, n, groups);
2833 /* Take tiled_sched, project it onto the shared tile loops and
2834 * the loops that will be wrapped over the threads and
2835 * store the result in gen->shared_sched.
2836 * Also compute a projection that projects out the loops that will be
2837 * wrapped over the threads and store this projection in gen->shared_proj.
2839 static void compute_shared_sched(struct gpu_gen *gen)
2841 isl_space *dim;
2842 isl_map *proj;
2843 isl_set *par;
2844 isl_union_map *sched;
2846 sched = isl_union_map_copy(gen->tiled_sched);
2848 dim = isl_union_map_get_space(sched);
2849 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2850 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2852 dim = isl_union_map_get_space(sched);
2853 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2855 gen->shared_sched = sched;
2856 gen->shared_proj = isl_union_map_from_map(proj);
2859 /* Group references of all arrays in the program.
2861 static void group_references(struct gpu_gen *gen)
2863 int i;
2864 isl_union_map *sched;
2866 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2867 isl_union_map_copy(gen->shared_proj));
2869 for (i = 0; i < gen->prog->n_array; ++i)
2870 group_array_references(gen, &gen->prog->array[i], sched);
2872 isl_union_map_free(sched);
2875 /* Free all array information that is local to the current kernel.
2877 static void free_local_array_info(struct gpu_gen *gen)
2879 int i, j;
2881 for (i = 0; i < gen->prog->n_array; ++i) {
2882 struct gpu_array_info *array = &gen->prog->array[i];
2884 for (j = 0; j < array->n_group; ++j)
2885 free_array_ref_group(array->groups[j]);
2886 free(array->groups);
2890 /* Compute the size of a bounding box around the origin and "set",
2891 * where "set" is assumed to contain only non-negative elements.
2892 * In particular, compute the maximal value of "set" in each direction
2893 * and add one.
2895 static __isl_give isl_multi_pw_aff *extract_size(__isl_take isl_set *set,
2896 __isl_keep isl_set *context)
2898 int i, n;
2899 isl_multi_pw_aff *mpa;
2901 n = isl_set_dim(set, isl_dim_set);
2902 mpa = isl_multi_pw_aff_zero(isl_set_get_space(set));
2903 for (i = 0; i < n; ++i) {
2904 isl_space *space;
2905 isl_aff *one;
2906 isl_pw_aff *bound;
2908 bound = isl_set_dim_max(isl_set_copy(set), i);
2909 bound = isl_pw_aff_coalesce(bound);
2910 bound = isl_pw_aff_gist(bound, isl_set_copy(context));
2912 space = isl_pw_aff_get_domain_space(bound);
2913 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
2914 one = isl_aff_add_constant_si(one, 1);
2915 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
2916 mpa = isl_multi_pw_aff_set_pw_aff(mpa, i, bound);
2918 isl_set_free(set);
2920 return mpa;
2923 /* Compute the effective grid size as a list of the sizes in each dimension.
2925 * The grid size specified by the user or set by default
2926 * in read_grid_sizes() and applied in tile_schedule(),
2927 * may be too large for the given code in the sense that
2928 * it may contain blocks that don't need to execute anything.
2929 * We therefore don't return this grid size, but instead the
2930 * smallest grid size that ensures that all blocks that actually
2931 * execute code are included in the grid.
2933 * We first extract a description of the grid, i.e., the possible values
2934 * of the block ids, from gen->tiled_sched.
2935 * The block ids are parameters in gen->tiled_sched.
2936 * We simply need to change them into set dimensions.
2938 * Then, for each block dimension, we compute the maximal value of the block id
2939 * and add one.
2941 static __isl_give isl_multi_pw_aff *extract_grid_size(struct gpu_gen *gen,
2942 struct ppcg_kernel *kernel)
2944 int i;
2945 isl_set *grid;
2947 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2948 grid = isl_set_from_params(grid);
2949 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2950 for (i = 0; i < gen->n_grid; ++i) {
2951 int pos;
2952 char name[20];
2954 snprintf(name, sizeof(name), "b%d", i);
2955 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2956 assert(pos >= 0);
2957 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2958 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2961 return extract_size(grid, kernel->context);
2964 /* Compute the size of a fixed bounding box around the origin and "set",
2965 * where "set" is assumed to contain only non-negative elements,
2966 * and store the results in "size".
2967 * In particular, compute the maximal value of "set" in each direction
2968 * and add one.
2970 static void extract_fixed_size(__isl_take isl_set *set, int *size)
2972 int i, n;
2973 isl_local_space *ls;
2974 isl_aff *obj;
2976 n = isl_set_dim(set, isl_dim_set);
2977 ls = isl_local_space_from_space(isl_set_get_space(set));
2978 obj = isl_aff_zero_on_domain(ls);
2979 for (i = 0; i < n; ++i) {
2980 isl_val *max;
2982 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 1);
2983 max = isl_set_max_val(set, obj);
2984 size[i] = isl_val_get_num_si(max) + 1;
2985 isl_val_free(max);
2986 obj = isl_aff_set_coefficient_si(obj, isl_dim_in, i, 0);
2988 isl_aff_free(obj);
2989 isl_set_free(set);
2992 /* Compute the effective block size as a list of the sizes in each dimension
2993 * and store the sizes in kernel->block_dim.
2995 * The block size specified by the user or set by default
2996 * in read_block_sizes() and applied in thread_tile_schedule(),
2997 * may be too large for the given code in the sense that
2998 * it may contain threads that don't need to execute anything.
2999 * We therefore don't store this block size in kernel->block_dim,
3000 * but instead the smallest block size that ensures that all threads
3001 * that actually execute code are included in the block.
3003 * The current implementation eliminates all parameters, ensuring
3004 * that the size is a fixed constant in each dimension.
3005 * In principle we could also compute parametric sizes.
3006 * We would have to make sure to project out all b%d and t%d parameters,
3007 * however.
3009 static void extract_block_size(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3011 int i;
3012 int nparam;
3013 isl_set *block;
3014 isl_multi_pw_aff *mpa;
3016 block = isl_union_map_params(isl_union_map_copy(gen->local_sched));
3017 block = isl_set_from_params(block);
3018 block = isl_set_add_dims(block, isl_dim_set, gen->n_block);
3019 kernel->n_block = gen->n_block;
3020 for (i = 0; i < gen->n_block; ++i) {
3021 int pos;
3022 char name[20];
3024 snprintf(name, sizeof(name), "t%d", i);
3025 pos = isl_set_find_dim_by_name(block, isl_dim_param, name);
3026 assert(pos >= 0);
3027 block = isl_set_equate(block, isl_dim_param, pos,
3028 isl_dim_set, i);
3030 nparam = isl_set_dim(block, isl_dim_param);
3031 block = isl_set_project_out(block, isl_dim_param, 0, nparam);
3033 extract_fixed_size(block, kernel->block_dim);
3036 void ppcg_kernel_free(void *user)
3038 struct ppcg_kernel *kernel = user;
3039 int i;
3041 if (!kernel)
3042 return;
3044 isl_multi_pw_aff_free(kernel->grid_size);
3045 isl_set_free(kernel->context);
3046 isl_union_set_free(kernel->arrays);
3047 isl_space_free(kernel->space);
3048 isl_ast_node_free(kernel->tree);
3050 for (i = 0; i < kernel->n_array; ++i)
3051 isl_pw_aff_list_free(kernel->array[i].bound);
3052 free(kernel->array);
3054 for (i = 0; i < kernel->n_var; ++i) {
3055 free(kernel->var[i].name);
3056 isl_vec_free(kernel->var[i].size);
3058 free(kernel->var);
3060 free(kernel);
3063 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
3064 struct ppcg_kernel_var *var)
3066 int j;
3067 struct gpu_array_tile *tile;
3068 isl_printer *p;
3069 char *name;
3071 var->array = group->array;
3073 tile = group->private_tile;
3074 var->type = ppcg_access_private;
3075 if (!tile) {
3076 tile = group->shared_tile;
3077 var->type = ppcg_access_shared;
3080 p = isl_printer_to_str(ctx);
3081 p = print_array_name(p, group);
3082 var->name = isl_printer_get_str(p);
3083 isl_printer_free(p);
3085 var->size = isl_vec_alloc(ctx, group->array->n_index);
3087 for (j = 0; j < group->array->n_index; ++j)
3088 var->size = isl_vec_set_element_val(var->size, j,
3089 isl_val_copy(tile->bound[j].size));
3092 static void create_kernel_vars(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3094 int i, j, n;
3096 n = 0;
3097 for (i = 0; i < gen->prog->n_array; ++i) {
3098 struct gpu_array_info *array = &gen->prog->array[i];
3100 for (j = 0; j < array->n_group; ++j) {
3101 struct gpu_array_ref_group *group = array->groups[j];
3102 if (group->private_tile || group->shared_tile)
3103 ++n;
3107 kernel->n_var = n;
3108 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3109 assert(kernel->var);
3111 n = 0;
3112 for (i = 0; i < gen->prog->n_array; ++i) {
3113 struct gpu_array_info *array = &gen->prog->array[i];
3115 for (j = 0; j < array->n_group; ++j) {
3116 struct gpu_array_ref_group *group = array->groups[j];
3117 if (!group->private_tile && !group->shared_tile)
3118 continue;
3119 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3120 ++n;
3125 /* The sizes of the arrays on the host that have been computed by
3126 * extract_array_info may depend on the parameters. Use the extra
3127 * constraints on the parameters that are valid at "host_domain"
3128 * to simplify these expressions and store the results in kernel->array.
3130 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3131 __isl_keep isl_set *host_domain)
3133 int i, j;
3134 isl_set *context;
3136 kernel->array = isl_calloc_array(gen->ctx,
3137 struct gpu_local_array_info, gen->prog->n_array);
3138 assert(kernel->array);
3139 kernel->n_array = gen->prog->n_array;
3141 context = isl_set_copy(host_domain);
3142 context = isl_set_params(context);
3144 for (i = 0; i < gen->prog->n_array; ++i) {
3145 struct gpu_array_info *array = &gen->prog->array[i];
3146 isl_pw_aff_list *local;
3148 if (array->n_group == 0)
3149 continue;
3151 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3153 for (j = 0; j < array->n_index; ++j) {
3154 isl_pw_aff *pwaff;
3156 pwaff = isl_pw_aff_copy(array->bound[j]);
3157 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3158 local = isl_pw_aff_list_add(local, pwaff);
3161 kernel->array[i].bound = local;
3163 isl_set_free(context);
3166 /* Find the element in gen->stmt that has the given "id".
3167 * Return NULL if no such gpu_stmt can be found.
3169 static struct gpu_stmt *find_stmt(struct gpu_prog *prog, __isl_keep isl_id *id)
3171 int i;
3173 for (i = 0; i < prog->n_stmts; ++i) {
3174 if (id == prog->stmts[i].id)
3175 break;
3178 return i < prog->n_stmts ? &prog->stmts[i] : NULL;
3181 /* Set gen->tile_len and gen->n_parallel to those of the statement
3182 * affected by the first map (part of the schedule)
3183 * on which this function is called.
3184 * Because of the way the schedule is constructed, the other statements
3185 * in the list, if any, should have the same values for these properties.
3187 static int extract_tile_len(__isl_take isl_map *map, void *user)
3189 struct gpu_gen *gen = (struct gpu_gen *) user;
3190 isl_id *id;
3191 struct gpu_stmt *stmt;
3193 id = isl_map_get_tuple_id(map, isl_dim_in);
3194 stmt = find_stmt(gen->prog, id);
3195 isl_id_free(id);
3197 isl_map_free(map);
3199 if (!stmt)
3200 isl_die(gen->ctx, isl_error_unknown,
3201 "statement not found", return -1);
3203 gen->tile_len = stmt->tile_len;
3204 gen->n_parallel = stmt->n_parallel;
3206 return -1;
3209 void ppcg_kernel_stmt_free(void *user)
3211 int i;
3212 struct ppcg_kernel_stmt *stmt = user;
3214 if (!stmt)
3215 return;
3217 switch (stmt->type) {
3218 case ppcg_kernel_copy:
3219 isl_ast_expr_free(stmt->u.c.index);
3220 isl_ast_expr_free(stmt->u.c.local_index);
3221 break;
3222 case ppcg_kernel_domain:
3223 for (i = 0; i < stmt->u.d.n_access; ++i) {
3224 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3225 free(stmt->u.d.access[i].local_name);
3227 free(stmt->u.d.access);
3228 break;
3229 case ppcg_kernel_sync:
3230 break;
3233 free(stmt);
3236 /* Set the options of "context" to
3238 * { space -> [x] : x >= first }
3240 static __isl_give isl_ast_build *set_unroll(
3241 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3242 int first)
3244 isl_ctx *ctx;
3245 isl_map *unroll;
3246 isl_union_map *opt;
3248 ctx = isl_ast_build_get_ctx(build);
3250 space = isl_space_from_domain(space);
3251 space = isl_space_add_dims(space, isl_dim_out, 1);
3252 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3253 unroll = isl_map_universe(space);
3254 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3255 opt = isl_union_map_from_map(unroll);
3257 build = isl_ast_build_set_options(build, opt);
3259 return build;
3262 /* Return a list of isl_ids of the form "prefix%d".
3264 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3265 int n, const char *prefix)
3267 int i;
3268 char name[10];
3269 isl_id_list *names;
3271 names = isl_id_list_alloc(ctx, n);
3272 for (i = 0; i < n; ++i) {
3273 isl_id *id;
3275 snprintf(name, sizeof(name), "%s%d", prefix, i);
3276 id = isl_id_alloc(ctx, name, NULL);
3277 names = isl_id_list_add(names, id);
3280 return names;
3283 /* Extend the schedule "schedule" with the part of "extension"
3284 * starting at "first" up to "len".
3286 static __isl_give isl_union_map *extend_schedule(
3287 __isl_take isl_union_map *schedule,
3288 __isl_take isl_union_map *extension, int first, int len)
3290 isl_space *space;
3291 isl_map *proj;
3292 isl_union_map *umap;
3293 isl_set *set;
3295 space = isl_union_map_get_space(schedule);
3296 space = isl_space_set_from_params(space);
3297 space = isl_space_add_dims(space, isl_dim_set, len);
3298 proj = isl_set_identity(isl_set_universe(space));
3299 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3300 extension = isl_union_map_apply_range(extension,
3301 isl_union_map_from_map(proj));
3303 schedule = isl_union_map_range_product(schedule, extension);
3305 return schedule;
3308 /* This function is called for each access to an array in each instance
3309 * in the kernel of some statement in the original code.
3310 * Replace that access by an access to global, shared or private memory
3311 * and store the results in *kernel_access.
3313 * Since the array in shared or private memory is just
3314 * a shifted copy of part of the original array, we simply need
3315 * to subtract the lower bound, which was computed in can_tile.
3316 * If any of the indices is strided, then we first add
3317 * shared_tile->bound[i].shift and divide by shared_tile->bound[i].stride.
3319 * If the given array is accessed directly from global memory,
3320 * we don't need to perform any shifting and simply simplify
3321 * the expression in the context of the domain instead.
3323 * If the array space (range of access) has no name, then we are
3324 * accessing an iterator in the original program.
3326 * The input stmt_access->access relation maps the iteration domain
3327 * of the current statement to an array element.
3328 * The first step is to reformulate
3329 * this access relation in terms of the loop iterators of the generated
3330 * code through precomposition with gen->stmt_it.
3332 * The expressions in "tile" are formulated in terms of the first
3333 * gen->shared_len dimensions of the computed schedule using the mapping
3334 * sched2shared which maps the loop iterators to these dimensions.
3336 static void compute_index_expression(struct gpu_gen *gen,
3337 struct ppcg_kernel_access *kernel_access,
3338 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3339 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3341 isl_map *access;
3342 isl_pw_multi_aff *pma;
3343 int i;
3344 unsigned n_index;
3345 struct gpu_array_tile *tile = NULL;
3347 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3348 int i;
3349 const char *name;
3350 struct gpu_array_ref_group *group;
3351 isl_printer *p;
3353 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3355 for (i = 0; i < gen->prog->n_array; ++i) {
3356 if (strcmp(name, gen->prog->array[i].name))
3357 continue;
3358 kernel_access->array = &gen->prog->array[i];
3359 kernel_access->local_array = &gen->kernel->array[i];
3361 assert(kernel_access->array);
3362 group = kernel_access->array->groups[stmt_access->group];
3363 p = isl_printer_to_str(gen->ctx);
3364 p = print_array_name(p, group);
3365 kernel_access->local_name = isl_printer_get_str(p);
3366 isl_printer_free(p);
3367 tile = group->private_tile;
3368 kernel_access->type = ppcg_access_private;
3369 if (!tile) {
3370 tile = group->shared_tile;
3371 kernel_access->type = ppcg_access_shared;
3374 if (!tile)
3375 kernel_access->type = ppcg_access_global;
3377 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3378 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3380 if (n_index == 0)
3381 return;
3383 access = isl_map_copy(stmt_access->access);
3384 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3385 pma = isl_pw_multi_aff_from_map(access);
3386 pma = isl_pw_multi_aff_coalesce(pma);
3388 for (i = 0; i < n_index; ++i) {
3389 isl_set *domain;
3390 isl_pw_aff *index;
3391 isl_ast_expr *expr;
3393 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3395 if (!kernel_access->array) {
3396 } else if (!tile) {
3397 domain = isl_map_domain(isl_map_copy(stmt_it));
3398 index = isl_pw_aff_coalesce(index);
3399 index = isl_pw_aff_gist(index, domain);
3400 } else {
3401 domain = isl_map_domain(isl_map_copy(stmt_it));
3402 index = shift_index(index, kernel_access->array,
3403 &tile->bound[i], domain,
3404 isl_map_copy(sched2shared));
3407 expr = isl_ast_build_expr_from_pw_aff(build, index);
3409 kernel_access->index = isl_ast_expr_list_add(
3410 kernel_access->index, expr);
3413 isl_pw_multi_aff_free(pma);
3416 /* This function is called for each instance of a user statement
3417 * in the kernel.
3419 * We attach a struct ppcg_kernel_stmt to the "node", containing
3420 * local information about the accesses.
3421 * This information is computed from stmt_it, which expresses the domain
3422 * elements in terms of the generated loops, and sched2shared,
3423 * which expresses the first shared_len dimensions of the schedule
3424 * computed by PPCG in terms of the generated loops.
3426 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3427 __isl_keep isl_ast_build *build, void *user)
3429 struct gpu_gen *gen = (struct gpu_gen *) user;
3430 struct ppcg_kernel_stmt *stmt;
3431 isl_id *id;
3432 isl_map *stmt_it, *sched2shared;
3433 isl_ast_expr *expr, *arg;
3434 isl_union_map *schedule;
3435 int i, n;
3436 struct gpu_stmt_access *access;
3438 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3439 if (!stmt)
3440 return isl_ast_node_free(node);
3442 expr = isl_ast_node_user_get_expr(node);
3443 arg = isl_ast_expr_get_op_arg(expr, 0);
3444 id = isl_ast_expr_get_id(arg);
3446 schedule = isl_ast_build_get_schedule(build);
3447 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3448 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3450 stmt->type = ppcg_kernel_domain;
3451 stmt->u.d.stmt = find_stmt(gen->prog, id);
3452 if (!stmt->u.d.stmt)
3453 goto error;
3455 n = 0;
3456 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3457 ++n;
3459 stmt->u.d.access = isl_calloc_array(gen->ctx,
3460 struct ppcg_kernel_access, n);
3461 if (!stmt->u.d.access)
3462 goto error;
3464 stmt->u.d.n_access = n;
3466 access = stmt->u.d.stmt->accesses;
3467 for (i = 0; i < n; ++i, access = access->next) {
3468 compute_index_expression(gen, &stmt->u.d.access[i], access,
3469 stmt_it, sched2shared, build);
3472 isl_id_free(id);
3473 isl_map_free(stmt_it);
3474 isl_map_free(sched2shared);
3475 isl_ast_expr_free(arg);
3476 isl_ast_expr_free(expr);
3478 id = isl_id_alloc(gen->ctx, NULL, stmt);
3479 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3480 return isl_ast_node_set_annotation(node, id);
3481 error:
3482 isl_id_free(id);
3483 isl_map_free(stmt_it);
3484 ppcg_kernel_stmt_free(stmt);
3485 isl_map_free(sched2shared);
3486 return isl_ast_node_free(node);
3489 /* This function is called when code has been generated for the shared
3490 * tile loops. The "schedule" refers only to the original statements.
3492 * We extend the schedule with that part of gen->local_sched that hasn't
3493 * been taken into account yet. This introduces parameters referring
3494 * to thread ids in the schedule, so we add them (with the appropriate
3495 * bounds to the context as well).
3496 * Finally, we set the appropriate unrolling options
3497 * if gen->first_unroll is set.
3499 static __isl_give isl_ast_node *create_domain_leaf(
3500 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3501 void *user)
3503 struct gpu_gen *gen = (struct gpu_gen *) user;
3504 isl_space *space;
3505 isl_union_map *sched;
3506 isl_ast_node *tree;
3507 isl_set *set;
3508 isl_id_list *iterators;
3509 int n;
3511 schedule = extend_schedule(schedule,
3512 isl_union_map_copy(gen->local_sched),
3513 gen->shared_len, gen->thread_tiled_len);
3515 space = isl_ast_build_get_schedule_space(build);
3516 set = isl_set_universe(space);
3517 set = add_bounded_parameters(set, gen->kernel->n_block,
3518 gen->kernel->block_dim, "t");
3519 build = isl_ast_build_restrict(build, set);
3521 n = gen->thread_tiled_len - gen->shared_len;
3523 if (gen->first_unroll >= 0) {
3524 space = isl_space_set_alloc(gen->ctx, 0, n);
3525 build = set_unroll(build, space, gen->first_unroll);
3527 iterators = generate_names(gen->ctx, n, "c");
3528 build = isl_ast_build_set_iterators(build, iterators);
3529 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3530 tree = isl_ast_build_ast_from_schedule(build, schedule);
3531 isl_ast_build_free(build);
3533 return tree;
3536 /* This function is called for each statement node in the AST of the code
3537 * for copying to or from shared/private memory.
3538 * Attach a pointer to a ppcg_kernel_stmt representing the copy
3539 * statement to the node.
3540 * The statement name is {read,write}_{shared,private}_<array>.
3542 * The schedule is of the form
3544 * [A -> T] -> L
3546 * where A refers to a piece of an array and T to the corresponding
3547 * shifted tile. We split this schedule into mappings L -> A and L -> T
3548 * and store the corresponding expressions in stmt->index and stmt->local_index,
3549 * where stmt points to the ppcg_kernel_stmt that is attached to the node.
3551 static __isl_give isl_ast_node *attach_copy_stmt(__isl_take isl_ast_node *node,
3552 __isl_keep isl_ast_build *build, void *user)
3554 struct gpu_gen *gen = (struct gpu_gen *) user;
3555 struct ppcg_kernel_stmt *stmt;
3556 isl_id *id;
3557 isl_ast_expr *expr;
3558 isl_space *space;
3559 isl_map *access, *local_access, *map;
3560 isl_pw_multi_aff *pma;
3561 const char *name;
3562 int array_index;
3564 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3565 if (!stmt)
3566 return isl_ast_node_free(node);
3568 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3569 name = isl_map_get_tuple_name(access, isl_dim_in);
3570 stmt->u.c.read = !strncmp(name, "read", 4);
3571 access = isl_map_reverse(access);
3572 space = isl_space_unwrap(isl_space_range(isl_map_get_space(access)));
3573 local_access = isl_map_copy(access);
3575 map = isl_map_domain_map(isl_map_universe(isl_space_copy(space)));
3576 id = isl_map_get_tuple_id(access, isl_dim_out);
3577 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3578 access = isl_map_apply_range(access, map);
3579 pma = isl_pw_multi_aff_from_map(access);
3580 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3581 stmt->u.c.index = expr;
3583 map = isl_map_range_map(isl_map_universe(space));
3584 id = isl_map_get_tuple_id(local_access, isl_dim_out);
3585 map = isl_map_set_tuple_id(map, isl_dim_in, id);
3586 local_access = isl_map_apply_range(local_access, map);
3587 pma = isl_pw_multi_aff_from_map(local_access);
3588 expr = isl_ast_build_call_from_pw_multi_aff(build, pma);
3589 stmt->u.c.local_index = expr;
3591 stmt->u.c.array = gen->copy_group->array;
3592 array_index = stmt->u.c.array - gen->prog->array;
3593 stmt->u.c.local_array = &gen->kernel->array[array_index];
3594 stmt->type = ppcg_kernel_copy;
3596 id = isl_id_alloc(gen->ctx, NULL, stmt);
3597 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3598 return isl_ast_node_set_annotation(node, id);
3601 /* Given a schedule of the form
3603 * [S -> A] -> L
3605 * (with S the first shared_len dimensions of the computed schedule,
3606 * A the array and L the schedule correponding to the generated loops),
3607 * indicating where the copying the array elements that need to be copied,
3608 * construct code for performing the copying.
3610 * "group" is the array reference group that is being copied
3611 * "type" is either "read" or "write"
3612 * private is set if copying needs to be performed to/from registers
3614 * We first construct a mapping to a shifted tile of the array,
3616 * [S -> A] -> T(S,A) (1)
3618 * If private is set, then we also use this mapping as a schedule
3619 * (which is already thread-specific and will be completely unrolled).
3620 * Otherwise, we wrap/tile the range over the threads.
3621 * The result is
3623 * [S -> A] -> T'(S,A)
3625 * Combined with the given schedule, we have
3627 * [S -> A] -> [L -> T'(S,A)] (2)
3629 * From the shifted tile mapping, we construct a mapping
3631 * [S -> A] -> [A -> T(S,A)]
3633 * and apply it to the schedule (2), obtaining
3635 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3637 * Note that we can project out S because it is uniquely defined by L.
3639 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3640 __isl_take isl_map *sched,
3641 const char *type, struct gpu_array_ref_group *group,
3642 __isl_take isl_ast_build *build, int private)
3644 const char *array_name;
3645 const char *mem = private ? "private" : "shared";
3646 char *name;
3647 isl_space *space;
3648 isl_ast_node *tree;
3649 isl_map *schedule, *shift, *map;
3650 isl_set *set;
3651 isl_id_list *iterators;
3652 int n;
3654 shift = isl_set_unwrap(isl_map_domain(isl_map_copy(sched)));
3655 array_name = isl_map_get_tuple_name(shift, isl_dim_out);
3656 shift = shift_access(shift, group);
3658 schedule = isl_map_copy(shift);
3659 if (!private)
3660 schedule = tile_access_schedule(gen, schedule);
3662 n = isl_map_dim(schedule, isl_dim_out);
3663 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3664 set = add_bounded_parameters(set, gen->kernel->n_block,
3665 gen->kernel->block_dim, "t");
3667 schedule = isl_map_range_product(sched, schedule);
3669 assert(array_name);
3670 name = isl_alloc_array(gen->ctx, char,
3671 strlen(type) + sizeof("_private_") + strlen(array_name) + 20);
3672 if (group->array->n_group > 1)
3673 sprintf(name, "%s_%s_%s_%d", type, mem, array_name, group->nr);
3674 else
3675 sprintf(name, "%s_%s_%s", type, mem, array_name);
3676 shift = isl_map_set_tuple_name(shift,
3677 isl_dim_out, name + strlen(type) + 1);
3679 space = isl_space_domain(isl_map_get_space(shift));
3680 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3681 map = isl_map_range_product(map, shift);
3683 schedule = isl_map_apply_domain(schedule, map);
3685 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, name);
3686 free(name);
3688 build = isl_ast_build_restrict(build, set);
3690 gen->copy_group = group;
3692 if (private) {
3693 space = isl_space_range(isl_map_get_space(schedule));
3694 space = isl_space_range(isl_space_unwrap(space));
3695 build = set_unroll(build, space, 0);
3697 iterators = generate_names(gen->ctx, n, "c");
3698 build = isl_ast_build_set_iterators(build, iterators);
3699 build = isl_ast_build_set_at_each_domain(build, &attach_copy_stmt, gen);
3700 tree = isl_ast_build_ast_from_schedule(build,
3701 isl_union_map_from_map(schedule));
3702 isl_ast_build_free(build);
3704 return tree;
3707 /* Return code for reading into or writing from shared memory
3708 * the given array reference group.
3710 * If we are performing a read from global memory to shared memory and
3711 * if the array involved is not a scalar, then we copy
3712 * the entire tile to shared memory. This may result in some extra
3713 * elements getting copied, but it should lead to simpler code
3714 * (which means that fewer registers may be needed) and less divergence.
3716 * Otherwise, we only copy the elements that will be read or have been written
3717 * in the kernel.
3720 * The input "sched" is of the form.
3722 * type[S -> A] -> L
3724 * with S the first shared_len dimensions of the computed schedule,
3725 * A the array and L the schedule correponding to the generated loops.
3727 * We first drop "type",
3729 * [S -> A] -> L
3731 * If the above conditions are satisfied, we project out A,
3732 * resulting in
3734 * S -> L
3736 * and then introduce the group tile [S -> T], resulting in
3738 * [S -> T] -> L
3740 static __isl_give isl_ast_node *copy_group_shared_accesses(
3741 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3742 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3744 const char *type;
3745 int read;
3746 isl_union_map *access;
3748 type = isl_map_get_tuple_name(sched, isl_dim_in);
3749 read = !strcmp(type, "read");
3751 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3753 if (read && group->array->n_index > 0) {
3754 isl_space *space;
3755 isl_map *map;
3757 space = isl_space_domain(isl_map_get_space(sched));
3758 space = isl_space_unwrap(space);
3759 map = isl_map_domain_map(isl_map_universe(space));
3760 sched = isl_map_apply_domain(sched, map);
3762 map = group_tile(group);
3763 map = isl_map_reverse(isl_map_domain_map(map));
3764 sched = isl_map_apply_domain(sched, map);
3767 return copy_access(gen, sched, type, group, build, 0);
3770 /* Return code for reading into or writing from private memory
3771 * the given array reference group.
3773 * Let S be the first shared_len dimensions of the computed schedule,
3774 * D the iteration domains, A the array and L the schedule correponding
3775 * to the generated loops.
3776 * "sched" is of the form
3778 * type[S -> A] -> L
3780 * where type is either "read" or "write".
3781 * We apply the privatization D -> S(t), with t the thread ids,
3782 * to the access relation D -> A to obtain the privatized access relation
3784 * S(t) -> A
3786 * We drop the type from "sched" and intersect with the privatized access
3787 * relation to obtain
3789 * [S(t) -> A] -> L
3791 static __isl_give isl_ast_node *copy_group_private_accesses(
3792 struct gpu_gen *gen, struct gpu_array_ref_group *group,
3793 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
3795 const char *type;
3796 int read;
3797 isl_union_map *priv;
3798 isl_union_map *access;
3799 isl_map *access_map;
3801 type = isl_map_get_tuple_name(sched, isl_dim_in);
3802 read = !strcmp(type, "read");
3804 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
3805 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
3806 priv);
3808 access = group_access_relation(group, read, !read);
3809 access = isl_union_map_apply_domain(access, priv);
3810 access_map = isl_map_from_union_map(access);
3812 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
3813 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
3815 return copy_access(gen, sched, type, group, build, 1);
3818 /* Return code for reading into or writing from shared or private memory.
3820 * "schedule" is of the form
3822 * type[S -> A] -> L
3824 * with S be the first shared_len dimensions of the computed schedule,
3825 * A the array and L the schedule correponding to the generated loops.
3826 * The array reference group is attached to "type".
3828 static __isl_give isl_ast_node *create_access_leaf(
3829 struct gpu_gen *gen, __isl_take isl_map *schedule,
3830 __isl_take isl_ast_build *build)
3832 struct gpu_array_ref_group *group;
3833 isl_id *id;
3835 id = isl_map_get_tuple_id(schedule, isl_dim_in);
3836 group = isl_id_get_user(id);
3837 isl_id_free(id);
3839 if (group->private_tile)
3840 return copy_group_private_accesses(gen, group, schedule,
3841 build);
3842 else
3843 return copy_group_shared_accesses(gen, group, schedule,
3844 build);
3847 /* Create a domain node representing a synchronization.
3849 static __isl_give isl_ast_node *create_sync_leaf(
3850 struct gpu_gen *gen, __isl_take isl_map *schedule,
3851 __isl_take isl_ast_build *build)
3853 struct ppcg_kernel_stmt *stmt;
3854 isl_id *id;
3855 isl_space *space;
3856 isl_ast_node *node;
3857 isl_ast_expr *expr;
3859 isl_map_free(schedule);
3861 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3862 if (!stmt)
3863 return NULL;
3865 stmt->type = ppcg_kernel_sync;
3867 space = isl_ast_build_get_schedule_space(build);
3868 space = isl_space_from_domain(space);
3869 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
3870 expr = isl_ast_build_call_from_pw_multi_aff(build,
3871 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3872 node = isl_ast_node_alloc_user(expr);
3873 isl_ast_build_free(build);
3875 id = isl_id_alloc(gen->ctx, NULL, stmt);
3876 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3877 return isl_ast_node_set_annotation(node, id);
3880 /* This function is called during the code generation at the point
3881 * where the schedule domain element is completely determined by
3882 * the generated code. The input schedule contains the original
3883 * statements as well as synchronization and copy "statements".
3884 * The latter are scheduled at different points than any of the original
3885 * statements, so they will only arrive here in isolation.
3887 * If the current schedule only refers to a single statement,
3888 * we check if it is a copy or synchronization statement and
3889 * call the appropriate functions.
3890 * Otherwise, we assume we are dealing with the original statements
3891 * and we call create_domain_leaf.
3893 static __isl_give isl_ast_node *create_kernel_leaf(
3894 __isl_take isl_ast_build *build, void *user)
3896 struct gpu_gen *gen = (struct gpu_gen *) user;
3897 isl_map *map;
3898 isl_union_map *schedule;
3899 const char *name;
3901 schedule = isl_ast_build_get_schedule(build);
3903 if (isl_union_map_n_map(schedule) != 1)
3904 return create_domain_leaf(schedule, build, user);
3906 map = isl_map_from_union_map(schedule);
3907 name = isl_map_get_tuple_name(map, isl_dim_in);
3908 if (!strcmp(name, "read") || !strcmp(name, "write"))
3909 return create_access_leaf(gen, map, build);
3910 if (!strcmp(name, "sync"))
3911 return create_sync_leaf(gen, map, build);
3913 return create_domain_leaf(isl_union_map_from_map(map), build, user);
3916 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
3917 * have value 0) and all even schedule dimensions as "unroll".
3919 * That is, the options look as follows
3921 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
3922 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
3924 * The even positions are used to be able to schedule copying blocks
3925 * and synchronization before or after each level of the shared memory
3926 * tile loops and we want to make sure that code for these is generated
3927 * separately (within each level).
3929 static __isl_give isl_ast_build *set_atomic_and_unroll(
3930 __isl_take isl_ast_build *build,
3931 __isl_take isl_space *space, int sched_len)
3933 isl_ctx *ctx;
3934 isl_map *map;
3935 isl_constraint *c;
3936 isl_union_map *opt;
3937 isl_local_space *ls;
3938 int i, n;
3940 ctx = isl_ast_build_get_ctx(build);
3942 space = isl_space_params(space);
3943 space = isl_space_add_dims(space, isl_dim_set, sched_len);
3944 space = isl_space_from_domain(space);
3945 space = isl_space_add_dims(space, isl_dim_out, 2);
3946 map = isl_map_universe(isl_space_copy(space));
3947 for (i = 0; i < sched_len; i += 2)
3948 map = isl_map_fix_si(map, isl_dim_in, i, 0);
3949 ls = isl_local_space_from_space(isl_map_get_space(map));
3950 c = isl_equality_alloc(ls);
3951 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3952 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3953 c = isl_constraint_set_constant_si(c, 1);
3954 map = isl_map_add_constraint(map, c);
3955 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3956 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
3957 opt = isl_union_map_from_map(map);
3959 map = isl_map_universe(space);
3960 ls = isl_local_space_from_space(isl_map_get_space(map));
3961 c = isl_equality_alloc(ls);
3962 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
3963 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
3964 map = isl_map_add_constraint(map, c);
3965 map = isl_map_project_out(map, isl_dim_out, 1, 1);
3966 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
3967 opt = isl_union_map_add_map(opt, map);
3969 build = isl_ast_build_set_options(build, opt);
3971 return build;
3974 /* Return a map that maps a space of dimension gen->shared_len
3975 * to its last dimensions starting at gen->tile_first.
3976 * The range is of dimension
3978 * 2 * (gen->shared_len - gen->tile_first) + 1
3980 * The input dimensions are mapped to the odd dimensions in the output,
3981 * while the even dimensions (except 2*pos) are fixed to 0.
3982 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
3983 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
3984 * are mapped to the output. The remaining input dimensions are projected
3985 * out and the corresponding output dimensions are fixed to 0.
3987 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
3988 __isl_take isl_space *space, int pos, int val)
3990 int i, n;
3991 isl_map *proj;
3993 space = isl_space_set_from_params(space);
3994 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
3995 space = isl_space_map_from_set(space);
3996 proj = isl_map_identity(space);
3997 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
3998 n = gen->shared_len - gen->tile_first;
3999 for (i = 0; i <= n; ++i) {
4000 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4001 if (i == pos)
4002 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4003 else
4004 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4007 if (pos < 0)
4008 return proj;
4010 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4011 gen->shared_len - (gen->tile_first + pos));
4012 for (i = pos; i < n; ++i)
4013 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4015 return proj;
4018 /* Given the AST context schedule "schedule" and the mapping from
4019 * domains to the shared tile loops "shared_sched", add a schedule
4020 * for a synchronization operation at position "val" of loop level "pos".
4022 * schedule is of the form
4024 * D -> L
4026 * (with D the iteration domains and L the already generated loops),
4027 * while shared_sched is of the form
4029 * D -> S
4031 * We combine them into
4033 * L -> S
4035 * apply a mapping
4037 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4039 * and use the result as a schedule for "sync".
4041 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4042 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4043 __isl_keep isl_union_map *shared_sched, int pos, int val)
4045 isl_space *space;
4046 isl_map *proj, *map;
4048 shared_sched = isl_union_map_copy(shared_sched);
4049 schedule = isl_union_map_copy(schedule);
4051 space = isl_union_map_get_space(shared_sched);
4052 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4053 map = isl_map_from_union_map(schedule);
4055 proj = insert_even(gen, space, pos, val);
4056 map = isl_map_apply_range(map, proj);
4057 map = isl_map_from_range(isl_map_wrap(map));
4058 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4060 res = isl_union_map_add_map(res, map);
4062 return res;
4065 /* Given the AST context schedule "schedule" and the mapping from
4066 * domains to the shared tile loops "shared_sched", add a schedule
4067 * for copying an array reference group to/from shared/private memory.
4068 * "read" is set if data should be copied from global memory
4069 * to shared/private memory.
4070 * "k" represents the current group
4071 * "s" is the total number of groups
4073 * We schedule an operation before or after the innermost loop
4074 * of "shared_sched" that affects the tile of the array reference group.
4076 * schedule is of the form
4078 * D -> L
4080 * (with D the iteration domains and L the already generated loops),
4081 * while shared_sched is of the form
4083 * D -> S
4085 * We first compute the access relation for the reference group
4087 * D -> A
4089 * and combine it with shared_sched into
4091 * D -> [S -> A]
4093 * If this results in an empty relation, no copying needs to be performed
4094 * at this point.
4095 * Otherwise, we invert the relation and combine it with "schedule" into
4097 * [S -> A] -> L
4099 * The actual additional piece of the schedule is obtained from combining
4101 * [S -> A] -> S
4103 * with a mapping
4105 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4107 * The position of "val" corresponds to the innermost loop that affects
4108 * the tile and the value indicates where the copying is scheduled
4109 * with respect to the actual kernel code (at value 0).
4110 * Reads are schedule before the code, writes to global memory from
4111 * private memory are scheduled at values 1 to s, writes to global
4112 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4114 * If we are scheduling a read from global memory to shared memory,
4115 * we insert a synchronization before the kernel code (at the innermost
4116 * level).
4117 * If we are scheduling a write to global memory, then we add
4118 * a synchronization after all writes (at value 2 *s + 2).
4119 * However, there is no need for a synchronization after the outermost loop.
4120 * A write to global memory from private memory at the innermost level
4121 * does not require a synchronization, because it is covered by
4122 * the synchronization after the kernel inserted by body_schedule.
4124 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4125 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4126 __isl_keep isl_union_map *shared_sched,
4127 struct gpu_array_ref_group *group, int read, int k, int s)
4129 int n;
4130 int pos, val;
4131 isl_space *space;
4132 isl_union_map *access;
4133 isl_map *map, *proj, *access_map;
4134 isl_id *id;
4136 access = group_access_relation(group, read, !read);
4137 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4138 access);
4140 if (isl_union_map_is_empty(access)) {
4141 isl_union_map_free(access);
4142 return res;
4145 access = isl_union_map_reverse(access);
4146 access = isl_union_map_apply_range(access,
4147 isl_union_map_copy(schedule));
4148 access_map = isl_map_from_union_map(access);
4150 space = isl_space_copy(group->array->dim);
4151 space = isl_space_from_range(space);
4152 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4153 map = isl_map_domain_map(isl_map_universe(space));
4155 space = isl_union_map_get_space(schedule);
4156 pos = group->last_shared + 1 - gen->tile_first;
4157 assert(pos >= 0);
4158 if (read)
4159 val = -2 - k;
4160 else if (group->private_tile)
4161 val = 1 + k;
4162 else
4163 val = 1 + s + 1 + k;
4164 proj = insert_even(gen, space, pos, val);
4165 map = isl_map_apply_range(map, proj);
4167 access_map = isl_map_range_product(access_map, map);
4169 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4170 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4172 res = isl_union_map_add_map(res, access_map);
4174 n = gen->shared_len - gen->tile_first;
4175 if (read) {
4176 if (!group->private_tile)
4177 res = add_sync_schedule(gen, res, schedule,
4178 shared_sched, n, -1);
4179 } else {
4180 if (pos == 0)
4181 return res;
4182 if (pos == n && group->private_tile)
4183 return res;
4184 res = add_sync_schedule(gen, res, schedule, shared_sched,
4185 pos, 2 * s + 2);
4188 return res;
4191 /* Return a schedule for the shared tile loops based on the current
4192 * AST context schedule.
4194 * We create a "shared_sched" that maps the domains to the first
4195 * shared_len dimensions of the computed schedule, project out the
4196 * first tile_first dimensions (as these are already covered by
4197 * the host code) and insert "statement-level" dimensions at even
4198 * positions so that we can schedule copy blocks and synchronization
4199 * before/after each level.
4201 * In particular, copy blocks are inserted inside the innermost
4202 * level that affect the tile. For the copying to global memory,
4203 * those from private memory are scheduled before those from shared
4204 * memory such that synchronization can be inserted between the two
4205 * at the innermost level.
4206 * Synchronization is inserted at the innermost level before the
4207 * actual kernel code if there is any copying from global memory
4208 * to shared memory. It is inserted unconditionally at the innermost
4209 * level after the actual kernel code and the copying to global memory
4210 * from private memory (if any). Finally, it is inserted after
4211 * any copying to global memory, except at the outermost level
4212 * and at the innermost level if there is no copying from shared
4213 * memory. The copying from private memory is covered by the unconditional
4214 * synchronization at the innermost level.
4216 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4217 __isl_take isl_union_map *schedule)
4219 isl_space *space;
4220 isl_union_map *res;
4221 isl_union_map *shared_sched;
4222 isl_union_map *sched;
4223 isl_map *proj, *map;
4224 int i, j, k, s;
4226 shared_sched = isl_union_map_copy(gen->tiled_sched);
4227 proj = projection(isl_union_map_get_space(shared_sched),
4228 gen->tiled_len, gen->shared_len);
4229 shared_sched = isl_union_map_apply_range(shared_sched,
4230 isl_union_map_from_map(proj));
4231 space = isl_union_map_get_space(shared_sched);
4232 proj = insert_even(gen, space, -1, 0);
4233 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4234 isl_union_map_from_map(proj));
4236 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4238 s = 0;
4239 for (i = 0; i < gen->prog->n_array; ++i)
4240 s += gen->prog->array[i].n_group;
4242 k = 0;
4243 for (i = 0; i < gen->prog->n_array; ++i) {
4244 struct gpu_array_info *array = &gen->prog->array[i];
4246 for (j = 0; j < array->n_group; ++j) {
4247 struct gpu_array_ref_group *group;
4249 group = array->groups[j];
4250 if (!group->private_tile && !group->shared_tile)
4251 continue;
4252 res = add_group_schedule(gen, res, schedule,
4253 shared_sched, group, 0, k, s);
4254 res = add_group_schedule(gen, res, schedule,
4255 shared_sched, group, 1, k, s);
4256 ++k;
4260 res = add_sync_schedule(gen, res, schedule, shared_sched,
4261 gen->shared_len - gen->tile_first, 1 + s);
4263 isl_union_map_free(shared_sched);
4264 isl_union_map_free(schedule);
4266 return res;
4269 /* Generate code for "kernel" in the given "context".
4271 * We first generate code for the shared tile loops (T1T, T1P and T2)
4272 * in a context that includes the block ids.
4273 * Within each iteration of these loops an additional code generation
4274 * is performed (within create_kernel_leaf) for the rest of the schedule
4275 * in a context that includes the thread ids.
4277 static __isl_give isl_ast_node *generate_kernel(struct gpu_gen *gen,
4278 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain,
4279 __isl_keep isl_multi_pw_aff *grid_size)
4281 isl_space *space;
4282 isl_set *set;
4283 isl_id_list *iterators;
4284 isl_union_map *schedule;
4285 isl_ast_node *tree;
4286 int sched_len;
4288 schedule = isl_ast_build_get_schedule(build);
4290 build = isl_ast_build_copy(build);
4291 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4292 space = isl_ast_build_get_schedule_space(build);
4293 set = isl_set_universe(isl_space_copy(space));
4294 set = add_bounded_parameters_dynamic(set, grid_size, "b");
4295 build = isl_ast_build_restrict(build, set);
4297 schedule = body_schedule(gen, schedule);
4299 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4301 build = set_atomic_and_unroll(build, space, sched_len);
4302 iterators = generate_names(gen->ctx, sched_len, "g");
4303 build = isl_ast_build_set_iterators(build, iterators);
4304 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4305 tree = isl_ast_build_ast_from_schedule(build, schedule);
4306 isl_ast_build_free(build);
4308 return tree;
4311 /* Attach "id" to the given node.
4313 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4314 __isl_keep isl_ast_build *build, void *user)
4316 isl_id *id = user;
4318 node = isl_ast_node_set_annotation(node, id);
4320 return node;
4323 /* Construct an AST node for performing a kernel launch and attach
4324 * the information about the kernel to that node.
4326 * The kernel AST has been constructed in the context of the range
4327 * of "schedule". In particular, the grid size has been computed
4328 * in the context. We therefore still need to make sure that these
4329 * constraints are expressed in the code. We do this by creating a schedule
4331 * kernel[] -> [S -> []]
4333 * where S is the schedule domain, i.e., the range of "schedule".
4334 * The AST generation will then create a single call surrounded by
4335 * all the condition in "S" that have not been expressed yet.
4337 * The kernel information is attached to this node in attach_id.
4339 static __isl_give isl_ast_node *construct_launch(
4340 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4341 __isl_take struct ppcg_kernel *kernel)
4343 isl_id *id;
4344 isl_ctx *ctx;
4345 isl_union_set *domain;
4346 isl_set *set;
4347 isl_map *map;
4348 isl_ast_node *node;
4350 ctx = isl_ast_build_get_ctx(build);
4352 id = isl_id_alloc(ctx, NULL, kernel);
4353 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4355 domain = isl_union_map_range(schedule);
4356 set = isl_set_from_union_set(domain);
4357 map = isl_map_from_domain(set);
4358 map = isl_map_from_range(isl_map_wrap(map));
4359 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4360 schedule = isl_union_map_from_map(map);
4362 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4363 node = isl_ast_build_ast_from_schedule(build, schedule);
4364 isl_ast_build_free(build);
4366 return node;
4369 /* This function is called for each leaf in the AST of the host code.
4370 * We first specialize the schedule to the site of the leaf, compute
4371 * the size of shared memory and then construct the body of host code
4372 * and the associated kernel.
4374 * The necessary information for printing the kernel launch is
4375 * stored in a struct ppcg_kernel and attached to the leaf node
4376 * created to represent the launch.
4378 static __isl_give isl_ast_node *create_host_leaf(
4379 __isl_take isl_ast_build *build, void *user)
4381 struct gpu_gen *gen = (struct gpu_gen *) user;
4382 isl_id *id;
4383 isl_ast_node *node;
4384 struct ppcg_kernel *kernel;
4385 isl_set *host_domain;
4386 isl_union_map *schedule;
4387 isl_union_map *local_sched;
4388 isl_union_map *access;
4389 isl_union_set *domain;
4390 int i;
4392 schedule = isl_ast_build_get_schedule(build);
4394 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4395 read_sizes(gen);
4397 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4399 local_sched = isl_union_map_copy(gen->sched);
4400 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4401 access = isl_union_map_union(isl_union_map_copy(gen->prog->read),
4402 isl_union_map_copy(gen->prog->write));
4403 access = isl_union_map_apply_domain(access,
4404 isl_union_map_copy(local_sched));
4406 gen->tiled_sched = tile_schedule(gen, local_sched);
4407 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4408 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4410 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4411 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4412 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4414 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4415 if (!kernel)
4416 goto error;
4418 kernel->id = gen->kernel_id++;
4419 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4420 kernel->grid_size = extract_grid_size(gen, kernel);
4421 extract_block_size(gen, kernel);
4422 kernel->arrays = isl_union_map_range(access);
4423 kernel->space = isl_ast_build_get_schedule_space(build);
4425 gen->private_access = NULL;
4426 compute_shared_sched(gen);
4427 gen->privatization = compute_privatization(gen);
4428 group_references(gen);
4429 compute_private_access(gen);
4430 check_shared_memory_bound(gen);
4431 host_domain = isl_set_from_union_set(isl_union_map_range(
4432 isl_union_map_copy(schedule)));
4433 localize_bounds(gen, kernel, host_domain);
4435 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4437 kernel->tree = generate_kernel(gen, build, host_domain,
4438 kernel->grid_size);
4439 create_kernel_vars(gen, kernel);
4441 free_local_array_info(gen);
4442 isl_map_free(gen->privatization);
4443 isl_union_map_free(gen->private_access);
4444 isl_union_map_free(gen->local_sched);
4445 isl_union_map_free(gen->tiled_sched);
4446 isl_union_map_free(gen->shared_sched);
4447 isl_union_map_free(gen->shared_proj);
4448 isl_set_free(host_domain);
4449 free(gen->tile_size);
4451 node = construct_launch(build, schedule, kernel);
4453 return node;
4454 error:
4455 isl_union_map_free(schedule);
4456 return NULL;
4459 /* Use isl to generate code for the outer gen->tile_first loops
4460 * of the global schedule in gen->sched, resulting in the host code.
4461 * Within each iteration of this partial schedule, i.e., for each kernel
4462 * launch, create_host_leaf takes care of generating the kernel code.
4464 static __isl_give isl_ast_node *generate_host_code(struct gpu_gen *gen)
4466 isl_ast_build *build;
4467 isl_ast_node *tree;
4468 isl_union_map *sched;
4469 isl_map *proj;
4470 isl_id_list *iterators;
4472 sched = isl_union_map_copy(gen->sched);
4473 proj = projection(isl_union_map_get_space(sched),
4474 gen->untiled_len, gen->tile_first);
4475 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
4477 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
4478 build = isl_ast_build_from_context(isl_set_copy(gen->prog->context));
4479 iterators = generate_names(gen->ctx, gen->tile_first, "h");
4480 build = isl_ast_build_set_iterators(build, iterators);
4481 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
4482 tree = isl_ast_build_ast_from_schedule(build, sched);
4483 isl_ast_build_free(build);
4485 return tree;
4488 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
4490 if (!str)
4491 return NULL;
4492 return isl_union_map_read_from_str(ctx, str);
4495 /* Information about the outermost tilable bands in the forest of bands.
4497 * tile_len and n_parallel are only sets on band_info structures
4498 * that correspond to outermost bands. For other bands (in particular,
4499 * ancestors of the outermost bands), n_parallal is set to 0.
4501 * prefix is the (padded) schedule leading up to the outermost tilable bands.
4503 * tile_first is the number of schedule dimensions in prefix.
4505 * suffix is the schedule of the outermost tilable bands and their descendants.
4507 struct band_info {
4508 struct gpu_gen *gen;
4509 int tile_first;
4510 int tile_len;
4511 int n_parallel;
4512 isl_union_map *prefix;
4513 isl_union_map *suffix;
4516 /* Set tile_len and n_parallel of the statement to that of
4517 * their outermost band, recorded in the band_info.
4519 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
4521 struct band_info *info = user;
4522 struct gpu_stmt *stmt;
4523 isl_id *id;
4525 id = isl_map_get_tuple_id(map, isl_dim_in);
4526 stmt = find_stmt(info->gen->prog, id);
4527 isl_id_free(id);
4529 stmt->tile_len = info->tile_len;
4530 stmt->n_parallel = info->n_parallel;
4532 isl_map_free(map);
4534 return 0;
4537 static void list_select_outer_band(struct gpu_gen *gen,
4538 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
4540 /* Check if this band has any parallel loops. If so, take it as
4541 * the outermost tilable band. If not, continue looking for the
4542 * outermost tilable band in the children of the current band.
4544 static void band_select_outer_band(struct gpu_gen *gen,
4545 __isl_take isl_band *band, int pos, struct band_info *info)
4547 int n = isl_band_n_member(band);
4548 int n_parallel;
4550 for (n_parallel = 0; n_parallel < n; ++n_parallel)
4551 if (!isl_band_member_is_zero_distance(band, n_parallel))
4552 break;
4554 info->n_parallel = n_parallel;
4555 if (n_parallel) {
4556 info->gen = gen;
4557 info->tile_first = pos;
4558 info->tile_len = n;
4559 info->prefix = isl_band_get_prefix_schedule(band);
4560 info->suffix = isl_union_map_flat_range_product(
4561 isl_band_get_partial_schedule(band),
4562 isl_band_get_suffix_schedule(band));
4563 isl_union_map_foreach_map(info->prefix,
4564 &set_stmt_tile_len, info);
4565 } else if (isl_band_has_children(band)) {
4566 isl_band_list *children;
4567 children = isl_band_get_children(band);
4568 list_select_outer_band(gen, children, pos + n, info);
4569 } else {
4570 info->gen = gen;
4571 info->tile_first = pos + n;
4572 info->tile_len = 0;
4573 info->prefix = isl_union_map_flat_range_product(
4574 isl_band_get_prefix_schedule(band),
4575 isl_band_get_partial_schedule(band));
4576 info->suffix = isl_band_get_suffix_schedule(band);
4577 isl_union_map_foreach_map(info->prefix,
4578 &set_stmt_tile_len, info);
4581 isl_band_free(band);
4584 /* Comparison function that returns a non-zero value for band_infos
4585 * with different tile_len fields or different n_parallel fields.
4587 static int cmp_band(const void *p1, const void *p2)
4589 const struct band_info *info1 = p1;
4590 const struct band_info *info2 = p2;
4592 if (info1->tile_len != info2->tile_len)
4593 return info1->tile_len - info2->tile_len;
4595 return info1->n_parallel - info2->n_parallel;
4598 /* Extend "umap" with coordinates with fixed value "val"
4599 * to a total length of "dst_len", assuming the original dimension is "src_len".
4601 static __isl_give isl_union_map *extend_range(
4602 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
4604 isl_space *dim;
4605 isl_map *map;
4606 int i;
4608 dim = isl_union_map_get_space(umap);
4609 map = isl_map_reverse(projection(dim, dst_len, src_len));
4610 for (i = src_len; i < dst_len; ++i)
4611 map = isl_map_fix_si(map, isl_dim_out, i, val);
4613 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
4615 return umap;
4618 /* Group bands with the same values for tile_len and n_parallel.
4619 * The prefix schedule is then extended with a fixed coordinate that
4620 * is different for each such group.
4621 * Note that the actual values for this coordinate are not important.
4622 * The bands have already been effectively separated at a higher level
4623 * or they are independent and may be executed in parallel.
4624 * The list of band_info has been sorted before this functions is called.
4626 static void separate_bands(struct band_info *info, int n)
4628 int i;
4629 int j = 0;
4631 for (i = 0; i < n; ++i) {
4632 int l = info[i].tile_first;
4634 if (i &&
4635 (info[i].tile_len != info[i - 1].tile_len ||
4636 info[i].n_parallel != info[i - 1].n_parallel))
4637 j++;
4639 info[i].prefix = extend_range(info[i].prefix,
4640 l, l + 1, j);
4641 info[i].tile_first = l + 1;
4645 /* Select the outermost bands in the elements of the list, align
4646 * their prefix schedules, separate bands with different values
4647 * for tile_len and/or n_parallel and then combine the resulting
4648 * prefix and suffix schedules into a single pair of prefix and
4649 * suffix schedules for the entire list.
4651 static void list_select_outer_band(struct gpu_gen *gen,
4652 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
4654 isl_band *band;
4655 int i;
4656 int n = isl_band_list_n_band(list);
4657 isl_ctx *ctx = isl_band_list_get_ctx(list);
4658 struct band_info *info;
4659 int max_tile_first;
4660 isl_union_map *prefix;
4661 isl_union_map *suffix;
4663 assert(n >= 1);
4664 info = isl_calloc_array(ctx, struct band_info, n);
4665 assert(info);
4667 max_tile_first = 0;
4668 for (i = 0; i < n; ++i) {
4669 band = isl_band_list_get_band(list, i);
4670 band_select_outer_band(gen, band, pos, &info[i]);
4671 if (info[i].tile_first > max_tile_first)
4672 max_tile_first = info[i].tile_first;
4675 for (i = 0; i < n; ++i) {
4676 if (info[i].tile_first == max_tile_first)
4677 continue;
4678 info[i].prefix = extend_range(info[i].prefix,
4679 info[i].tile_first, max_tile_first, 0);
4680 info[i].tile_first = max_tile_first;
4683 qsort(info, n, sizeof(struct band_info), &cmp_band);
4685 for (i = 0; i < n - 1; ++i)
4686 if (info[i].tile_len != info[i + 1].tile_len ||
4687 info[i].n_parallel != info[i + 1].n_parallel)
4688 break;
4690 if (i < n -1)
4691 separate_bands(info, n);
4693 prefix = info[0].prefix;
4694 suffix = info[0].suffix;
4696 for (i = 1; i < n; ++i) {
4697 prefix = isl_union_map_union(prefix, info[i].prefix);
4698 suffix = isl_union_map_union(suffix, info[i].suffix);
4701 list_info->tile_first = info[0].tile_first;
4702 list_info->tile_len = -1;
4703 list_info->prefix = prefix;
4704 list_info->suffix = suffix;
4706 isl_band_list_free(list);
4707 free(info);
4710 /* Select the outermost tilable band that (by construction)
4711 * has at least one parallel loop.
4712 * The starting position of the aligned band is stored in the pair
4713 * gen->tile_first.
4714 * The sizes and number of parallel loops may be different in different
4715 * parts of the band forest and are therefore stored in the gpu_stmts.
4717 * Return the complete schedule, with the tilable bands aligned
4718 * at gen->tile_first and padded with zero, if needed.
4720 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
4721 __isl_keep isl_schedule *schedule)
4723 isl_band_list *list;
4724 struct band_info info;
4726 gen->n_parallel = 0;
4727 gen->tile_len = -1;
4729 list = isl_schedule_get_band_forest(schedule);
4731 list_select_outer_band(gen, list, 0, &info);
4733 gen->tile_first = info.tile_first;
4734 info.suffix = align_range(info.suffix);
4736 return isl_union_map_flat_range_product(info.prefix, info.suffix);
4739 /* Set gen->untiled_len to the number of scheduling dimensions
4740 * for the schedule of the first domain.
4741 * We assume here that this number is the same for all domains.
4743 static int set_untiled_len(__isl_take isl_map *map, void *user)
4745 unsigned *untiled_len = user;
4747 *untiled_len = isl_map_dim(map, isl_dim_out);
4749 isl_map_free(map);
4750 return -1;
4753 /* Compute an appropriate schedule based on the accesses in
4754 * gen->read and gen->write.
4756 * We use the dependences in gen->prog->scop to compute
4757 * a schedule that has a parallel loop in each tilable band.
4758 * Finally, we select the outermost tilable band.
4760 static void compute_schedule(struct gpu_gen *gen)
4762 isl_union_set *domain;
4763 isl_union_map *dep_raw, *dep;
4764 isl_union_map *sched;
4765 isl_schedule *schedule;
4767 dep_raw = isl_union_map_copy(gen->prog->scop->dep_flow);
4769 dep = isl_union_map_copy(gen->prog->scop->dep_false);
4770 dep = isl_union_map_union(dep, dep_raw);
4771 dep = isl_union_map_coalesce(dep);
4773 domain = isl_union_set_copy(gen->prog->scop->domain);
4774 domain = isl_union_set_intersect_params(domain,
4775 isl_set_copy(gen->prog->scop->context));
4776 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
4777 isl_union_map_copy(dep), dep);
4778 if (gen->options->debug->dump_schedule)
4779 isl_schedule_dump(schedule);
4781 sched = select_outer_tilable_band(gen, schedule);
4783 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
4784 sched = isl_union_map_intersect_domain(sched, domain);
4785 gen->sched = sched;
4787 isl_schedule_free(schedule);
4790 /* Compute the sets of array elements that need to be copied in and out.
4792 * In particular, for each array that is written anywhere in gen->prog and
4793 * that is visible outside the corresponding scop, we copy out its entire
4794 * extent.
4796 * Any array elements that is read without first being written needs
4797 * to be copied in. Furthermore, if there are any array elements that
4798 * are copied out, but that are not written inside gen->prog, then
4799 * they also need to be copied in to ensure that the value after execution
4800 * is the same as the value before execution.
4801 * While computing the set of array elements that
4802 * are copied out but not written, we intersect both sets with the context.
4803 * This helps in those cases where the arrays are declared with a fixed size,
4804 * while the accesses are parametric and the context assigns a fixed value
4805 * to the parameters.
4807 static void compute_copy_in_and_out(struct gpu_gen *gen)
4809 int i;
4810 isl_union_set *write;
4811 isl_union_set *copy_in, *copy_out;
4812 isl_union_set *not_written;
4813 isl_union_map *uninitialized;
4815 write = isl_union_map_range(isl_union_map_copy(gen->prog->write));
4816 write = isl_union_set_intersect_params(write,
4817 isl_set_copy(gen->prog->context));
4818 copy_out = isl_union_set_empty(isl_union_set_get_space(write));
4820 for (i = 0; i < gen->prog->n_array; ++i) {
4821 isl_space *space;
4822 isl_set *write_i;
4823 int empty;
4825 if (gen->prog->array[i].local)
4826 continue;
4828 space = isl_space_copy(gen->prog->array[i].dim);
4829 write_i = isl_union_set_extract_set(write, space);
4830 empty = isl_set_fast_is_empty(write_i);
4831 isl_set_free(write_i);
4832 if (empty)
4833 continue;
4835 write_i = isl_set_copy(gen->prog->array[i].extent);
4836 copy_out = isl_union_set_add_set(copy_out, write_i);
4839 copy_out = isl_union_set_intersect_params(copy_out,
4840 isl_set_copy(gen->prog->context));
4842 gen->prog->copy_out = isl_union_set_copy(copy_out);
4844 uninitialized = isl_union_map_copy(gen->prog->scop->live_in);
4845 copy_in = isl_union_map_range(uninitialized);
4847 not_written = isl_union_set_subtract(copy_out, write);
4848 copy_in = isl_union_set_union(copy_in, not_written);
4849 gen->prog->copy_in = copy_in;
4852 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
4853 struct gpu_stmt_access **next_access)
4855 struct gpu_stmt_access *access;
4856 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
4858 access = isl_alloc_type(ctx, struct gpu_stmt_access);
4859 assert(access);
4860 access->next = NULL;
4861 access->read = expr->acc.read;
4862 access->write = expr->acc.write;
4863 access->access = isl_map_copy(expr->acc.access);
4865 *next_access = access;
4866 next_access = &(*next_access)->next;
4867 return next_access;
4870 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
4871 struct gpu_stmt_access **next_access)
4873 int i;
4875 for (i = 0; i < expr->n_arg; ++i)
4876 next_access = expr_extract_accesses(expr->args[i],
4877 next_access);
4879 if (expr->type == pet_expr_access)
4880 next_access = expr_extract_access(expr, next_access);
4882 return next_access;
4885 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
4887 struct gpu_stmt_access **next_access = &stmt->accesses;
4889 stmt->accesses = NULL;
4890 expr_extract_accesses(stmt->body, next_access);
4893 /* Return an array of gpu_stmt representing the statements in "scop".
4895 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct ppcg_scop *scop,
4896 __isl_keep isl_set *context)
4898 int i;
4899 struct gpu_stmt *stmts;
4901 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
4902 if (!stmts)
4903 return NULL;
4905 for (i = 0; i < scop->n_stmt; ++i) {
4906 struct gpu_stmt *s = &stmts[i];
4908 s->id = isl_set_get_tuple_id(scop->stmts[i]->domain);
4909 s->body = scop->stmts[i]->body;
4910 pet_stmt_extract_accesses(s);
4913 return stmts;
4916 /* Replace the scop in the "input" file by equivalent code
4917 * that uses the GPU and print the result to "out".
4918 * "scop" is assumed to correspond to this scop.
4919 * The code before the scop is first copied to "out",
4920 * then the transformed scop is printed and finally
4921 * the code after the scop is copied to "out".
4922 * After generating an AST for the transformed scop as explained below,
4923 * we call "print" to print the AST in the desired output format
4924 * to a printer hooked up to "out".
4926 * We first compute a schedule that respects the dependences
4927 * of the original program and select the outermost band
4928 * of tilable dimensions that has at least one parallel loop.
4929 * We then have three blocks of dimensions
4931 * H B G
4933 * The tilable band "B" is first tiled according to "tile" sizes, resulting
4934 * in
4936 * H T P G
4938 * For each iteration of the T loop and for each array, we compute
4939 * the array elements accessed by that iteration, construct a rectangular
4940 * box around it and shift it to the origin. The result is used
4941 * as shared memory for the array.
4943 * We then split off at most 2 parallel loops from the T loops and
4944 * at most 3 parallel loops from the P loops
4946 * H T1 T2 P1 P2 G
4948 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
4949 * according to "grid"/"block" sizes.
4951 * H T1T T1P T2 P1T P1P P2 G
4953 * Finally, the T1P and P1P iterators are equated to the block and
4954 * thread dimensions respectively and so are effectively removed.
4955 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
4956 * are run on the GPU.
4958 * Code is generated in three stages. We first generate code for the
4959 * host (the H loops), with iterators h%d. Then, for each leaf node
4960 * of the resulting AST, we generate code for the shared loops (up to
4961 * and including T2), with iterators g%d and after equating the H loops
4962 * to h%d parameters and the T1P loops to the block dimensions.
4963 * Finally, we generate code for the remaining loops in a similar fashion.
4965 int generate_gpu(isl_ctx *ctx, const char *input, FILE *out,
4966 struct ppcg_scop *scop, struct ppcg_options *options,
4967 __isl_give isl_printer *(*print)(__isl_take isl_printer *p,
4968 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
4969 void *user), void *user)
4971 struct gpu_gen gen;
4972 struct gpu_prog *prog;
4973 isl_ast_node *tree;
4974 isl_printer *p;
4975 FILE *in;
4977 if (!scop)
4978 return -1;
4980 in = fopen(input, "r");
4981 copy(in, out, 0, scop->start);
4983 prog = gpu_prog_alloc(ctx, scop);
4984 if (!prog)
4985 return -1;
4987 p = isl_printer_to_file(ctx, out);
4988 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
4990 gen.ctx = ctx;
4991 gen.prog = prog;
4992 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
4993 gen.options = options;
4995 compute_schedule(&gen);
4996 compute_copy_in_and_out(&gen);
4998 gen.kernel_id = 0;
4999 tree = generate_host_code(&gen);
5000 p = ppcg_print_exposed_declarations(p, prog->scop);
5001 p = print(p, prog, tree, user);
5002 isl_ast_node_free(tree);
5004 clear_gpu_gen(&gen);
5006 isl_printer_free(p);
5008 gpu_prog_free(prog);
5010 copy(in, out, scop->end, -1);
5011 fclose(in);
5013 return p ? 0 : -1;
5016 struct gpu_prog *gpu_prog_alloc(isl_ctx *ctx, struct ppcg_scop *scop)
5018 struct gpu_prog *prog;
5020 if (!scop)
5021 return NULL;
5023 prog = isl_calloc_type(ctx, struct gpu_prog);
5024 assert(prog);
5026 prog->ctx = ctx;
5027 prog->scop = scop;
5028 prog->context = isl_set_copy(scop->context);
5029 prog->n_stmts = scop->n_stmt;
5030 prog->stmts = extract_stmts(ctx, scop, prog->context);
5031 prog->read = isl_union_map_copy(scop->reads);
5032 prog->write = isl_union_map_copy(scop->writes);
5034 if (!prog->stmts)
5035 return gpu_prog_free(prog);
5037 collect_array_info(prog);
5039 return prog;
5042 void *gpu_prog_free(struct gpu_prog *prog)
5044 if (!prog)
5045 return NULL;
5046 free_array_info(prog);
5047 free_stmts(prog->stmts, prog->n_stmts);
5048 isl_union_set_free(prog->copy_in);
5049 isl_union_set_free(prog->copy_out);
5050 isl_union_map_free(prog->read);
5051 isl_union_map_free(prog->write);
5052 isl_set_free(prog->context);
5053 free(prog);
5054 return NULL;