CUDA backend: do not declare or allocate arrays that are not accessed
[ppcg.git] / opencl.c
blob60226d1c370c79ffa4b462691ac55ebb25c26195
1 /*
2 * Copyright 2013 Ecole Normale Superieure
4 * Use of this software is governed by the MIT license
6 * Written by Sven Verdoolaege and Riyadh Baghdadi,
7 * Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
8 */
10 #include <ctype.h>
11 #include <limits.h>
12 #include <string.h>
14 #include <isl/aff.h>
15 #include <isl/ast.h>
17 #include "opencl.h"
18 #include "gpu_print.h"
19 #include "gpu.h"
20 #include "ppcg.h"
21 #include "print.h"
22 #include "schedule.h"
24 #define min(a, b) (((a) < (b)) ? (a) : (b))
25 #define max(a, b) (((a) > (b)) ? (a) : (b))
27 /* options are the global options passed to generate_opencl.
28 * input is the name of the input file.
29 * output is the user-specified output file name and may be NULL
30 * if not specified by the user.
31 * kernel_c_name is the name of the kernel_c file.
32 * kprinter is an isl_printer for the kernel file.
33 * host_c is the generated source file for the host code. kernel_c is
34 * the generated source file for the kernel.
36 struct opencl_info {
37 struct ppcg_options *options;
38 const char *input;
39 const char *output;
40 char kernel_c_name[PATH_MAX];
42 isl_printer *kprinter;
44 FILE *host_c;
45 FILE *kernel_c;
48 /* Open the file called "name" for writing or print an error message.
50 static FILE *open_or_croak(const char *name)
52 FILE *file;
54 file = fopen(name, "w");
55 if (!file)
56 fprintf(stderr, "Failed to open \"%s\" for writing\n", name);
57 return file;
60 /* Open the host .c file and the kernel .h and .cl files for writing.
61 * Their names are derived from info->output (or info->input if
62 * the user did not specify an output file name).
63 * Add the necessary includes to these files, including those specified
64 * by the user.
66 * Return 0 on success and -1 on failure.
68 static int opencl_open_files(struct opencl_info *info)
70 char name[PATH_MAX];
71 int i;
72 int len;
74 if (info->output) {
75 const char *ext;
77 ext = strrchr(info->output, '.');
78 len = ext ? ext - info->output : strlen(info->output);
79 memcpy(name, info->output, len);
81 info->host_c = open_or_croak(info->output);
82 } else {
83 len = ppcg_extract_base_name(name, info->input);
85 strcpy(name + len, "_host.c");
86 info->host_c = open_or_croak(name);
89 memcpy(info->kernel_c_name, name, len);
90 strcpy(info->kernel_c_name + len, "_kernel.cl");
91 info->kernel_c = open_or_croak(info->kernel_c_name);
93 if (!info->host_c || !info->kernel_c)
94 return -1;
96 fprintf(info->host_c, "#include <assert.h>\n");
97 fprintf(info->host_c, "#include <stdio.h>\n");
98 fprintf(info->host_c, "#include \"ocl_utilities.h\"\n");
99 if (info->options->opencl_embed_kernel_code) {
100 fprintf(info->host_c, "#include \"%s\"\n\n",
101 info->kernel_c_name);
104 for (i = 0; i < info->options->opencl_n_include_file; ++i) {
105 info->kprinter = isl_printer_print_str(info->kprinter,
106 "#include <");
107 info->kprinter = isl_printer_print_str(info->kprinter,
108 info->options->opencl_include_files[i]);
109 info->kprinter = isl_printer_print_str(info->kprinter, ">\n");
112 return 0;
115 /* Write text to a file and escape some special characters that would break a
116 * C string.
118 static void opencl_print_escaped(const char *str, const char *end, FILE *file)
120 const char *prev = str;
122 while ((str = strpbrk(prev, "\"\\")) && str < end) {
123 fwrite(prev, 1, str - prev, file);
124 fprintf(file, "\\%c", *str);
125 prev = str + 1;
128 if (*prev)
129 fwrite(prev, 1, end - prev, file);
132 /* Write text to a file as a C string literal.
134 * This function also prints any characters after the last newline, although
135 * normally the input string should end with a newline.
137 static void opencl_print_as_c_string(const char *str, FILE *file)
139 const char *prev = str;
141 while ((str = strchr(prev, '\n'))) {
142 fprintf(file, "\n\"");
143 opencl_print_escaped(prev, str, file);
144 fprintf(file, "\\n\"");
146 prev = str + 1;
149 if (*prev) {
150 fprintf(file, "\n\"");
151 opencl_print_escaped(prev, prev + strlen(prev), file);
152 fprintf(file, "\"");
156 /* Write the code that we have accumulated in the kernel isl_printer to the
157 * kernel.cl file. If the opencl_embed_kernel_code option has been set, print
158 * the code as a C string literal. Start that string literal with an empty
159 * line, such that line numbers reported by the OpenCL C compiler match those
160 * of the kernel file.
162 * Return 0 on success and -1 on failure.
164 static int opencl_write_kernel_file(struct opencl_info *opencl)
166 char *raw = isl_printer_get_str(opencl->kprinter);
168 if (!raw)
169 return -1;
171 if (opencl->options->opencl_embed_kernel_code) {
172 fprintf(opencl->kernel_c,
173 "static const char kernel_code[] = \"\\n\"");
174 opencl_print_as_c_string(raw, opencl->kernel_c);
175 fprintf(opencl->kernel_c, ";\n");
176 } else
177 fprintf(opencl->kernel_c, "%s", raw);
179 free(raw);
181 return 0;
184 /* Close all output files. Write the kernel contents to the kernel file before
185 * closing it.
187 * Return 0 on success and -1 on failure.
189 static int opencl_close_files(struct opencl_info *info)
191 int r = 0;
193 if (info->kernel_c) {
194 r = opencl_write_kernel_file(info);
195 fclose(info->kernel_c);
197 if (info->host_c)
198 fclose(info->host_c);
200 return r;
203 static __isl_give isl_printer *opencl_print_host_macros(
204 __isl_take isl_printer *p)
206 const char *macros =
207 "#define openclCheckReturn(ret) \\\n"
208 " if (ret != CL_SUCCESS) {\\\n"
209 " fprintf(stderr, \"OpenCL error: %s\\n\", "
210 "opencl_error_string(ret)); \\\n"
211 " fflush(stderr); \\\n"
212 " assert(ret == CL_SUCCESS);\\\n }\n";
214 p = isl_printer_start_line(p);
215 p = isl_printer_print_str(p, macros);
216 p = isl_printer_end_line(p);
218 p = isl_ast_op_type_print_macro(isl_ast_op_max, p);
220 return p;
223 static __isl_give isl_printer *opencl_declare_device_arrays(
224 __isl_take isl_printer *p, struct gpu_prog *prog)
226 int i;
228 for (i = 0; i < prog->n_array; ++i) {
229 if (gpu_array_is_read_only_scalar(&prog->array[i]))
230 continue;
231 p = isl_printer_start_line(p);
232 p = isl_printer_print_str(p, "cl_mem dev_");
233 p = isl_printer_print_str(p, prog->array[i].name);
234 p = isl_printer_print_str(p, ";");
235 p = isl_printer_end_line(p);
237 p = isl_printer_start_line(p);
238 p = isl_printer_end_line(p);
239 return p;
242 /* Given an array, check whether its positive size guard expression is
243 * trivial.
245 static int is_array_positive_size_guard_trivial(struct gpu_array_info *array)
247 isl_set *guard;
248 int is_trivial;
250 guard = gpu_array_positive_size_guard(array);
251 is_trivial = isl_set_plain_is_universe(guard);
252 isl_set_free(guard);
253 return is_trivial;
256 /* Allocate a device array for "array'.
258 * Emit a max-expression to ensure the device array can contain at least one
259 * element if the array's positive size guard expression is not trivial.
261 static __isl_give isl_printer *allocate_device_array(__isl_take isl_printer *p,
262 struct gpu_array_info *array)
264 int need_lower_bound;
266 p = ppcg_start_block(p);
268 p = isl_printer_start_line(p);
269 p = isl_printer_print_str(p, "dev_");
270 p = isl_printer_print_str(p, array->name);
271 p = isl_printer_print_str(p, " = clCreateBuffer(context, ");
272 p = isl_printer_print_str(p, "CL_MEM_READ_WRITE, ");
274 need_lower_bound = !is_array_positive_size_guard_trivial(array);
275 if (need_lower_bound) {
276 p = isl_printer_print_str(p, "max(sizeof(");
277 p = isl_printer_print_str(p, array->type);
278 p = isl_printer_print_str(p, "), ");
280 p = gpu_array_info_print_size(p, array);
281 if (need_lower_bound)
282 p = isl_printer_print_str(p, ")");
284 p = isl_printer_print_str(p, ", NULL, &err);");
285 p = isl_printer_end_line(p);
286 p = isl_printer_start_line(p);
287 p = isl_printer_print_str(p, "openclCheckReturn(err);");
288 p = isl_printer_end_line(p);
290 p = ppcg_end_block(p);
292 return p;
295 /* Allocate device arrays.
297 static __isl_give isl_printer *opencl_allocate_device_arrays(
298 __isl_take isl_printer *p, struct gpu_prog *prog)
300 int i;
302 for (i = 0; i < prog->n_array; ++i) {
303 struct gpu_array_info *array = &prog->array[i];
305 if (gpu_array_is_read_only_scalar(array))
306 continue;
308 p = allocate_device_array(p, array);
310 p = isl_printer_start_line(p);
311 p = isl_printer_end_line(p);
312 return p;
315 /* Print a call to the OpenCL clSetKernelArg() function which sets
316 * the arguments of the kernel. arg_name and arg_index are the name and the
317 * index of the kernel argument. The index of the leftmost argument of
318 * the kernel is 0 whereas the index of the rightmost argument of the kernel
319 * is n - 1, where n is the total number of the kernel arguments.
320 * read_only_scalar is a boolean that indicates whether the argument is a read
321 * only scalar.
323 static __isl_give isl_printer *opencl_set_kernel_argument(
324 __isl_take isl_printer *p, int kernel_id,
325 const char *arg_name, int arg_index, int read_only_scalar)
327 p = isl_printer_start_line(p);
328 p = isl_printer_print_str(p,
329 "openclCheckReturn(clSetKernelArg(kernel");
330 p = isl_printer_print_int(p, kernel_id);
331 p = isl_printer_print_str(p, ", ");
332 p = isl_printer_print_int(p, arg_index);
333 p = isl_printer_print_str(p, ", sizeof(");
335 if (read_only_scalar) {
336 p = isl_printer_print_str(p, arg_name);
337 p = isl_printer_print_str(p, "), &");
338 } else
339 p = isl_printer_print_str(p, "cl_mem), (void *) &dev_");
341 p = isl_printer_print_str(p, arg_name);
342 p = isl_printer_print_str(p, "));");
343 p = isl_printer_end_line(p);
345 return p;
348 /* Print the block sizes as a list of the sizes in each
349 * dimension.
351 static __isl_give isl_printer *opencl_print_block_sizes(
352 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
354 int i;
356 if (kernel->n_block > 0)
357 for (i = 0; i < kernel->n_block; ++i) {
358 if (i)
359 p = isl_printer_print_str(p, ", ");
360 p = isl_printer_print_int(p, kernel->block_dim[i]);
362 else
363 p = isl_printer_print_str(p, "1");
365 return p;
368 /* Set the arguments of the OpenCL kernel by printing a call to the OpenCL
369 * clSetKernelArg() function for each kernel argument.
371 static __isl_give isl_printer *opencl_set_kernel_arguments(
372 __isl_take isl_printer *p, struct gpu_prog *prog,
373 struct ppcg_kernel *kernel)
375 int i, n, ro;
376 unsigned nparam;
377 isl_space *space;
378 int arg_index = 0;
380 for (i = 0; i < prog->n_array; ++i) {
381 isl_set *arr;
382 int empty;
384 space = isl_space_copy(prog->array[i].space);
385 arr = isl_union_set_extract_set(kernel->arrays, space);
386 empty = isl_set_plain_is_empty(arr);
387 isl_set_free(arr);
388 if (empty)
389 continue;
390 ro = gpu_array_is_read_only_scalar(&prog->array[i]);
391 opencl_set_kernel_argument(p, kernel->id, prog->array[i].name,
392 arg_index, ro);
393 arg_index++;
396 space = isl_union_set_get_space(kernel->arrays);
397 nparam = isl_space_dim(space, isl_dim_param);
398 for (i = 0; i < nparam; ++i) {
399 const char *name;
401 name = isl_space_get_dim_name(space, isl_dim_param, i);
402 opencl_set_kernel_argument(p, kernel->id, name, arg_index, 1);
403 arg_index++;
405 isl_space_free(space);
407 n = isl_space_dim(kernel->space, isl_dim_set);
408 for (i = 0; i < n; ++i) {
409 const char *name;
411 name = isl_space_get_dim_name(kernel->space, isl_dim_set, i);
412 opencl_set_kernel_argument(p, kernel->id, name, arg_index, 1);
413 arg_index++;
416 return p;
419 /* Print the arguments to a kernel declaration or call. If "types" is set,
420 * then print a declaration (including the types of the arguments).
422 * The arguments are printed in the following order
423 * - the arrays accessed by the kernel
424 * - the parameters
425 * - the host loop iterators
427 static __isl_give isl_printer *opencl_print_kernel_arguments(
428 __isl_take isl_printer *p, struct gpu_prog *prog,
429 struct ppcg_kernel *kernel, int types)
431 int i, n;
432 int first = 1;
433 unsigned nparam;
434 isl_space *space;
435 const char *type;
437 for (i = 0; i < prog->n_array; ++i) {
438 isl_set *arr;
439 int empty;
441 space = isl_space_copy(prog->array[i].space);
442 arr = isl_union_set_extract_set(kernel->arrays, space);
443 empty = isl_set_plain_is_empty(arr);
444 isl_set_free(arr);
445 if (empty)
446 continue;
448 if (!first)
449 p = isl_printer_print_str(p, ", ");
451 if (types)
452 p = gpu_array_info_print_declaration_argument(p,
453 &prog->array[i], "__global");
454 else
455 p = gpu_array_info_print_call_argument(p,
456 &prog->array[i]);
458 first = 0;
461 space = isl_union_set_get_space(kernel->arrays);
462 nparam = isl_space_dim(space, isl_dim_param);
463 for (i = 0; i < nparam; ++i) {
464 const char *name;
466 name = isl_space_get_dim_name(space, isl_dim_param, i);
468 if (!first)
469 p = isl_printer_print_str(p, ", ");
470 if (types)
471 p = isl_printer_print_str(p, "int ");
472 p = isl_printer_print_str(p, name);
474 first = 0;
476 isl_space_free(space);
478 n = isl_space_dim(kernel->space, isl_dim_set);
479 type = isl_options_get_ast_iterator_type(prog->ctx);
480 for (i = 0; i < n; ++i) {
481 const char *name;
483 if (!first)
484 p = isl_printer_print_str(p, ", ");
485 name = isl_space_get_dim_name(kernel->space, isl_dim_set, i);
486 if (types) {
487 p = isl_printer_print_str(p, type);
488 p = isl_printer_print_str(p, " ");
490 p = isl_printer_print_str(p, name);
492 first = 0;
495 return p;
498 /* Print the header of the given kernel.
500 static __isl_give isl_printer *opencl_print_kernel_header(
501 __isl_take isl_printer *p, struct gpu_prog *prog,
502 struct ppcg_kernel *kernel)
504 p = isl_printer_start_line(p);
505 p = isl_printer_print_str(p, "__kernel void kernel");
506 p = isl_printer_print_int(p, kernel->id);
507 p = isl_printer_print_str(p, "(");
508 p = opencl_print_kernel_arguments(p, prog, kernel, 1);
509 p = isl_printer_print_str(p, ")");
510 p = isl_printer_end_line(p);
512 return p;
515 /* Print a list of iterators of type "type" with names "ids" to "p".
516 * Each iterator is assigned the corresponding opencl identifier returned
517 * by the function "opencl_id".
518 * Unlike the equivalent function in the CUDA backend which prints iterators
519 * in reverse order to promote coalescing, this function does not print
520 * iterators in reverse order. The OpenCL backend currently does not take
521 * into account any coalescing considerations.
523 static __isl_give isl_printer *print_iterators(__isl_take isl_printer *p,
524 const char *type, __isl_keep isl_id_list *ids, const char *opencl_id)
526 int i, n;
528 n = isl_id_list_n_id(ids);
529 if (n <= 0)
530 return p;
531 p = isl_printer_start_line(p);
532 p = isl_printer_print_str(p, type);
533 p = isl_printer_print_str(p, " ");
534 for (i = 0; i < n; ++i) {
535 isl_id *id;
537 if (i)
538 p = isl_printer_print_str(p, ", ");
539 id = isl_id_list_get_id(ids, i);
540 p = isl_printer_print_id(p, id);
541 isl_id_free(id);
542 p = isl_printer_print_str(p, " = ");
543 p = isl_printer_print_str(p, opencl_id);
544 p = isl_printer_print_str(p, "(");
545 p = isl_printer_print_int(p, i);
546 p = isl_printer_print_str(p, ")");
548 p = isl_printer_print_str(p, ";");
549 p = isl_printer_end_line(p);
551 return p;
554 static __isl_give isl_printer *opencl_print_kernel_iterators(
555 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
557 isl_ctx *ctx = isl_ast_node_get_ctx(kernel->tree);
558 const char *type;
560 type = isl_options_get_ast_iterator_type(ctx);
562 p = print_iterators(p, type, kernel->block_ids, "get_group_id");
563 p = print_iterators(p, type, kernel->thread_ids, "get_local_id");
565 return p;
568 static __isl_give isl_printer *opencl_print_kernel_var(
569 __isl_take isl_printer *p, struct ppcg_kernel_var *var)
571 int j;
572 isl_val *v;
574 p = isl_printer_start_line(p);
575 if (var->type == ppcg_access_shared)
576 p = isl_printer_print_str(p, "__local ");
577 p = isl_printer_print_str(p, var->array->type);
578 p = isl_printer_print_str(p, " ");
579 p = isl_printer_print_str(p, var->name);
580 for (j = 0; j < var->array->n_index; ++j) {
581 p = isl_printer_print_str(p, "[");
582 v = isl_vec_get_element_val(var->size, j);
583 p = isl_printer_print_val(p, v);
584 p = isl_printer_print_str(p, "]");
585 isl_val_free(v);
587 p = isl_printer_print_str(p, ";");
588 p = isl_printer_end_line(p);
590 return p;
593 static __isl_give isl_printer *opencl_print_kernel_vars(
594 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
596 int i;
598 for (i = 0; i < kernel->n_var; ++i)
599 p = opencl_print_kernel_var(p, &kernel->var[i]);
601 return p;
604 /* Print a call to barrier() which is a sync statement.
605 * All work-items in a work-group executing the kernel on a processor must
606 * execute the barrier() function before any are allowed to continue execution
607 * beyond the barrier.
608 * The flag CLK_LOCAL_MEM_FENCE makes the barrier function either flush any
609 * variables stored in local memory or queue a memory fence to ensure correct
610 * ordering of memory operations to local memory.
611 * The flag CLK_GLOBAL_MEM_FENCE makes the barrier function queue a memory
612 * fence to ensure correct ordering of memory operations to global memory.
614 static __isl_give isl_printer *opencl_print_sync(__isl_take isl_printer *p,
615 struct ppcg_kernel_stmt *stmt)
617 p = isl_printer_start_line(p);
618 p = isl_printer_print_str(p,
619 "barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE);");
620 p = isl_printer_end_line(p);
622 return p;
625 /* Data structure containing function names for which the calls
626 * should be changed from
628 * name(arg)
630 * to
632 * opencl_name((type) (arg))
634 static struct ppcg_opencl_fn {
635 const char *name;
636 const char *opencl_name;
637 const char *type;
638 } opencl_fn[] = {
639 { "expf", "exp", "float" },
640 { "powf", "pow", "float" },
641 { "sqrtf", "sqrt", "float" },
644 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
646 /* If the name of function called by "expr" matches any of those
647 * in ppcg_opencl_fn, then replace the call by a cast to the corresponding
648 * type in ppcg_opencl_fn and a call to corresponding OpenCL function.
650 static __isl_give pet_expr *map_opencl_call(__isl_take pet_expr *expr,
651 void *user)
653 const char *name;
654 int i;
656 name = pet_expr_call_get_name(expr);
657 for (i = 0; i < ARRAY_SIZE(opencl_fn); ++i) {
658 pet_expr *arg;
660 if (strcmp(name, opencl_fn[i].name))
661 continue;
662 expr = pet_expr_call_set_name(expr, opencl_fn[i].opencl_name);
663 arg = pet_expr_get_arg(expr, 0);
664 arg = pet_expr_new_cast(opencl_fn[i].type, arg);
665 expr = pet_expr_set_arg(expr, 0, arg);
667 return expr;
670 /* Print the body of a statement from the input program,
671 * for use in OpenCL code.
673 * Before calling ppcg_kernel_print_domain to print the actual statement body,
674 * we first modify this body to take into account that the output code
675 * is OpenCL code. In particular, if the statement calls any function
676 * with a "f" suffix, then it needs to be replaced by a call to
677 * the corresponding function without suffix after casting the argument
678 * to a float.
680 static __isl_give isl_printer *print_opencl_kernel_domain(
681 __isl_take isl_printer *p, struct ppcg_kernel_stmt *stmt)
683 struct pet_stmt *ps;
684 pet_tree *tree;
686 ps = stmt->u.d.stmt->stmt;
687 tree = pet_tree_copy(ps->body);
688 ps->body = pet_tree_map_call_expr(ps->body, &map_opencl_call, NULL);
689 p = ppcg_kernel_print_domain(p, stmt);
690 pet_tree_free(ps->body);
691 ps->body = tree;
693 return p;
696 /* This function is called for each user statement in the AST,
697 * i.e., for each kernel body statement, copy statement or sync statement.
699 static __isl_give isl_printer *opencl_print_kernel_stmt(
700 __isl_take isl_printer *p,
701 __isl_take isl_ast_print_options *print_options,
702 __isl_keep isl_ast_node *node, void *user)
704 isl_id *id;
705 struct ppcg_kernel_stmt *stmt;
707 id = isl_ast_node_get_annotation(node);
708 stmt = isl_id_get_user(id);
709 isl_id_free(id);
711 isl_ast_print_options_free(print_options);
713 switch (stmt->type) {
714 case ppcg_kernel_copy:
715 return ppcg_kernel_print_copy(p, stmt);
716 case ppcg_kernel_sync:
717 return opencl_print_sync(p, stmt);
718 case ppcg_kernel_domain:
719 return print_opencl_kernel_domain(p, stmt);
722 return p;
725 /* Return true if there is a double array in prog->array or
726 * if any of the types in prog->scop involve any doubles.
727 * To check the latter condition, we simply search for the string "double"
728 * in the type definitions, which may result in false positives.
730 static __isl_give int any_double_elements(struct gpu_prog *prog)
732 int i;
734 for (i = 0; i < prog->n_array; ++i)
735 if (strcmp(prog->array[i].type, "double") == 0)
736 return 1;
738 for (i = 0; i < prog->scop->pet->n_type; ++i) {
739 struct pet_type *type = prog->scop->pet->types[i];
741 if (strstr(type->definition, "double"))
742 return 1;
745 return 0;
748 /* Prints a #pragma to enable support for double floating-point
749 * precision. OpenCL 1.0 adds support for double precision floating-point as
750 * an optional extension. An application that wants to use double will need to
751 * include the #pragma OPENCL EXTENSION cl_khr_fp64 : enable directive before
752 * any double precision data type is declared in the kernel code.
754 static __isl_give isl_printer *opencl_enable_double_support(
755 __isl_take isl_printer *p)
757 p = isl_printer_start_line(p);
758 p = isl_printer_print_str(p, "#pragma OPENCL EXTENSION cl_khr_fp64 :"
759 " enable");
760 p = isl_printer_end_line(p);
761 p = isl_printer_start_line(p);
762 p = isl_printer_end_line(p);
764 return p;
767 static __isl_give isl_printer *opencl_print_kernel(struct gpu_prog *prog,
768 struct ppcg_kernel *kernel, __isl_take isl_printer *p)
770 isl_ctx *ctx = isl_ast_node_get_ctx(kernel->tree);
771 isl_ast_print_options *print_options;
773 print_options = isl_ast_print_options_alloc(ctx);
774 print_options = isl_ast_print_options_set_print_user(print_options,
775 &opencl_print_kernel_stmt, NULL);
777 p = isl_printer_set_output_format(p, ISL_FORMAT_C);
778 p = opencl_print_kernel_header(p, prog, kernel);
779 p = isl_printer_print_str(p, "{");
780 p = isl_printer_end_line(p);
781 p = isl_printer_indent(p, 4);
782 p = opencl_print_kernel_iterators(p, kernel);
783 p = opencl_print_kernel_vars(p, kernel);
784 p = isl_printer_end_line(p);
785 p = gpu_print_macros(p, kernel->tree);
786 p = isl_ast_node_print(kernel->tree, p, print_options);
787 p = isl_printer_indent(p, -4);
788 p = isl_printer_start_line(p);
789 p = isl_printer_print_str(p, "}");
790 p = isl_printer_end_line(p);
792 return p;
795 struct print_host_user_data_opencl {
796 struct opencl_info *opencl;
797 struct gpu_prog *prog;
800 /* This function prints the i'th block size multiplied by the i'th grid size,
801 * where i (a parameter to this function) is one of the possible dimensions of
802 * grid sizes and block sizes.
803 * If the dimension of block sizes is not equal to the dimension of grid sizes
804 * the output is calculated as follows:
806 * Suppose that:
807 * block_sizes[dim1] is the list of blocks sizes and it contains dim1 elements.
808 * grid_sizes[dim2] is the list of grid sizes and it contains dim2 elements.
810 * The output is:
811 * If (i > dim2) then the output is block_sizes[i]
812 * If (i > dim1) then the output is grid_sizes[i]
814 static __isl_give isl_printer *opencl_print_total_number_of_work_items_for_dim(
815 __isl_take isl_printer *p, struct ppcg_kernel *kernel, int i)
817 int grid_dim, block_dim;
818 isl_pw_aff *bound_grid;
820 grid_dim = isl_multi_pw_aff_dim(kernel->grid_size, isl_dim_set);
821 block_dim = kernel->n_block;
823 if (i < min(grid_dim, block_dim)) {
824 bound_grid = isl_multi_pw_aff_get_pw_aff(kernel->grid_size, i);
825 p = isl_printer_print_str(p, "(");
826 p = isl_printer_print_pw_aff(p, bound_grid);
827 p = isl_printer_print_str(p, ") * ");
828 p = isl_printer_print_int(p, kernel->block_dim[i]);
829 isl_pw_aff_free(bound_grid);
830 } else if (i >= grid_dim)
831 p = isl_printer_print_int(p, kernel->block_dim[i]);
832 else {
833 bound_grid = isl_multi_pw_aff_get_pw_aff(kernel->grid_size, i);
834 p = isl_printer_print_pw_aff(p, bound_grid);
835 isl_pw_aff_free(bound_grid);
838 return p;
841 /* Print a list that represents the total number of work items. The list is
842 * constructed by performing an element-wise multiplication of the block sizes
843 * and the grid sizes. To explain how the list is constructed, suppose that:
844 * block_sizes[dim1] is the list of blocks sizes and it contains dim1 elements.
845 * grid_sizes[dim2] is the list of grid sizes and it contains dim2 elements.
847 * The output of this function is constructed as follows:
848 * If (dim1 > dim2) then the output is the following list:
849 * grid_sizes[0]*block_sizes[0], ..., grid_sizes[dim2-1]*block_sizes[dim2-1],
850 * block_sizes[dim2], ..., block_sizes[dim1-2], block_sizes[dim1-1].
852 * If (dim2 > dim1) then the output is the following list:
853 * grid_sizes[0]*block_sizes[0], ..., grid_sizes[dim1-1] * block_sizes[dim1-1],
854 * grid_sizes[dim1], grid_sizes[dim2-2], grid_sizes[dim2-1].
856 * To calculate the total number of work items out of the list constructed by
857 * this function, the user should multiply the elements of the list.
859 static __isl_give isl_printer *opencl_print_total_number_of_work_items_as_list(
860 __isl_take isl_printer *p, struct ppcg_kernel *kernel)
862 int i;
863 int grid_dim, block_dim;
865 grid_dim = isl_multi_pw_aff_dim(kernel->grid_size, isl_dim_set);
866 block_dim = kernel->n_block;
868 if ((grid_dim <= 0) || (block_dim <= 0)) {
869 p = isl_printer_print_str(p, "1");
870 return p;
873 for (i = 0; i <= max(grid_dim, block_dim) - 1; i++) {
874 if (i > 0)
875 p = isl_printer_print_str(p, ", ");
877 p = opencl_print_total_number_of_work_items_for_dim(p,
878 kernel, i);
881 return p;
884 /* Copy "array" from the host to the device (to_host = 0) or
885 * back from the device to the host (to_host = 1).
887 static __isl_give isl_printer *copy_array(__isl_take isl_printer *p,
888 struct gpu_array_info *array, int to_host)
890 p = isl_printer_start_line(p);
891 p = isl_printer_print_str(p, "openclCheckReturn(");
892 if (to_host)
893 p = isl_printer_print_str(p, "clEnqueueReadBuffer");
894 else
895 p = isl_printer_print_str(p, "clEnqueueWriteBuffer");
896 p = isl_printer_print_str(p, "(queue, dev_");
897 p = isl_printer_print_str(p, array->name);
898 p = isl_printer_print_str(p, ", CL_TRUE, 0, ");
899 p = gpu_array_info_print_size(p, array);
901 if (gpu_array_is_scalar(array))
902 p = isl_printer_print_str(p, ", &");
903 else
904 p = isl_printer_print_str(p, ", ");
905 p = isl_printer_print_str(p, array->name);
906 p = isl_printer_print_str(p, ", 0, NULL, NULL));");
907 p = isl_printer_end_line(p);
909 return p;
912 /* Copy "array" from the host to the device.
914 static __isl_give isl_printer *copy_array_to_device(__isl_take isl_printer *p,
915 void *user)
917 struct gpu_array_info *array = user;
919 return copy_array(p, array, 0);
922 /* Copy "array" back from the device to the host.
924 static __isl_give isl_printer *copy_array_from_device(__isl_take isl_printer *p,
925 void *user)
927 struct gpu_array_info *array = user;
929 return copy_array(p, array, 1);
932 /* Copy the "copy" arrays from the host to the device (to_host = 0) or
933 * back from the device to the host (to_host = 1).
935 * Only perform the copying for arrays with strictly positive size.
937 static __isl_give isl_printer *opencl_copy_arrays(__isl_take isl_printer *p,
938 struct gpu_prog *prog, __isl_keep isl_union_set *copy, int to_host)
940 int i;
942 for (i = 0; i < prog->n_array; ++i) {
943 struct gpu_array_info *array = &prog->array[i];
944 isl_space *space;
945 isl_set *copy_i;
946 isl_set *guard;
947 int empty;
949 if (gpu_array_is_read_only_scalar(array))
950 continue;
952 space = isl_space_copy(array->space);
953 copy_i = isl_union_set_extract_set(copy, space);
954 empty = isl_set_plain_is_empty(copy_i);
955 isl_set_free(copy_i);
956 if (empty)
957 continue;
959 guard = gpu_array_positive_size_guard(array);
960 p = ppcg_print_guarded(p, guard, isl_set_copy(prog->context),
961 to_host ? &copy_array_from_device :
962 &copy_array_to_device, array);
965 p = isl_printer_start_line(p);
966 p = isl_printer_end_line(p);
967 return p;
970 /* Copy the prog->copy_in arrays from the host to the device.
972 static __isl_give isl_printer *opencl_copy_arrays_to_device(
973 __isl_take isl_printer *p, struct gpu_prog *prog)
975 return opencl_copy_arrays(p, prog, prog->copy_in, 0);
978 /* Copy the prog->copy_out arrays back from the device to the host.
980 static __isl_give isl_printer *opencl_copy_arrays_from_device(
981 __isl_take isl_printer *p, struct gpu_prog *prog)
983 return opencl_copy_arrays(p, prog, prog->copy_out, 1);
986 /* Print the user statement of the host code to "p".
988 * In particular, print a block of statements that defines the grid
989 * and the work group and then launches the kernel.
991 * A grid is composed of many work groups (blocks), each work group holds
992 * many work-items (threads).
994 * global_work_size[kernel->n_block] represents the total number of work
995 * items. It points to an array of kernel->n_block unsigned
996 * values that describe the total number of work-items that will execute
997 * the kernel. The total number of work-items is computed as:
998 * global_work_size[0] *...* global_work_size[kernel->n_block - 1].
1000 * The size of each work group (i.e. the number of work-items in each work
1001 * group) is described using block_size[kernel->n_block]. The total
1002 * number of work-items in a block (work-group) is computed as:
1003 * block_size[0] *... * block_size[kernel->n_block - 1].
1005 * For more information check:
1006 * http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/clEnqueueNDRangeKernel.html
1008 static __isl_give isl_printer *opencl_print_host_user(
1009 __isl_take isl_printer *p,
1010 __isl_take isl_ast_print_options *print_options,
1011 __isl_keep isl_ast_node *node, void *user)
1013 isl_id *id;
1014 struct ppcg_kernel *kernel;
1015 struct print_host_user_data_opencl *data;
1017 id = isl_ast_node_get_annotation(node);
1018 kernel = isl_id_get_user(id);
1019 isl_id_free(id);
1021 data = (struct print_host_user_data_opencl *) user;
1023 p = isl_printer_start_line(p);
1024 p = isl_printer_print_str(p, "{");
1025 p = isl_printer_end_line(p);
1026 p = isl_printer_indent(p, 2);
1028 p = isl_printer_start_line(p);
1029 p = isl_printer_print_str(p, "size_t global_work_size[");
1031 if (kernel->n_block > 0)
1032 p = isl_printer_print_int(p, kernel->n_block);
1033 else
1034 p = isl_printer_print_int(p, 1);
1036 p = isl_printer_print_str(p, "] = {");
1037 p = opencl_print_total_number_of_work_items_as_list(p, kernel);
1038 p = isl_printer_print_str(p, "};");
1039 p = isl_printer_end_line(p);
1041 p = isl_printer_start_line(p);
1042 p = isl_printer_print_str(p, "size_t block_size[");
1044 if (kernel->n_block > 0)
1045 p = isl_printer_print_int(p, kernel->n_block);
1046 else
1047 p = isl_printer_print_int(p, 1);
1049 p = isl_printer_print_str(p, "] = {");
1050 p = opencl_print_block_sizes(p, kernel);
1051 p = isl_printer_print_str(p, "};");
1052 p = isl_printer_end_line(p);
1054 p = isl_printer_start_line(p);
1055 p = isl_printer_print_str(p, "cl_kernel kernel");
1056 p = isl_printer_print_int(p, kernel->id);
1057 p = isl_printer_print_str(p, " = clCreateKernel(program, \"kernel");
1058 p = isl_printer_print_int(p, kernel->id);
1059 p = isl_printer_print_str(p, "\", &err);");
1060 p = isl_printer_end_line(p);
1061 p = isl_printer_start_line(p);
1062 p = isl_printer_print_str(p, "openclCheckReturn(err);");
1063 p = isl_printer_end_line(p);
1065 opencl_set_kernel_arguments(p, data->prog, kernel);
1067 p = isl_printer_start_line(p);
1068 p = isl_printer_print_str(p, "openclCheckReturn(clEnqueueNDRangeKernel"
1069 "(queue, kernel");
1070 p = isl_printer_print_int(p, kernel->id);
1071 p = isl_printer_print_str(p, ", ");
1072 if (kernel->n_block > 0)
1073 p = isl_printer_print_int(p, kernel->n_block);
1074 else
1075 p = isl_printer_print_int(p, 1);
1077 p = isl_printer_print_str(p, ", NULL, global_work_size, "
1078 "block_size, "
1079 "0, NULL, NULL));");
1080 p = isl_printer_end_line(p);
1081 p = isl_printer_start_line(p);
1082 p = isl_printer_print_str(p, "openclCheckReturn("
1083 "clReleaseKernel(kernel");
1084 p = isl_printer_print_int(p, kernel->id);
1085 p = isl_printer_print_str(p, "));");
1086 p = isl_printer_end_line(p);
1087 p = isl_printer_start_line(p);
1088 p = isl_printer_print_str(p, "clFinish(queue);");
1089 p = isl_printer_end_line(p);
1090 p = isl_printer_indent(p, -2);
1091 p = isl_printer_start_line(p);
1092 p = isl_printer_print_str(p, "}");
1093 p = isl_printer_end_line(p);
1095 p = isl_printer_start_line(p);
1096 p = isl_printer_end_line(p);
1098 data->opencl->kprinter = opencl_print_kernel(data->prog, kernel,
1099 data->opencl->kprinter);
1101 isl_ast_print_options_free(print_options);
1103 return p;
1106 static __isl_give isl_printer *opencl_print_host_code(
1107 __isl_take isl_printer *p, struct gpu_prog *prog,
1108 __isl_keep isl_ast_node *tree, struct opencl_info *opencl)
1110 isl_ast_print_options *print_options;
1111 isl_ctx *ctx = isl_ast_node_get_ctx(tree);
1112 struct print_host_user_data_opencl data = { opencl, prog };
1114 print_options = isl_ast_print_options_alloc(ctx);
1115 print_options = isl_ast_print_options_set_print_user(print_options,
1116 &opencl_print_host_user, &data);
1118 p = gpu_print_macros(p, tree);
1119 p = isl_ast_node_print(tree, p, print_options);
1121 return p;
1124 /* Create an OpenCL device, context, command queue and build the kernel.
1125 * input is the name of the input file provided to ppcg.
1127 static __isl_give isl_printer *opencl_setup(__isl_take isl_printer *p,
1128 const char *input, struct opencl_info *info)
1130 p = isl_printer_start_line(p);
1131 p = isl_printer_print_str(p, "cl_device_id device;");
1132 p = isl_printer_end_line(p);
1133 p = isl_printer_start_line(p);
1134 p = isl_printer_print_str(p, "cl_context context;");
1135 p = isl_printer_end_line(p);
1136 p = isl_printer_start_line(p);
1137 p = isl_printer_print_str(p, "cl_program program;");
1138 p = isl_printer_end_line(p);
1139 p = isl_printer_start_line(p);
1140 p = isl_printer_print_str(p, "cl_command_queue queue;");
1141 p = isl_printer_end_line(p);
1142 p = isl_printer_start_line(p);
1143 p = isl_printer_print_str(p, "cl_int err;");
1144 p = isl_printer_end_line(p);
1145 p = isl_printer_start_line(p);
1146 p = isl_printer_print_str(p, "device = opencl_create_device(");
1147 p = isl_printer_print_int(p, info->options->opencl_use_gpu);
1148 p = isl_printer_print_str(p, ");");
1149 p = isl_printer_end_line(p);
1150 p = isl_printer_start_line(p);
1151 p = isl_printer_print_str(p, "context = clCreateContext(NULL, 1, "
1152 "&device, NULL, NULL, &err);");
1153 p = isl_printer_end_line(p);
1154 p = isl_printer_start_line(p);
1155 p = isl_printer_print_str(p, "openclCheckReturn(err);");
1156 p = isl_printer_end_line(p);
1157 p = isl_printer_start_line(p);
1158 p = isl_printer_print_str(p, "queue = clCreateCommandQueue"
1159 "(context, device, 0, &err);");
1160 p = isl_printer_end_line(p);
1161 p = isl_printer_start_line(p);
1162 p = isl_printer_print_str(p, "openclCheckReturn(err);");
1163 p = isl_printer_end_line(p);
1165 p = isl_printer_start_line(p);
1166 p = isl_printer_print_str(p, "program = ");
1168 if (info->options->opencl_embed_kernel_code) {
1169 p = isl_printer_print_str(p, "opencl_build_program_from_string("
1170 "context, device, kernel_code, "
1171 "sizeof(kernel_code), \"");
1172 } else {
1173 p = isl_printer_print_str(p, "opencl_build_program_from_file("
1174 "context, device, \"");
1175 p = isl_printer_print_str(p, info->kernel_c_name);
1176 p = isl_printer_print_str(p, "\", \"");
1179 if (info->options->opencl_compiler_options)
1180 p = isl_printer_print_str(p,
1181 info->options->opencl_compiler_options);
1183 p = isl_printer_print_str(p, "\");");
1184 p = isl_printer_end_line(p);
1185 p = isl_printer_start_line(p);
1186 p = isl_printer_end_line(p);
1188 return p;
1191 static __isl_give isl_printer *opencl_release_cl_objects(
1192 __isl_take isl_printer *p, struct opencl_info *info)
1194 p = isl_printer_start_line(p);
1195 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseCommandQueue"
1196 "(queue));");
1197 p = isl_printer_end_line(p);
1198 p = isl_printer_start_line(p);
1199 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseProgram"
1200 "(program));");
1201 p = isl_printer_end_line(p);
1202 p = isl_printer_start_line(p);
1203 p = isl_printer_print_str(p, "openclCheckReturn(clReleaseContext"
1204 "(context));");
1205 p = isl_printer_end_line(p);
1207 return p;
1210 /* Free the device array corresponding to "array"
1212 static __isl_give isl_printer *release_device_array(__isl_take isl_printer *p,
1213 struct gpu_array_info *array)
1215 p = isl_printer_start_line(p);
1216 p = isl_printer_print_str(p, "openclCheckReturn("
1217 "clReleaseMemObject(dev_");
1218 p = isl_printer_print_str(p, array->name);
1219 p = isl_printer_print_str(p, "));");
1220 p = isl_printer_end_line(p);
1222 return p;
1225 /* Free the device arrays.
1227 static __isl_give isl_printer *opencl_release_device_arrays(
1228 __isl_take isl_printer *p, struct gpu_prog *prog)
1230 int i;
1232 for (i = 0; i < prog->n_array; ++i) {
1233 struct gpu_array_info *array = &prog->array[i];
1234 if (gpu_array_is_read_only_scalar(array))
1235 continue;
1237 p = release_device_array(p, array);
1239 return p;
1242 /* Given a gpu_prog "prog" and the corresponding transformed AST
1243 * "tree", print the entire OpenCL code to "p".
1245 static __isl_give isl_printer *print_opencl(__isl_take isl_printer *p,
1246 struct gpu_prog *prog, __isl_keep isl_ast_node *tree,
1247 struct gpu_types *types, void *user)
1249 struct opencl_info *opencl = user;
1251 opencl->kprinter = isl_printer_set_output_format(opencl->kprinter,
1252 ISL_FORMAT_C);
1253 if (any_double_elements(prog))
1254 opencl->kprinter = opencl_enable_double_support(
1255 opencl->kprinter);
1256 if (opencl->options->opencl_print_kernel_types)
1257 opencl->kprinter = gpu_print_types(opencl->kprinter, types,
1258 prog);
1260 if (!opencl->kprinter)
1261 return isl_printer_free(p);
1263 p = ppcg_start_block(p);
1265 p = opencl_print_host_macros(p);
1267 p = opencl_declare_device_arrays(p, prog);
1268 p = opencl_setup(p, opencl->input, opencl);
1269 p = opencl_allocate_device_arrays(p, prog);
1270 p = opencl_copy_arrays_to_device(p, prog);
1272 p = opencl_print_host_code(p, prog, tree, opencl);
1274 p = opencl_copy_arrays_from_device(p, prog);
1275 p = opencl_release_device_arrays(p, prog);
1276 p = opencl_release_cl_objects(p, opencl);
1278 p = ppcg_end_block(p);
1280 return p;
1283 /* Transform the code in the file called "input" by replacing
1284 * all scops by corresponding OpenCL code.
1285 * The host code is written to "output" or a name derived from
1286 * "input" if "output" is NULL.
1287 * The kernel code is placed in separate files with names
1288 * derived from "output" or "input".
1290 * We let generate_gpu do all the hard work and then let it call
1291 * us back for printing the AST in print_opencl.
1293 * To prepare for this printing, we first open the output files
1294 * and we close them after generate_gpu has finished.
1296 int generate_opencl(isl_ctx *ctx, struct ppcg_options *options,
1297 const char *input, const char *output)
1299 struct opencl_info opencl = { options, input, output };
1300 int r;
1302 opencl.kprinter = isl_printer_to_str(ctx);
1303 r = opencl_open_files(&opencl);
1305 if (r >= 0)
1306 r = generate_gpu(ctx, input, opencl.host_c, options,
1307 &print_opencl, &opencl);
1309 if (opencl_close_files(&opencl) < 0)
1310 r = -1;
1311 isl_printer_free(opencl.kprinter);
1313 return r;