gpu.c: keep track of local kernel variables in ppcg_kernel
[ppcg.git] / gpu.c
blobbf133b6ba4655530a3d8ffd56ed5a2ea7b8d9dc4
1 /*
2 * Copyright 2010-2011 INRIA Saclay
3 * Copyright 2012 Ecole Normale Superieure
5 * Use of this software is governed by the GNU LGPLv2.1 license
7 * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8 * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9 * 91893 Orsay, France
10 * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
13 #include <assert.h>
14 #include <stdlib.h>
16 #include <isl/polynomial.h>
17 #include <isl/union_set.h>
18 #include <isl/aff.h>
19 #include <isl/ilp.h>
20 #include <isl/flow.h>
21 #include <isl/band.h>
22 #include <isl/schedule.h>
23 #include <isl/options.h>
24 #include <isl/ast_build.h>
26 #include "gpu.h"
27 #include "cuda_common.h"
28 #include "schedule.h"
29 #include "pet_printer.h"
30 #include "ppcg_options.h"
32 static void print_indent(FILE *dst, int indent)
34 fprintf(dst, "%*s", indent, "");
37 /* The fields stride, shift and shift_map only contain valid information
38 * if shift != NULL.
39 * If so, they express that current index is such that if you add shift,
40 * then the result is always a multiple of stride.
41 * shift_map contains the mapping
43 * i -> (i + shift)/stride
45 * Let D represent the initial shared_len dimensions of the computed schedule.
46 * The spaces of "lb" and "shift" are of the form
48 * D -> [b]
50 * "shift_map" is of the form
52 * [D -> i] -> [D -> (i + shift(D))/stride]
54 struct gpu_array_bound {
55 isl_int size;
56 isl_aff *lb;
58 isl_int stride;
59 isl_aff *shift;
60 isl_basic_map *shift_map;
63 struct gpu_array_info;
65 /* A group of array references in a kernel that should be handled together.
66 * If private_bound is not NULL, then it is mapped to registers.
67 * Otherwise, if shared_bound is not NULL, it is mapped to shared memory.
68 * Otherwise, it is accessed from global memory.
70 struct gpu_array_ref_group {
71 /* The references in this group access this array. */
72 struct gpu_array_info *array;
73 /* Position of this group in the list of reference groups of array. */
74 int nr;
76 /* The following fields are use during the construction of the groups.
77 * access is the combined access relation relative to the shared
78 * memory tiling. In particular, the domain of the map corresponds
79 * to the first shared_len dimensions of the computed schedule.
80 * write is set if any access in the group is a write.
82 isl_map *access;
83 int write;
85 /* For each index, size and offset of piece in shared memory. */
86 struct gpu_array_bound *shared_bound;
88 /* For each index, size and offset of piece in private memory. */
89 struct gpu_array_bound *private_bound;
91 /* References in this group; point to elements of a linked list. */
92 int n_ref;
93 struct gpu_stmt_access **refs;
95 /* Last shared memory tile dimension that affects tile of this group. */
96 int last_shared;
99 struct gpu_array_info {
100 isl_space *dim;
101 /* Element type. */
102 char *type;
103 /* Element size. */
104 int size;
105 /* Name of the array. */
106 char *name;
107 /* Number of indices. */
108 unsigned n_index;
109 /* For each index, a bound on the array in that direction. */
110 isl_pw_aff **bound;
112 /* All references to this array; point to elements of a linked list. */
113 int n_ref;
114 struct gpu_stmt_access **refs;
116 /* The reference groups associated to this array. */
117 int n_group;
118 struct gpu_array_ref_group **groups;
120 /* For scalars, is this scalar read-only within the entire program? */
121 int read_only;
124 /* Print the name of the local copy of a given group of array references.
126 static __isl_give isl_printer *print_array_name(__isl_take isl_printer *p,
127 struct gpu_array_ref_group *group)
129 int global = 0;
131 if (group->private_bound)
132 p = isl_printer_print_str(p, "private_");
133 else if (group->shared_bound)
134 p = isl_printer_print_str(p, "shared_");
135 else
136 global = 1;
137 p = isl_printer_print_str(p, group->array->name);
138 if (!global && group->array->n_group > 1) {
139 p = isl_printer_print_str(p, "_");
140 p = isl_printer_print_int(p, group->nr);
143 return p;
146 /* Collect all references to the given array and store pointers to them
147 * in array->refs.
149 static void collect_references(struct gpu_gen *gen,
150 struct gpu_array_info *array)
152 int i;
153 int n;
155 n = 0;
156 for (i = 0; i < gen->n_stmts; ++i) {
157 struct gpu_stmt *stmt = &gen->stmts[i];
158 struct gpu_stmt_access *access;
160 for (access = stmt->accesses; access; access = access->next) {
161 const char *name;
162 name = isl_map_get_tuple_name(access->access,
163 isl_dim_out);
164 if (name && !strcmp(array->name, name))
165 n++;
169 array->n_ref = n;
170 array->refs = isl_alloc_array(gen->ctx, struct gpu_stmt_access *, n);
171 assert(array->refs);
173 n = 0;
174 for (i = 0; i < gen->n_stmts; ++i) {
175 struct gpu_stmt *stmt = &gen->stmts[i];
176 struct gpu_stmt_access *access;
178 for (access = stmt->accesses; access; access = access->next) {
179 const char *name;
180 name = isl_map_get_tuple_name(access->access,
181 isl_dim_out);
182 if (!name || strcmp(array->name, name))
183 continue;
185 array->refs[n++] = access;
190 static struct gpu_array_bound *create_bound_list(isl_ctx *ctx, int n_index)
192 int i;
193 struct gpu_array_bound *bound;
195 bound = isl_alloc_array(ctx, struct gpu_array_bound, n_index);
196 assert(bound);
198 for (i = 0; i < n_index; ++i) {
199 isl_int_init(bound[i].size);
200 bound[i].lb = NULL;
201 isl_int_init(bound[i].stride);
202 bound[i].shift = NULL;
203 bound[i].shift_map = NULL;
206 return bound;
209 static void free_bound_list(struct gpu_array_bound *bound, int n_index)
211 int j;
213 if (!bound)
214 return;
216 for (j = 0; j < n_index; ++j) {
217 isl_int_clear(bound[j].size);
218 isl_int_clear(bound[j].stride);
219 isl_aff_free(bound[j].lb);
220 isl_aff_free(bound[j].shift);
221 isl_basic_map_free(bound[j].shift_map);
223 free(bound);
226 static struct pet_array *find_array(struct pet_scop *scop,
227 __isl_keep isl_set *accessed)
229 int i;
230 isl_id *id;
232 id = isl_set_get_tuple_id(accessed);
234 for (i = 0; i < scop->n_array; ++i) {
235 isl_id *id_i;
237 id_i = isl_set_get_tuple_id(scop->arrays[i]->extent);
238 isl_id_free(id_i);
239 if (id == id_i)
240 break;
242 isl_id_free(id);
244 return i < scop->n_array ? scop->arrays[i] : NULL;
247 /* Compute bounds on the host arrays based on the accessed elements
248 * and collect all references to the array.
250 * If the array is zero-dimensional, i.e., a scalar, we check
251 * whether it is read-only.
253 static int extract_array_info(__isl_take isl_set *array, void *user)
255 int i;
256 struct gpu_gen *gen = (struct gpu_gen *)user;
257 const char *name;
258 int n_index;
259 isl_pw_aff **bounds;
260 struct pet_array *pa;
262 n_index = isl_set_dim(array, isl_dim_set);
263 name = isl_set_get_tuple_name(array);
264 bounds = isl_alloc_array(isl_set_get_ctx(array),
265 isl_pw_aff *, n_index);
266 assert(bounds);
267 gen->array[gen->n_array].dim = isl_set_get_space(array);
268 gen->array[gen->n_array].name = strdup(name);
269 gen->array[gen->n_array].n_index = n_index;
270 gen->array[gen->n_array].bound = bounds;
272 pa = find_array(gen->scop, array);
273 assert(pa);
275 gen->array[gen->n_array].type = strdup(pa->element_type);
276 gen->array[gen->n_array].size = pa->element_size;
278 if (n_index == 0) {
279 isl_set *space;
280 isl_union_map *write;
281 int empty;
283 write = isl_union_map_copy(gen->write);
284 space = isl_set_universe(isl_set_get_space(array));
285 write = isl_union_map_intersect_range(write,
286 isl_union_set_from_set(space));
287 empty = isl_union_map_is_empty(write);
288 isl_union_map_free(write);
290 gen->array[gen->n_array].read_only = empty;
293 for (i = 0; i < n_index; ++i) {
294 isl_set *dom;
295 isl_local_space *ls;
296 isl_aff *one;
297 isl_pw_aff *bound;
298 isl_set *size = i == 0 ? array : pa->extent;
300 bound = isl_set_dim_max(isl_set_copy(size), i);
301 assert(bound);
302 dom = isl_pw_aff_domain(isl_pw_aff_copy(bound));
303 ls = isl_local_space_from_space(isl_set_get_space(dom));
304 one = isl_aff_zero_on_domain(ls);
305 one = isl_aff_add_constant_si(one, 1);
306 bound = isl_pw_aff_add(bound, isl_pw_aff_alloc(dom, one));
307 bound = isl_pw_aff_gist(bound, isl_set_copy(gen->context));
309 bounds[i] = bound;
312 collect_references(gen, &gen->array[gen->n_array]);
314 gen->n_array++;
316 isl_set_free(array);
317 return 0;
320 void collect_array_info(struct gpu_gen *gen)
322 isl_union_set *arrays;
324 arrays = isl_union_map_range(isl_union_map_copy(gen->read));
325 arrays = isl_union_set_union(arrays,
326 isl_union_map_range(isl_union_map_copy(gen->write)));
327 arrays = isl_union_set_coalesce(arrays);
329 gen->n_array = isl_union_set_n_set(arrays);
330 gen->array = isl_alloc_array(gen->ctx,
331 struct gpu_array_info, gen->n_array);
332 assert(gen->array);
333 gen->n_array = 0;
334 isl_union_set_foreach_set(arrays, &extract_array_info, gen);
335 isl_union_set_free(arrays);
338 static void free_array_info(struct gpu_gen *gen)
340 int i, j;
342 for (i = 0; i < gen->n_array; ++i) {
343 int n_index = gen->array[i].n_index;
344 free(gen->array[i].type);
345 free(gen->array[i].name);
346 for (j = 0; j < n_index; ++j)
347 isl_pw_aff_free(gen->array[i].bound[j]);
348 isl_space_free(gen->array[i].dim);
349 free(gen->array[i].bound);
350 free(gen->array[i].refs);
352 free(gen->array);
355 /* Check if a gpu array is a scalar. A scalar is a value that is not stored
356 * as an array or through a pointer reference, but as single data element. At
357 * the moment, scalars are represented as zero dimensional arrays.
359 static int gpu_array_is_scalar(struct gpu_array_info *array)
361 return (array->n_index == 0);
364 /* Is "array" a read-only scalar?
366 static int gpu_array_is_read_only_scalar(struct gpu_array_info *array)
368 return gpu_array_is_scalar(array) && array->read_only;
371 static void declare_device_arrays(struct gpu_gen *gen)
373 int i;
375 for (i = 0; i < gen->n_array; ++i) {
376 if (gpu_array_is_read_only_scalar(&gen->array[i]))
377 continue;
378 fprintf(gen->cuda.host_c, "%s *dev_%s;\n",
379 gen->array[i].type, gen->array[i].name);
381 fprintf(gen->cuda.host_c, "\n");
384 static void print_array_size(struct gpu_gen *gen, FILE *out,
385 struct gpu_array_info *array)
387 int i;
388 isl_printer *prn;
390 prn = isl_printer_to_file(gen->ctx, out);
391 prn = isl_printer_set_output_format(prn, ISL_FORMAT_C);
392 for (i = 0; i < array->n_index; ++i) {
393 prn = isl_printer_print_str(prn, "(");
394 prn = isl_printer_print_pw_aff(prn, array->bound[i]);
395 prn = isl_printer_print_str(prn, ") * ");
397 prn = isl_printer_print_str(prn, "sizeof(");
398 prn = isl_printer_print_str(prn, array->type);
399 prn = isl_printer_print_str(prn, ")");
400 isl_printer_free(prn);
403 static void allocate_device_arrays(struct gpu_gen *gen)
405 int i;
407 for (i = 0; i < gen->n_array; ++i) {
408 if (gpu_array_is_read_only_scalar(&gen->array[i]))
409 continue;
410 fprintf(gen->cuda.host_c,
411 "cudaCheckReturn(cudaMalloc((void **) &dev_%s, ",
412 gen->array[i].name);
413 print_array_size(gen, gen->cuda.host_c, &gen->array[i]);
414 fprintf(gen->cuda.host_c, "));\n");
416 fprintf(gen->cuda.host_c, "\n");
419 static void free_device_arrays(struct gpu_gen *gen)
421 int i;
423 for (i = 0; i < gen->n_array; ++i) {
424 if (gpu_array_is_read_only_scalar(&gen->array[i]))
425 continue;
426 fprintf(gen->cuda.host_c, "cudaCheckReturn(cudaFree(dev_%s));\n",
427 gen->array[i].name);
431 static void copy_arrays_to_device(struct gpu_gen *gen)
433 int i;
435 for (i = 0; i < gen->n_array; ++i) {
436 isl_space *dim;
437 isl_set *read_i;
438 int empty;
440 if (gpu_array_is_read_only_scalar(&gen->array[i]))
441 continue;
443 dim = isl_space_copy(gen->array[i].dim);
444 read_i = isl_union_set_extract_set(gen->copy_in, dim);
445 empty = isl_set_fast_is_empty(read_i);
446 isl_set_free(read_i);
447 if (empty)
448 continue;
450 fprintf(gen->cuda.host_c, "cudaCheckReturn(cudaMemcpy(dev_%s,",
451 gen->array[i].name);
453 if (gpu_array_is_scalar(&(gen->array[i])))
454 fprintf(gen->cuda.host_c, " &%s, ",
455 gen->array[i].name);
456 else
457 fprintf(gen->cuda.host_c, " %s, ", gen->array[i].name);
459 print_array_size(gen, gen->cuda.host_c, &gen->array[i]);
460 fprintf(gen->cuda.host_c, ", cudaMemcpyHostToDevice));\n");
462 fprintf(gen->cuda.host_c, "\n");
465 static void copy_arrays_from_device(struct gpu_gen *gen)
467 int i;
468 isl_union_set *write;
469 write = isl_union_map_range(isl_union_map_copy(gen->write));
471 for (i = 0; i < gen->n_array; ++i) {
472 isl_space *dim;
473 isl_set *write_i;
474 int empty;
476 dim = isl_space_copy(gen->array[i].dim);
477 write_i = isl_union_set_extract_set(write, dim);
478 empty = isl_set_fast_is_empty(write_i);
479 isl_set_free(write_i);
480 if (empty)
481 continue;
483 fprintf(gen->cuda.host_c, "cudaCheckReturn(cudaMemcpy(");
484 if (gpu_array_is_scalar(&gen->array[i]))
485 fprintf(gen->cuda.host_c, "&%s, ", gen->array[i].name);
486 else
487 fprintf(gen->cuda.host_c, "%s, ", gen->array[i].name);
488 fprintf(gen->cuda.host_c, "dev_%s, ", gen->array[i].name);
489 print_array_size(gen, gen->cuda.host_c, &gen->array[i]);
490 fprintf(gen->cuda.host_c, ", cudaMemcpyDeviceToHost));\n");
493 isl_union_set_free(write);
494 fprintf(gen->cuda.host_c, "\n");
497 /* Internal data structure for extract_size_of_type.
498 * "type" specifies the name of the space that we want to extract.
499 * "res" is used to store the subset of that space.
501 struct ppcg_extract_size_data {
502 const char *type;
503 isl_set *res;
506 /* This function is called for each set in a union_set.
507 * If the name of the set matches data->type, we store the
508 * set in data->res.
510 static int extract_size_of_type(__isl_take isl_set *size, void *user)
512 struct ppcg_extract_size_data *data = user;
513 const char *name;
515 name = isl_set_get_tuple_name(size);
516 if (name && !strcmp(name, data->type)) {
517 data->res = size;
518 return -1;
521 isl_set_free(size);
522 return 0;
525 /* Given a union map { kernel[i] -> *[...] },
526 * return the range in the space called "type" for the kernel with
527 * sequence number "id".
529 static __isl_give isl_set *extract_sizes(__isl_keep isl_union_map *sizes,
530 const char *type, int id)
532 isl_space *space;
533 isl_set *dom;
534 isl_union_set *local_sizes;
535 struct ppcg_extract_size_data data = { type, NULL };
537 if (!sizes)
538 return NULL;
540 space = isl_union_map_get_space(sizes);
541 space = isl_space_set_from_params(space);
542 space = isl_space_add_dims(space, isl_dim_set, 1);
543 space = isl_space_set_tuple_name(space, isl_dim_set, "kernel");
544 dom = isl_set_universe(space);
545 dom = isl_set_fix_si(dom, isl_dim_set, 0, id);
547 local_sizes = isl_union_set_apply(isl_union_set_from_set(dom),
548 isl_union_map_copy(sizes));
549 isl_union_set_foreach_set(local_sizes, &extract_size_of_type, &data);
550 isl_union_set_free(local_sizes);
551 return data.res;
554 /* Given a singleton set, extract the first (at most *len) elements
555 * of the single integer tuple into *sizes and update *len if needed.
557 static void read_sizes_from_set(__isl_take isl_set *set, int *sizes, int *len)
559 int i;
560 int dim;
561 isl_int v;
563 if (!set)
564 return;
566 dim = isl_set_dim(set, isl_dim_set);
567 if (dim < *len)
568 *len = dim;
570 isl_int_init(v);
572 for (i = 0; i < *len; ++i) {
573 int ok;
575 ok = isl_set_plain_is_fixed(set, isl_dim_set, i, &v);
576 assert(ok);
578 sizes[i] = isl_int_get_si(v);
581 isl_int_clear(v);
583 isl_set_free(set);
586 /* Extract user specified "tile" sizes from the "sizes" command line option,
587 * defaulting to option->tile_size in each dimension.
589 static void read_tile_sizes(struct gpu_gen *gen)
591 int n;
592 isl_set *size;
594 gen->tile_size = isl_alloc_array(gen->ctx, int, gen->tile_len);
595 assert(gen->tile_size);
596 for (n = 0; n < gen->tile_len; ++n)
597 gen->tile_size[n] = gen->options->tile_size;
599 size = extract_sizes(gen->sizes, "tile", gen->kernel_id);
600 read_sizes_from_set(size, gen->tile_size, &gen->tile_len);
602 if (gen->n_parallel > gen->tile_len)
603 gen->n_parallel = gen->tile_len;
606 /* Extract user specified "block" sizes from the "sizes" command line option,
607 * after filling in some potentially useful defaults.
609 static void read_block_sizes(struct gpu_gen *gen)
611 int n;
612 isl_set *size;
614 n = gen->n_parallel;
615 gen->n_block = (n <= 3) ? n : 3;
616 switch (gen->n_block) {
617 case 1:
618 gen->block_dim[0] = 512;
619 break;
620 case 2:
621 gen->block_dim[0] = 32;
622 gen->block_dim[1] = 16;
623 break;
624 default:
625 gen->block_dim[0] = 32;
626 gen->block_dim[1] = 4;
627 gen->block_dim[2] = 4;
628 break;
631 size = extract_sizes(gen->sizes, "block", gen->kernel_id);
632 read_sizes_from_set(size, gen->block_dim, &gen->n_block);
635 /* Extract user specified "grid" sizes from the "sizes" command line option,
636 * after filling in some potentially useful defaults.
638 static void read_grid_sizes(struct gpu_gen *gen)
640 int n = gen->n_parallel;
641 isl_set *size;
643 gen->n_grid = (n <= 2) ? n : 2;
644 switch (gen->n_grid) {
645 case 1:
646 gen->grid_dim[0] = 32768;
647 break;
648 default:
649 gen->grid_dim[0] = 256;
650 gen->grid_dim[1] = 256;
651 break;
654 size = extract_sizes(gen->sizes, "grid", gen->kernel_id);
655 read_sizes_from_set(size, gen->grid_dim, &gen->n_grid);
658 /* Extract user specified sizes from the "sizes" command line option
659 * after filling in some potentially useful defaults.
661 static void read_sizes(struct gpu_gen *gen)
663 read_tile_sizes(gen);
664 read_block_sizes(gen);
665 read_grid_sizes(gen);
668 static void free_stmts(struct gpu_stmt *stmts, int n)
670 int i;
672 for (i = 0; i < n; ++i) {
673 struct gpu_stmt_access *access, *next;
675 for (access = stmts[i].accesses; access; access = next) {
676 next = access->next;
677 isl_map_free(access->access);
678 free(access);
681 isl_set_free(stmts[i].domain);
683 free(stmts);
686 void clear_gpu_gen(struct gpu_gen *gen)
688 free_stmts(gen->stmts, gen->n_stmts);
689 free_array_info(gen);
690 isl_union_map_free(gen->sizes);
691 isl_set_free(gen->context);
692 isl_union_set_free(gen->copy_in);
693 isl_union_map_free(gen->sched);
694 isl_union_map_free(gen->read);
695 isl_union_map_free(gen->write);
698 static void print_reverse_list(FILE *out, int len, int *list)
700 int i;
702 if (len == 0)
703 return;
705 fprintf(out, "(");
706 for (i = 0; i < len; ++i) {
707 if (i)
708 fprintf(out, ", ");
709 fprintf(out, "%d", list[len - 1 - i]);
711 fprintf(out, ")");
714 /* Construct a map from a domain of dimensionality "len"
715 * to a domain of dimensionality "len" + "tile_len" that tiles
716 * the "tile_len" coordinates starting at "first".
717 * In particular, [s_i] -> [s_i / tile_size[i], s_i % tile_size[i]].
718 * "dim" prescribes the parameters.
720 static __isl_give isl_map *tile(__isl_take isl_space *dim, int len,
721 int first, int tile_len, int *tile_size)
723 int i;
724 isl_int v;
725 isl_basic_map *bmap;
726 isl_constraint *c;
727 isl_local_space *ls;
729 isl_int_init(v);
731 dim = isl_space_add_dims(dim, isl_dim_in, len);
732 dim = isl_space_add_dims(dim, isl_dim_out, len + tile_len);
733 bmap = isl_basic_map_universe(isl_space_copy(dim));
734 ls = isl_local_space_from_space(dim);
736 for (i = 0; i < len - tile_len; ++i) {
737 int j = i < first ? i : i + tile_len;
738 int k = i < first ? i : i + 2 * tile_len;
740 c = isl_equality_alloc(isl_local_space_copy(ls));
741 isl_int_set_si(v, -1);
742 isl_constraint_set_coefficient(c, isl_dim_in, j, v);
743 isl_int_set_si(v, 1);
744 isl_constraint_set_coefficient(c, isl_dim_out, k, v);
745 bmap = isl_basic_map_add_constraint(bmap, c);
748 for (i = 0; i < tile_len; ++i) {
749 c = isl_equality_alloc(isl_local_space_copy(ls));
750 isl_int_set_si(v, -1);
751 isl_constraint_set_coefficient(c, isl_dim_in, first + i, v);
752 isl_int_set_si(v, tile_size[i]);
753 isl_constraint_set_coefficient(c, isl_dim_out, first + i, v);
754 isl_int_set_si(v, 1);
755 isl_constraint_set_coefficient(c, isl_dim_out,
756 first + i + tile_len, v);
757 bmap = isl_basic_map_add_constraint(bmap, c);
759 c = isl_inequality_alloc(isl_local_space_copy(ls));
760 isl_int_set_si(v, 1);
761 isl_constraint_set_coefficient(c, isl_dim_out,
762 first + i + tile_len, v);
763 bmap = isl_basic_map_add_constraint(bmap, c);
765 c = isl_inequality_alloc(isl_local_space_copy(ls));
766 isl_int_set_si(v, -1);
767 isl_constraint_set_coefficient(c, isl_dim_out,
768 first + i + tile_len, v);
769 isl_int_set_si(v, tile_size[i] - 1);
770 isl_constraint_set_constant(c, v);
771 bmap = isl_basic_map_add_constraint(bmap, c);
774 isl_local_space_free(ls);
775 isl_int_clear(v);
777 return isl_map_from_basic_map(bmap);
780 /* Construct a map from a domain of dimensionality "len"
781 * to a domain of dimensionality "len" + "wrap_len" that "wraps"
782 * the "wrap_len" coordinates starting at "first" according to "wrap_size".
783 * In particular, [s_i] -> [s_i, s_i % wrap_size[i]].
784 * To do so, we need extra variables corresponding to [s_i / wrap_size[i]],
785 * that are projected out at the end.
786 * "dim" prescribes the parameters.
788 static __isl_give isl_map *wrap(__isl_take isl_space *dim, int len,
789 int first, int wrap_len, int *wrap_size)
791 int i;
792 isl_basic_map *bmap;
793 isl_constraint *c;
794 isl_local_space *ls;
796 dim = isl_space_add_dims(dim, isl_dim_in, len);
797 dim = isl_space_add_dims(dim, isl_dim_out, len + 2 * wrap_len);
798 bmap = isl_basic_map_universe(isl_space_copy(dim));
799 ls = isl_local_space_from_space(dim);
801 for (i = 0; i < len; ++i) {
802 int k = i < first + wrap_len ? i : i + 2 * wrap_len;
804 c = isl_equality_alloc(isl_local_space_copy(ls));
805 isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
806 isl_constraint_set_coefficient_si(c, isl_dim_out, k, 1);
807 bmap = isl_basic_map_add_constraint(bmap, c);
810 for (i = 0; i < wrap_len; ++i) {
811 c = isl_equality_alloc(isl_local_space_copy(ls));
812 isl_constraint_set_coefficient_si(c, isl_dim_out,
813 first + i, -1);
814 isl_constraint_set_coefficient_si(c, isl_dim_out,
815 first + wrap_len + i, 1);
816 isl_constraint_set_coefficient_si(c, isl_dim_out,
817 first + 2 * wrap_len + i, wrap_size[i]);
818 bmap = isl_basic_map_add_constraint(bmap, c);
820 c = isl_inequality_alloc(isl_local_space_copy(ls));
821 isl_constraint_set_coefficient_si(c, isl_dim_out,
822 first + wrap_len + i, 1);
823 bmap = isl_basic_map_add_constraint(bmap, c);
825 c = isl_inequality_alloc(isl_local_space_copy(ls));
826 isl_constraint_set_coefficient_si(c, isl_dim_out,
827 first + wrap_len + i, -1);
828 isl_constraint_set_constant_si(c, wrap_size[i] - 1);
829 bmap = isl_basic_map_add_constraint(bmap, c);
832 isl_local_space_free(ls);
834 bmap = isl_basic_map_project_out(bmap, isl_dim_out,
835 first + 2 * wrap_len, wrap_len);
837 return isl_map_from_basic_map(bmap);
840 /* Add "n" parameters named prefix%d.
842 static __isl_give isl_set *add_params( __isl_take isl_set *set,
843 int n, const char *prefix)
845 int i;
846 unsigned nparam;
847 char name[20];
849 nparam = isl_set_dim(set, isl_dim_param);
850 set = isl_set_add_dims(set, isl_dim_param, n);
852 for (i = 0; i < n; ++i) {
853 snprintf(name, sizeof(name), "%s%d", prefix, i);
854 set = isl_set_set_dim_name(set, isl_dim_param,
855 nparam + i, name);
858 return set;
861 /* Equate the "n" dimensions of "set" starting at "first" to
862 * freshly created parameters named prefix%d.
864 static __isl_give isl_set *parametrize(__isl_take isl_set *set,
865 int first, int n, const char *prefix)
867 int i;
868 unsigned nparam;
869 isl_int v;
870 isl_space *dim;
871 isl_basic_set *bset;
872 isl_constraint *c;
873 isl_local_space *ls;
875 nparam = isl_set_dim(set, isl_dim_param);
877 set = add_params(set, n, prefix);
879 dim = isl_set_get_space(set);
880 bset = isl_basic_set_universe(isl_space_copy(dim));
881 ls = isl_local_space_from_space(dim);
883 isl_int_init(v);
885 for (i = 0; i < n; ++i) {
886 c = isl_equality_alloc(isl_local_space_copy(ls));
887 isl_int_set_si(v, -1);
888 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
889 isl_int_set_si(v, 1);
890 isl_constraint_set_coefficient(c, isl_dim_set, first + i, v);
891 bset = isl_basic_set_add_constraint(bset, c);
894 isl_int_clear(v);
895 isl_local_space_free(ls);
897 return isl_set_intersect(set, isl_set_from_basic_set(bset));
900 /* Given a parameter space "space", create a set of dimension "len"
901 * of which the "n" dimensions starting at "first" are equated to
902 * freshly created parameters named prefix%d.
904 static __isl_give isl_set *parametrization(__isl_take isl_space *space,
905 int len, int first, int n, const char *prefix)
907 isl_set *set;
909 space = isl_space_set_from_params(space);
910 space = isl_space_add_dims(space, isl_dim_set, len);
911 set = isl_set_universe(space);
913 return parametrize(set, first, n, prefix);
916 /* Tile the B loops over the tile sizes and then tile/wrap
917 * the T1 loops over the blocks.
919 static __isl_give isl_union_map *tile_schedule(struct gpu_gen *gen,
920 __isl_take isl_union_map *sched)
922 isl_space *dim;
923 isl_map *tiling, *block_tiling;
925 dim = isl_union_map_get_space(sched);
926 tiling = tile(isl_space_copy(dim), gen->untiled_len,
927 gen->tile_first, gen->tile_len, gen->tile_size);
929 if (gen->options->wrap)
930 block_tiling = wrap(dim, gen->untiled_len + gen->tile_len,
931 gen->tile_first, gen->n_grid, gen->grid_dim);
932 else
933 block_tiling = tile(dim, gen->untiled_len + gen->tile_len,
934 gen->tile_first, gen->n_grid, gen->grid_dim);
936 gen->tiled_len = gen->untiled_len + gen->tile_len + gen->n_grid;
938 tiling = isl_map_apply_range(tiling, block_tiling);
940 sched = isl_union_map_apply_range(sched,
941 isl_union_map_from_map(tiling));
943 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
945 return sched;
948 /* Equate the "T1P" iterators in the tiled schedule "sched"
949 * to the block dimensions.
951 static __isl_give isl_union_map *parametrize_tiled_schedule(
952 struct gpu_gen *gen, __isl_take isl_union_map *sched)
954 isl_space *dim;
955 isl_set *par;
957 dim = isl_union_map_get_space(sched);
958 par = parametrization(dim, gen->tiled_len,
959 gen->tile_first + gen->n_grid, gen->n_grid, "b");
960 sched = isl_union_map_intersect_range(sched,
961 isl_union_set_from_set(par));
963 return sched;
966 /* Tile/wrap the P1 loops over the threads.
968 static __isl_give isl_union_map *thread_tile_schedule(struct gpu_gen *gen,
969 __isl_take isl_union_map *sched)
971 isl_space *dim;
972 isl_map *tiling;
973 isl_set *par;
975 dim = isl_union_map_get_space(sched);
977 if (gen->options->wrap)
978 tiling = wrap(isl_space_copy(dim), gen->tiled_len,
979 gen->shared_len, gen->n_block, gen->block_dim);
980 else
981 tiling = tile(isl_space_copy(dim), gen->tiled_len,
982 gen->shared_len, gen->n_block, gen->block_dim);
983 gen->thread_tiled_len = gen->tiled_len + gen->n_block;
985 sched = isl_union_map_apply_range(sched,
986 isl_union_map_from_map(tiling));
988 par = parametrization(dim, gen->thread_tiled_len,
989 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
990 gen->n_block, "t");
991 sched = isl_union_map_intersect_range(sched,
992 isl_union_set_from_set(par));
994 gen->shared_len = gen->tile_first + gen->tile_len + gen->n_grid;
996 return sched;
999 /* If the user asked for it, scale the shared memory tile loops
1000 * (T1T and T2) of "sched" by gen->tile_size[i].
1001 * If we are not performing "wrapping", then additionally scale the T1P
1002 * loops by gen->grid_dim[i].
1004 static __isl_give isl_union_map *scale_tile_loops(struct gpu_gen *gen,
1005 __isl_take isl_union_map *sched)
1007 int i;
1008 isl_space *dim;
1009 isl_basic_map *scale;
1010 isl_constraint *c;
1011 isl_local_space *ls;
1013 if (!gen->options->scale_tile_loops)
1014 return sched;
1016 dim = isl_union_map_get_space(sched);
1017 dim = isl_space_add_dims(dim, isl_dim_in, gen->tiled_len);
1018 dim = isl_space_add_dims(dim, isl_dim_out, gen->tiled_len);
1019 scale = isl_basic_map_universe(isl_space_copy(dim));
1020 ls = isl_local_space_from_space(dim);
1022 for (i = 0; i < gen->tiled_len; ++i) {
1023 int f = 1;
1025 if (i >= gen->tile_first && i < gen->tile_first + gen->n_grid) {
1026 f = gen->tile_size[i - gen->tile_first];
1027 if (!gen->options->wrap)
1028 f *= gen->grid_dim[i - gen->tile_first];
1029 } else if (i >= gen->tile_first + gen->n_grid &&
1030 i < gen->tile_first + gen->n_grid + gen->tile_len) {
1031 f = gen->tile_size[i - (gen->tile_first + gen->n_grid)];
1034 c = isl_equality_alloc(isl_local_space_copy(ls));
1035 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1036 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1037 scale = isl_basic_map_add_constraint(scale, c);
1040 isl_local_space_free(ls);
1042 sched = isl_union_map_apply_range(sched,
1043 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1045 return sched;
1048 /* If we are not performing "wrapping" and if the user asked for it,
1049 * scale the thread tile loops (P1T) of "sched" by gen->block_dim[i].
1051 static __isl_give isl_union_map *scale_thread_tile_loops(struct gpu_gen *gen,
1052 __isl_take isl_union_map *sched)
1054 int i;
1055 isl_space *dim;
1056 isl_basic_map *scale;
1057 isl_constraint *c;
1058 isl_local_space *ls;
1060 if (gen->options->wrap)
1061 return sched;
1062 if (!gen->options->scale_tile_loops)
1063 return sched;
1065 dim = isl_union_map_get_space(sched);
1066 dim = isl_space_add_dims(dim, isl_dim_in, gen->thread_tiled_len);
1067 dim = isl_space_add_dims(dim, isl_dim_out, gen->thread_tiled_len);
1068 scale = isl_basic_map_universe(isl_space_copy(dim));
1069 ls = isl_local_space_from_space(dim);
1071 for (i = 0; i < gen->thread_tiled_len; ++i) {
1072 int f = 1;
1074 if (i >= gen->shared_len &&
1075 i < gen->shared_len + gen->n_block)
1076 f = gen->block_dim[i - gen->shared_len];
1078 c = isl_equality_alloc(isl_local_space_copy(ls));
1079 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1080 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1081 scale = isl_basic_map_add_constraint(scale, c);
1084 isl_local_space_free(ls);
1086 sched = isl_union_map_apply_range(sched,
1087 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1089 return sched;
1092 /* If we are not performing "wrapping" and if the user asked for it,
1093 * scale the "n_tile" loops starting at "first" of "sched" by gen->block_dim[i].
1095 static __isl_give isl_union_map *scale_access_tile_loops(struct gpu_gen *gen,
1096 __isl_take isl_union_map *sched, int len, int first, int n_tile)
1098 int i;
1099 isl_space *dim;
1100 isl_basic_map *scale;
1101 isl_constraint *c;
1102 isl_local_space *ls;
1104 if (gen->options->wrap)
1105 return sched;
1106 if (!gen->options->scale_tile_loops)
1107 return sched;
1109 dim = isl_union_map_get_space(sched);
1110 dim = isl_space_add_dims(dim, isl_dim_in, len);
1111 dim = isl_space_add_dims(dim, isl_dim_out, len);
1112 scale = isl_basic_map_universe(isl_space_copy(dim));
1113 ls = isl_local_space_from_space(dim);
1115 for (i = 0; i < len; ++i) {
1116 int f = 1;
1118 if (i >= first && i < first + n_tile)
1119 f = gen->block_dim[i - first];
1121 c = isl_equality_alloc(isl_local_space_copy(ls));
1122 isl_constraint_set_coefficient_si(c, isl_dim_in, i, f);
1123 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
1124 scale = isl_basic_map_add_constraint(scale, c);
1127 isl_local_space_free(ls);
1129 sched = isl_union_map_apply_range(sched,
1130 isl_union_map_from_map(isl_map_from_basic_map(scale)));
1132 return sched;
1135 /* Add "len" parameters p[i] called prefix%d,
1136 * with bounds to 0 <= p[i] < size[i].
1138 __isl_give isl_set *add_bounded_parameters(__isl_take isl_set *set,
1139 int len, int *size, const char *prefix)
1141 int i;
1142 unsigned nparam;
1143 isl_int v;
1144 isl_space *dim;
1145 isl_basic_set *bset;
1146 isl_constraint *c;
1147 isl_local_space *ls;
1148 char name[20];
1150 nparam = isl_set_dim(set, isl_dim_param);
1151 set = isl_set_add_dims(set, isl_dim_param, len);
1153 for (i = 0; i < len; ++i) {
1154 snprintf(name, sizeof(name), "%s%d", prefix, i);
1155 set = isl_set_set_dim_name(set, isl_dim_param,
1156 nparam + i, name);
1159 dim = isl_set_get_space(set);
1160 bset = isl_basic_set_universe(isl_space_copy(dim));
1161 ls = isl_local_space_from_space(dim);
1163 isl_int_init(v);
1165 for (i = 0; i < len; ++i) {
1166 c = isl_inequality_alloc(isl_local_space_copy(ls));
1167 isl_int_set_si(v, 1);
1168 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
1169 bset = isl_basic_set_add_constraint(bset, c);
1171 c = isl_inequality_alloc(isl_local_space_copy(ls));
1172 isl_int_set_si(v, -1);
1173 isl_constraint_set_coefficient(c, isl_dim_param, nparam + i, v);
1174 isl_int_set_si(v, size[i] - 1);
1175 isl_constraint_set_constant(c, v);
1176 bset = isl_basic_set_add_constraint(bset, c);
1179 isl_int_clear(v);
1180 isl_local_space_free(ls);
1182 return isl_set_intersect(set, isl_set_from_basic_set(bset));
1185 /* Given a mapping "sched" of the form
1187 * [D -> A] -> [D -> T(A)]
1189 * apply the mapping encoded in bounds[i].shift_map to the range of "sched".
1190 * The mappings in bounds[i].shift_map are of the form
1192 * [D -> a] -> [D -> s(D,a)]
1194 * We first compose them with a mapping
1196 * [D -> v] -> v
1198 * (If bounds[i].shift_map is not set, then it is assumed to be
1199 * an identity mapping and then we use this second mapping instead.)
1200 * This results in
1202 * [D -> a] -> s(D,a)
1204 * We precompose them with a projection on the i th dimension to obtain
1206 * [D -> T] -> s(D,T)
1208 * and collect these into
1210 * [D -> T] -> S(D,T)
1212 * Introducing D in the range yields
1214 * [D -> T] -> [D -> S(D,T)]
1216 * and application to "sched" yields
1218 * [D -> A] -> [D -> S(D,T(A))]
1220 static __isl_give isl_map *pre_shift(__isl_take isl_map *sched,
1221 int n_index, struct gpu_array_bound *bounds)
1223 int i;
1224 isl_ctx *ctx = isl_map_get_ctx(sched);
1225 isl_space *space, *space2;
1226 isl_basic_map *def;
1227 isl_map *map, *id, *pre_shift;
1229 space = isl_space_range(isl_map_get_space(sched));
1230 space2 = isl_space_from_domain(isl_space_copy(space));
1231 pre_shift = isl_map_universe(space2);
1232 space = isl_space_domain(isl_space_unwrap(space));
1233 id = isl_map_identity(isl_space_map_from_set(isl_space_copy(space)));
1234 space = isl_space_from_domain(space);
1235 space = isl_space_add_dims(space, isl_dim_out, 1);
1236 def = isl_basic_map_range_map(isl_basic_map_universe(space));
1238 for (i = 0; i < n_index; ++i) {
1239 isl_basic_map *bmap, *drop;
1240 isl_map *proj;
1242 space = isl_space_alloc(ctx, 0, n_index, n_index);
1243 proj = isl_map_identity(space);
1244 proj = isl_map_project_out(proj, isl_dim_out,
1245 i + 1, n_index - (i + 1));
1246 proj = isl_map_project_out(proj, isl_dim_out, 0, i);
1247 proj = isl_map_product(isl_map_copy(id), proj);
1249 if (!bounds[i].shift_map)
1250 bmap = isl_basic_map_copy(def);
1251 else {
1252 bmap = isl_basic_map_copy(bounds[i].shift_map);
1253 bmap = isl_basic_map_apply_range(bmap,
1254 isl_basic_map_copy(def));
1257 map = isl_map_from_basic_map(bmap);
1258 map = isl_map_apply_range(proj, map);
1259 pre_shift = isl_map_flat_range_product(pre_shift, map);
1262 isl_map_free(id);
1263 isl_basic_map_free(def);
1265 space = isl_space_domain(isl_map_get_space(pre_shift));
1266 map = isl_map_domain_map(isl_map_universe(isl_space_unwrap(space)));
1267 pre_shift = isl_map_range_product(map, pre_shift);
1269 sched = isl_map_apply_range(sched, pre_shift);
1271 return sched;
1274 /* Given an access relation to a tile of an array, construct a map that
1275 * maps each element in the space of the access relation
1276 * to a copy of the tile shifted to the origin
1277 * (based on the lower bounds in group->private_bound or group->shared_bound).
1278 * If any of the indices is strided, then {private,shared}_bound[i].shift_map
1279 * is applied to the index first.
1280 * The domain space of the resulting map is that of access "access",
1281 * while the range space is anonymous.
1282 * The resulting map only encodes the mapping to the shift tile and
1283 * not the constraints of "access".
1285 * Let the space of the access relation be
1287 * D -> A
1289 * We first construct an identity relation on a wrapped copy of this space,
1290 * except that it strips off the name of array
1292 * [D -> A] -> [D -> T(A)] (1)
1294 * The bounds in bounds[i].lb are of the form
1296 * D -> b(D)
1298 * We collect them into
1300 * D -> B(D)
1302 * and then transform them into
1304 * [D -> T] -> T - B(D) (2)
1306 * Combining those two mappings (1) and (2) yields
1308 * [D -> A] -> T(A) - B(D)
1310 * If there are any strides, then (1) is first transformed into (1')
1312 * [D -> A] -> [D -> T'(A)] (1')
1314 * by a call to pre_shift.
1316 static __isl_give isl_map *shift_access(__isl_take isl_map *access,
1317 struct gpu_array_ref_group *group)
1319 int i;
1320 isl_space *space;
1321 isl_map *id1, *id2;
1322 isl_map *map;
1323 isl_map *shift;
1324 isl_map *sched;
1325 struct gpu_array_bound *bounds;
1326 int n_index = group->array->n_index;
1328 bounds = group->private_bound;
1329 if (!bounds)
1330 bounds = group->shared_bound;
1332 space = isl_space_domain(isl_map_get_space(access));
1333 space = isl_space_map_from_set(space);
1334 id1 = isl_map_identity(space);
1335 space = isl_space_range(isl_map_get_space(access));
1336 space = isl_space_map_from_set(space);
1337 space = isl_space_set_tuple_name(space, isl_dim_out, NULL);
1338 id2 = isl_map_identity(space);
1339 sched = isl_map_product(id1, id2);
1341 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1342 space = isl_space_from_domain(isl_space_domain(space));
1343 shift = isl_map_universe(space);
1344 for (i = 0; i < n_index; ++i) {
1345 map = isl_map_from_aff(isl_aff_copy(bounds[i].lb));
1346 shift = isl_map_flat_range_product(shift, map);
1349 space = isl_space_unwrap(isl_space_range(isl_map_get_space(sched)));
1350 map = isl_map_universe(space);
1351 id1 = isl_map_range_map(isl_map_copy(map));
1352 map = isl_map_domain_map(map);
1353 shift = isl_map_neg(shift);
1354 shift = isl_map_apply_range(map, shift);
1355 shift = isl_map_sum(id1, shift);
1357 for (i = 0; i < n_index; ++i)
1358 if (bounds[i].shift_map)
1359 break;
1361 if (i < n_index)
1362 sched = pre_shift(sched, n_index, bounds);
1364 sched = isl_map_apply_range(sched, shift);
1366 isl_map_free(access);
1368 return sched;
1371 /* Given a schedule that iterates over all elements in a piece of an array,
1372 * perform tiling/wrapping over the threads.
1374 * In particular, we tile the final iterators so that the final thread
1375 * dimension runs over the final array dimension.
1376 * However, if those final iterators have only a single iteration,
1377 * we try to tile earlier iterators instead.
1379 static __isl_give isl_map *tile_access_schedule(struct gpu_gen *gen,
1380 __isl_take isl_map *sched)
1382 isl_space *dim;
1383 isl_union_map *usched;
1384 isl_map *tiling;
1385 isl_set *par;
1386 unsigned nvar = isl_map_dim(sched, isl_dim_out);
1387 int n_tile;
1388 int first;
1390 n_tile = gen->n_block;
1391 if (n_tile > nvar) {
1392 int i;
1393 sched = isl_map_insert_dims(sched,
1394 isl_dim_out, 0, n_tile - nvar);
1395 for (i = 0; i < n_tile - nvar; ++i)
1396 sched = isl_map_fix_si(sched, isl_dim_out, i, 0);
1397 nvar = n_tile;
1400 first = nvar - n_tile;
1402 for (; first > 0; first --)
1403 if (!isl_map_plain_is_fixed(sched, isl_dim_out,
1404 first + n_tile - 1, NULL))
1405 break;
1407 dim = isl_map_get_space(sched);
1408 dim = isl_space_params(dim);
1409 if (gen->options->wrap)
1410 tiling = wrap(isl_space_copy(dim), nvar, first,
1411 n_tile, gen->block_dim);
1412 else
1413 tiling = tile(isl_space_copy(dim), nvar, first,
1414 n_tile, gen->block_dim);
1415 sched = isl_map_apply_range(sched, tiling);
1417 par = parametrization(dim, nvar + n_tile, first + n_tile, n_tile, "t");
1418 sched = isl_map_intersect_range(sched, par);
1420 usched = isl_union_map_from_map(sched);
1421 usched = scale_access_tile_loops(gen, usched, nvar + n_tile,
1422 first, n_tile);
1423 sched = isl_map_from_union_map(usched);
1425 return sched;
1428 /* Given an index expression "pa" into a tile of an array, adjust the expression
1429 * to a shift of the tile to the origin
1430 * (based on the lower bounds in "bound".
1431 * If the index is strided, then we first add
1432 * bound->shift and divide by bound->stride.
1433 * In the end, we compute the gist with respect to "domain".
1435 * All of the input expression "pa", the set "domain" and
1436 * the output are expressed in terms of the AST schedule domain.
1437 * The expressions in "bound" are expressed
1438 * in terms of the first shared_len dimensions of the schedule computed by PPCG.
1439 * The mapping "sched2shared" maps the former domain to the latter domain.
1441 static __isl_give isl_pw_aff *shift_index(__isl_take isl_pw_aff *pa,
1442 struct gpu_array_info *array,
1443 struct gpu_array_bound *bound, __isl_take isl_set *domain,
1444 __isl_take isl_map *sched2shared)
1446 isl_map *map;
1447 isl_pw_aff *tmp;
1448 isl_pw_multi_aff *pma;
1450 if (bound->shift) {
1451 map = isl_map_from_aff(isl_aff_copy(bound->shift));
1452 map = isl_map_apply_range(isl_map_copy(sched2shared), map);
1453 pma = isl_pw_multi_aff_from_map(map);
1454 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1455 isl_pw_multi_aff_free(pma);
1456 pa = isl_pw_aff_add(pa, tmp);
1457 pa = isl_pw_aff_scale_down(pa, bound->stride);
1461 map = isl_map_from_aff(isl_aff_copy(bound->lb));
1462 map = isl_map_apply_range(sched2shared, map);
1463 pma = isl_pw_multi_aff_from_map(map);
1464 tmp = isl_pw_multi_aff_get_pw_aff(pma, 0);
1465 isl_pw_multi_aff_free(pma);
1466 pa = isl_pw_aff_sub(pa, tmp);
1467 pa = isl_pw_aff_coalesce(pa);
1468 pa = isl_pw_aff_gist(pa, domain);
1470 return pa;
1473 /* Return the union of all read (read = 1) and/or write (write = 1)
1474 * access relations in the group.
1476 static __isl_give isl_union_map *group_access_relation(
1477 struct gpu_array_ref_group *group, int read, int write)
1479 int i;
1480 isl_union_map *access;
1482 access = isl_union_map_empty(isl_map_get_space(group->access));
1483 for (i = 0; i < group->n_ref; ++i) {
1484 isl_map *map_i;
1486 if (!((read && group->refs[i]->read) ||
1487 (write && group->refs[i]->write)))
1488 continue;
1489 map_i = isl_map_copy(group->refs[i]->access);
1490 access = isl_union_map_union(access,
1491 isl_union_map_from_map(map_i));
1494 return access;
1497 /* Check that none of the shared memory tiles involve any strides.
1499 static int no_strides(struct gpu_array_ref_group *group)
1501 int i;
1502 int n_index = group->array->n_index;
1504 for (i = 0; i < n_index; ++i)
1505 if (group->shared_bound[i].shift)
1506 return 0;
1508 return 1;
1511 /* Return a map from the first shared_len dimensions of the computed
1512 * schedule to the values of the given index "i"
1513 * of the elements in the array tile in global memory that corresponds
1514 * to the shared memory copy.
1515 * In particular, if a is the index, then the range of the map
1517 * { D -> [a] }
1519 * is constrained as follows
1521 * tile_offset(D) <= a <= tile_offset(D) + tile_size - 1
1523 * and
1525 * 0 <= a <= array_size - 1
1528 static __isl_give isl_map *group_tile_dim(struct gpu_array_ref_group *group,
1529 int i)
1531 isl_aff *aff;
1532 isl_space *space;
1533 isl_map *map, *tile, *gt;
1534 isl_set *bound;
1536 map = isl_map_from_aff(isl_aff_copy(group->shared_bound[i].lb));
1537 space = isl_space_range(isl_map_get_space(map));
1538 map = isl_map_apply_range(map, isl_map_lex_le(isl_space_copy(space)));
1539 tile = map;
1541 aff = isl_aff_copy(group->shared_bound[i].lb);
1542 aff = isl_aff_add_constant(aff, group->shared_bound[i].size);
1543 map = isl_map_from_aff(aff);
1544 gt = isl_map_lex_gt(space);
1545 map = isl_map_apply_range(map, isl_map_copy(gt));
1546 tile = isl_map_intersect(tile, map);
1548 tile = isl_map_lower_bound_si(tile, isl_dim_out, 0, 0);
1550 bound = isl_set_from_pw_aff(isl_pw_aff_copy(group->array->bound[i]));
1551 bound = isl_set_apply(bound, gt);
1552 tile = isl_map_intersect_range(tile, bound);
1554 return tile;
1557 /* Return a map from the first shared_len dimensions of the computed
1558 * schedule to the array tile in
1559 * global memory that corresponds to the shared memory copy.
1561 static __isl_give isl_map *group_tile(struct gpu_array_ref_group *group)
1563 int i;
1564 int n_index = group->array->n_index;
1565 isl_map *tile;
1567 tile = group_tile_dim(group, 0);
1568 for (i = 1; i < n_index; ++i) {
1569 isl_map *tile_i;
1571 tile_i = group_tile_dim(group, i);
1572 tile = isl_map_flat_range_product(tile, tile_i);
1575 tile = isl_map_set_tuple_name(tile, isl_dim_out, group->array->name);
1577 return tile;
1580 /* Given a mapping "sched" from the AST schedule to a domain,
1581 * return the corresponding mapping from the AST schedule to
1582 * to the first shared_len dimensions of the schedule computed by PPCG.
1584 static __isl_give isl_map *compute_sched_to_shared(struct gpu_gen *gen,
1585 __isl_take isl_map *sched)
1587 isl_union_map *umap;
1588 isl_space *space;
1589 isl_map *map;
1591 space = isl_space_range(isl_map_get_space(sched));
1592 space = isl_space_from_domain(space);
1593 space = isl_space_add_dims(space, isl_dim_out, gen->shared_len);
1595 umap = isl_union_map_copy(gen->shared_sched);
1596 umap = isl_union_map_apply_range(umap,
1597 isl_union_map_copy(gen->shared_proj));
1598 map = isl_union_map_extract_map(umap, space);
1599 isl_union_map_free(umap);
1601 sched = isl_map_apply_range(sched, map);
1602 sched = isl_map_detect_equalities(sched);
1604 return sched;
1607 /* Set unroll[j] if the input dimension j is involved in
1608 * the index expression represented by bmap.
1610 static int check_unroll(__isl_take isl_basic_map *bmap, void *user)
1612 int i, j;
1613 int n_in = isl_basic_map_dim(bmap, isl_dim_in);
1614 int n_out = isl_basic_map_dim(bmap, isl_dim_out);
1615 int *unroll = user;
1617 for (i = 0; i < n_out; ++i) {
1618 isl_constraint *c;
1619 int ok;
1621 ok = isl_basic_map_has_defining_equality(bmap,
1622 isl_dim_out, i, &c);
1623 assert(ok);
1624 for (j = 0; j < n_in; ++j)
1625 if (isl_constraint_involves_dims(c, isl_dim_in, j, 1))
1626 unroll[j] = 1;
1627 isl_constraint_free(c);
1630 isl_basic_map_free(bmap);
1631 return 0;
1634 /* Given an array pos mapping input dimensions to the corresponding
1635 * output dimension, construct the corresponding map.
1637 static __isl_give isl_map *permutation(__isl_take isl_space *dim,
1638 int *pos, int len)
1640 int i;
1641 isl_constraint *c;
1642 isl_basic_map *bmap;
1643 isl_local_space *ls;
1645 dim = isl_space_add_dims(dim, isl_dim_in, len);
1646 dim = isl_space_add_dims(dim, isl_dim_out, len);
1647 bmap = isl_basic_map_universe(isl_space_copy(dim));
1648 ls = isl_local_space_from_space(dim);
1650 for (i = 0; i < len; ++i) {
1651 c = isl_equality_alloc(isl_local_space_copy(ls));
1652 isl_constraint_set_coefficient_si(c, isl_dim_in, i, -1);
1653 isl_constraint_set_coefficient_si(c, isl_dim_out, pos[i], 1);
1654 bmap = isl_basic_map_add_constraint(bmap, c);
1656 isl_local_space_free(ls);
1658 return isl_map_from_basic_map(bmap);
1661 /* Find all loops involved in any of the index expressions for any of
1662 * the private accesses, move them innermost and then mark them as
1663 * requiring unrolling by setting gen->first_unroll.
1664 * The loops involved should all be parallel because of the checks
1665 * we performed in check_private_group_access. Moving them innermost
1666 * is therefore a valid transformation.
1668 * Loops up to gen->shared_len are generated before the mapping to
1669 * threads is applied. They should therefore be ignored.
1671 static __isl_give isl_union_map *interchange_for_unroll(struct gpu_gen *gen,
1672 __isl_take isl_union_map *sched)
1674 int i, j;
1675 int unroll[gen->thread_tiled_len];
1676 int perm[gen->thread_tiled_len];
1677 isl_space *dim;
1678 isl_map *permute;
1679 int len = gen->shared_len + gen->n_parallel + gen->n_block;
1681 gen->first_unroll = -1;
1683 for (i = 0; i < gen->thread_tiled_len; ++i)
1684 unroll[i] = 0;
1685 for (i = 0; i < gen->n_array; ++i) {
1686 struct gpu_array_info *array = &gen->array[i];
1688 for (j = 0; j < array->n_group; ++j) {
1689 isl_union_map *access;
1690 isl_map *acc;
1692 if (!array->groups[j]->private_bound)
1693 continue;
1695 access = group_access_relation(array->groups[j], 1, 1);
1696 access = isl_union_map_apply_domain(access,
1697 isl_union_map_copy(sched));
1699 acc = isl_map_from_union_map(access);
1700 isl_map_foreach_basic_map(acc, &check_unroll, unroll);
1702 isl_map_free(acc);
1706 for (i = gen->shared_len; i < len; ++i)
1707 if (unroll[i])
1708 break;
1710 if (i >= len)
1711 return sched;
1713 for (i = len; i < gen->thread_tiled_len; ++i)
1714 if (unroll[i])
1715 return sched;
1717 j = 0;
1718 for (i = 0; i < gen->shared_len; ++i)
1719 perm[i] = j++;
1720 for (i = gen->shared_len; i < gen->thread_tiled_len; ++i)
1721 if (!unroll[i])
1722 perm[i] = j++;
1723 gen->first_unroll = j - gen->shared_len;
1724 for (i = gen->shared_len; i < len; ++i)
1725 if (unroll[i])
1726 perm[i] = j++;
1728 dim = isl_union_map_get_space(sched);
1729 permute = permutation(dim, perm, gen->thread_tiled_len);
1730 sched = isl_union_map_apply_range(sched,
1731 isl_union_map_from_map(permute));
1733 return sched;
1736 static void print_kernel_iterators(struct gpu_gen *gen)
1738 int i;
1739 const char *block_dims[] = { "blockIdx.x", "blockIdx.y" };
1740 const char *thread_dims[] = { "threadIdx.x", "threadIdx.y",
1741 "threadIdx.z" };
1743 if (gen->n_grid > 0) {
1744 print_indent(gen->cuda.kernel_c, 4);
1745 fprintf(gen->cuda.kernel_c, "int ");
1746 for (i = 0; i < gen->n_grid; ++i) {
1747 if (i)
1748 fprintf(gen->cuda.kernel_c, ", ");
1749 fprintf(gen->cuda.kernel_c, "b%d = %s",
1750 i, block_dims[gen->n_grid - 1 - i]);
1752 fprintf(gen->cuda.kernel_c, ";\n");
1755 if (gen->n_block > 0) {
1756 print_indent(gen->cuda.kernel_c, 4);
1757 fprintf(gen->cuda.kernel_c, "int ");
1758 for (i = 0; i < gen->n_block; ++i) {
1759 if (i)
1760 fprintf(gen->cuda.kernel_c, ", ");
1761 fprintf(gen->cuda.kernel_c, "t%d = %s",
1762 i, thread_dims[gen->n_block - 1 - i]);
1764 fprintf(gen->cuda.kernel_c, ";\n");
1768 /* Given a constraint
1770 * a(p,i) + j = g f(e)
1772 * or -a(p,i) - j = g f(e) if sign < 0,
1773 * store a(p,i) in bound->shift and g (stride) in bound->stride.
1774 * a(p,i) is assumed to be an expression in only the parameters
1775 * and the input dimensions.
1777 static void extract_stride(__isl_keep isl_constraint *c,
1778 struct gpu_array_bound *bound, isl_int stride, int sign)
1780 int i;
1781 isl_int v;
1782 isl_space *space;
1783 unsigned nparam;
1784 unsigned nvar;
1785 isl_aff *aff;
1787 isl_int_set(bound->stride, stride);
1789 space = isl_constraint_get_space(c);
1790 space = isl_space_domain(space);
1792 nparam = isl_space_dim(space, isl_dim_param);
1793 nvar = isl_space_dim(space, isl_dim_set);
1795 isl_int_init(v);
1797 isl_constraint_get_constant(c, &v);
1798 if (sign < 0)
1799 isl_int_neg(v, v);
1800 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1801 aff = isl_aff_set_constant(aff, v);
1803 for (i = 0; i < nparam; ++i) {
1804 isl_constraint_get_coefficient(c, isl_dim_param, i, &v);
1805 if (isl_int_is_zero(v))
1806 continue;
1807 if (sign < 0)
1808 isl_int_neg(v, v);
1809 aff = isl_aff_add_coefficient(aff, isl_dim_param, i, v);
1812 for (i = 0; i < nvar; ++i) {
1813 isl_constraint_get_coefficient(c, isl_dim_in, i, &v);
1814 if (isl_int_is_zero(v))
1815 continue;
1816 if (sign < 0)
1817 isl_int_neg(v, v);
1818 aff = isl_aff_add_coefficient(aff, isl_dim_in, i, v);
1821 isl_int_clear(v);
1823 bound->shift = aff;
1826 /* Given an equality constraint of a map with a single output dimension j,
1827 * check if the constraint is of the form
1829 * a(p,i) + j = g f(e)
1831 * with a(p,i) an expression in the parameters and input dimensions
1832 * and f(e) an expression in the existentially quantified variables.
1833 * If so, and if g is larger than any such g from a previously considered
1834 * constraint, then call extract_stride to record the stride information
1835 * in bound.
1837 static int check_stride_constraint(__isl_take isl_constraint *c, void *user)
1839 int i;
1840 isl_int v, stride;
1841 unsigned n_div;
1842 struct gpu_array_bound *bound = user;
1844 isl_int_init(v);
1845 isl_int_init(stride);
1847 n_div = isl_constraint_dim(c, isl_dim_div);
1848 isl_constraint_get_coefficient(c, isl_dim_out, 0, &v);
1850 if (n_div && (isl_int_is_one(v) || isl_int_is_negone(v))) {
1851 int s = isl_int_sgn(v);
1852 isl_int_set_si(stride, 0);
1853 for (i = 0; i < n_div; ++i) {
1854 isl_constraint_get_coefficient(c, isl_dim_div, i, &v);
1855 isl_int_gcd(stride, stride, v);
1857 if (!isl_int_is_zero(stride) &&
1858 isl_int_gt(stride, bound->stride))
1859 extract_stride(c, bound, stride, s);
1862 isl_int_clear(stride);
1863 isl_int_clear(v);
1865 isl_constraint_free(c);
1866 return 0;
1869 /* Given contraints on an array index i, check if we can find
1870 * a shift a(p) and a stride g such that
1872 * a(p) + i = 0 mod g
1874 * If so, record the information in bound and apply the mapping
1875 * i -> (i + a(p))/g to the array index in bounds and return
1876 * the new constraints.
1877 * If not, simply return the original constraints.
1879 * If bounds is a subset of the space
1881 * D -> i
1883 * then the bound recorded in bound->shift is of the form
1885 * D -> s(D)
1887 * with s(D) equal to a(p) above.
1888 * The mapping recorded in bound->shift_map is of the form
1890 * [D -> i] -> [D -> (i + S(D))/g]
1892 * This mapping is computed as follows.
1893 * We first introduce "i" in the domain through precomposition
1894 * with [D -> i] -> D obtaining
1896 * [D -> i] -> s(D)
1898 * Adding [D -> i] -> i produces
1900 * [D -> i] -> i + s(D)
1902 * and the domain product with [D -> i] -> D yields
1904 * [D -> i] -> [D -> i + s(D)]
1906 * Composition with [D -> i] -> [D -> i/g] gives the desired result.
1908 static __isl_give isl_basic_map *check_stride(struct gpu_array_bound *bound,
1909 __isl_take isl_basic_map *bounds)
1911 isl_space *space;
1912 isl_basic_map *hull;
1913 isl_basic_map *shift, *id, *bmap, *scale;
1914 isl_basic_set *bset;
1915 isl_aff *aff;
1917 isl_int_set_si(bound->stride, -1);
1919 hull = isl_basic_map_affine_hull(isl_basic_map_copy(bounds));
1921 isl_basic_map_foreach_constraint(hull, &check_stride_constraint, bound);
1923 isl_basic_map_free(hull);
1925 if (isl_int_is_neg(bound->stride))
1926 return bounds;
1928 shift = isl_basic_map_from_aff(isl_aff_copy(bound->shift));
1929 space = isl_basic_map_get_space(bounds);
1930 bmap = isl_basic_map_domain_map(isl_basic_map_universe(space));
1931 shift = isl_basic_map_apply_range(bmap, shift);
1932 space = isl_basic_map_get_space(bounds);
1933 id = isl_basic_map_range_map(isl_basic_map_universe(space));
1934 shift = isl_basic_map_sum(id, shift);
1935 space = isl_basic_map_get_space(bounds);
1936 id = isl_basic_map_domain_map(isl_basic_map_universe(space));
1937 shift = isl_basic_map_range_product(id, shift);
1939 space = isl_space_domain(isl_basic_map_get_space(bounds));
1940 id = isl_basic_map_identity(isl_space_map_from_set(space));
1941 space = isl_space_range(isl_basic_map_get_space(bounds));
1942 aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
1943 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, 0, 1);
1944 aff = isl_aff_scale_down(aff, bound->stride);
1945 scale = isl_basic_map_from_aff(aff);
1946 scale = isl_basic_map_product(id, scale);
1948 bound->shift_map = isl_basic_map_apply_range(shift, scale);
1949 bmap = isl_basic_map_copy(bound->shift_map);
1950 bset = isl_basic_set_apply(isl_basic_map_wrap(bounds), bmap);
1951 bounds = isl_basic_set_unwrap(bset);
1953 return bounds;
1956 /* Data used in compute_array_dim_size and compute_size_in_direction.
1958 * pos is the position of the variable representing the array index,
1959 * i.e., the variable for which want to compute the size. This variable
1960 * is also the last variable in the set.
1962 struct gpu_size_info {
1963 isl_basic_set *bset;
1964 struct gpu_array_bound *bound;
1965 int pos;
1968 /* Given a constraint from the basic set describing the bounds on
1969 * an array index, check if it is a lower bound, say m i >= b(x), and,
1970 * if so, check whether the expression "i - ceil(b(x)/m) + 1" has a constant
1971 * upper bound. If so, and if this bound is smaller than any bound
1972 * derived from earlier constraints, set the size to this bound on
1973 * the expression and the lower bound to ceil(b(x)/m).
1975 static int compute_size_in_direction(__isl_take isl_constraint *c, void *user)
1977 struct gpu_size_info *size = user;
1978 unsigned nparam;
1979 unsigned n_div;
1980 isl_int v;
1982 nparam = isl_basic_set_dim(size->bset, isl_dim_param);
1983 n_div = isl_constraint_dim(c, isl_dim_div);
1985 if (isl_constraint_involves_dims(c, isl_dim_div, 0, n_div)) {
1986 isl_constraint_free(c);
1987 return 0;
1990 isl_int_init(v);
1992 isl_constraint_get_coefficient(c, isl_dim_set, size->pos, &v);
1994 if (isl_int_is_pos(v)) {
1995 isl_aff *aff;
1996 isl_aff *lb;
1997 enum isl_lp_result res;
1999 aff = isl_constraint_get_bound(c, isl_dim_set, size->pos);
2000 aff = isl_aff_ceil(aff);
2002 lb = isl_aff_copy(aff);
2004 aff = isl_aff_neg(aff);
2005 aff = isl_aff_add_coefficient_si(aff, isl_dim_in, size->pos, 1);
2007 res = isl_basic_set_max(size->bset, aff, &v);
2008 isl_aff_free(aff);
2010 if (res == isl_lp_ok) {
2011 isl_int_add_ui(v, v, 1);
2012 if (isl_int_is_neg(size->bound->size) ||
2013 isl_int_lt(v, size->bound->size)) {
2014 isl_int_set(size->bound->size, v);
2015 lb = isl_aff_drop_dims(lb, isl_dim_in,
2016 size->pos, 1);
2017 isl_aff_free(size->bound->lb);
2018 size->bound->lb = isl_aff_copy(lb);
2021 isl_aff_free(lb);
2024 isl_int_clear(v);
2025 isl_constraint_free(c);
2027 return 0;
2030 /* Given a basic map "bounds" that maps parameters and input dimensions
2031 * to a single output dimension, look for an expression in the parameters
2032 * and input dimensions such that the range of the output dimension shifted
2033 * by this expression is a constant.
2035 * In particular, we currently only consider lower bounds on the output
2036 * dimension as candidate expressions.
2038 static int compute_array_dim_size(struct gpu_array_bound *bound,
2039 __isl_take isl_basic_map *bounds)
2041 struct gpu_size_info size;
2043 bounds = isl_basic_map_detect_equalities(bounds);
2044 bounds = check_stride(bound, bounds);
2046 isl_int_set_si(bound->size, -1);
2047 bound->lb = NULL;
2049 size.bound = bound;
2050 size.pos = isl_basic_map_dim(bounds, isl_dim_in);
2051 size.bset = isl_basic_map_wrap(bounds);
2052 size.bset = isl_basic_set_flatten(size.bset);
2053 size.bset = isl_set_simple_hull(isl_basic_set_compute_divs(size.bset));
2054 isl_basic_set_foreach_constraint(size.bset, &compute_size_in_direction,
2055 &size);
2056 isl_basic_set_free(size.bset);
2058 return isl_int_is_nonneg(bound->size) ? 0 : -1;
2061 /* Check if we can find a shared memory tile for the given array
2062 * based on the given accesses, and if so, put the results
2063 * in array->shared_bound.
2065 * We project the accesses on each index in turn and look for a parametric
2066 * offset such that the size is constant.
2068 static int can_tile_for_shared_memory(struct gpu_array_info *array,
2069 __isl_keep isl_map *access, struct gpu_array_bound *bounds)
2071 int i;
2073 for (i = 0; i < array->n_index; ++i) {
2074 isl_map *access_i;
2075 isl_basic_map *hull;
2077 access_i = isl_map_copy(access);
2078 access_i = isl_map_project_out(access_i, isl_dim_out, 0, i);
2079 access_i = isl_map_project_out(access_i, isl_dim_out,
2080 1, array->n_index - (i + 1));
2081 access_i = isl_map_compute_divs(access_i);
2082 hull = isl_map_simple_hull(access_i);
2083 if (compute_array_dim_size(&bounds[i], hull) < 0)
2084 return 0;
2087 return 1;
2090 /* Construct a map with input the shared tile loops and the loops that
2091 * will be wrapped around the threads that relates these later loops
2092 * to the thread indices and then projects them out.
2094 static __isl_give isl_map *compute_privatization(struct gpu_gen *gen)
2096 isl_map *priv;
2097 isl_map *tiling;
2098 isl_map *proj;
2099 isl_set *par;
2100 isl_space *dim;
2102 dim = isl_union_map_get_space(gen->shared_sched);
2104 if (gen->options->wrap)
2105 tiling = wrap(isl_space_copy(dim), gen->shared_len + gen->n_block,
2106 gen->shared_len, gen->n_block, gen->block_dim);
2107 else
2108 tiling = tile(isl_space_copy(dim), gen->shared_len + gen->n_block,
2109 gen->shared_len, gen->n_block, gen->block_dim);
2111 priv = tiling;
2113 par = parametrization(dim, gen->shared_len + 2 * gen->n_block,
2114 gen->tile_first + gen->tile_len + gen->n_grid + gen->n_block,
2115 gen->n_block, "t");
2117 priv = isl_map_align_params(priv, isl_set_get_space(par));
2118 priv = isl_map_intersect_range(priv, par);
2120 dim = isl_map_get_space(priv);
2121 dim = isl_space_drop_dims(dim, isl_dim_in, 0, isl_space_dim(dim, isl_dim_in));
2122 dim = isl_space_drop_dims(dim, isl_dim_out, 0, isl_space_dim(dim, isl_dim_out));
2123 proj = projection(dim, gen->shared_len + 2 * gen->n_block,
2124 gen->shared_len);
2126 priv = isl_map_apply_range(priv, proj);
2128 return priv;
2131 /* Construct a map from domain_dim to domain_dim that increments
2132 * the dimension at position "pos" and leaves all other dimensions
2133 * constant.
2135 static __isl_give isl_map *next(__isl_take isl_space *domain_dim, int pos)
2137 int i;
2138 int len = isl_space_dim(domain_dim, isl_dim_set);
2139 isl_space *dim;
2140 isl_basic_map *next;
2141 isl_local_space *ls;
2143 dim = isl_space_map_from_set(domain_dim);
2144 next = isl_basic_map_universe(isl_space_copy(dim));
2145 ls = isl_local_space_from_space(dim);
2147 for (i = 0; i < len; ++i) {
2148 isl_constraint *c;
2150 c = isl_equality_alloc(isl_local_space_copy(ls));
2151 isl_constraint_set_coefficient_si(c, isl_dim_in, i, 1);
2152 isl_constraint_set_coefficient_si(c, isl_dim_out, i, -1);
2153 if (i == pos)
2154 isl_constraint_set_constant_si(c, 1);
2155 next = isl_basic_map_add_constraint(next, c);
2158 isl_local_space_free(ls);
2160 return isl_map_from_basic_map(next);
2163 /* Check if the given access is coalesced.
2164 * That is, check whether incrementing the dimension that will get
2165 * wrapped over the last thread index results in incrementing
2166 * the last array index.
2168 * This function is only called for access relations without reuse.
2170 static int access_is_coalesced(struct gpu_gen *gen,
2171 __isl_keep isl_union_map *access)
2173 isl_space *dim;
2174 isl_map *access_map;
2175 isl_map *next_thread_x;
2176 isl_map *next_element;
2177 isl_map *map;
2178 int coalesced;
2180 access = isl_union_map_copy(access);
2181 access = isl_union_map_apply_domain(access,
2182 isl_union_map_copy(gen->tiled_sched));
2183 access_map = isl_map_from_union_map(access);
2185 dim = isl_map_get_space(access_map);
2186 dim = isl_space_domain(dim);
2187 next_thread_x = next(dim, gen->shared_len + gen->n_block - 1);
2189 dim = isl_map_get_space(access_map);
2190 dim = isl_space_range(dim);
2191 next_element = next(dim, isl_space_dim(dim, isl_dim_set) - 1);
2193 map = isl_map_apply_domain(next_thread_x, isl_map_copy(access_map));
2194 map = isl_map_apply_range(map, access_map);
2196 coalesced = isl_map_is_subset(map, next_element);
2198 isl_map_free(next_element);
2199 isl_map_free(map);
2201 return coalesced;
2204 /* Given an access relation in terms of the first gen->shared_len + gen->n_block
2205 * dimensions of the computed schedule, check if it is bijective for
2206 * fixed values of the first gen->shared_len dimensions.
2207 * We perform this check by equating these dimensions to parameters.
2209 static int access_is_bijective(struct gpu_gen *gen, __isl_keep isl_map *access)
2211 int res;
2212 isl_set *par;
2213 isl_space *space;
2215 access = isl_map_copy(access);
2216 space = isl_space_params(isl_map_get_space(access));
2217 par = parametrization(space, gen->shared_len + gen->n_block,
2218 0, gen->shared_len, "s");
2219 access = isl_map_intersect_domain(access, par);
2220 res = isl_map_is_bijective(access);
2221 isl_map_free(access);
2223 return res;
2226 /* For the given array reference group, check whether the access is private
2227 * to the thread. That is, check that any given array element
2228 * is only accessed by a single thread.
2229 * We compute an access relation that maps the shared tile loop iterators
2230 * and the shared point loop iterators that will be wrapped over the
2231 * threads to the array elements.
2232 * We actually check that those iterators that will be wrapped
2233 * partition the array space. This check is stricter than necessary
2234 * since several iterations may be mapped onto the same thread
2235 * and then they could be allowed to access the same memory elements,
2236 * but our check does not allow this situation.
2238 * We also check that the index expression only depends on parallel
2239 * loops. That way, we can move those loops innermost and unroll them.
2240 * Again, we use a test that is stricter than necessary.
2241 * We actually check whether the index expression only depends
2242 * on the iterators that are wrapped over the threads.
2243 * These are necessarily parallel, but there may be more parallel loops.
2245 * Combining the injectivity of the first test with the single-valuedness
2246 * of the second test, we simply test for bijectivity.
2248 * If it turns out we can use registers, we compute the private memory
2249 * tile size using can_tile_for_shared_memory, after introducing a dependence
2250 * on the thread indices.
2252 * Before performing any of the above computations, we first check
2253 * if there is any reuse on the reference group. If not, we simply
2254 * return. If, moreover, the access is coalesced then we also remove
2255 * the shared memory tiling since we should just use global memory instead.
2257 static void check_private_group_access(struct gpu_gen *gen,
2258 struct gpu_array_ref_group *group)
2260 isl_map *acc;
2261 isl_union_map *access;
2262 int n_index = group->array->n_index;
2264 access = group_access_relation(group, 1, 1);
2265 if (isl_union_map_is_injective(access)) {
2266 if (group->shared_bound && access_is_coalesced(gen, access)) {
2267 free_bound_list(group->shared_bound, n_index);
2268 group->shared_bound = NULL;
2270 isl_union_map_free(access);
2271 return;
2273 access = isl_union_map_apply_domain(access,
2274 isl_union_map_copy(gen->shared_sched));
2276 acc = isl_map_from_union_map(access);
2278 if (!access_is_bijective(gen, acc)) {
2279 isl_map_free(acc);
2280 return;
2283 group->private_bound = create_bound_list(gen->ctx, n_index);
2284 acc = isl_map_apply_domain(acc, isl_map_copy(gen->privatization));
2285 if (!can_tile_for_shared_memory(group->array, acc,
2286 group->private_bound)) {
2287 free_bound_list(group->private_bound, n_index);
2288 group->private_bound = NULL;
2291 isl_map_free(acc);
2294 /* Look for the last shared tile loop that affects the offset of the
2295 * shared or private tile and store the result in array->last_shared.
2296 * If there is no such loop, then array->last_shared is set to a value
2297 * before the first shared tile loop, in particular gen->tile_first - 1.
2299 static void set_last_shared(struct gpu_gen *gen,
2300 struct gpu_array_ref_group *group)
2302 int i, j;
2303 struct gpu_array_bound *bounds;
2304 int n_index = group->array->n_index;
2306 bounds = group->private_bound;
2307 if (!bounds)
2308 bounds = group->shared_bound;
2309 if (!bounds)
2310 return;
2312 for (j = gen->shared_len - 1; j >= gen->tile_first; --j) {
2313 for (i = 0; i < n_index; ++i) {
2314 isl_aff *lb;
2315 isl_aff *shift;
2317 lb = bounds[i].lb;
2318 if (isl_aff_involves_dims(lb, isl_dim_in, j, 1))
2319 break;
2321 shift = bounds[i].shift;
2322 if (!shift)
2323 continue;
2324 if (isl_aff_involves_dims(shift, isl_dim_in, j, 1))
2325 break;
2327 if (i < n_index)
2328 break;
2330 group->last_shared = j;
2333 /* Compute the sizes of all private arrays for the current kernel,
2334 * as well as the offsets of the private pieces in the original arrays.
2335 * If we cannot or don't want to privatize a given array group,
2336 * we use the shared memory tile sizes computed in
2337 * compute_group_shared_bound instead.
2339 * If we have been able to find a private or shared tile,
2340 * we also look for the last shared tile loop that affects the offset
2341 * (and therefore the group tile) and store the result in group->last_shared.
2343 * A privatized copy of all access relations from reference groups that
2344 * are mapped to private memory is stored in gen->privatization.
2346 static void compute_private_size(struct gpu_gen *gen)
2348 int i, j;
2349 isl_union_map *private;
2351 if (!gen->options->use_private_memory)
2352 return;
2354 private = isl_union_map_empty(isl_union_map_get_space(gen->shared_sched));
2356 for (i = 0; i < gen->n_array; ++i) {
2357 struct gpu_array_info *array = &gen->array[i];
2359 if (gpu_array_is_read_only_scalar(array))
2360 continue;
2362 for (j = 0; j < array->n_group; ++j) {
2363 check_private_group_access(gen, array->groups[j]);
2365 if (!array->groups[j]->private_bound)
2366 continue;
2368 private = isl_union_map_union(private,
2369 group_access_relation(array->groups[j], 1, 1));
2372 for (j = 0; j < array->n_group; ++j) {
2373 array->groups[j]->last_shared = gen->shared_len - 1;
2374 set_last_shared(gen, array->groups[j]);
2378 if (isl_union_map_is_empty(private))
2379 isl_union_map_free(private);
2380 else {
2381 isl_union_map *priv;
2383 private = isl_union_map_apply_domain(private,
2384 isl_union_map_copy(gen->shared_sched));
2385 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
2386 private = isl_union_map_apply_domain(private, priv);
2387 gen->private_access = private;
2391 /* Compute the size of the tile specified by the list "bound" of n_index
2392 * gpu_array_bounds in number of elements and put the result in *size.
2394 static void tile_size(unsigned n_index, struct gpu_array_bound *bound,
2395 isl_int *size)
2397 int i;
2399 isl_int_set_si(*size, 1);
2401 for (i = 0; i < n_index; ++i)
2402 isl_int_mul(*size, *size, bound[i].size);
2405 /* If max_shared_memory is not set to infinity (-1), then make
2406 * sure that the total amount of shared memory required by the
2407 * array reference groups mapped to shared memory is no larger
2408 * than this maximum.
2410 * We apply a greedy approach and discard (keep in global memory)
2411 * those groups that would result in a total memory size that
2412 * is larger than the maximum.
2414 static void check_shared_memory_bound(struct gpu_gen *gen)
2416 int i, j;
2417 isl_int left, size;
2419 if (gen->options->max_shared_memory < 0)
2420 return;
2422 isl_int_init(left);
2423 isl_int_init(size);
2424 isl_int_set_si(left, gen->options->max_shared_memory);
2426 for (i = 0; i < gen->n_array; ++i) {
2427 struct gpu_array_info *array = &gen->array[i];
2429 for (j = 0; j < array->n_group; ++j) {
2430 struct gpu_array_ref_group *group;
2432 group = array->groups[j];
2433 if (!group->shared_bound)
2434 continue;
2436 tile_size(array->n_index, group->shared_bound, &size);
2437 isl_int_mul_ui(size, size, array->size);
2439 if (isl_int_le(size, left)) {
2440 isl_int_sub(left, left, size);
2441 continue;
2444 free_bound_list(group->shared_bound, array->n_index);
2445 group->shared_bound = NULL;
2449 isl_int_clear(size);
2450 isl_int_clear(left);
2453 /* Fill up the groups array with singleton groups, i.e., one group
2454 * per reference, initializing the array, access, write and refs fields.
2455 * In particular the access field is initialized to the scheduled
2456 * access relation of the array reference.
2458 * Return the number of elements initialized, i.e., the number of
2459 * active references in the current kernel.
2461 static int populate_array_references(struct gpu_array_info *array,
2462 __isl_keep isl_union_map *sched, struct gpu_array_ref_group **groups)
2464 int i;
2465 int n;
2466 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2468 n = 0;
2469 for (i = 0; i < array->n_ref; ++i) {
2470 isl_union_map *umap;
2471 isl_map *map;
2472 struct gpu_array_ref_group *group;
2473 struct gpu_stmt_access *access = array->refs[i];
2475 map = isl_map_copy(access->access);
2476 umap = isl_union_map_from_map(map);
2477 umap = isl_union_map_apply_domain(umap,
2478 isl_union_map_copy(sched));
2480 if (isl_union_map_is_empty(umap)) {
2481 isl_union_map_free(umap);
2482 continue;
2485 map = isl_map_from_union_map(umap);
2486 map = isl_map_detect_equalities(map);
2488 group = isl_calloc_type(ctx, struct gpu_array_ref_group);
2489 assert(group);
2490 group->array = array;
2491 group->access = map;
2492 group->write = access->write;
2493 group->refs = &array->refs[i];
2495 groups[n++] = group;
2498 return n;
2501 static void free_array_ref_group(struct gpu_array_ref_group *group,
2502 int n_index)
2504 if (!group)
2505 return;
2506 free_bound_list(group->shared_bound, n_index);
2507 free_bound_list(group->private_bound, n_index);
2508 isl_map_free(group->access);
2509 free(group->refs);
2510 free(group);
2513 /* Given a map where the input dimensions represent the tile loops,
2514 * eliminate the innermost of those that have a fixed value
2515 * until we reach one that does not (obviously) have a fixed value.
2517 static __isl_give isl_map *eliminate_fixed_inner_loops(
2518 __isl_take isl_map *access)
2520 int i, n;
2522 n = isl_map_dim(access, isl_dim_in);
2524 for (i = n - 1; i >= 0; --i) {
2525 if (!isl_map_plain_is_fixed(access, isl_dim_in, i, NULL))
2526 break;
2527 access = isl_map_eliminate(access, isl_dim_in, i, 1);
2529 return access;
2532 /* Check if the access relations of group1 and group2 overlap within
2533 * the innermost loop. In particular, ignore any inner dimension
2534 * with a fixed value.
2535 * The copying to and from shared memory will be performed within
2536 * the innermost actual loop so we are only allowed to consider
2537 * the dimensions up to that innermost loop while checking whether
2538 * two access relations overlap.
2540 static int accesses_overlap(struct gpu_array_ref_group *group1,
2541 struct gpu_array_ref_group *group2)
2543 int empty;
2544 isl_map *access1, *access2;
2546 access1 = isl_map_copy(group1->access);
2547 access1 = eliminate_fixed_inner_loops(access1);
2548 access2 = isl_map_copy(group2->access);
2549 access2 = eliminate_fixed_inner_loops(access2);
2550 access1 = isl_map_intersect(access1, access2);
2551 empty = isl_map_is_empty(access1);
2552 isl_map_free(access1);
2554 return !empty;
2557 /* If two groups have overlapping access relations (within the innermost
2558 * loop) and if one of them involves a write, then merge the two groups
2559 * into one.
2561 * We keep track of the grouping in "leader". leader[j] points to
2562 * an earlier group array element that belongs to the same group,
2563 * or the array element j itself if this element is the first in the group.
2565 * Return the number of group leaders.
2567 static int group_overlapping_writes(int n,
2568 struct gpu_array_ref_group **groups, int *leader)
2570 int i, j;
2571 int n_group = n;
2573 for (i = 0; i < n; ++i) {
2574 int l = i;
2575 groups[l]->n_ref = 1;
2576 for (j = i - 1; j >= 0; --j) {
2577 if (leader[j] != j)
2578 continue;
2579 if (!groups[l]->write && !groups[j]->write)
2580 continue;
2582 if (!accesses_overlap(groups[l], groups[j]))
2583 continue;
2585 groups[j]->access = isl_map_union(groups[j]->access,
2586 groups[l]->access);
2587 groups[j]->write = 1;
2588 groups[l]->access = NULL;
2589 groups[j]->n_ref += groups[l]->n_ref;
2590 l = leader[l] = j;
2591 n_group--;
2593 leader[i] = l;
2596 return n_group;
2599 /* Compute the size of the shared array corresponding to the given
2600 * array reference group, based on the accesses from the current kernel,
2601 * as well as the offset of the shared piece in the original array.
2603 static void compute_group_shared_bound(struct gpu_gen *gen,
2604 struct gpu_array_info *array, struct gpu_array_ref_group *group)
2606 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2608 if (!gen->options->use_shared_memory)
2609 return;
2610 if (gpu_array_is_read_only_scalar(array))
2611 return;
2613 group->shared_bound = create_bound_list(ctx, array->n_index);
2614 if (!can_tile_for_shared_memory(array, group->access,
2615 group->shared_bound)) {
2616 free_bound_list(group->shared_bound, array->n_index);
2617 group->shared_bound = NULL;
2621 /* Is the size of the tile specified by "bound" smaller than the sum of
2622 * the sizes of the tiles specified by "bound1" and "bound2"?
2624 static int smaller_tile(unsigned n_index, struct gpu_array_bound *bound,
2625 struct gpu_array_bound *bound1, struct gpu_array_bound *bound2)
2627 int smaller;
2628 isl_int size, size1, size2;
2630 isl_int_init(size);
2631 isl_int_init(size1);
2632 isl_int_init(size2);
2634 tile_size(n_index, bound, &size);
2635 tile_size(n_index, bound1, &size1);
2636 tile_size(n_index, bound2, &size2);
2638 isl_int_sub(size, size, size1);
2639 isl_int_sub(size, size, size2);
2640 smaller = isl_int_is_neg(size);
2642 isl_int_clear(size2);
2643 isl_int_clear(size1);
2644 isl_int_clear(size);
2646 return smaller;
2649 /* Given an initial grouping of array references and shared memory tiles
2650 * for each group that allows for a shared memory tile, merge two groups
2651 * if both have a shared memory tile, the merged group also has
2652 * a shared memory tile and the size of the tile for the merge group
2653 * is smaller than the sum of the tile sizes of the individual groups.
2655 * Return the number of group leaders after merging.
2657 static int group_common_shared_memory_tile(struct gpu_array_info *array, int n,
2658 struct gpu_array_ref_group **groups, int *leader, int n_group)
2660 int i, j;
2661 isl_ctx *ctx = isl_space_get_ctx(array->dim);
2663 for (i = 0; n_group > 1 && i < n; ++i) {
2664 int l = i;
2665 if (leader[i] != i)
2666 continue;
2667 if (!groups[i]->shared_bound)
2668 continue;
2669 for (j = i - 1; j >= 0; --j) {
2670 isl_map *map;
2671 int empty;
2672 struct gpu_array_bound *shared_bound;
2674 if (leader[j] != j)
2675 continue;
2676 if (!groups[j]->shared_bound)
2677 continue;
2679 map = isl_map_intersect(isl_map_copy(groups[l]->access),
2680 isl_map_copy(groups[j]->access));
2681 empty = isl_map_is_empty(map);
2682 isl_map_free(map);
2684 if (empty)
2685 continue;
2687 map = isl_map_union(isl_map_copy(groups[l]->access),
2688 isl_map_copy(groups[j]->access));
2689 shared_bound = create_bound_list(ctx, array->n_index);
2690 if (!can_tile_for_shared_memory(array, map,
2691 shared_bound) ||
2692 !smaller_tile(array->n_index, shared_bound,
2693 groups[l]->shared_bound,
2694 groups[j]->shared_bound)) {
2695 isl_map_free(map);
2696 free_bound_list(shared_bound, array->n_index);
2697 continue;
2700 free_bound_list(groups[j]->shared_bound,
2701 array->n_index);
2702 groups[j]->shared_bound = shared_bound;
2703 isl_map_free(groups[j]->access);
2704 groups[j]->access = map;
2705 groups[j]->n_ref += groups[l]->n_ref;
2706 l = leader[l] = j;
2707 n_group--;
2711 return n_group;
2714 /* Extract an array of array reference groups from the array of references
2715 * and the grouping information in "leader".
2717 * Store the results in array->n_group and array->groups.
2719 static void extract_array_groups(isl_ctx *ctx, struct gpu_array_info *array,
2720 int n, struct gpu_array_ref_group **groups, int *leader, int n_group)
2722 int i, j;
2724 for (i = 2; i < n; ++i)
2725 leader[i] = leader[leader[i]];
2727 array->n_group = n_group;
2728 array->groups = isl_alloc_array(ctx, struct gpu_array_ref_group *,
2729 n_group);
2730 assert(array->groups);
2732 j = 0;
2733 for (i = 0; i < n; ++i) {
2734 int k, l;
2735 struct gpu_stmt_access **refs;
2737 if (leader[i] != i) {
2738 groups[i]->refs = NULL;
2739 free_array_ref_group(groups[i], array->n_index);
2740 continue;
2743 refs = isl_alloc_array(ctx, struct gpu_stmt_access *,
2744 groups[i]->n_ref);
2745 assert(refs);
2746 l = 0;
2747 for (k = i; k < n; ++k)
2748 if (leader[k] == i) {
2749 refs[l++] = *groups[k]->refs;
2750 (*groups[k]->refs)->group = j;
2753 groups[i]->refs = refs;
2754 groups[i]->nr = j;
2755 array->groups[j++] = groups[i];
2759 /* Group array references that should be considered together when
2760 * deciding whether to access them from private, shared or global memory.
2762 * In particular, if two array references overlap and if one of them
2763 * is a write, then the two references are grouped together.
2764 * Furthermore, if two groups admit a shared memory tile and if the
2765 * combination of the two also admits a shared memory tile, we merge
2766 * the two groups.
2768 * During the construction the group->refs field points to a single
2769 * array reference inside the array of array references, while
2770 * group->n_ref contains the number of element in leader that
2771 * (directly or indirectly) point to this group, provided the group
2772 * is a leader.
2774 static void group_array_references(struct gpu_gen *gen,
2775 struct gpu_array_info *array, __isl_keep isl_union_map *sched)
2777 int i;
2778 int n, n_group;
2779 isl_ctx *ctx = isl_union_map_get_ctx(sched);
2780 struct gpu_array_ref_group **groups;
2781 int *leader;
2783 groups = isl_calloc_array(ctx, struct gpu_array_ref_group *,
2784 array->n_ref);
2785 assert(groups);
2787 n = populate_array_references(array, sched, groups);
2789 leader = isl_alloc_array(ctx, int, n);
2790 assert(leader);
2792 n_group = group_overlapping_writes(n, groups, leader);
2794 for (i = 0; i < n; ++i)
2795 if (leader[i] == i)
2796 compute_group_shared_bound(gen, array, groups[i]);
2798 n_group = group_common_shared_memory_tile(array, n, groups,
2799 leader, n_group);
2801 extract_array_groups(ctx, array, n, groups, leader, n_group);
2803 free(leader);
2804 free(groups);
2807 /* Take tiled_sched, project it onto the shared tile loops and
2808 * the loops that will be wrapped over the threads and
2809 * store the result in gen->shared_sched.
2810 * Also compute a projection that projects out the loops that will be
2811 * wrapped over the threads and store this projection in gen->shared_proj.
2813 static void compute_shared_sched(struct gpu_gen *gen)
2815 isl_space *dim;
2816 isl_map *proj;
2817 isl_set *par;
2818 isl_union_map *sched;
2820 sched = isl_union_map_copy(gen->tiled_sched);
2822 dim = isl_union_map_get_space(sched);
2823 proj = projection(dim, gen->tiled_len, gen->shared_len + gen->n_block);
2824 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
2826 dim = isl_union_map_get_space(sched);
2827 proj = projection(dim, gen->shared_len + gen->n_block, gen->shared_len);
2829 gen->shared_sched = sched;
2830 gen->shared_proj = isl_union_map_from_map(proj);
2833 /* Group references of all arrays in the program.
2835 static void group_references(struct gpu_gen *gen)
2837 int i;
2838 isl_union_map *sched;
2840 sched = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
2841 isl_union_map_copy(gen->shared_proj));
2843 for (i = 0; i < gen->n_array; ++i)
2844 group_array_references(gen, &gen->array[i], sched);
2846 isl_union_map_free(sched);
2849 /* Free all array information that is local to the current kernel.
2851 static void free_local_array_info(struct gpu_gen *gen)
2853 int i, j;
2855 for (i = 0; i < gen->n_array; ++i) {
2856 struct gpu_array_info *array = &gen->array[i];
2858 for (j = 0; j < array->n_group; ++j)
2859 free_array_ref_group(array->groups[j], array->n_index);
2860 free(array->groups);
2864 /* Extract a description of the grid, i.e., the possible values
2865 * of the block ids, from gen->tiled_sched.
2866 * The block ids are parameters in gen->tiled_sched.
2867 * We simply need to change them into set dimensions.
2869 static __isl_give isl_set *extract_grid(struct gpu_gen *gen)
2871 int i;
2872 isl_set *grid;
2874 grid = isl_union_map_params(isl_union_map_copy(gen->tiled_sched));
2875 grid = isl_set_from_params(grid);
2876 grid = isl_set_add_dims(grid, isl_dim_set, gen->n_grid);
2877 for (i = 0; i < gen->n_grid; ++i) {
2878 int pos;
2879 char name[20];
2881 snprintf(name, sizeof(name), "b%d", i);
2882 pos = isl_set_find_dim_by_name(grid, isl_dim_param, name);
2883 assert(pos >= 0);
2884 grid = isl_set_equate(grid, isl_dim_param, pos, isl_dim_set, i);
2885 grid = isl_set_project_out(grid, isl_dim_param, pos, 1);
2888 return grid;
2891 enum ppcg_kernel_access_type {
2892 ppcg_access_global,
2893 ppcg_access_shared,
2894 ppcg_access_private
2897 /* Representation of a local variable in a kernel.
2899 struct ppcg_kernel_var {
2900 struct gpu_array_info *array;
2901 enum ppcg_kernel_access_type type;
2902 char *name;
2903 isl_vec *size;
2906 /* Representation of a kernel.
2908 * id is the sequence number of the kernel.
2910 * the first n_block elements of block_dim represent the size of the block.
2912 * grid contains the values of the block ids.
2914 * context is a parametric set containing the values of the parameters
2915 * for which this kernel may be run.
2917 * arrays is the set of accessed array elements.
2919 * space is the schedule space of the AST context. That is, it represents
2920 * the loops of the generated host code containing the kernel launch.
2922 * n_array is the total number of arrays in the input program and also
2923 * the number of element in the array array.
2924 * array contains information about each array that is local
2925 * to the current kernel. If an array is not ussed in a kernel,
2926 * then the corresponding entry does not contain any information.
2928 struct ppcg_kernel {
2929 int id;
2931 int n_block;
2932 int block_dim[3];
2934 isl_set *grid;
2935 isl_set *context;
2937 isl_union_set *arrays;
2939 isl_space *space;
2941 int n_array;
2942 struct gpu_local_array_info *array;
2944 int n_var;
2945 struct ppcg_kernel_var *var;
2948 void ppcg_kernel_free(void *user)
2950 struct ppcg_kernel *kernel = user;
2951 int i;
2953 if (!kernel)
2954 return;
2956 isl_set_free(kernel->grid);
2957 isl_set_free(kernel->context);
2958 isl_union_set_free(kernel->arrays);
2959 isl_space_free(kernel->space);
2961 for (i = 0; i < kernel->n_array; ++i)
2962 isl_pw_aff_list_free(kernel->array[i].bound);
2963 free(kernel->array);
2965 for (i = 0; i < kernel->n_var; ++i) {
2966 free(kernel->var[i].name);
2967 isl_vec_free(kernel->var[i].size);
2969 free(kernel->var);
2971 free(kernel);
2974 static void create_kernel_var(isl_ctx *ctx, struct gpu_array_ref_group *group,
2975 struct ppcg_kernel_var *var)
2977 int j;
2978 struct gpu_array_bound *bounds;
2979 isl_printer *p;
2980 char *name;
2982 var->array = group->array;
2984 bounds = group->private_bound;
2985 var->type = ppcg_access_private;
2986 if (!bounds) {
2987 bounds = group->shared_bound;
2988 var->type = ppcg_access_shared;
2991 p = isl_printer_to_str(ctx);
2992 p = print_array_name(p, group);
2993 var->name = isl_printer_get_str(p);
2994 isl_printer_free(p);
2996 var->size = isl_vec_alloc(ctx, group->array->n_index);
2998 for (j = 0; j < group->array->n_index; ++j)
2999 var->size = isl_vec_set_element(var->size, j, bounds[j].size);
3002 static void print_kernel_var(FILE *out, struct ppcg_kernel_var *var)
3004 int j;
3005 isl_int v;
3007 print_indent(out, 4);
3008 if (var->type == ppcg_access_shared)
3009 fprintf(out, "__shared__ ");
3010 fprintf(out, "%s %s", var->array->type, var->name);
3011 isl_int_init(v);
3012 for (j = 0; j < var->array->n_index; ++j) {
3013 fprintf(out, "[");
3014 isl_vec_get_element(var->size, j, &v);
3015 isl_int_print(out, v, 0);
3016 fprintf(out, "]");
3018 isl_int_clear(v);
3019 fprintf(out, ";\n");
3022 static void print_shared_arrays(struct gpu_gen *gen, struct ppcg_kernel *kernel)
3024 int i, j, n;
3026 n = 0;
3027 for (i = 0; i < gen->n_array; ++i) {
3028 struct gpu_array_info *array = &gen->array[i];
3030 for (j = 0; j < array->n_group; ++j) {
3031 struct gpu_array_ref_group *group = array->groups[j];
3032 if (group->private_bound || group->shared_bound)
3033 ++n;
3037 kernel->n_var = n;
3038 kernel->var = isl_calloc_array(gen->ctx, struct ppcg_kernel_var, n);
3039 assert(kernel->var);
3041 n = 0;
3042 for (i = 0; i < gen->n_array; ++i) {
3043 struct gpu_array_info *array = &gen->array[i];
3045 for (j = 0; j < array->n_group; ++j) {
3046 struct gpu_array_ref_group *group = array->groups[j];
3047 if (!group->private_bound && !group->shared_bound)
3048 continue;
3049 create_kernel_var(gen->ctx, group, &kernel->var[n]);
3050 ++n;
3054 for (i = 0; i < kernel->n_var; ++i)
3055 print_kernel_var(gen->cuda.kernel_c, &kernel->var[i]);
3058 /* The sizes of the arrays on the host that have been computed by
3059 * extract_array_info may depend on the parameters. Use the extra
3060 * constraints on the parameters that are valid at "host_domain"
3061 * to simplify these expressions and store the results in kernel->array.
3063 static void localize_bounds(struct gpu_gen *gen, struct ppcg_kernel *kernel,
3064 __isl_keep isl_set *host_domain)
3066 int i, j;
3067 isl_set *context;
3069 kernel->array = isl_calloc_array(gen->ctx,
3070 struct gpu_local_array_info, gen->n_array);
3071 assert(kernel->array);
3072 kernel->n_array = gen->n_array;
3074 context = isl_set_copy(host_domain);
3075 context = isl_set_params(context);
3077 for (i = 0; i < gen->n_array; ++i) {
3078 struct gpu_array_info *array = &gen->array[i];
3079 isl_pw_aff_list *local;
3081 if (array->n_group == 0)
3082 continue;
3084 local = isl_pw_aff_list_alloc(gen->ctx, array->n_index);
3086 for (j = 0; j < array->n_index; ++j) {
3087 isl_pw_aff *pwaff;
3089 pwaff = isl_pw_aff_copy(array->bound[j]);
3090 pwaff = isl_pw_aff_gist(pwaff, isl_set_copy(context));
3091 local = isl_pw_aff_list_add(local, pwaff);
3094 kernel->array[i].bound = local;
3096 isl_set_free(context);
3099 /* Find the element in gen->stmt that has the given "id".
3100 * Return NULL if no such gpu_stmt can be found.
3102 static struct gpu_stmt *find_stmt(struct gpu_gen *gen, __isl_keep isl_id *id)
3104 int i;
3106 for (i = 0; i < gen->n_stmts; ++i) {
3107 isl_id *id_i;
3109 id_i = isl_set_get_tuple_id(gen->stmts[i].domain);
3110 isl_id_free(id_i);
3111 if (id == id_i)
3112 break;
3115 return i < gen->n_stmts ? &gen->stmts[i] : NULL;
3118 /* Set gen->tile_len and gen->n_parallel to those of the statement
3119 * affected by the first map (part of the schedule)
3120 * on which this function is called.
3121 * Because of the way the schedule is constructed, the other statements
3122 * in the list, if any, should have the same values for these properties.
3124 static int extract_tile_len(__isl_take isl_map *map, void *user)
3126 struct gpu_gen *gen = (struct gpu_gen *) user;
3127 isl_id *id;
3128 struct gpu_stmt *stmt;
3130 id = isl_map_get_tuple_id(map, isl_dim_in);
3131 stmt = find_stmt(gen, id);
3132 isl_id_free(id);
3134 isl_map_free(map);
3136 if (!stmt)
3137 isl_die(gen->ctx, isl_error_unknown,
3138 "statement not found", return -1);
3140 gen->tile_len = stmt->tile_len;
3141 gen->n_parallel = stmt->n_parallel;
3143 return -1;
3146 /* Print the arguments to a kernel declaration or call. If "types" is set,
3147 * then print a declaration (including the types of the arguments).
3149 * The arguments are printed in the following order
3150 * - the arrays accessed by the kernel
3151 * - the parameters
3152 * - the host loop iterators
3154 static __isl_give isl_printer *print_kernel_arguments(__isl_take isl_printer *p,
3155 struct gpu_gen *gen, struct ppcg_kernel *kernel, int types)
3157 int i, n;
3158 int first = 1;
3159 unsigned nparam;
3160 isl_space *space;
3161 const char *type;
3163 for (i = 0; i < gen->n_array; ++i) {
3164 isl_set *arr;
3165 int empty;
3167 space = isl_space_copy(gen->array[i].dim);
3168 arr = isl_union_set_extract_set(kernel->arrays, space);
3169 empty = isl_set_fast_is_empty(arr);
3170 isl_set_free(arr);
3171 if (empty)
3172 continue;
3174 if (!first)
3175 p = isl_printer_print_str(p, ", ");
3177 if (types) {
3178 p = isl_printer_print_str(p, gen->array[i].type);
3179 p = isl_printer_print_str(p, " ");
3182 if (gpu_array_is_read_only_scalar(&gen->array[i])) {
3183 p = isl_printer_print_str(p, gen->array[i].name);
3184 } else {
3185 if (types)
3186 p = isl_printer_print_str(p, "*");
3187 else
3188 p = isl_printer_print_str(p, "dev_");
3189 p = isl_printer_print_str(p, gen->array[i].name);
3192 first = 0;
3195 space = isl_union_set_get_space(kernel->arrays);
3196 nparam = isl_space_dim(space, isl_dim_param);
3197 for (i = 0; i < nparam; ++i) {
3198 const char *name;
3200 name = isl_space_get_dim_name(space, isl_dim_param, i);
3202 if (!first)
3203 p = isl_printer_print_str(p, ", ");
3204 if (types)
3205 p = isl_printer_print_str(p, "int ");
3206 p = isl_printer_print_str(p, name);
3208 first = 0;
3210 isl_space_free(space);
3212 n = isl_space_dim(kernel->space, isl_dim_set);
3213 type = isl_options_get_ast_iterator_type(gen->ctx);
3214 for (i = 0; i < n; ++i) {
3215 const char *name;
3216 isl_id *id;
3218 if (!first)
3219 p = isl_printer_print_str(p, ", ");
3220 name = isl_space_get_dim_name(kernel->space, isl_dim_set, i);
3221 if (types) {
3222 p = isl_printer_print_str(p, type);
3223 p = isl_printer_print_str(p, " ");
3225 p = isl_printer_print_str(p, name);
3227 first = 0;
3230 return p;
3233 /* Print the header of the given kernel.
3235 static __isl_give isl_printer *print_kernel_header(__isl_take isl_printer *p,
3236 struct gpu_gen *gen, struct ppcg_kernel *kernel)
3238 p = isl_printer_start_line(p);
3239 p = isl_printer_print_str(p, "__global__ void kernel");
3240 p = isl_printer_print_int(p, kernel->id);
3241 p = isl_printer_print_str(p, "(");
3242 p = print_kernel_arguments(p, gen, kernel, 1);
3243 p = isl_printer_print_str(p, ")");
3245 return p;
3248 /* Print the header of the given kernel to both gen->cuda.kernel_h
3249 * and gen->cuda.kernel_c.
3251 static void print_kernel_headers(struct gpu_gen *gen,
3252 struct ppcg_kernel *kernel)
3254 isl_printer *p;
3256 p = isl_printer_to_file(gen->ctx, gen->cuda.kernel_h);
3257 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
3258 p = print_kernel_header(p, gen, kernel);
3259 p = isl_printer_print_str(p, ";");
3260 p = isl_printer_end_line(p);
3261 isl_printer_free(p);
3263 p = isl_printer_to_file(gen->ctx, gen->cuda.kernel_c);
3264 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
3265 p = print_kernel_header(p, gen, kernel);
3266 p = isl_printer_end_line(p);
3267 isl_printer_free(p);
3270 enum ppcg_kernel_stmt_type {
3271 ppcg_kernel_copy,
3272 ppcg_kernel_domain,
3273 ppcg_kernel_sync
3276 /* Instance specific information about an access inside a kernel statement.
3278 * type indicates whether it is a global, shared or private access
3279 * array is the original array information and may be NULL in case
3280 * of an affine expression
3281 * local_array is a pointer to the appropriate element in the "array"
3282 * array of the ppcg_kernel to which this access belongs. It is
3283 * NULL whenever array is NULL.
3284 * local_name is the name of the array or its local copy
3285 * index is the sequence of local index expressions
3287 struct ppcg_kernel_access {
3288 enum ppcg_kernel_access_type type;
3289 struct gpu_array_info *array;
3290 struct gpu_local_array_info *local_array;
3291 char *local_name;
3292 isl_ast_expr_list *index;
3295 /* Representation of special statements, in particular copy statements
3296 * and __syncthreads statements, inside a kernel.
3298 * type represents the kind of statement
3301 * for ppcg_kernel_copy statements we have
3303 * read is set if the statement should copy data from global memory
3304 * to shared memory or registers.
3306 * domain is the (parametric) domain of index and local_index
3308 * index expresses the array element that needs to be copied in terms
3309 * of parameters
3310 * local_index expresses the corresponding element in the tile
3312 * array refers to the original array being copied
3313 * local_array is a pointer to the appropriate element in the "array"
3314 * array of the ppcg_kernel to which this copy access belongs
3317 * for ppcg_kernel_domain statements we have
3319 * stmt is the corresponding input statement
3321 * n_access is the number of accesses in stmt
3322 * access is an array of local information about the accesses
3324 struct ppcg_kernel_stmt {
3325 enum ppcg_kernel_stmt_type type;
3327 union {
3328 struct {
3329 int read;
3330 isl_set *domain;
3331 isl_pw_multi_aff *index;
3332 isl_pw_multi_aff *local_index;
3333 struct gpu_array_info *array;
3334 struct gpu_local_array_info *local_array;
3335 } c;
3336 struct {
3337 struct gpu_stmt *stmt;
3339 int n_access;
3340 struct ppcg_kernel_access *access;
3341 } d;
3342 } u;
3345 void ppcg_kernel_stmt_free(void *user)
3347 int i;
3348 struct ppcg_kernel_stmt *stmt = user;
3350 if (!stmt)
3351 return;
3353 switch (stmt->type) {
3354 case ppcg_kernel_copy:
3355 isl_set_free(stmt->u.c.domain);
3356 isl_pw_multi_aff_free(stmt->u.c.index);
3357 isl_pw_multi_aff_free(stmt->u.c.local_index);
3358 break;
3359 case ppcg_kernel_domain:
3360 for (i = 0; i < stmt->u.d.n_access; ++i) {
3361 isl_ast_expr_list_free(stmt->u.d.access[i].index);
3362 free(stmt->u.d.access[i].local_name);
3364 free(stmt->u.d.access);
3365 break;
3366 case ppcg_kernel_sync:
3367 break;
3370 free(stmt);
3373 /* Print an access based on the information in "access".
3374 * If this an access to global memory, then the index expression
3375 * is linearized.
3377 * If access->array is NULL, then we are
3378 * accessing an iterator in the original program.
3380 static __isl_give isl_printer *print_access(__isl_take isl_printer *p,
3381 struct ppcg_kernel_access *access)
3383 int i;
3384 unsigned n_index;
3385 struct gpu_array_info *array;
3386 isl_pw_aff_list *bound;
3388 array = access->array;
3389 bound = array ? access->local_array->bound : NULL;
3390 if (!array)
3391 p = isl_printer_print_str(p, "(");
3392 else {
3393 if (access->type == ppcg_access_global &&
3394 gpu_array_is_scalar(array) && !array->read_only)
3395 p = isl_printer_print_str(p, "*");
3396 p = isl_printer_print_str(p, access->local_name);
3397 if (gpu_array_is_scalar(array))
3398 return p;
3399 p = isl_printer_print_str(p, "[");
3402 n_index = isl_ast_expr_list_n_ast_expr(access->index);
3403 if (access->type == ppcg_access_global)
3404 for (i = 0; i + 1 < n_index; ++i)
3405 p = isl_printer_print_str(p, "(");
3407 for (i = 0; i < n_index; ++i) {
3408 isl_ast_expr *index;
3410 index = isl_ast_expr_list_get_ast_expr(access->index, i);
3411 if (array && i) {
3412 if (access->type == ppcg_access_global) {
3413 isl_pw_aff *bound_i;
3414 bound_i = isl_pw_aff_list_get_pw_aff(bound, i);
3415 p = isl_printer_print_str(p, ") * (");
3416 p = isl_printer_print_pw_aff(p, bound_i);
3417 p = isl_printer_print_str(p, ") + ");
3418 isl_pw_aff_free(bound_i);
3419 } else
3420 p = isl_printer_print_str(p, "][");
3422 p = isl_printer_print_ast_expr(p, index);
3423 isl_ast_expr_free(index);
3425 if (!array)
3426 p = isl_printer_print_str(p, ")");
3427 else
3428 p = isl_printer_print_str(p, "]");
3430 return p;
3433 struct cuda_access_print_info {
3434 int i;
3435 struct ppcg_kernel_stmt *stmt;
3438 /* To print the cuda accesses we walk the list of cuda accesses simultaneously
3439 * with the pet printer. This means that whenever the pet printer prints a
3440 * pet access expression we have the corresponding cuda access available and can
3441 * print the modified access.
3443 static __isl_give isl_printer *print_cuda_access(__isl_take isl_printer *p,
3444 struct pet_expr *expr, void *usr)
3446 struct cuda_access_print_info *info =
3447 (struct cuda_access_print_info *) usr;
3449 p = print_access(p, &info->stmt->u.d.access[info->i]);
3450 info->i++;
3452 return p;
3455 static __isl_give isl_printer *print_stmt_body(__isl_take isl_printer *p,
3456 struct ppcg_kernel_stmt *stmt)
3458 struct cuda_access_print_info info;
3460 info.i = 0;
3461 info.stmt = stmt;
3463 p = isl_printer_start_line(p);
3464 p = print_pet_expr(p, stmt->u.d.stmt->body, &print_cuda_access, &info);
3465 p = isl_printer_print_str(p, ";");
3466 p = isl_printer_end_line(p);
3468 return p;
3471 /* Set the options of "context" to
3473 * { space -> [x] : x >= first }
3475 static __isl_give isl_ast_build *set_unroll(
3476 __isl_take isl_ast_build *build, __isl_take isl_space *space,
3477 int first)
3479 isl_ctx *ctx;
3480 isl_map *unroll;
3481 isl_union_map *opt;
3483 ctx = isl_ast_build_get_ctx(build);
3485 space = isl_space_from_domain(space);
3486 space = isl_space_add_dims(space, isl_dim_out, 1);
3487 space = isl_space_set_tuple_name(space, isl_dim_out, "unroll");
3488 unroll = isl_map_universe(space);
3489 unroll = isl_map_lower_bound_si(unroll, isl_dim_out, 0, first);
3490 opt = isl_union_map_from_map(unroll);
3492 build = isl_ast_build_set_options(build, opt);
3494 return build;
3497 /* Return a list of isl_ids of the form "prefix%d".
3499 static __isl_give isl_id_list *generate_names(isl_ctx *ctx,
3500 int n, const char *prefix)
3502 int i;
3503 char name[10];
3504 isl_id_list *names;
3506 names = isl_id_list_alloc(ctx, n);
3507 for (i = 0; i < n; ++i) {
3508 isl_id *id;
3510 snprintf(name, sizeof(name), "%s%d", prefix, i);
3511 id = isl_id_alloc(ctx, name, NULL);
3512 names = isl_id_list_add(names, id);
3515 return names;
3518 /* Extend the schedule "schedule" with the part of "extension"
3519 * starting at "first" up to "len".
3521 static __isl_give isl_union_map *extend_schedule(
3522 __isl_take isl_union_map *schedule,
3523 __isl_take isl_union_map *extension, int first, int len)
3525 isl_space *space;
3526 isl_map *proj;
3527 isl_union_map *umap;
3528 isl_set *set;
3530 space = isl_union_map_get_space(schedule);
3531 space = isl_space_set_from_params(space);
3532 space = isl_space_add_dims(space, isl_dim_set, len);
3533 proj = isl_set_identity(isl_set_universe(space));
3534 proj = isl_map_project_out(proj, isl_dim_out, 0, first);
3535 extension = isl_union_map_apply_range(extension,
3536 isl_union_map_from_map(proj));
3538 schedule = isl_union_map_range_product(schedule, extension);
3540 return schedule;
3543 /* This function is called for each access to an array in each instance
3544 * in the kernel of some statement in the original code.
3545 * Replace that access by an access to global, shared or private memory
3546 * and store the results in *kernel_access.
3548 * Since the array in shared or private memory is just
3549 * a shifted copy of part of the original array, we simply need
3550 * to subtract the lower bound, which was computed
3551 * in can_tile_for_shared_memory.
3552 * If any of the indices is strided, then we first add
3553 * shared_bound[i].shift and divide by shared_bound[i].stride.
3555 * If the given array is accessed directly from global memory,
3556 * we don't need to perform any shifting and simply simplify
3557 * the expression in the context of the domain instead.
3559 * If the array space (range of access) has no name, then we are
3560 * accessing an iterator in the original program.
3562 * The input stmt_access->access relation maps the iteration domain
3563 * of the current statement to an array element.
3564 * The first step is to reformulate
3565 * this access relation in terms of the loop iterators of the generated
3566 * code through precomposition with gen->stmt_it.
3568 * The expressions in "bounds" are formulated in terms of the first
3569 * gen->shared_len dimensions of the computed schedule using the mapping
3570 * sched2shared which maps the loop iterators to these dimensions.
3572 static void compute_index_expression(struct gpu_gen *gen,
3573 struct ppcg_kernel_access *kernel_access,
3574 struct gpu_stmt_access *stmt_access, __isl_keep isl_map *stmt_it,
3575 __isl_keep isl_map *sched2shared, __isl_keep isl_ast_build *build)
3577 isl_map *access;
3578 isl_pw_multi_aff *pma;
3579 int i;
3580 unsigned n_index;
3581 struct gpu_array_bound *bounds = NULL;
3583 if (isl_map_has_tuple_name(stmt_access->access, isl_dim_out)) {
3584 int i;
3585 const char *name;
3586 struct gpu_array_ref_group *group;
3587 isl_printer *p;
3589 name = isl_map_get_tuple_name(stmt_access->access, isl_dim_out);
3591 for (i = 0; i < gen->n_array; ++i) {
3592 if (strcmp(name, gen->array[i].name))
3593 continue;
3594 kernel_access->array = &gen->array[i];
3595 kernel_access->local_array = &gen->kernel->array[i];
3597 assert(kernel_access->array);
3598 group = kernel_access->array->groups[stmt_access->group];
3599 p = isl_printer_to_str(gen->ctx);
3600 p = print_array_name(p, group);
3601 kernel_access->local_name = isl_printer_get_str(p);
3602 isl_printer_free(p);
3603 bounds = group->private_bound;
3604 kernel_access->type = ppcg_access_private;
3605 if (!bounds) {
3606 bounds = group->shared_bound;
3607 kernel_access->type = ppcg_access_shared;
3610 if (!bounds)
3611 kernel_access->type = ppcg_access_global;
3613 n_index = isl_map_dim(stmt_access->access, isl_dim_out);
3614 kernel_access->index = isl_ast_expr_list_alloc(gen->ctx, n_index);
3616 if (n_index == 0)
3617 return;
3619 access = isl_map_copy(stmt_access->access);
3620 access = isl_map_apply_range(isl_map_copy(stmt_it), access);
3621 pma = isl_pw_multi_aff_from_map(access);
3622 pma = isl_pw_multi_aff_coalesce(pma);
3624 for (i = 0; i < n_index; ++i) {
3625 isl_set *domain;
3626 isl_pw_aff *index;
3627 isl_ast_expr *expr;
3629 index = isl_pw_multi_aff_get_pw_aff(pma, i);
3631 if (!kernel_access->array) {
3632 } else if (!bounds) {
3633 domain = isl_map_domain(isl_map_copy(stmt_it));
3634 index = isl_pw_aff_coalesce(index);
3635 index = isl_pw_aff_gist(index, domain);
3636 } else {
3637 domain = isl_map_domain(isl_map_copy(stmt_it));
3638 index = shift_index(index, kernel_access->array,
3639 &bounds[i], domain, isl_map_copy(sched2shared));
3642 expr = isl_ast_build_expr_from_pw_aff(build, index);
3644 kernel_access->index = isl_ast_expr_list_add(
3645 kernel_access->index, expr);
3648 isl_pw_multi_aff_free(pma);
3651 /* This function is called for each instance of a user statement
3652 * in the kernel.
3654 * We attach a struct ppcg_kernel_stmt to the "node", containing
3655 * local information about the accesses.
3656 * This information is computed from stmt_it, which expresses the domain
3657 * elements in terms of the generated loops, and sched2shared,
3658 * which expresses the first shared_len dimensions of the schedule
3659 * computed by PPCG in terms of the generated loops.
3661 static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node,
3662 __isl_keep isl_ast_build *build, void *user)
3664 struct gpu_gen *gen = (struct gpu_gen *) user;
3665 struct ppcg_kernel_stmt *stmt;
3666 isl_id *id;
3667 isl_map *stmt_it, *sched2shared;
3668 isl_ast_expr *expr, *arg;
3669 isl_union_map *schedule;
3670 int i, n;
3671 struct gpu_stmt_access *access;
3673 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3674 if (!stmt)
3675 return isl_ast_node_free(node);
3677 expr = isl_ast_node_user_get_expr(node);
3678 arg = isl_ast_expr_get_op_arg(expr, 0);
3679 id = isl_ast_expr_get_id(arg);
3681 schedule = isl_ast_build_get_schedule(build);
3682 stmt_it = isl_map_reverse(isl_map_from_union_map(schedule));
3683 sched2shared = compute_sched_to_shared(gen, isl_map_copy(stmt_it));
3685 stmt->type = ppcg_kernel_domain;
3686 stmt->u.d.stmt = find_stmt(gen, id);
3687 if (!stmt->u.d.stmt)
3688 goto error;
3690 n = 0;
3691 for (access = stmt->u.d.stmt->accesses; access; access = access->next)
3692 ++n;
3694 stmt->u.d.access = isl_calloc_array(gen->ctx,
3695 struct ppcg_kernel_access, n);
3696 if (!stmt->u.d.access)
3697 goto error;
3699 stmt->u.d.n_access = n;
3701 access = stmt->u.d.stmt->accesses;
3702 for (i = 0; i < n; ++i, access = access->next) {
3703 compute_index_expression(gen, &stmt->u.d.access[i], access,
3704 stmt_it, sched2shared, build);
3707 isl_id_free(id);
3708 isl_map_free(stmt_it);
3709 isl_map_free(sched2shared);
3710 isl_ast_expr_free(arg);
3711 isl_ast_expr_free(expr);
3713 id = isl_id_alloc(gen->ctx, NULL, stmt);
3714 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3715 return isl_ast_node_set_annotation(node, id);
3716 error:
3717 isl_id_free(id);
3718 isl_map_free(stmt_it);
3719 ppcg_kernel_stmt_free(stmt);
3720 isl_map_free(sched2shared);
3721 return isl_ast_node_free(node);
3724 /* This function is called when code has been generated for the shared
3725 * tile loops. The "schedule" refers only to the original statements.
3727 * We extend the schedule with that part of gen->local_sched that hasn't
3728 * been taken into account yet. This introduces parameters referring
3729 * to thread ids in the schedule, so we add them (with the appropriate
3730 * bounds to the context as well).
3731 * Finally, we set the appropriate unrolling options
3732 * if gen->first_unroll is set.
3734 static __isl_give isl_ast_node *create_domain_leaf(
3735 __isl_take isl_union_map *schedule, __isl_take isl_ast_build *build,
3736 void *user)
3738 struct gpu_gen *gen = (struct gpu_gen *) user;
3739 isl_space *space;
3740 isl_union_map *sched;
3741 isl_ast_node *tree;
3742 isl_set *set;
3743 isl_id_list *iterators;
3744 int n;
3746 schedule = extend_schedule(schedule,
3747 isl_union_map_copy(gen->local_sched),
3748 gen->shared_len, gen->thread_tiled_len);
3750 space = isl_ast_build_get_schedule_space(build);
3751 set = isl_set_universe(space);
3752 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3753 build = isl_ast_build_restrict(build, set);
3755 n = gen->thread_tiled_len - gen->shared_len;
3757 if (gen->first_unroll >= 0) {
3758 space = isl_space_set_alloc(gen->ctx, 0, n);
3759 build = set_unroll(build, space, gen->first_unroll);
3761 iterators = generate_names(gen->ctx, n, "c");
3762 build = isl_ast_build_set_iterators(build, iterators);
3763 build = isl_ast_build_set_at_each_domain(build, &at_each_domain, gen);
3764 tree = isl_ast_build_ast_from_schedule(build, schedule);
3765 isl_ast_build_free(build);
3767 return tree;
3770 /* Add parameters corresponding to the dimensions in the schedule
3771 * space of "context" and equate them to the dimensions in the range
3772 * of "map".
3774 static __isl_give isl_map *parametrize_iterators(__isl_take isl_map *map,
3775 __isl_keep isl_ast_build *build)
3777 int i, n, n_param;
3778 isl_space *space;
3780 space = isl_ast_build_get_schedule_space(build);
3781 n = isl_map_dim(map, isl_dim_out);
3782 n_param = isl_map_dim(map, isl_dim_param);
3783 map = isl_map_add_dims(map, isl_dim_param, n);
3784 for (i = 0; i < n; ++i) {
3785 isl_id *id;
3787 id = isl_space_get_dim_id(space, isl_dim_set, i);
3788 map = isl_map_set_dim_id(map, isl_dim_param, n_param + i, id);
3789 map = isl_map_equate(map, isl_dim_param, n_param + i,
3790 isl_dim_out, i);
3793 isl_space_free(space);
3795 return map;
3798 /* This function is called for each leaf in the AST of the code
3799 * for copying to or from shared/private memory.
3800 * The statement name is {read,write}_{shared,private}_<array>.
3802 * The schedule is of the form
3804 * [A -> T] -> L
3806 * where A refers to a piece of an array and T to the corresponding
3807 * shifted tile. We first turn the iterators in L into parameters
3808 * and then store A in stmt->index and T in stmt->local_index,
3809 * where stmt represents the copy statement.
3811 static __isl_give isl_ast_node *create_copy_leaf(
3812 __isl_take isl_ast_build *build, void *user)
3814 struct gpu_gen *gen = (struct gpu_gen *) user;
3815 struct ppcg_kernel_stmt *stmt;
3816 isl_id *id;
3817 isl_ast_expr *expr;
3818 isl_ast_node *node;
3819 isl_space *space;
3820 isl_map *access;
3821 isl_set *local_access;
3822 const char *name;
3823 int array_index;
3825 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
3826 if (!stmt)
3827 return isl_ast_build_free(build);
3829 access = isl_map_from_union_map(isl_ast_build_get_schedule(build));
3830 name = isl_map_get_tuple_name(access, isl_dim_in);
3831 stmt->u.c.read = !strncmp(name, "read", 4);
3832 access = parametrize_iterators(access, build);
3833 access = isl_set_unwrap(isl_map_domain(access));
3835 local_access = isl_map_range(isl_map_copy(access));
3837 stmt->u.c.domain = isl_map_params(isl_map_copy(access));
3838 stmt->u.c.index = isl_pw_multi_aff_from_set(isl_map_domain(access));
3839 stmt->u.c.local_index = isl_pw_multi_aff_from_set(local_access);
3840 stmt->u.c.array = gen->copy_group->array;
3841 array_index = stmt->u.c.array - gen->array;
3842 stmt->u.c.local_array = &gen->kernel->array[array_index];
3843 stmt->type = ppcg_kernel_copy;
3845 space = isl_ast_build_get_schedule_space(build);
3846 space = isl_space_from_domain(space);
3847 space = isl_space_set_tuple_name(space, isl_dim_out, name);
3848 expr = isl_ast_build_call_from_pw_multi_aff(build,
3849 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
3850 node = isl_ast_node_alloc_user(expr);
3851 isl_ast_build_free(build);
3853 id = isl_id_alloc(gen->ctx, NULL, stmt);
3854 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
3855 return isl_ast_node_set_annotation(node, id);
3858 /* Given a schedule of the form
3860 * [S -> A] -> L
3862 * (with S the first shared_len dimensions of the computed schedule,
3863 * A the array and L the schedule correponding to the generated loops),
3864 * indicating where the copying the array elements that need to be copied,
3865 * construct code for performing the copying.
3867 * "group" is the array reference group that is being copied
3868 * "type" is either "read" or "write"
3869 * private is set if copying needs to be performed to/from registers
3871 * We first construct a mapping to a shifted tile of the array,
3873 * [S -> A] -> T(S,A) (1)
3875 * If private is set, then we also use this mapping as a schedule
3876 * (which is already thread-specific and will be completely unrolled).
3877 * Otherwise, we wrap/tile the range over the threads.
3878 * The result is
3880 * [S -> A] -> T'(S,A)
3882 * Combined with the given schedule, we have
3884 * [S -> A] -> [L -> T'(S,A)] (2)
3886 * From the shifted tile mapping, we construct a mapping
3888 * [S -> A] -> [A -> T(S,A)]
3890 * and apply it to the schedule (2), obtaining
3892 * [A -> T(S(L),A)] -> [L -> T'(S(L),A)]
3894 * Note that we can project out S because it is uniquely defined by L.
3896 static __isl_give isl_ast_node *copy_access(struct gpu_gen *gen,
3897 __isl_take isl_map *sched,
3898 const char *type, struct gpu_array_ref_group *group,
3899 __isl_take isl_ast_build *build, int private)
3901 const char *array_name;
3902 const char *mem = private ? "private" : "shared";
3903 char *name;
3904 isl_space *space;
3905 isl_ast_node *tree;
3906 isl_map *schedule, *shift, *map;
3907 isl_set *set;
3908 isl_id_list *iterators;
3909 int n;
3911 shift = isl_set_unwrap(isl_map_domain(isl_map_copy(sched)));
3912 array_name = isl_map_get_tuple_name(shift, isl_dim_out);
3913 shift = shift_access(shift, group);
3915 schedule = isl_map_copy(shift);
3916 if (!private)
3917 schedule = tile_access_schedule(gen, schedule);
3919 n = isl_map_dim(schedule, isl_dim_out);
3920 set = isl_set_universe(isl_ast_build_get_schedule_space(build));
3921 set = add_bounded_parameters(set, gen->n_block, gen->block_dim, "t");
3923 schedule = isl_map_range_product(sched, schedule);
3925 assert(array_name);
3926 name = isl_alloc_array(gen->ctx, char,
3927 strlen(type) + sizeof("_private_") + strlen(array_name) + 20);
3928 if (group->array->n_group > 1)
3929 sprintf(name, "%s_%s_%s_%d", type, mem, array_name, group->nr);
3930 else
3931 sprintf(name, "%s_%s_%s", type, mem, array_name);
3932 shift = isl_map_set_tuple_name(shift,
3933 isl_dim_out, name + strlen(type) + 1);
3935 space = isl_space_domain(isl_map_get_space(shift));
3936 map = isl_map_range_map(isl_map_universe(isl_space_unwrap(space)));
3937 map = isl_map_range_product(map, shift);
3939 schedule = isl_map_apply_domain(schedule, map);
3941 schedule = isl_map_set_tuple_name(schedule, isl_dim_in, name);
3942 free(name);
3944 build = isl_ast_build_restrict(build, set);
3946 gen->copy_group = group;
3947 gen->copy_bound = group->shared_bound;
3949 if (private) {
3950 space = isl_space_range(isl_map_get_space(schedule));
3951 space = isl_space_range(isl_space_unwrap(space));
3952 build = set_unroll(build, space, 0);
3954 iterators = generate_names(gen->ctx, n, "c");
3955 build = isl_ast_build_set_iterators(build, iterators);
3956 build = isl_ast_build_set_create_leaf(build, &create_copy_leaf, gen);
3957 tree = isl_ast_build_ast_from_schedule(build,
3958 isl_union_map_from_map(schedule));
3959 isl_ast_build_free(build);
3961 return tree;
3964 /* Return code for reading into or writing from shared memory
3965 * the given array reference group.
3967 * If we are performing a read from global memory to shared memory,
3968 * if the array involved is not a scalar and if the definition of the
3969 * shared memory tiles does not involve any strides, then we copy
3970 * the entire tile to shared memory. This may result in some extra
3971 * elements getting copied, but it should lead to simpler code
3972 * (which means that fewer registers may be needed) and less divergence.
3974 * Otherwise, we only copy the elements that will be read or have been written
3975 * in the kernel.
3977 * Note that the absence of stride requirement can easily be lifted.
3978 * We would just need to add constraints of the form
3980 * shift + a = stride * alpha
3983 * The input "sched" is of the form.
3985 * type[S -> A] -> L
3987 * with S the first shared_len dimensions of the computed schedule,
3988 * A the array and L the schedule correponding to the generated loops.
3990 * We first drop "type",
3992 * [S -> A] -> L
3994 * If the above conditions are satisfied, we project out A,
3995 * resulting in
3997 * S -> L
3999 * and then introduce the group tile [S -> T], resulting in
4001 * [S -> T] -> L
4003 static __isl_give isl_ast_node *copy_group_shared_accesses(
4004 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4005 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4007 const char *type;
4008 int read;
4009 isl_union_map *access;
4011 type = isl_map_get_tuple_name(sched, isl_dim_in);
4012 read = !strcmp(type, "read");
4014 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4016 if (read && group->array->n_index > 0 && no_strides(group)) {
4017 isl_space *space;
4018 isl_map *map;
4020 space = isl_space_domain(isl_map_get_space(sched));
4021 space = isl_space_unwrap(space);
4022 map = isl_map_domain_map(isl_map_universe(space));
4023 sched = isl_map_apply_domain(sched, map);
4025 map = group_tile(group);
4026 map = isl_map_reverse(isl_map_domain_map(map));
4027 sched = isl_map_apply_domain(sched, map);
4030 return copy_access(gen, sched, type, group, build, 0);
4033 /* Return code for reading into or writing from private memory
4034 * the given array reference group.
4036 * Let S be the first shared_len dimensions of the computed schedule,
4037 * D the iteration domains, A the array and L the schedule correponding
4038 * to the generated loops.
4039 * "sched" is of the form
4041 * type[S -> A] -> L
4043 * where type is either "read" or "write".
4044 * We apply the privatization D -> S(t), with t the thread ids,
4045 * to the access relation D -> A to obtain the privatized access relation
4047 * S(t) -> A
4049 * We drop the type from "sched" and intersect with the privatized access
4050 * relation to obtain
4052 * [S(t) -> A] -> L
4054 static __isl_give isl_ast_node *copy_group_private_accesses(
4055 struct gpu_gen *gen, struct gpu_array_ref_group *group,
4056 __isl_take isl_map *sched, __isl_take isl_ast_build *build)
4058 const char *type;
4059 int read;
4060 isl_union_map *priv;
4061 isl_union_map *access;
4062 isl_map *access_map;
4064 type = isl_map_get_tuple_name(sched, isl_dim_in);
4065 read = !strcmp(type, "read");
4067 priv = isl_union_map_from_map(isl_map_copy(gen->privatization));
4068 priv = isl_union_map_apply_range(isl_union_map_copy(gen->shared_sched),
4069 priv);
4071 access = group_access_relation(group, read, !read);
4072 access = isl_union_map_apply_domain(access, priv);
4073 access_map = isl_map_from_union_map(access);
4075 sched = isl_map_reset_tuple_id(sched, isl_dim_in);
4076 sched = isl_map_intersect_domain(sched, isl_map_wrap(access_map));
4078 return copy_access(gen, sched, type, group, build, 1);
4081 /* Return code for reading into or writing from shared or private memory.
4083 * "schedule" is of the form
4085 * type[S -> A] -> L
4087 * with S be the first shared_len dimensions of the computed schedule,
4088 * A the array and L the schedule correponding to the generated loops.
4089 * The array reference group is attached to "type".
4091 static __isl_give isl_ast_node *create_access_leaf(
4092 struct gpu_gen *gen, __isl_take isl_map *schedule,
4093 __isl_take isl_ast_build *build)
4095 struct gpu_array_ref_group *group;
4096 isl_id *id;
4098 id = isl_map_get_tuple_id(schedule, isl_dim_in);
4099 group = isl_id_get_user(id);
4100 isl_id_free(id);
4102 if (group->private_bound)
4103 return copy_group_private_accesses(gen, group, schedule,
4104 build);
4105 else
4106 return copy_group_shared_accesses(gen, group, schedule,
4107 build);
4110 /* Create a domain node representing a synchronization.
4112 static __isl_give isl_ast_node *create_sync_leaf(
4113 struct gpu_gen *gen, __isl_take isl_map *schedule,
4114 __isl_take isl_ast_build *build)
4116 struct ppcg_kernel_stmt *stmt;
4117 isl_id *id;
4118 isl_space *space;
4119 isl_ast_node *node;
4120 isl_ast_expr *expr;
4122 isl_map_free(schedule);
4124 stmt = isl_calloc_type(gen->ctx, struct ppcg_kernel_stmt);
4125 if (!stmt)
4126 return NULL;
4128 stmt->type = ppcg_kernel_sync;
4130 space = isl_ast_build_get_schedule_space(build);
4131 space = isl_space_from_domain(space);
4132 space = isl_space_set_tuple_name(space, isl_dim_out, "sync");
4133 expr = isl_ast_build_call_from_pw_multi_aff(build,
4134 isl_pw_multi_aff_from_multi_aff(isl_multi_aff_zero(space)));
4135 node = isl_ast_node_alloc_user(expr);
4136 isl_ast_build_free(build);
4138 id = isl_id_alloc(gen->ctx, NULL, stmt);
4139 id = isl_id_set_free_user(id, &ppcg_kernel_stmt_free);
4140 return isl_ast_node_set_annotation(node, id);
4143 /* This function is called during the code generation at the point
4144 * where the schedule domain element is completely determined by
4145 * the generated code. The input schedule contains the original
4146 * statements as well as synchronization and copy "statements".
4147 * The latter are scheduled at different points than any of the original
4148 * statements, so they will only arrive here in isolation.
4150 * If the current schedule only refers to a single statement,
4151 * we check if it is a copy or synchronization statement and
4152 * call the appropriate functions.
4153 * Otherwise, we assume we are dealing with the original statements
4154 * and we call create_domain_leaf.
4156 static __isl_give isl_ast_node *create_kernel_leaf(
4157 __isl_take isl_ast_build *build, void *user)
4159 struct gpu_gen *gen = (struct gpu_gen *) user;
4160 isl_map *map;
4161 isl_union_map *schedule;
4162 const char *name;
4164 schedule = isl_ast_build_get_schedule(build);
4166 if (isl_union_map_n_map(schedule) != 1)
4167 return create_domain_leaf(schedule, build, user);
4169 map = isl_map_from_union_map(schedule);
4170 name = isl_map_get_tuple_name(map, isl_dim_in);
4171 if (!strcmp(name, "read") || !strcmp(name, "write"))
4172 return create_access_leaf(gen, map, build);
4173 if (!strcmp(name, "sync"))
4174 return create_sync_leaf(gen, map, build);
4176 return create_domain_leaf(isl_union_map_from_map(map), build, user);
4179 /* Mark all odd schedule dimensions as "atomic" (when the even dimensions
4180 * have value 0) and all even schedule dimensions as "unroll".
4182 * That is, the options look as follows
4184 * { [0, b, 0, d, ..., 0] -> atomic[i] : exists a : i = 2 a + 1;
4185 * [a, b, c, d, ..., z] -> unroll[i] : exists a : i = 2 a }
4187 * The even positions are used to be able to schedule copying blocks
4188 * and synchronization before or after each level of the shared memory
4189 * tile loops and we want to make sure that code for these is generated
4190 * separately (within each level).
4192 static __isl_give isl_ast_build *set_atomic_and_unroll(
4193 __isl_take isl_ast_build *build,
4194 __isl_take isl_space *space, int sched_len)
4196 isl_ctx *ctx;
4197 isl_map *map;
4198 isl_constraint *c;
4199 isl_union_map *opt;
4200 isl_local_space *ls;
4201 int i, n;
4203 ctx = isl_ast_build_get_ctx(build);
4205 space = isl_space_params(space);
4206 space = isl_space_add_dims(space, isl_dim_set, sched_len);
4207 space = isl_space_from_domain(space);
4208 space = isl_space_add_dims(space, isl_dim_out, 2);
4209 map = isl_map_universe(isl_space_copy(space));
4210 for (i = 0; i < sched_len; i += 2)
4211 map = isl_map_fix_si(map, isl_dim_in, i, 0);
4212 ls = isl_local_space_from_space(isl_map_get_space(map));
4213 c = isl_equality_alloc(ls);
4214 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4215 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4216 c = isl_constraint_set_constant_si(c, 1);
4217 map = isl_map_add_constraint(map, c);
4218 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4219 map = isl_map_set_tuple_name(map, isl_dim_out, "atomic");
4220 opt = isl_union_map_from_map(map);
4222 map = isl_map_universe(space);
4223 ls = isl_local_space_from_space(isl_map_get_space(map));
4224 c = isl_equality_alloc(ls);
4225 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 0, 1);
4226 c = isl_constraint_set_coefficient_si(c, isl_dim_out, 1, 2);
4227 map = isl_map_add_constraint(map, c);
4228 map = isl_map_project_out(map, isl_dim_out, 1, 1);
4229 map = isl_map_set_tuple_name(map, isl_dim_out, "unroll");
4230 opt = isl_union_map_add_map(opt, map);
4232 build = isl_ast_build_set_options(build, opt);
4234 return build;
4237 /* Print an access to the element in the private/shared memory copy
4238 * described by "stmt". The index of the copy is recorded in
4239 * stmt->local_index.
4241 static __isl_give isl_printer *stmt_print_local_index(__isl_take isl_printer *p,
4242 struct ppcg_kernel_stmt *stmt)
4244 int i;
4245 const char *name;
4246 struct gpu_array_info *array = stmt->u.c.array;
4248 name = isl_pw_multi_aff_get_tuple_name(stmt->u.c.local_index,
4249 isl_dim_out);
4250 p = isl_printer_print_str(p, name);
4251 for (i = 0; i < array->n_index; ++i) {
4252 isl_pw_aff *pa;
4253 pa = isl_pw_multi_aff_get_pw_aff(stmt->u.c.local_index, i);
4255 p = isl_printer_print_str(p, "[");
4256 p = isl_printer_print_pw_aff(p, pa);
4257 p = isl_printer_print_str(p, "]");
4259 isl_pw_aff_free(pa);
4262 return p;
4265 /* Print an access to the element in the global memory copy
4266 * described by "stmt". The index of the copy is recorded in
4267 * stmt->index.
4269 * The copy in global memory has been linearized, so we need to take
4270 * the array size into account.
4272 static __isl_give isl_printer *stmt_print_global_index(
4273 __isl_take isl_printer *p, struct ppcg_kernel_stmt *stmt)
4275 int i;
4276 struct gpu_array_info *array = stmt->u.c.array;
4277 isl_pw_aff_list *bound = stmt->u.c.local_array->bound;
4279 if (gpu_array_is_scalar(array)) {
4280 if (!array->read_only)
4281 p = isl_printer_print_str(p, "*");
4282 p = isl_printer_print_str(p, array->name);
4283 return p;
4286 p = isl_printer_print_str(p, array->name);
4287 p = isl_printer_print_str(p, "[");
4288 for (i = 0; i + 1 < array->n_index; ++i)
4289 p = isl_printer_print_str(p, "(");
4290 for (i = 0; i < array->n_index; ++i) {
4291 isl_pw_aff *pa = isl_pw_multi_aff_get_pw_aff(stmt->u.c.index, i);
4292 pa = isl_pw_aff_coalesce(pa);
4293 pa = isl_pw_aff_gist_params(pa, isl_set_copy(stmt->u.c.domain));
4294 if (i) {
4295 isl_pw_aff *bound_i;
4296 bound_i = isl_pw_aff_list_get_pw_aff(bound, i);
4297 p = isl_printer_print_str(p, ") * (");
4298 p = isl_printer_print_pw_aff(p, bound_i);
4299 p = isl_printer_print_str(p, ") + ");
4300 isl_pw_aff_free(bound_i);
4302 p = isl_printer_print_pw_aff(p, pa);
4303 isl_pw_aff_free(pa);
4305 p = isl_printer_print_str(p, "]");
4307 return p;
4310 /* Print a copy statement.
4312 * A read copy statement is printed as
4314 * local = global;
4316 * while a write copy statement is printed as
4318 * global = local;
4320 static __isl_give isl_printer *print_copy(__isl_take isl_printer *p,
4321 struct ppcg_kernel_stmt *stmt)
4323 p = isl_printer_start_line(p);
4324 if (stmt->u.c.read) {
4325 p = stmt_print_local_index(p, stmt);
4326 p = isl_printer_print_str(p, " = ");
4327 p = stmt_print_global_index(p, stmt);
4328 } else {
4329 p = stmt_print_global_index(p, stmt);
4330 p = isl_printer_print_str(p, " = ");
4331 p = stmt_print_local_index(p, stmt);
4333 p = isl_printer_print_str(p, ";");
4334 p = isl_printer_end_line(p);
4336 return p;
4339 /* Print a sync statement.
4341 static __isl_give isl_printer *print_sync(__isl_take isl_printer *p,
4342 struct ppcg_kernel_stmt *stmt)
4344 p = isl_printer_start_line(p);
4345 p = isl_printer_print_str(p, "__syncthreads();");
4346 p = isl_printer_end_line(p);
4348 return p;
4351 /* Return a map that maps a space of dimension gen->shared_len
4352 * to its last dimensions starting at gen->tile_first.
4353 * The range is of dimension
4355 * 2 * (gen->shared_len - gen->tile_first) + 1
4357 * The input dimensions are mapped to the odd dimensions in the output,
4358 * while the even dimensions (except 2*pos) are fixed to 0.
4359 * Output dimension 2*pos (if pos >= 0) is fixed to "val".
4360 * If pos >= 0, then only the pos first dimensions starting at gen->tile_first
4361 * are mapped to the output. The remaining input dimensions are projected
4362 * out and the corresponding output dimensions are fixed to 0.
4364 static __isl_give isl_map *insert_even(struct gpu_gen *gen,
4365 __isl_take isl_space *space, int pos, int val)
4367 int i, n;
4368 isl_map *proj;
4370 space = isl_space_set_from_params(space);
4371 space = isl_space_add_dims(space, isl_dim_set, gen->shared_len);
4372 space = isl_space_map_from_set(space);
4373 proj = isl_map_identity(space);
4374 proj = isl_map_project_out(proj, isl_dim_out, 0, gen->tile_first);
4375 n = gen->shared_len - gen->tile_first;
4376 for (i = 0; i <= n; ++i) {
4377 proj = isl_map_insert_dims(proj, isl_dim_out, 2 * i, 1);
4378 if (i == pos)
4379 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, val);
4380 else
4381 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i, 0);
4384 if (pos < 0)
4385 return proj;
4387 proj = isl_map_eliminate(proj, isl_dim_in, gen->tile_first + pos,
4388 gen->shared_len - (gen->tile_first + pos));
4389 for (i = pos; i < n; ++i)
4390 proj = isl_map_fix_si(proj, isl_dim_out, 2 * i + 1, 0);
4392 return proj;
4395 /* Given the AST context schedule "schedule" and the mapping from
4396 * domains to the shared tile loops "shared_sched", add a schedule
4397 * for a synchronization operation at position "val" of loop level "pos".
4399 * schedule is of the form
4401 * D -> L
4403 * (with D the iteration domains and L the already generated loops),
4404 * while shared_sched is of the form
4406 * D -> S
4408 * We combine them into
4410 * L -> S
4412 * apply a mapping
4414 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4416 * and use the result as a schedule for "sync".
4418 static __isl_give isl_union_map *add_sync_schedule(struct gpu_gen *gen,
4419 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4420 __isl_keep isl_union_map *shared_sched, int pos, int val)
4422 isl_space *space;
4423 isl_map *proj, *map;
4425 shared_sched = isl_union_map_copy(shared_sched);
4426 schedule = isl_union_map_copy(schedule);
4428 space = isl_union_map_get_space(shared_sched);
4429 schedule = isl_union_map_apply_domain(shared_sched, schedule);
4430 map = isl_map_from_union_map(schedule);
4432 proj = insert_even(gen, space, pos, val);
4433 map = isl_map_apply_range(map, proj);
4434 map = isl_map_from_range(isl_map_wrap(map));
4435 map = isl_map_set_tuple_name(map, isl_dim_in, "sync");
4437 res = isl_union_map_add_map(res, map);
4439 return res;
4442 /* Given the AST context schedule "schedule" and the mapping from
4443 * domains to the shared tile loops "shared_sched", add a schedule
4444 * for copying an array reference group to/from shared/private memory.
4445 * "read" is set if data should be copied from global memory
4446 * to shared/private memory.
4447 * "k" represents the current group
4448 * "s" is the total number of groups
4450 * We schedule an operation before or after the innermost loop
4451 * of "shared_sched" that affects the tile of the array reference group.
4453 * schedule is of the form
4455 * D -> L
4457 * (with D the iteration domains and L the already generated loops),
4458 * while shared_sched is of the form
4460 * D -> S
4462 * We first compute the access relation for the reference group
4464 * D -> A
4466 * and combine it with shared_sched into
4468 * D -> [S -> A]
4470 * If this results in an empty relation, no copying needs to be performed
4471 * at this point.
4472 * Otherwise, we invert the relation and combine it with "schedule" into
4474 * [S -> A] -> L
4476 * The actual additional piece of the schedule is obtained from combining
4478 * [S -> A] -> S
4480 * with a mapping
4482 * [s_0,...] -> [0,s_{tile_first},0,..., val, 0, 0, ... 0]
4484 * The position of "val" corresponds to the innermost loop that affects
4485 * the tile and the value indicates where the copying is scheduled
4486 * with respect to the actual kernel code (at value 0).
4487 * Reads are schedule before the code, writes to global memory from
4488 * private memory are scheduled at values 1 to s, writes to global
4489 * memory from shared memory are scheduled at values s + 2 to 2 * s + 1.
4491 * If we are scheduling a read from global memory to shared memory,
4492 * we insert a synchronization before the kernel code (at the innermost
4493 * level).
4494 * If we are scheduling a write to global memory, then we add
4495 * a synchronization after all writes (at value 2 *s + 2).
4496 * However, there is no need for a synchronization after the outermost loop.
4497 * A write to global memory from private memory at the innermost level
4498 * does not require a synchronization, because it is covered by
4499 * the synchronization after the kernel inserted by body_schedule.
4501 static __isl_give isl_union_map *add_group_schedule(struct gpu_gen *gen,
4502 __isl_take isl_union_map *res, __isl_keep isl_union_map *schedule,
4503 __isl_keep isl_union_map *shared_sched,
4504 struct gpu_array_ref_group *group, int read, int k, int s)
4506 int n;
4507 int pos, val;
4508 isl_space *space;
4509 isl_union_map *access;
4510 isl_map *map, *proj, *access_map;
4511 isl_id *id;
4513 access = group_access_relation(group, read, !read);
4514 access = isl_union_map_range_product(isl_union_map_copy(shared_sched),
4515 access);
4517 if (isl_union_map_is_empty(access)) {
4518 isl_union_map_free(access);
4519 return res;
4522 access = isl_union_map_reverse(access);
4523 access = isl_union_map_apply_range(access,
4524 isl_union_map_copy(schedule));
4525 access_map = isl_map_from_union_map(access);
4527 space = isl_space_copy(group->array->dim);
4528 space = isl_space_from_range(space);
4529 space = isl_space_add_dims(space, isl_dim_in, gen->shared_len);
4530 map = isl_map_domain_map(isl_map_universe(space));
4532 space = isl_union_map_get_space(schedule);
4533 pos = group->last_shared + 1 - gen->tile_first;
4534 if (read)
4535 val = -2 - k;
4536 else if (group->private_bound)
4537 val = 1 + k;
4538 else
4539 val = 1 + s + 1 + k;
4540 proj = insert_even(gen, space, pos, val);
4541 map = isl_map_apply_range(map, proj);
4543 access_map = isl_map_range_product(access_map, map);
4545 id = isl_id_alloc(gen->ctx, read ? "read" : "write", group);
4546 access_map = isl_map_set_tuple_id(access_map, isl_dim_in, id);
4548 res = isl_union_map_add_map(res, access_map);
4550 n = gen->shared_len - gen->tile_first;
4551 if (read) {
4552 if (!group->private_bound)
4553 res = add_sync_schedule(gen, res, schedule,
4554 shared_sched, n, -1);
4555 } else {
4556 if (pos == 0)
4557 return res;
4558 if (pos == n && group->private_bound)
4559 return res;
4560 res = add_sync_schedule(gen, res, schedule, shared_sched,
4561 pos, 2 * s + 2);
4564 return res;
4567 /* Return a schedule for the shared tile loops based on the current
4568 * AST context schedule.
4570 * We create a "shared_sched" that maps the domains to the first
4571 * shared_len dimensions of the computed schedule, project out the
4572 * first tile_first dimensions (as these are already covered by
4573 * the host code) and insert "statement-level" dimensions at even
4574 * positions so that we can schedule copy blocks and synchronization
4575 * before/after each level.
4577 * In particular, copy blocks are inserted inside the innermost
4578 * level that affect the tile. For the copying to global memory,
4579 * those from private memory are scheduled before those from shared
4580 * memory such that synchronization can be inserted between the two
4581 * at the innermost level.
4582 * Synchronization is inserted at the innermost level before the
4583 * actual kernel code if there is any copying from global memory
4584 * to shared memory. It is inserted unconditionally at the innermost
4585 * level after the actual kernel code and the copying to global memory
4586 * from private memory (if any). Finally, it is inserted after
4587 * any copying to global memory, except at the outermost level
4588 * and at the innermost level if there is no copying from shared
4589 * memory. The copying from private memory is covered by the unconditional
4590 * synchronization at the innermost level.
4592 static __isl_give isl_union_map *body_schedule(struct gpu_gen *gen,
4593 __isl_take isl_union_map *schedule)
4595 isl_space *space;
4596 isl_union_map *res;
4597 isl_union_map *shared_sched;
4598 isl_union_map *sched;
4599 isl_map *proj, *map;
4600 int i, j, k, s;
4602 shared_sched = isl_union_map_copy(gen->tiled_sched);
4603 proj = projection(isl_union_map_get_space(shared_sched),
4604 gen->tiled_len, gen->shared_len);
4605 shared_sched = isl_union_map_apply_range(shared_sched,
4606 isl_union_map_from_map(proj));
4607 space = isl_union_map_get_space(shared_sched);
4608 proj = insert_even(gen, space, -1, 0);
4609 sched = isl_union_map_apply_range(isl_union_map_copy(shared_sched),
4610 isl_union_map_from_map(proj));
4612 res = isl_union_map_range_product(isl_union_map_copy(schedule), sched);
4614 s = 0;
4615 for (i = 0; i < gen->n_array; ++i)
4616 s += gen->array[i].n_group;
4618 k = 0;
4619 for (i = 0; i < gen->n_array; ++i) {
4620 struct gpu_array_info *array = &gen->array[i];
4622 for (j = 0; j < array->n_group; ++j) {
4623 struct gpu_array_ref_group *group;
4625 group = array->groups[j];
4626 if (!group->private_bound && !group->shared_bound)
4627 continue;
4628 res = add_group_schedule(gen, res, schedule,
4629 shared_sched, group, 0, k, s);
4630 res = add_group_schedule(gen, res, schedule,
4631 shared_sched, group, 1, k, s);
4632 ++k;
4636 res = add_sync_schedule(gen, res, schedule, shared_sched,
4637 gen->shared_len - gen->tile_first, 1 + s);
4639 isl_union_map_free(shared_sched);
4640 isl_union_map_free(schedule);
4642 return res;
4645 /* This function is called for each user statement in the AST,
4646 * i.e., for each kernel body statement, copy statement or sync statement.
4648 static __isl_give isl_printer *print_kernel_stmt(__isl_take isl_printer *p,
4649 __isl_keep isl_ast_node *node, void *user)
4651 isl_id *id;
4652 struct ppcg_kernel_stmt *stmt;
4654 id = isl_ast_node_get_annotation(node);
4655 stmt = isl_id_get_user(id);
4656 isl_id_free(id);
4658 switch (stmt->type) {
4659 case ppcg_kernel_copy:
4660 return print_copy(p, stmt);
4661 case ppcg_kernel_sync:
4662 return print_sync(p, stmt);
4663 case ppcg_kernel_domain:
4664 return print_stmt_body(p, stmt);
4667 return p;
4670 static int print_macro(enum isl_ast_op_type type, void *user)
4672 isl_printer **p = user;
4674 if (type == isl_ast_op_fdiv_q)
4675 return 0;
4677 *p = isl_ast_op_type_print_macro(type, *p);
4679 return 0;
4682 /* Print the required macros for "node", including one for floord.
4683 * We always print a macro for floord as it may also appear in the statements.
4685 static __isl_give isl_printer *print_macros(
4686 __isl_keep isl_ast_node *node, __isl_take isl_printer *p)
4688 p = isl_ast_op_type_print_macro(isl_ast_op_fdiv_q, p);
4689 if (isl_ast_node_foreach_ast_op_type(node, &print_macro, &p) < 0)
4690 return isl_printer_free(p);
4691 return p;
4694 /* Generate code for "kernel" in the given "context" and print
4695 * the result to gen->cuda.kernel_c.
4697 * We first generate code for the shared tile loops (T1T, T1P and T2)
4698 * in a context that includes the block ids.
4699 * Within each iteration of these loops an additional code generation
4700 * is performed (within create_kernel_leaf) for the rest of the schedule
4701 * in a context that includes the thread ids.
4703 static void print_kernel(struct gpu_gen *gen, struct ppcg_kernel *kernel,
4704 __isl_keep isl_ast_build *build, __isl_keep isl_set *host_domain)
4706 isl_space *space;
4707 isl_set *set;
4708 isl_ast_node *tree;
4709 isl_ast_print_options *print_options;
4710 isl_printer *p;
4711 isl_id_list *iterators;
4712 isl_union_map *schedule;
4713 int sched_len;
4715 schedule = isl_ast_build_get_schedule(build);
4717 build = isl_ast_build_copy(build);
4718 build = isl_ast_build_restrict(build, isl_set_copy(host_domain));
4719 space = isl_ast_build_get_schedule_space(build);
4720 set = isl_set_universe(isl_space_copy(space));
4721 set = add_bounded_parameters(set, gen->n_grid, gen->grid_dim, "b");
4722 build = isl_ast_build_restrict(build, set);
4724 schedule = body_schedule(gen, schedule);
4726 sched_len = 2 * (gen->shared_len - gen->tile_first) + 1;
4728 build = set_atomic_and_unroll(build, space, sched_len);
4729 iterators = generate_names(gen->ctx, sched_len, "g");
4730 build = isl_ast_build_set_iterators(build, iterators);
4731 build = isl_ast_build_set_create_leaf(build, &create_kernel_leaf, gen);
4732 tree = isl_ast_build_ast_from_schedule(build, schedule);
4733 isl_ast_build_free(build);
4735 print_kernel_headers(gen, kernel);
4736 fprintf(gen->cuda.kernel_c, "{\n");
4737 print_kernel_iterators(gen);
4738 print_shared_arrays(gen, kernel);
4739 fprintf(gen->cuda.kernel_c, "\n");
4741 print_options = isl_ast_print_options_alloc(gen->ctx);
4742 print_options = isl_ast_print_options_set_print_user(print_options,
4743 &print_kernel_stmt, gen);
4745 p = isl_printer_to_file(gen->ctx, gen->cuda.kernel_c);
4746 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
4747 p = isl_printer_indent(p, 4);
4748 p = print_macros(tree, p);
4749 p = isl_ast_node_print(tree, p, print_options);
4750 isl_printer_free(p);
4752 isl_ast_print_options_free(print_options);
4754 isl_ast_node_free(tree);
4756 fprintf(gen->cuda.kernel_c, "}\n");
4759 /* Attach "id" to the given node.
4761 static __isl_give isl_ast_node *attach_id(__isl_take isl_ast_node *node,
4762 __isl_keep isl_ast_build *build, void *user)
4764 isl_id *id = user;
4766 node = isl_ast_node_set_annotation(node, id);
4768 return node;
4771 /* Construct an AST node for performing a kernel launch and attach
4772 * the information about the kernel to that node.
4774 * The kernel AST has been constructed in the context of the range
4775 * of "schedule". In particular, the grid size has been computed
4776 * in the context. We therefore still need to make sure that these
4777 * constraints are expressed in the code. We do this by creating a schedule
4779 * kernel[] -> [S -> []]
4781 * where S is the schedule domain, i.e., the range of "schedule".
4782 * The AST generation will then create a single call surrounded by
4783 * all the condition in "S" that have not been expressed yet.
4785 * The kernel information is attached to this node in attach_id.
4787 static __isl_give isl_ast_node *construct_launch(
4788 __isl_take isl_ast_build *build, __isl_take isl_union_map *schedule,
4789 __isl_take struct ppcg_kernel *kernel)
4791 isl_id *id;
4792 isl_ctx *ctx;
4793 isl_union_set *domain;
4794 isl_set *set;
4795 isl_map *map;
4796 isl_ast_node *node;
4798 ctx = isl_ast_build_get_ctx(build);
4800 id = isl_id_alloc(ctx, NULL, kernel);
4801 id = isl_id_set_free_user(id, &ppcg_kernel_free);
4803 domain = isl_union_map_range(schedule);
4804 set = isl_set_from_union_set(domain);
4805 map = isl_map_from_domain(set);
4806 map = isl_map_from_range(isl_map_wrap(map));
4807 map = isl_map_set_tuple_name(map, isl_dim_in, "kernel");
4808 schedule = isl_union_map_from_map(map);
4810 build = isl_ast_build_set_at_each_domain(build, &attach_id, id);
4811 node = isl_ast_build_ast_from_schedule(build, schedule);
4812 isl_ast_build_free(build);
4814 return node;
4817 /* This function is called for each leaf in the AST of the host code.
4818 * We first specialize the schedule to the site of the leaf, compute
4819 * the size of shared memory and then construct the body of host code
4820 * and the associated kernel.
4822 * The necessary information for printing the kernel launch is
4823 * stored in a struct ppcg_kernel and attached to the leaf node
4824 * created to represent the launch.
4826 static __isl_give isl_ast_node *create_host_leaf(
4827 __isl_take isl_ast_build *build, void *user)
4829 struct gpu_gen *gen = (struct gpu_gen *) user;
4830 isl_id *id;
4831 isl_ast_node *node;
4832 struct ppcg_kernel *kernel;
4833 isl_set *host_domain;
4834 isl_union_map *schedule;
4835 isl_union_map *local_sched;
4836 isl_union_map *access;
4837 isl_union_set *domain;
4838 int i;
4840 schedule = isl_ast_build_get_schedule(build);
4842 isl_union_map_foreach_map(schedule, &extract_tile_len, gen);
4843 read_sizes(gen);
4845 domain = isl_union_map_domain(isl_union_map_copy(schedule));
4847 local_sched = isl_union_map_copy(gen->sched);
4848 local_sched = isl_union_map_intersect_domain(local_sched, domain);
4849 access = isl_union_map_union(isl_union_map_copy(gen->read),
4850 isl_union_map_copy(gen->write));
4851 access = isl_union_map_apply_domain(access,
4852 isl_union_map_copy(local_sched));
4854 gen->tiled_sched = tile_schedule(gen, local_sched);
4855 gen->tiled_sched = parametrize_tiled_schedule(gen, gen->tiled_sched);
4856 gen->tiled_sched = scale_tile_loops(gen, gen->tiled_sched);
4858 kernel = gen->kernel = isl_calloc_type(gen->ctx, struct ppcg_kernel);
4859 if (!kernel)
4860 goto error;
4862 kernel->id = gen->kernel_id++;
4863 kernel->n_block = gen->n_block;
4864 for (i = 0; i < gen->n_block; ++i)
4865 kernel->block_dim[i] = gen->block_dim[i];
4866 kernel->grid = extract_grid(gen);
4867 kernel->context = isl_union_map_params(isl_union_map_copy(schedule));
4868 kernel->arrays = isl_union_map_range(access);
4869 kernel->space = isl_ast_build_get_schedule_space(build);
4871 gen->local_sched = isl_union_map_copy(gen->tiled_sched);
4873 gen->local_sched = thread_tile_schedule(gen, gen->local_sched);
4874 gen->local_sched = scale_thread_tile_loops(gen, gen->local_sched);
4876 gen->private_access = NULL;
4877 compute_shared_sched(gen);
4878 gen->privatization = compute_privatization(gen);
4879 group_references(gen);
4880 compute_private_size(gen);
4881 check_shared_memory_bound(gen);
4882 host_domain = isl_set_from_union_set(isl_union_map_range(
4883 isl_union_map_copy(schedule)));
4884 localize_bounds(gen, kernel, host_domain);
4886 gen->local_sched = interchange_for_unroll(gen, gen->local_sched);
4888 print_kernel(gen, kernel, build, host_domain);
4890 free_local_array_info(gen);
4891 isl_map_free(gen->privatization);
4892 isl_union_map_free(gen->private_access);
4893 isl_union_map_free(gen->local_sched);
4894 isl_union_map_free(gen->tiled_sched);
4895 isl_union_map_free(gen->shared_sched);
4896 isl_union_map_free(gen->shared_proj);
4897 isl_set_free(host_domain);
4898 free(gen->tile_size);
4900 node = construct_launch(build, schedule, kernel);
4902 return node;
4903 error:
4904 isl_union_map_free(schedule);
4905 return NULL;
4908 /* Print the effective grid size as a list of the sizes in each
4909 * dimension, from innermost to outermost.
4911 * The grid size specified by the user or set by default
4912 * in read_grid_sizes() and applied in tile_schedule(),
4913 * may be too large for the given code in the sense that
4914 * it may contain blocks that don't need to execute anything.
4915 * We therefore don't print this grid size, but instead the
4916 * smallest grid size that ensures that all blocks that actually
4917 * execute code are included in the grid.
4919 * For each block dimension, we compute the maximal value of the block id
4920 * and add one.
4922 static __isl_give isl_printer *print_grid_size(__isl_take isl_printer *p,
4923 struct ppcg_kernel *kernel)
4925 int i;
4926 int dim;
4928 dim = isl_set_dim(kernel->grid, isl_dim_set);
4929 if (dim == 0)
4930 return p;
4932 p = isl_printer_print_str(p, "(");
4933 for (i = dim - 1; i >= 0; --i) {
4934 isl_space *space;
4935 isl_aff *one;
4936 isl_pw_aff *bound ;
4938 bound = isl_set_dim_max(isl_set_copy(kernel->grid), i);
4939 bound = isl_pw_aff_coalesce(bound);
4940 bound = isl_pw_aff_gist(bound, isl_set_copy(kernel->context));
4942 space = isl_pw_aff_get_domain_space(bound);
4943 one = isl_aff_zero_on_domain(isl_local_space_from_space(space));
4944 one = isl_aff_add_constant_si(one, 1);
4945 bound = isl_pw_aff_add(bound, isl_pw_aff_from_aff(one));
4946 p = isl_printer_print_pw_aff(p, bound);
4947 isl_pw_aff_free(bound);
4949 if (i > 0)
4950 p = isl_printer_print_str(p, ", ");
4953 p = isl_printer_print_str(p, ")");
4955 return p;
4958 /* Print the grid definition.
4960 static __isl_give isl_printer *print_grid(__isl_take isl_printer *p,
4961 struct ppcg_kernel *kernel)
4963 p = isl_printer_start_line(p);
4964 p = isl_printer_print_str(p, "dim3 k");
4965 p = isl_printer_print_int(p, kernel->id);
4966 p = isl_printer_print_str(p, "_dimGrid");
4967 p = print_grid_size(p, kernel);
4968 p = isl_printer_print_str(p, ";");
4969 p = isl_printer_end_line(p);
4971 return p;
4974 /* Print the user statement of the host code to "p".
4976 * In particular, print a block of statements that defines the grid
4977 * and the block and then launches the kernel.
4979 static __isl_give isl_printer *print_host_user(__isl_take isl_printer *p,
4980 __isl_keep isl_ast_node *node, void *user)
4982 struct gpu_gen *gen = (struct gpu_gen *) user;
4983 isl_id *id;
4984 struct ppcg_kernel *kernel;
4986 id = isl_ast_node_get_annotation(node);
4987 kernel = isl_id_get_user(id);
4988 isl_id_free(id);
4990 p = isl_printer_start_line(p);
4991 p = isl_printer_print_str(p, "{");
4992 p = isl_printer_end_line(p);
4993 p = isl_printer_indent(p, 2);
4995 p = isl_printer_start_line(p);
4996 p = isl_printer_print_str(p, "dim3 k");
4997 p = isl_printer_print_int(p, kernel->id);
4998 p = isl_printer_print_str(p, "_dimBlock");
4999 print_reverse_list(isl_printer_get_file(p),
5000 kernel->n_block, kernel->block_dim);
5001 p = isl_printer_print_str(p, ";");
5002 p = isl_printer_end_line(p);
5004 p = print_grid(p, kernel);
5006 p = isl_printer_start_line(p);
5007 p = isl_printer_print_str(p, "kernel");
5008 p = isl_printer_print_int(p, kernel->id);
5009 p = isl_printer_print_str(p, " <<<k");
5010 p = isl_printer_print_int(p, kernel->id);
5011 p = isl_printer_print_str(p, "_dimGrid, k");
5012 p = isl_printer_print_int(p, kernel->id);
5013 p = isl_printer_print_str(p, "_dimBlock>>> (");
5014 p = print_kernel_arguments(p, gen, kernel, 0);
5015 p = isl_printer_print_str(p, ");");
5016 p = isl_printer_end_line(p);
5018 p = isl_printer_start_line(p);
5019 p = isl_printer_print_str(p, "cudaCheckKernel();");
5020 p = isl_printer_end_line(p);
5022 p = isl_printer_indent(p, -2);
5023 p = isl_printer_start_line(p);
5024 p = isl_printer_print_str(p, "}");
5025 p = isl_printer_end_line(p);
5027 p = isl_printer_start_line(p);
5028 p = isl_printer_end_line(p);
5030 return p;
5033 /* Use isl to generate code for the outer gen->tile_first loops
5034 * of the global schedule in gen->sched, resulting in the host code.
5035 * Within each iteration of this partial schedule, i.e., for each kernel
5036 * launch, create_host_leaf takes care of generating the kernel code.
5038 static void print_isl_host_code(struct gpu_gen *gen)
5040 isl_ast_build *build;
5041 isl_ast_node *tree;
5042 isl_ast_print_options *print_options;
5043 isl_printer *p;
5044 isl_union_map *sched;
5045 isl_map *proj;
5046 isl_id_list *iterators;
5048 sched = isl_union_map_copy(gen->sched);
5049 proj = projection(isl_union_map_get_space(sched),
5050 gen->untiled_len, gen->tile_first);
5051 sched = isl_union_map_apply_range(sched, isl_union_map_from_map(proj));
5053 isl_options_set_ast_build_group_coscheduled(gen->ctx, 1);
5054 build = isl_ast_build_from_context(isl_set_copy(gen->context));
5055 iterators = generate_names(gen->ctx, gen->tile_first, "h");
5056 build = isl_ast_build_set_iterators(build, iterators);
5057 build = isl_ast_build_set_create_leaf(build, &create_host_leaf, gen);
5058 tree = isl_ast_build_ast_from_schedule(build, sched);
5059 isl_ast_build_free(build);
5061 print_options = isl_ast_print_options_alloc(gen->ctx);
5062 print_options = isl_ast_print_options_set_print_user(print_options,
5063 &print_host_user, gen);
5065 p = isl_printer_to_file(gen->ctx, gen->cuda.host_c);
5066 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
5067 p = print_macros(tree, p);
5068 p = isl_ast_node_print(tree, p, print_options);
5069 isl_printer_free(p);
5071 isl_ast_print_options_free(print_options);
5073 isl_ast_node_free(tree);
5076 void print_cuda_macros(struct gpu_gen *gen)
5078 const char *macros =
5079 "#define cudaCheckReturn(ret) assert((ret) == cudaSuccess)\n"
5080 "#define cudaCheckKernel()"
5081 " assert(cudaGetLastError() == cudaSuccess)\n\n";
5082 fputs(macros, gen->cuda.host_c);
5085 void print_host_code(struct gpu_gen *gen)
5087 fprintf(gen->cuda.host_c, "{\n");
5089 print_cuda_macros(gen);
5091 declare_device_arrays(gen);
5093 allocate_device_arrays(gen);
5094 copy_arrays_to_device(gen);
5096 gen->kernel_id = 0;
5097 print_isl_host_code(gen);
5099 copy_arrays_from_device(gen);
5100 free_device_arrays(gen);
5102 fprintf(gen->cuda.host_c, "}\n");
5105 __isl_give isl_set *add_context_from_str(__isl_take isl_set *set,
5106 const char *str)
5108 isl_ctx *ctx;
5109 isl_set *context;
5111 if (!str)
5112 return set;
5114 ctx = isl_set_get_ctx(set);
5115 context = isl_set_read_from_str(ctx, str);
5116 context = isl_set_align_params(context, isl_set_get_space(set));
5117 set = isl_set_intersect(set, context);
5119 return set;
5122 __isl_give isl_union_map *extract_sizes_from_str(isl_ctx *ctx, const char *str)
5124 if (!str)
5125 return NULL;
5126 return isl_union_map_read_from_str(ctx, str);
5129 /* Return the union of all iteration domains of the gen->stmts[i].
5131 static __isl_give isl_union_set *extract_domain(struct gpu_gen *gen)
5133 int i;
5134 isl_union_set *domain;
5136 domain = isl_union_set_empty(isl_set_get_space(gen->context));
5137 for (i = 0; i < gen->n_stmts; ++i) {
5138 isl_set *domain_i;
5140 domain_i = isl_set_copy(gen->stmts[i].domain);
5141 domain = isl_union_set_union(domain,
5142 isl_union_set_from_set(domain_i));
5145 return domain;
5148 /* Information about the outermost tilable bands in the forest of bands.
5150 * tile_len and n_parallel are only sets on band_info structures
5151 * that correspond to outermost bands. For other bands (in particular,
5152 * ancestors of the outermost bands), n_parallal is set to 0.
5154 * prefix is the (padded) schedule leading up to the outermost tilable bands.
5156 * tile_first is the number of schedule dimensions in prefix.
5158 * suffix is the schedule of the outermost tilable bands and their descendants.
5160 struct band_info {
5161 struct gpu_gen *gen;
5162 int tile_first;
5163 int tile_len;
5164 int n_parallel;
5165 isl_union_map *prefix;
5166 isl_union_map *suffix;
5169 /* Set tile_len and n_parallel of the statement to that of
5170 * their outermost band, recorded in the band_info.
5172 static int set_stmt_tile_len(__isl_take isl_map *map, void *user)
5174 struct band_info *info = user;
5175 struct gpu_stmt *stmt;
5176 isl_id *id;
5178 id = isl_map_get_tuple_id(map, isl_dim_in);
5179 stmt = find_stmt(info->gen, id);
5180 isl_id_free(id);
5182 stmt->tile_len = info->tile_len;
5183 stmt->n_parallel = info->n_parallel;
5185 isl_map_free(map);
5187 return 0;
5190 static void list_select_outer_band(struct gpu_gen *gen,
5191 __isl_take isl_band_list *list, int pos, struct band_info *list_info);
5193 /* Check if this band has any parallel loops. If so, take it as
5194 * the outermost tilable band. If not, continue looking for the
5195 * outermost tilable band in the children of the current band.
5197 static void band_select_outer_band(struct gpu_gen *gen,
5198 __isl_take isl_band *band, int pos, struct band_info *info)
5200 int n = isl_band_n_member(band);
5201 int n_parallel;
5203 for (n_parallel = 0; n_parallel < n; ++n_parallel)
5204 if (!isl_band_member_is_zero_distance(band, n_parallel))
5205 break;
5207 info->n_parallel = n_parallel;
5208 if (n_parallel) {
5209 info->gen = gen;
5210 info->tile_first = pos;
5211 info->tile_len = n;
5212 info->prefix = isl_band_get_prefix_schedule(band);
5213 info->suffix = isl_union_map_flat_range_product(
5214 isl_band_get_partial_schedule(band),
5215 isl_band_get_suffix_schedule(band));
5216 isl_union_map_foreach_map(info->prefix,
5217 &set_stmt_tile_len, info);
5218 } else if (isl_band_has_children(band)) {
5219 isl_band_list *children;
5220 children = isl_band_get_children(band);
5221 list_select_outer_band(gen, children, pos + n, info);
5222 } else {
5223 info->gen = gen;
5224 info->tile_first = pos + n;
5225 info->tile_len = 0;
5226 info->prefix = isl_union_map_flat_range_product(
5227 isl_band_get_prefix_schedule(band),
5228 isl_band_get_partial_schedule(band));
5229 info->suffix = isl_band_get_suffix_schedule(band);
5230 isl_union_map_foreach_map(info->prefix,
5231 &set_stmt_tile_len, info);
5234 isl_band_free(band);
5237 /* Comparison function that returns a non-zero value for band_infos
5238 * with different tile_len fields or different n_parallel fields.
5240 static int cmp_band(const void *p1, const void *p2)
5242 const struct band_info *info1 = p1;
5243 const struct band_info *info2 = p2;
5245 if (info1->tile_len != info2->tile_len)
5246 return info1->tile_len - info2->tile_len;
5248 return info1->n_parallel - info2->n_parallel;
5251 /* Extend "umap" with coordinates with fixed value "val"
5252 * to a total length of "dst_len", assuming the original dimension is "src_len".
5254 static __isl_give isl_union_map *extend_range(
5255 __isl_take isl_union_map *umap, int src_len, int dst_len, int val)
5257 isl_space *dim;
5258 isl_map *map;
5259 int i;
5261 dim = isl_union_map_get_space(umap);
5262 map = isl_map_reverse(projection(dim, dst_len, src_len));
5263 for (i = src_len; i < dst_len; ++i)
5264 map = isl_map_fix_si(map, isl_dim_out, i, val);
5266 umap = isl_union_map_apply_range(umap, isl_union_map_from_map(map));
5268 return umap;
5271 /* Group bands with the same values for tile_len and n_parallel.
5272 * The prefix schedule is then extended with a fixed coordinate that
5273 * is different for each such group.
5274 * Note that the actual values for this coordinate are not important.
5275 * The bands have already been effectively separated at a higher level
5276 * or they are independent and may be executed in parallel.
5277 * The list of band_info has been sorted before this functions is called.
5279 static void separate_bands(struct band_info *info, int n)
5281 int i;
5282 int j = 0;
5284 for (i = 0; i < n; ++i) {
5285 int l = info[i].tile_first;
5287 if (i &&
5288 (info[i].tile_len != info[i - 1].tile_len ||
5289 info[i].n_parallel != info[i - 1].n_parallel))
5290 j++;
5292 info[i].prefix = extend_range(info[i].prefix,
5293 l, l + 1, j);
5294 info[i].tile_first = l + 1;
5298 /* Select the outermost bands in the elements of the list, align
5299 * their prefix schedules, separate bands with different values
5300 * for tile_len and/or n_parallel and then combine the resulting
5301 * prefix and suffix schedules into a single pair of prefix and
5302 * suffix schedules for the entire list.
5304 static void list_select_outer_band(struct gpu_gen *gen,
5305 __isl_take isl_band_list *list, int pos, struct band_info *list_info)
5307 isl_band *band;
5308 int i;
5309 int n = isl_band_list_n_band(list);
5310 isl_ctx *ctx = isl_band_list_get_ctx(list);
5311 struct band_info *info;
5312 int max_tile_first;
5313 isl_union_map *prefix;
5314 isl_union_map *suffix;
5316 assert(n >= 1);
5317 info = isl_calloc_array(ctx, struct band_info, n);
5318 assert(info);
5320 max_tile_first = 0;
5321 for (i = 0; i < n; ++i) {
5322 band = isl_band_list_get_band(list, i);
5323 band_select_outer_band(gen, band, pos, &info[i]);
5324 if (info[i].tile_first > max_tile_first)
5325 max_tile_first = info[i].tile_first;
5328 for (i = 0; i < n; ++i) {
5329 if (info[i].tile_first == max_tile_first)
5330 continue;
5331 info[i].prefix = extend_range(info[i].prefix,
5332 info[i].tile_first, max_tile_first, 0);
5333 info[i].tile_first = max_tile_first;
5336 qsort(info, n, sizeof(struct band_info), &cmp_band);
5338 for (i = 0; i < n - 1; ++i)
5339 if (info[i].tile_len != info[i + 1].tile_len ||
5340 info[i].n_parallel != info[i + 1].n_parallel)
5341 break;
5343 if (i < n -1)
5344 separate_bands(info, n);
5346 prefix = info[0].prefix;
5347 suffix = info[0].suffix;
5349 for (i = 1; i < n; ++i) {
5350 prefix = isl_union_map_union(prefix, info[i].prefix);
5351 suffix = isl_union_map_union(suffix, info[i].suffix);
5354 list_info->tile_first = info[0].tile_first;
5355 list_info->tile_len = -1;
5356 list_info->prefix = prefix;
5357 list_info->suffix = suffix;
5359 isl_band_list_free(list);
5360 free(info);
5363 /* Select the outermost tilable band that (by construction)
5364 * has at least one parallel loop.
5365 * The starting position of the aligned band is stored in the pair
5366 * gen->tile_first.
5367 * The sizes and number of parallel loops may be different in different
5368 * parts of the band forest and are therefore stored in the gpu_stmts.
5370 * Return the complete schedule, with the tilable bands aligned
5371 * at gen->tile_first and padded with zero, if needed.
5373 static __isl_give isl_union_map *select_outer_tilable_band(struct gpu_gen *gen,
5374 __isl_keep isl_schedule *schedule)
5376 isl_band_list *list;
5377 struct band_info info;
5379 gen->n_parallel = 0;
5380 gen->tile_len = -1;
5382 list = isl_schedule_get_band_forest(schedule);
5384 list_select_outer_band(gen, list, 0, &info);
5386 gen->tile_first = info.tile_first;
5387 info.suffix = align_range(info.suffix);
5389 return isl_union_map_flat_range_product(info.prefix, info.suffix);
5392 /* Set gen->untiled_len to the number of scheduling dimensions
5393 * for the schedule of the first domain.
5394 * We assume here that this number is the same for all domains.
5396 static int set_untiled_len(__isl_take isl_map *map, void *user)
5398 unsigned *untiled_len = user;
5400 *untiled_len = isl_map_dim(map, isl_dim_out);
5402 isl_map_free(map);
5403 return -1;
5406 /* Compute an appropriate schedule based on the accesses in
5407 * gen->read and gen->write.
5409 * We first compute dependences and then use those to compute
5410 * a schedule that has a parallel loop in each tilable band.
5411 * Finally, we select the outermost tilable band.
5413 static void compute_schedule(struct gpu_gen *gen,
5414 __isl_take isl_union_map *sched)
5416 isl_union_set *domain;
5417 isl_union_map *empty;
5418 isl_union_map *dep_raw, *dep2, *dep3, *dep;
5419 isl_union_map *uninitialized;
5420 isl_schedule *schedule;
5422 empty = isl_union_map_empty(isl_union_map_get_space(sched));
5424 isl_union_map_compute_flow(isl_union_map_copy(gen->read),
5425 isl_union_map_copy(gen->write), empty,
5426 isl_union_map_copy(sched),
5427 &dep_raw, NULL, &uninitialized, NULL);
5428 isl_union_map_compute_flow(isl_union_map_copy(gen->write),
5429 isl_union_map_copy(gen->write),
5430 isl_union_map_copy(gen->read),
5431 isl_union_map_copy(sched),
5432 &dep2, &dep3, NULL, NULL);
5433 isl_union_map_free(sched);
5435 gen->copy_in = isl_union_map_range(uninitialized);
5437 dep = isl_union_map_union(dep2, dep3);
5438 dep = isl_union_map_union(dep, dep_raw);
5439 dep = isl_union_map_coalesce(dep);
5441 domain = extract_domain(gen);
5442 schedule = isl_union_set_compute_schedule(isl_union_set_copy(domain),
5443 isl_union_map_copy(dep), dep);
5445 sched = select_outer_tilable_band(gen, schedule);
5447 isl_union_map_foreach_map(sched, &set_untiled_len, &gen->untiled_len);
5448 sched = isl_union_map_intersect_domain(sched, domain);
5449 gen->sched = sched;
5451 isl_schedule_free(schedule);
5454 static struct gpu_stmt_access **expr_extract_access(struct pet_expr *expr,
5455 struct gpu_stmt_access **next_access)
5457 struct gpu_stmt_access *access;
5458 isl_ctx *ctx = isl_map_get_ctx(expr->acc.access);
5460 access = isl_alloc_type(ctx, struct gpu_stmt_access);
5461 assert(access);
5462 access->next = NULL;
5463 access->read = expr->acc.read;
5464 access->write = expr->acc.write;
5465 access->access = isl_map_copy(expr->acc.access);
5467 *next_access = access;
5468 next_access = &(*next_access)->next;
5469 return next_access;
5472 static struct gpu_stmt_access **expr_extract_accesses(struct pet_expr *expr,
5473 struct gpu_stmt_access **next_access)
5475 int i;
5477 for (i = 0; i < expr->n_arg; ++i)
5478 next_access = expr_extract_accesses(expr->args[i],
5479 next_access);
5481 if (expr->type == pet_expr_access)
5482 next_access = expr_extract_access(expr, next_access);
5484 return next_access;
5487 static void pet_stmt_extract_accesses(struct gpu_stmt *stmt)
5489 struct gpu_stmt_access **next_access = &stmt->accesses;
5491 stmt->accesses = NULL;
5492 expr_extract_accesses(stmt->body, next_access);
5495 /* Return an array of gpu_stmt representing the statements in "scop".
5497 static struct gpu_stmt *extract_stmts(isl_ctx *ctx, struct pet_scop *scop,
5498 __isl_keep isl_set *context)
5500 int i;
5501 struct gpu_stmt *stmts;
5503 stmts = isl_calloc_array(ctx, struct gpu_stmt, scop->n_stmt);
5504 assert(stmts);
5506 for (i = 0; i < scop->n_stmt; ++i) {
5507 struct gpu_stmt *s = &stmts[i];
5509 s->domain = isl_set_copy(scop->stmts[i]->domain);
5510 s->domain = isl_set_intersect_params(s->domain,
5511 isl_set_copy(context));
5512 s->body = scop->stmts[i]->body;
5513 pet_stmt_extract_accesses(s);
5516 return stmts;
5519 /* Replace the scop in the "input" file by equivalent code
5520 * that uses the GPU. "scop" is assumed to correspond to this scop.
5522 * We first compute a schedule that respects the dependences
5523 * of the original program and select the outermost band
5524 * of tilable dimensions that has at least one parallel loop.
5525 * We then have three blocks of dimensions
5527 * H B G
5529 * The tilable band "B" is first tiled according to "tile" sizes, resulting
5530 * in
5532 * H T P G
5534 * For each iteration of the T loop and for each array, we compute
5535 * the array elements accessed by that iteration, construct a rectangular
5536 * box around it and shift it to the origin. The result is used
5537 * as shared memory for the array.
5539 * We then split off at most 2 parallel loops from the T loops and
5540 * at most 3 parallel loops from the P loops
5542 * H T1 T2 P1 P2 G
5544 * The T1/P1 loops are then tiled or "wrapped" over the blocks/threads,
5545 * according to "grid"/"block" sizes.
5547 * H T1T T1P T2 P1T P1P P2 G
5549 * Finally, the T1P and P1P iterators are equated to the block and
5550 * thread dimensions respectively and so are effectively removed.
5551 * The H loops are run on the host. The T1T, T2, P1T, P2 and G loops
5552 * are run on the GPU.
5554 * Code is generated in three stages. We first generate code for the
5555 * host (the H loops), with iterators h%d. Then, for each leaf node
5556 * of the resulting AST, we generate code for the shared loops (up to
5557 * and including T2), with iterators g%d and after equating the H loops
5558 * to h%d parameters and the T1P loops to the block dimensions.
5559 * Finally, we generate code for the remaining loops in a similar fashion.
5561 int generate_cuda(isl_ctx *ctx, struct pet_scop *scop,
5562 struct ppcg_options *options, const char *input)
5564 isl_union_map *sched;
5565 struct gpu_gen gen;
5567 if (!scop)
5568 return -1;
5570 scop = pet_scop_align_params(scop);
5572 gen.ctx = ctx;
5573 gen.context = isl_set_copy(scop->context);
5574 gen.context = add_context_from_str(gen.context, options->ctx);
5575 gen.sizes = extract_sizes_from_str(ctx, options->sizes);
5576 gen.n_stmts = scop->n_stmt;
5577 gen.stmts = extract_stmts(ctx, scop, gen.context);
5578 gen.read = pet_scop_collect_reads(scop);
5579 gen.write = pet_scop_collect_writes(scop);
5580 gen.options = options;
5581 gen.scop = scop;
5583 cuda_open_files(&gen.cuda, input);
5585 collect_array_info(&gen);
5587 sched = pet_scop_collect_schedule(scop);
5589 compute_schedule(&gen, sched);
5591 print_host_code(&gen);
5593 clear_gpu_gen(&gen);
5595 cuda_close_files(&gen.cuda);
5597 return 0;