rtl: ICE with thread_local and inline asm [PR104777]
[official-gcc.git] / gcc / omp-oacc-kernels-decompose.cc
blobecbd3071e5dfbb19c3f1ae71f6a5f28324d7c188
1 /* Decompose OpenACC 'kernels' constructs into parts, a sequence of compute
2 constructs
4 Copyright (C) 2020-2022 Free Software Foundation, Inc.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "target.h"
27 #include "tree.h"
28 #include "langhooks.h"
29 #include "gimple.h"
30 #include "tree-pass.h"
31 #include "cgraph.h"
32 #include "fold-const.h"
33 #include "gimplify.h"
34 #include "gimple-iterator.h"
35 #include "gimple-walk.h"
36 #include "gomp-constants.h"
37 #include "omp-general.h"
38 #include "diagnostic-core.h"
41 /* This preprocessing pass is run immediately before lower_omp. It decomposes
42 OpenACC 'kernels' constructs into parts, a sequence of compute constructs.
44 The translation is as follows:
45 - The entire 'kernels' region is turned into a 'data' region with clauses
46 taken from the 'kernels' region. New 'create' clauses are added for all
47 variables declared at the top level in the kernels region.
48 - Any loop nests annotated with an OpenACC 'loop' directive are wrapped in
49 a new compute construct.
50 - 'loop' directives without an explicit 'independent' or 'seq' clause
51 get an 'auto' clause added; other clauses are preserved on the loop
52 or moved to the new surrounding compute construct, as applicable.
53 - Any sequences of other code (non-loops, non-OpenACC 'loop's) are wrapped
54 in new "gang-single" compute construct: 'worker'/'vector' parallelism is
55 preserved, but 'num_gangs (1)' is enforced.
56 - Both points above only apply at the topmost level in the region, that
57 is, the transformation does not introduce new compute constructs inside
58 nested statement bodies. In particular, this means that a
59 gang-parallelizable loop inside an 'if' statement is made "gang-single".
60 - In order to make the host wait only once for the whole region instead
61 of once per device kernel launch, the new compute constructs are
62 annotated 'async'. Unless the original 'kernels' construct already was
63 marked 'async', the entire region ends with a 'wait' directive. If the
64 original 'kernels' construct was marked 'async', the synthesized 'async'
65 clauses use the original 'kernels' construct's 'async' argument
66 (possibly implicit).
70 /*TODO Things are conceptually wrong here: 'loop' clauses may be hidden behind
71 'device_type', so we have to defer a lot of processing until we're in the
72 offloading compilation. "Fortunately", GCC doesn't support the OpenACC
73 'device_type' clause yet, so we get away that. */
76 /* Helper function for decompose_kernels_region_body. If STMT contains a
77 "top-level" OMP_FOR statement, returns a pointer to that statement;
78 returns NULL otherwise.
80 A "top-level" OMP_FOR statement is one that is possibly accompanied by
81 small snippets of setup code. Specifically, this function accepts an
82 OMP_FOR possibly wrapped in a singleton bind and a singleton try
83 statement to allow for a local loop variable, but not an OMP_FOR
84 statement nested in any other constructs. Alternatively, it accepts a
85 non-singleton bind containing only assignments and then an OMP_FOR
86 statement at the very end. The former style can be generated by the C
87 frontend, the latter by the Fortran frontend. */
89 static gimple *
90 top_level_omp_for_in_stmt (gimple *stmt)
92 if (gimple_code (stmt) == GIMPLE_OMP_FOR)
93 return stmt;
95 if (gimple_code (stmt) == GIMPLE_BIND)
97 gimple_seq body = gimple_bind_body (as_a <gbind *> (stmt));
98 if (gimple_seq_singleton_p (body))
100 /* Accept an OMP_FOR statement, or a try statement containing only
101 a single OMP_FOR. */
102 gimple *maybe_for_or_try = gimple_seq_first_stmt (body);
103 if (gimple_code (maybe_for_or_try) == GIMPLE_OMP_FOR)
104 return maybe_for_or_try;
105 else if (gimple_code (maybe_for_or_try) == GIMPLE_TRY)
107 gimple_seq try_body = gimple_try_eval (maybe_for_or_try);
108 if (!gimple_seq_singleton_p (try_body))
109 return NULL;
110 gimple *maybe_omp_for_stmt = gimple_seq_first_stmt (try_body);
111 if (gimple_code (maybe_omp_for_stmt) == GIMPLE_OMP_FOR)
112 return maybe_omp_for_stmt;
115 else
117 gimple_stmt_iterator gsi;
118 /* Accept only a block of optional assignments followed by an
119 OMP_FOR at the end. No other kinds of statements allowed. */
120 for (gsi = gsi_start (body); !gsi_end_p (gsi); gsi_next (&gsi))
122 gimple *body_stmt = gsi_stmt (gsi);
123 if (gimple_code (body_stmt) == GIMPLE_ASSIGN)
124 continue;
125 else if (gimple_code (body_stmt) == GIMPLE_OMP_FOR
126 && gsi_one_before_end_p (gsi))
127 return body_stmt;
128 else
129 return NULL;
134 return NULL;
137 /* Helper for adjust_region_code: evaluate the statement at GSI_P. */
139 static tree
140 adjust_region_code_walk_stmt_fn (gimple_stmt_iterator *gsi_p,
141 bool *handled_ops_p,
142 struct walk_stmt_info *wi)
144 int *region_code = (int *) wi->info;
146 gimple *stmt = gsi_stmt (*gsi_p);
147 switch (gimple_code (stmt))
149 case GIMPLE_OMP_FOR:
151 tree clauses = gimple_omp_for_clauses (stmt);
152 if (omp_find_clause (clauses, OMP_CLAUSE_INDEPENDENT))
154 /* Explicit 'independent' clause. */
155 /* Keep going; recurse into loop body. */
156 break;
158 else if (omp_find_clause (clauses, OMP_CLAUSE_SEQ))
160 /* Explicit 'seq' clause. */
161 /* We'll "parallelize" if at some level a loop construct has been
162 marked up by the user as unparallelizable ('seq' clause; we'll
163 respect that in the later processing). Given that the user has
164 explicitly marked it up, this loop construct cannot be
165 performance-critical, and in this case it's also fine to
166 "parallelize" instead of "gang-single", because any outer or
167 inner loops may still exploit the available parallelism. */
168 /* Keep going; recurse into loop body. */
169 break;
171 else
173 /* Explicit or implicit 'auto' clause. */
174 /* The user would like this loop analyzed ('auto' clause) and
175 typically parallelized, but we don't have available yet the
176 compiler logic to analyze this, so can't parallelize it here, so
177 we'd very likely be running into a performance problem if we
178 were to execute this unparallelized, thus forward the whole loop
179 nest to 'parloops'. */
180 *region_code = GF_OMP_TARGET_KIND_OACC_KERNELS;
181 /* Terminate: final decision for this region. */
182 *handled_ops_p = true;
183 return integer_zero_node;
185 gcc_unreachable ();
188 case GIMPLE_COND:
189 case GIMPLE_GOTO:
190 case GIMPLE_SWITCH:
191 case GIMPLE_ASM:
192 case GIMPLE_TRANSACTION:
193 case GIMPLE_RETURN:
194 /* Statement that might constitute some looping/control flow pattern. */
195 /* The user would like this code analyzed (implicit inside a 'kernels'
196 region) and typically parallelized, but we don't have available yet
197 the compiler logic to analyze this, so can't parallelize it here, so
198 we'd very likely be running into a performance problem if we were to
199 execute this unparallelized, thus forward the whole thing to
200 'parloops'. */
201 *region_code = GF_OMP_TARGET_KIND_OACC_KERNELS;
202 /* Terminate: final decision for this region. */
203 *handled_ops_p = true;
204 return integer_zero_node;
206 default:
207 /* Keep going. */
208 break;
211 return NULL;
214 /* Adjust the REGION_CODE for the region in GS. */
216 static void
217 adjust_region_code (gimple_seq gs, int *region_code)
219 struct walk_stmt_info wi;
220 memset (&wi, 0, sizeof (wi));
221 wi.info = region_code;
222 walk_gimple_seq (gs, adjust_region_code_walk_stmt_fn, NULL, &wi);
225 /* Helper function for make_loops_gang_single for walking the tree. If the
226 statement indicated by GSI_P is an OpenACC for loop with a gang clause,
227 issue a warning and remove the clause. */
229 static tree
230 visit_loops_in_gang_single_region (gimple_stmt_iterator *gsi_p,
231 bool *handled_ops_p,
232 struct walk_stmt_info *)
234 *handled_ops_p = false;
236 gimple *stmt = gsi_stmt (*gsi_p);
237 switch (gimple_code (stmt))
239 case GIMPLE_OMP_FOR:
240 /*TODO Given the current 'adjust_region_code' algorithm, this is
241 actually... */
242 gcc_unreachable ();
245 tree clauses = gimple_omp_for_clauses (stmt);
246 tree prev_clause = NULL;
247 for (tree clause = clauses; clause; clause = OMP_CLAUSE_CHAIN (clause))
249 if (OMP_CLAUSE_CODE (clause) == OMP_CLAUSE_GANG)
251 /* It makes no sense to have a 'gang' clause in a "gang-single"
252 region, so warn and remove it. */
253 warning_at (gimple_location (stmt), 0,
254 "conditionally executed loop in %<kernels%> region"
255 " will be executed by a single gang;"
256 " ignoring %<gang%> clause");
257 if (prev_clause != NULL)
258 OMP_CLAUSE_CHAIN (prev_clause) = OMP_CLAUSE_CHAIN (clause);
259 else
260 clauses = OMP_CLAUSE_CHAIN (clause);
262 break;
264 prev_clause = clause;
266 gimple_omp_for_set_clauses (stmt, clauses);
268 /* No need to recurse into nested statements; no loop nested inside
269 this loop can be gang-partitioned. */
270 sorry ("%<gang%> loop in %<gang-single%> region");
271 *handled_ops_p = true;
272 break;
274 default:
275 break;
278 return NULL;
281 /* Visit all nested OpenACC loops in the sequence indicated by GS. This
282 statement is expected to be inside a gang-single region. Issue a warning
283 for any loops inside it that have gang clauses and remove the clauses. */
285 static void
286 make_loops_gang_single (gimple_seq gs)
288 struct walk_stmt_info wi;
289 memset (&wi, 0, sizeof (wi));
290 walk_gimple_seq (gs, visit_loops_in_gang_single_region, NULL, &wi);
293 /* Construct a "gang-single" compute construct at LOC containing the STMTS.
294 Annotate with CLAUSES, which must not contain a 'num_gangs' clause, and an
295 additional 'num_gangs (1)' clause to force "gang-single" execution. */
297 static gimple *
298 make_region_seq (location_t loc, gimple_seq stmts,
299 tree num_gangs_clause,
300 tree num_workers_clause,
301 tree vector_length_clause,
302 tree clauses)
304 /* This correctly unshares the entire clause chain rooted here. */
305 clauses = unshare_expr (clauses);
307 dump_user_location_t loc_stmts_first = gimple_seq_first (stmts);
309 /* Figure out the region code for this region. */
310 /* Optimistic default: assume "setup code", no looping; thus not
311 performance-critical. */
312 int region_code = GF_OMP_TARGET_KIND_OACC_PARALLEL_KERNELS_GANG_SINGLE;
313 adjust_region_code (stmts, &region_code);
315 if (region_code == GF_OMP_TARGET_KIND_OACC_PARALLEL_KERNELS_GANG_SINGLE)
317 if (dump_enabled_p ())
318 /*TODO MSG_MISSED_OPTIMIZATION? */
319 dump_printf_loc (MSG_NOTE, loc_stmts_first,
320 "beginning %<gang-single%> part"
321 " in OpenACC %<kernels%> region\n");
323 /* Synthesize a 'num_gangs (1)' clause. */
324 tree gang_single_clause = build_omp_clause (loc, OMP_CLAUSE_NUM_GANGS);
325 OMP_CLAUSE_OPERAND (gang_single_clause, 0) = integer_one_node;
326 OMP_CLAUSE_CHAIN (gang_single_clause) = clauses;
327 clauses = gang_single_clause;
329 /* Remove and issue warnings about gang clauses on any OpenACC
330 loops nested inside this sequentially executed statement. */
331 make_loops_gang_single (stmts);
333 else if (region_code == GF_OMP_TARGET_KIND_OACC_KERNELS)
335 if (dump_enabled_p ())
336 dump_printf_loc (MSG_NOTE, loc_stmts_first,
337 "beginning %<parloops%> part"
338 " in OpenACC %<kernels%> region\n");
340 /* As we're transforming a 'GF_OMP_TARGET_KIND_OACC_KERNELS' into another
341 'GF_OMP_TARGET_KIND_OACC_KERNELS', this isn't doing any of the clauses
342 mangling that 'make_region_loop_nest' is doing. */
343 /* Re-assemble the clauses stripped off earlier. */
344 if (num_gangs_clause != NULL)
346 tree c = unshare_expr (num_gangs_clause);
347 OMP_CLAUSE_CHAIN (c) = clauses;
348 clauses = c;
350 if (num_workers_clause != NULL)
352 tree c = unshare_expr (num_workers_clause);
353 OMP_CLAUSE_CHAIN (c) = clauses;
354 clauses = c;
356 if (vector_length_clause != NULL)
358 tree c = unshare_expr (vector_length_clause);
359 OMP_CLAUSE_CHAIN (c) = clauses;
360 clauses = c;
363 else
364 gcc_unreachable ();
366 /* Build the gang-single region. */
367 gimple *single_region = gimple_build_omp_target (NULL, region_code, clauses);
368 gimple_set_location (single_region, loc);
369 gbind *single_body = gimple_build_bind (NULL, stmts, make_node (BLOCK));
370 gimple_omp_set_body (single_region, single_body);
372 return single_region;
375 /* Helper function for make_region_loop_nest. Adds a 'num_gangs'
376 ('num_workers', 'vector_length') clause to the given CLAUSES, either the one
377 from the parent compute construct (PARENT_CLAUSE) or a new one based on the
378 loop's own LOOP_CLAUSE ('gang (num: N)' or similar for 'worker' or 'vector'
379 clauses) with the given CLAUSE_CODE. Does nothing if neither PARENT_CLAUSE
380 nor LOOP_CLAUSE exist. Returns the new clauses. */
382 static tree
383 add_parent_or_loop_num_clause (tree parent_clause, tree loop_clause,
384 omp_clause_code clause_code, tree clauses)
386 if (parent_clause != NULL)
388 tree num_clause = unshare_expr (parent_clause);
389 OMP_CLAUSE_CHAIN (num_clause) = clauses;
390 clauses = num_clause;
392 else if (loop_clause != NULL)
394 /* The kernels region does not have a 'num_gangs' clause, but the loop
395 itself had a 'gang (num: N)' clause. Honor it by adding a
396 'num_gangs (N)' clause on the compute construct. */
397 tree num = OMP_CLAUSE_OPERAND (loop_clause, 0);
398 tree new_num_clause
399 = build_omp_clause (OMP_CLAUSE_LOCATION (loop_clause), clause_code);
400 OMP_CLAUSE_OPERAND (new_num_clause, 0) = num;
401 OMP_CLAUSE_CHAIN (new_num_clause) = clauses;
402 clauses = new_num_clause;
404 return clauses;
407 /* Helper for make_region_loop_nest, looking for 'worker (num: N)' or 'vector
408 (length: N)' clauses in nested loops. Removes the argument, transferring it
409 to the enclosing compute construct (via WI->INFO). If arguments within the
410 same loop nest conflict, emits a warning.
412 This function also decides whether to add an 'auto' clause on each of these
413 nested loops. */
415 struct adjust_nested_loop_clauses_wi_info
417 tree *loop_gang_clause_ptr;
418 tree *loop_worker_clause_ptr;
419 tree *loop_vector_clause_ptr;
422 static tree
423 adjust_nested_loop_clauses (gimple_stmt_iterator *gsi_p, bool *,
424 struct walk_stmt_info *wi)
426 struct adjust_nested_loop_clauses_wi_info *wi_info
427 = (struct adjust_nested_loop_clauses_wi_info *) wi->info;
428 gimple *stmt = gsi_stmt (*gsi_p);
430 if (gimple_code (stmt) == GIMPLE_OMP_FOR)
432 bool add_auto_clause = true;
433 tree loop_clauses = gimple_omp_for_clauses (stmt);
434 tree loop_clause = loop_clauses;
435 for (; loop_clause; loop_clause = OMP_CLAUSE_CHAIN (loop_clause))
437 tree *outer_clause_ptr = NULL;
438 switch (OMP_CLAUSE_CODE (loop_clause))
440 case OMP_CLAUSE_GANG:
441 outer_clause_ptr = wi_info->loop_gang_clause_ptr;
442 break;
443 case OMP_CLAUSE_WORKER:
444 outer_clause_ptr = wi_info->loop_worker_clause_ptr;
445 break;
446 case OMP_CLAUSE_VECTOR:
447 outer_clause_ptr = wi_info->loop_vector_clause_ptr;
448 break;
449 case OMP_CLAUSE_SEQ:
450 case OMP_CLAUSE_INDEPENDENT:
451 case OMP_CLAUSE_AUTO:
452 add_auto_clause = false;
453 default:
454 break;
456 if (outer_clause_ptr != NULL)
458 if (OMP_CLAUSE_OPERAND (loop_clause, 0) != NULL
459 && *outer_clause_ptr == NULL)
461 /* Transfer the clause to the enclosing compute construct and
462 remove the numerical argument from the 'loop'. */
463 *outer_clause_ptr = unshare_expr (loop_clause);
464 OMP_CLAUSE_OPERAND (loop_clause, 0) = NULL;
466 else if (OMP_CLAUSE_OPERAND (loop_clause, 0) != NULL &&
467 OMP_CLAUSE_OPERAND (*outer_clause_ptr, 0) != NULL)
469 /* See if both of these are the same constant. If they
470 aren't, emit a warning. */
471 tree old_op = OMP_CLAUSE_OPERAND (*outer_clause_ptr, 0);
472 tree new_op = OMP_CLAUSE_OPERAND (loop_clause, 0);
473 if (!(cst_and_fits_in_hwi (old_op) &&
474 cst_and_fits_in_hwi (new_op) &&
475 int_cst_value (old_op) == int_cst_value (new_op)))
477 const char *clause_name
478 = omp_clause_code_name[OMP_CLAUSE_CODE (loop_clause)];
479 error_at (gimple_location (stmt),
480 "cannot honor conflicting %qs clause",
481 clause_name);
482 inform (OMP_CLAUSE_LOCATION (*outer_clause_ptr),
483 "location of the previous clause"
484 " in the same loop nest");
486 OMP_CLAUSE_OPERAND (loop_clause, 0) = NULL;
490 if (add_auto_clause)
492 tree auto_clause
493 = build_omp_clause (gimple_location (stmt), OMP_CLAUSE_AUTO);
494 OMP_CLAUSE_CHAIN (auto_clause) = loop_clauses;
495 gimple_omp_for_set_clauses (stmt, auto_clause);
499 return NULL;
502 /* Helper for make_region_loop_nest. Transform OpenACC 'kernels'/'loop'
503 construct clauses into OpenACC 'parallel'/'loop' construct ones. */
505 static tree
506 transform_kernels_loop_clauses (gimple *omp_for,
507 tree num_gangs_clause,
508 tree num_workers_clause,
509 tree vector_length_clause,
510 tree clauses)
512 /* If this loop in a kernels region does not have an explicit 'seq',
513 'independent', or 'auto' clause, we must give it an explicit 'auto'
514 clause.
515 We also check for 'gang (num: N)' clauses. These must not appear in
516 kernels regions that have their own 'num_gangs' clause. Otherwise, they
517 must be converted and put on the region; similarly for 'worker' and
518 'vector' clauses. */
519 bool add_auto_clause = true;
520 tree loop_gang_clause = NULL, loop_worker_clause = NULL,
521 loop_vector_clause = NULL;
522 tree loop_clauses = gimple_omp_for_clauses (omp_for);
523 for (tree loop_clause = loop_clauses;
524 loop_clause;
525 loop_clause = OMP_CLAUSE_CHAIN (loop_clause))
527 bool found_num_clause = false;
528 tree *clause_ptr, clause_to_check;
529 switch (OMP_CLAUSE_CODE (loop_clause))
531 case OMP_CLAUSE_GANG:
532 found_num_clause = true;
533 clause_ptr = &loop_gang_clause;
534 clause_to_check = num_gangs_clause;
535 break;
536 case OMP_CLAUSE_WORKER:
537 found_num_clause = true;
538 clause_ptr = &loop_worker_clause;
539 clause_to_check = num_workers_clause;
540 break;
541 case OMP_CLAUSE_VECTOR:
542 found_num_clause = true;
543 clause_ptr = &loop_vector_clause;
544 clause_to_check = vector_length_clause;
545 break;
546 case OMP_CLAUSE_INDEPENDENT:
547 case OMP_CLAUSE_SEQ:
548 case OMP_CLAUSE_AUTO:
549 add_auto_clause = false;
550 default:
551 break;
553 if (found_num_clause && OMP_CLAUSE_OPERAND (loop_clause, 0) != NULL)
555 if (clause_to_check)
557 const char *clause_name
558 = omp_clause_code_name[OMP_CLAUSE_CODE (loop_clause)];
559 const char *parent_clause_name
560 = omp_clause_code_name[OMP_CLAUSE_CODE (clause_to_check)];
561 error_at (OMP_CLAUSE_LOCATION (loop_clause),
562 "argument not permitted on %qs clause"
563 " in OpenACC %<kernels%> region with a %qs clause",
564 clause_name, parent_clause_name);
565 inform (OMP_CLAUSE_LOCATION (clause_to_check),
566 "location of OpenACC %<kernels%>");
568 /* Copy the 'gang (N)'/'worker (N)'/'vector (N)' clause to the
569 enclosing compute construct. */
570 *clause_ptr = unshare_expr (loop_clause);
571 OMP_CLAUSE_CHAIN (*clause_ptr) = NULL;
572 /* Leave a 'gang'/'worker'/'vector' clause on the 'loop', but without
573 argument. */
574 OMP_CLAUSE_OPERAND (loop_clause, 0) = NULL;
577 if (add_auto_clause)
579 tree auto_clause = build_omp_clause (gimple_location (omp_for),
580 OMP_CLAUSE_AUTO);
581 OMP_CLAUSE_CHAIN (auto_clause) = loop_clauses;
582 loop_clauses = auto_clause;
584 gimple_omp_for_set_clauses (omp_for, loop_clauses);
585 /* We must also recurse into the loop; it might contain nested loops having
586 their own 'worker (num: W)' or 'vector (length: V)' clauses. Turn these
587 into 'worker'/'vector' clauses on the compute construct. */
588 struct walk_stmt_info wi;
589 memset (&wi, 0, sizeof (wi));
590 struct adjust_nested_loop_clauses_wi_info wi_info;
591 wi_info.loop_gang_clause_ptr = &loop_gang_clause;
592 wi_info.loop_worker_clause_ptr = &loop_worker_clause;
593 wi_info.loop_vector_clause_ptr = &loop_vector_clause;
594 wi.info = &wi_info;
595 gimple *body = gimple_omp_body (omp_for);
596 walk_gimple_seq (body, adjust_nested_loop_clauses, NULL, &wi);
597 /* Check if there were conflicting numbers of workers or vector length. */
598 if (loop_gang_clause != NULL &&
599 OMP_CLAUSE_OPERAND (loop_gang_clause, 0) == NULL)
600 loop_gang_clause = NULL;
601 if (loop_worker_clause != NULL &&
602 OMP_CLAUSE_OPERAND (loop_worker_clause, 0) == NULL)
603 loop_worker_clause = NULL;
604 if (loop_vector_clause != NULL &&
605 OMP_CLAUSE_OPERAND (loop_vector_clause, 0) == NULL)
606 vector_length_clause = NULL;
608 /* If the kernels region had 'num_gangs', 'num_worker', 'vector_length'
609 clauses, add these to this new compute construct. */
610 clauses
611 = add_parent_or_loop_num_clause (num_gangs_clause, loop_gang_clause,
612 OMP_CLAUSE_NUM_GANGS, clauses);
613 clauses
614 = add_parent_or_loop_num_clause (num_workers_clause, loop_worker_clause,
615 OMP_CLAUSE_NUM_WORKERS, clauses);
616 clauses
617 = add_parent_or_loop_num_clause (vector_length_clause, loop_vector_clause,
618 OMP_CLAUSE_VECTOR_LENGTH, clauses);
620 return clauses;
623 /* Construct a possibly gang-parallel compute construct containing the STMT,
624 which must be identical to, or a bind containing, the loop OMP_FOR.
626 The NUM_GANGS_CLAUSE, NUM_WORKERS_CLAUSE, and VECTOR_LENGTH_CLAUSE are
627 optional clauses from the original kernels region and must not be contained
628 in the other CLAUSES. The newly created compute construct is annotated with
629 the optional NUM_GANGS_CLAUSE as well as the other CLAUSES. If there is no
630 NUM_GANGS_CLAUSE but the loop has a 'gang (num: N)' clause, that is
631 converted to a 'num_gangs (N)' clause on the new compute construct, and
632 similarly for 'worker' and 'vector' clauses.
634 The outermost loop gets an 'auto' clause unless there already is an
635 'seq'/'independent'/'auto' clause. Nested loops inside OMP_FOR are treated
636 similarly by the adjust_nested_loop_clauses function. */
638 static gimple *
639 make_region_loop_nest (gimple *omp_for, gimple_seq stmts,
640 tree num_gangs_clause,
641 tree num_workers_clause,
642 tree vector_length_clause,
643 tree clauses)
645 /* This correctly unshares the entire clause chain rooted here. */
646 clauses = unshare_expr (clauses);
648 /* Figure out the region code for this region. */
649 /* Optimistic default: assume that the loop nest is parallelizable
650 (essentially, no GIMPLE_OMP_FOR with (explicit or implicit) 'auto' clause,
651 and no un-annotated loops). */
652 int region_code = GF_OMP_TARGET_KIND_OACC_PARALLEL_KERNELS_PARALLELIZED;
653 adjust_region_code (stmts, &region_code);
655 if (region_code == GF_OMP_TARGET_KIND_OACC_PARALLEL_KERNELS_PARALLELIZED)
657 if (dump_enabled_p ())
658 /* This is not MSG_OPTIMIZED_LOCATIONS, as we're just doing what the
659 user asked us to. */
660 dump_printf_loc (MSG_NOTE, omp_for,
661 "parallelized loop nest"
662 " in OpenACC %<kernels%> region\n");
664 clauses = transform_kernels_loop_clauses (omp_for,
665 num_gangs_clause,
666 num_workers_clause,
667 vector_length_clause,
668 clauses);
670 else if (region_code == GF_OMP_TARGET_KIND_OACC_KERNELS)
672 if (dump_enabled_p ())
673 dump_printf_loc (MSG_NOTE, omp_for,
674 "forwarded loop nest"
675 " in OpenACC %<kernels%> region"
676 " to %<parloops%> for analysis\n");
678 /* We're transforming one 'GF_OMP_TARGET_KIND_OACC_KERNELS' into another
679 'GF_OMP_TARGET_KIND_OACC_KERNELS', so don't have to
680 'transform_kernels_loop_clauses'. */
681 /* Re-assemble the clauses stripped off earlier. */
682 clauses
683 = add_parent_or_loop_num_clause (num_gangs_clause, NULL,
684 OMP_CLAUSE_NUM_GANGS, clauses);
685 clauses
686 = add_parent_or_loop_num_clause (num_workers_clause, NULL,
687 OMP_CLAUSE_NUM_WORKERS, clauses);
688 clauses
689 = add_parent_or_loop_num_clause (vector_length_clause, NULL,
690 OMP_CLAUSE_VECTOR_LENGTH, clauses);
692 else
693 gcc_unreachable ();
695 gimple *parallel_body_bind
696 = gimple_build_bind (NULL, stmts, make_node (BLOCK));
697 gimple *parallel_region
698 = gimple_build_omp_target (parallel_body_bind, region_code, clauses);
699 gimple_set_location (parallel_region, gimple_location (omp_for));
701 return parallel_region;
704 /* Eliminate any binds directly inside BIND by adding their statements to
705 BIND (i.e., modifying it in place), excluding binds that hold only an
706 OMP_FOR loop and associated setup/cleanup code. Recurse into binds but
707 not other statements. Return a chain of the local variables of eliminated
708 binds, i.e., the local variables found in nested binds. If
709 INCLUDE_TOPLEVEL_VARS is true, this also includes the variables belonging
710 to BIND itself. */
712 static tree
713 flatten_binds (gbind *bind, bool include_toplevel_vars = false)
715 tree vars = NULL, last_var = NULL;
717 if (include_toplevel_vars)
719 vars = gimple_bind_vars (bind);
720 last_var = vars;
723 gimple_seq new_body = NULL;
724 gimple_seq body_sequence = gimple_bind_body (bind);
725 gimple_stmt_iterator gsi, gsi_n;
726 for (gsi = gsi_start (body_sequence); !gsi_end_p (gsi); gsi = gsi_n)
728 /* Advance the iterator here because otherwise it would be invalidated
729 by moving statements below. */
730 gsi_n = gsi;
731 gsi_next (&gsi_n);
733 gimple *stmt = gsi_stmt (gsi);
734 /* Flatten bind statements, except the ones that contain only an
735 OpenACC for loop. */
736 if (gimple_code (stmt) == GIMPLE_BIND
737 && !top_level_omp_for_in_stmt (stmt))
739 gbind *inner_bind = as_a <gbind *> (stmt);
740 /* Flatten recursively, and collect all variables. */
741 tree inner_vars = flatten_binds (inner_bind, true);
742 gimple_seq inner_sequence = gimple_bind_body (inner_bind);
743 if (flag_checking)
745 for (gimple_stmt_iterator inner_gsi = gsi_start (inner_sequence);
746 !gsi_end_p (inner_gsi);
747 gsi_next (&inner_gsi))
749 gimple *inner_stmt = gsi_stmt (inner_gsi);
750 gcc_assert (gimple_code (inner_stmt) != GIMPLE_BIND
751 || top_level_omp_for_in_stmt (inner_stmt));
754 gimple_seq_add_seq (&new_body, inner_sequence);
755 /* Find the last variable; we will append others to it. */
756 while (last_var != NULL && TREE_CHAIN (last_var) != NULL)
757 last_var = TREE_CHAIN (last_var);
758 if (last_var != NULL)
760 TREE_CHAIN (last_var) = inner_vars;
761 last_var = inner_vars;
763 else
765 vars = inner_vars;
766 last_var = vars;
769 else
770 gimple_seq_add_stmt (&new_body, stmt);
773 /* Put the possibly transformed body back into the bind. */
774 gimple_bind_set_body (bind, new_body);
775 return vars;
778 /* Helper function for places where we construct data regions. Wraps the BODY
779 inside a try-finally construct at LOC that calls __builtin_GOACC_data_end
780 in its cleanup block. Returns this try statement. */
782 static gimple *
783 make_data_region_try_statement (location_t loc, gimple *body)
785 tree data_end_fn = builtin_decl_explicit (BUILT_IN_GOACC_DATA_END);
786 gimple *call = gimple_build_call (data_end_fn, 0);
787 gimple_seq cleanup = NULL;
788 gimple_seq_add_stmt (&cleanup, call);
789 gimple *try_stmt = gimple_build_try (body, cleanup, GIMPLE_TRY_FINALLY);
790 gimple_set_location (body, loc);
791 return try_stmt;
794 /* If INNER_BIND_VARS holds variables, build an OpenACC data region with
795 location LOC containing BODY and having 'create (var)' clauses for each
796 variable (as a side effect, such variables also get TREE_ADDRESSABLE set).
797 If INNER_CLEANUP is present, add a try-finally statement with
798 this cleanup code in the finally block. Return the new data region, or
799 the original BODY if no data region was needed. */
801 static gimple *
802 maybe_build_inner_data_region (location_t loc, gimple *body,
803 tree inner_bind_vars, gimple *inner_cleanup)
805 /* Is this an instantiation of a template? (In this case, we don't care what
806 the generic decl is - just whether the function decl has one.) */
807 bool generic_inst_p
808 = (lang_hooks.decls.get_generic_function_decl (current_function_decl)
809 != NULL);
811 /* Build data 'create (var)' clauses for these local variables.
812 Below we will add these to a data region enclosing the entire body
813 of the decomposed kernels region. */
814 tree prev_mapped_var = NULL, next = NULL, artificial_vars = NULL,
815 inner_data_clauses = NULL;
816 for (tree v = inner_bind_vars; v; v = next)
818 next = TREE_CHAIN (v);
819 if (DECL_ARTIFICIAL (v)
820 || TREE_CODE (v) == CONST_DECL
821 || generic_inst_p)
823 /* If this is an artificial temporary, it need not be mapped. We
824 move its declaration into the bind inside the data region.
825 Also avoid mapping variables if we are inside a template
826 instantiation; the code does not contain all the copies to
827 temporaries that would make this legal. */
828 TREE_CHAIN (v) = artificial_vars;
829 artificial_vars = v;
830 if (prev_mapped_var != NULL)
831 TREE_CHAIN (prev_mapped_var) = next;
832 else
833 inner_bind_vars = next;
835 else
837 /* Otherwise, build the map clause. */
838 tree new_clause = build_omp_clause (loc, OMP_CLAUSE_MAP);
839 OMP_CLAUSE_SET_MAP_KIND (new_clause, GOMP_MAP_ALLOC);
840 OMP_CLAUSE_DECL (new_clause) = v;
841 OMP_CLAUSE_SIZE (new_clause) = DECL_SIZE_UNIT (v);
842 OMP_CLAUSE_CHAIN (new_clause) = inner_data_clauses;
843 inner_data_clauses = new_clause;
845 prev_mapped_var = v;
847 /* See <https://gcc.gnu.org/PR100280>. */
848 if (!TREE_ADDRESSABLE (v))
850 /* Request that OMP lowering make 'v' addressable. */
851 OMP_CLAUSE_MAP_DECL_MAKE_ADDRESSABLE (new_clause) = 1;
853 if (dump_enabled_p ())
855 const dump_user_location_t d_u_loc
856 = dump_user_location_t::from_location_t (loc);
857 /* PR100695 "Format decoder, quoting in 'dump_printf' etc." */
858 #if __GNUC__ >= 10
859 # pragma GCC diagnostic push
860 # pragma GCC diagnostic ignored "-Wformat"
861 #endif
862 dump_printf_loc (MSG_NOTE, d_u_loc,
863 "OpenACC %<kernels%> decomposition:"
864 " variable %<%T%> declared in block"
865 " requested to be made addressable\n",
867 #if __GNUC__ >= 10
868 # pragma GCC diagnostic pop
869 #endif
875 if (artificial_vars)
876 body = gimple_build_bind (artificial_vars, body, make_node (BLOCK));
878 /* If we determined above that there are variables that need to be created
879 on the device, construct a data region for them and wrap the body
880 inside that. */
881 if (inner_data_clauses != NULL)
883 gcc_assert (inner_bind_vars != NULL);
884 gimple *inner_data_region
885 = gimple_build_omp_target (NULL, GF_OMP_TARGET_KIND_OACC_DATA_KERNELS,
886 inner_data_clauses);
887 gimple_set_location (inner_data_region, loc);
888 /* Make sure __builtin_GOACC_data_end is called at the end. */
889 gimple *try_stmt = make_data_region_try_statement (loc, body);
890 gimple_omp_set_body (inner_data_region, try_stmt);
891 gimple *bind_body;
892 if (inner_cleanup != NULL)
893 /* Clobber all the inner variables that need to be clobbered. */
894 bind_body = gimple_build_try (inner_data_region, inner_cleanup,
895 GIMPLE_TRY_FINALLY);
896 else
897 bind_body = inner_data_region;
898 body = gimple_build_bind (inner_bind_vars, bind_body, make_node (BLOCK));
901 return body;
904 static void
905 add_wait (location_t loc, gimple_seq *region_body)
907 /* A "#pragma acc wait" is just a call GOACC_wait (acc_async_sync, 0). */
908 tree wait_fn = builtin_decl_explicit (BUILT_IN_GOACC_WAIT);
909 tree sync_arg = build_int_cst (integer_type_node, GOMP_ASYNC_SYNC);
910 gimple *wait_call = gimple_build_call (wait_fn, 2,
911 sync_arg, integer_zero_node);
912 gimple_set_location (wait_call, loc);
913 gimple_seq_add_stmt (region_body, wait_call);
916 /* Helper function of decompose_kernels_region_body. The statements in
917 REGION_BODY are expected to be decomposed parts; add an 'async' clause to
918 each. Also add a 'wait' directive at the end of the sequence. */
920 static void
921 add_async_clauses_and_wait (location_t loc, gimple_seq *region_body)
923 tree default_async_queue
924 = build_int_cst (integer_type_node, GOMP_ASYNC_NOVAL);
925 for (gimple_stmt_iterator gsi = gsi_start (*region_body);
926 !gsi_end_p (gsi);
927 gsi_next (&gsi))
929 gimple *stmt = gsi_stmt (gsi);
930 tree target_clauses = gimple_omp_target_clauses (stmt);
931 tree new_async_clause = build_omp_clause (loc, OMP_CLAUSE_ASYNC);
932 OMP_CLAUSE_OPERAND (new_async_clause, 0) = default_async_queue;
933 OMP_CLAUSE_CHAIN (new_async_clause) = target_clauses;
934 target_clauses = new_async_clause;
935 gimple_omp_target_set_clauses (as_a <gomp_target *> (stmt),
936 target_clauses);
938 add_wait (loc, region_body);
941 /* Auxiliary analysis of the body of a kernels region, to determine for each
942 OpenACC loop whether it is control-dependent (i.e., not necessarily
943 executed every time the kernels region is entered) or not.
944 We say that a loop is control-dependent if there is some cond, switch, or
945 goto statement that jumps over it, forwards or backwards. For example,
946 if the loop is controlled by an if statement, then a jump to the true
947 block, the false block, or from one of those blocks to the control flow
948 join point will necessarily jump over the loop.
949 This analysis implements an ad-hoc union-find data structure classifying
950 statements into "control-flow regions" as follows: Most statements are in
951 the same region as their predecessor, except that each OpenACC loop is in
952 a region of its own, and each OpenACC loop's successor starts a new
953 region. We then unite the regions of any statements linked by jumps,
954 placing any cond, switch, or goto statement in the same region as its
955 target label(s).
956 In the end, control dependence of OpenACC loops can be determined by
957 comparing their immediate predecessor and successor statements' regions.
958 A jump crosses the loop if and only if the predecessor and successor are
959 in the same region. (If there is no predecessor or successor, the loop
960 is executed unconditionally.)
961 The methods in this class identify statements by their index in the
962 kernels region's body. */
964 class control_flow_regions
966 public:
967 /* Initialize an instance and pre-compute the control-flow region
968 information for the statement sequence SEQ. */
969 control_flow_regions (gimple_seq seq);
971 /* Return true if the statement with the given index IDX in the analyzed
972 statement sequence is an unconditionally executed OpenACC loop. */
973 bool is_unconditional_oacc_for_loop (size_t idx);
975 private:
976 /* Find the region representative for the statement identified by index
977 STMT_IDX. */
978 size_t find_rep (size_t stmt_idx);
980 /* Union the regions containing the statements represented by
981 representatives A and B. */
982 void union_reps (size_t a, size_t b);
984 /* Helper for the constructor. Performs the actual computation of the
985 control-flow regions in the statement sequence SEQ. */
986 void compute_regions (gimple_seq seq);
988 /* The mapping from statement indices to region representatives. */
989 vec <size_t> representatives;
991 /* A cache mapping statement indices to a flag indicating whether the
992 statement is a top level OpenACC for loop. */
993 vec <bool> omp_for_loops;
996 control_flow_regions::control_flow_regions (gimple_seq seq)
998 representatives.create (1);
999 omp_for_loops.create (1);
1000 compute_regions (seq);
1003 bool
1004 control_flow_regions::is_unconditional_oacc_for_loop (size_t idx)
1006 if (idx == 0 || idx == representatives.length () - 1)
1007 /* The first or last statement in the kernels region. This means that
1008 there is no room before or after it for a jump or a label. Thus
1009 there cannot be a jump across it, so it is unconditional. */
1010 return true;
1011 /* Otherwise, the loop is unconditional if the statements before and after
1012 it are in different control flow regions. Scan forward and backward,
1013 skipping over neighboring OpenACC for loops, to find these preceding
1014 statements. */
1015 size_t prev_index = idx - 1;
1016 while (prev_index > 0 && omp_for_loops [prev_index] == true)
1017 prev_index--;
1018 /* If all preceding statements are also OpenACC loops, all of these are
1019 unconditional. */
1020 if (prev_index == 0)
1021 return true;
1022 size_t succ_index = idx + 1;
1023 while (succ_index < omp_for_loops.length ()
1024 && omp_for_loops [succ_index] == true)
1025 succ_index++;
1026 /* If all following statements are also OpenACC loops, all of these are
1027 unconditional. */
1028 if (succ_index == omp_for_loops.length ())
1029 return true;
1030 return (find_rep (prev_index) != find_rep (succ_index));
1033 size_t
1034 control_flow_regions::find_rep (size_t stmt_idx)
1036 size_t rep = stmt_idx, aux = stmt_idx;
1037 /* Find the root representative of this statement. */
1038 while (representatives[rep] != rep)
1039 rep = representatives[rep];
1040 /* Compress the path from the original statement to the representative. */
1041 while (representatives[aux] != rep)
1043 size_t tmp = representatives[aux];
1044 representatives[aux] = rep;
1045 aux = tmp;
1047 return rep;
1050 void
1051 control_flow_regions::union_reps (size_t a, size_t b)
1053 a = find_rep (a);
1054 b = find_rep (b);
1055 representatives[b] = a;
1058 void
1059 control_flow_regions::compute_regions (gimple_seq seq)
1061 hash_map <gimple *, size_t> control_flow_reps;
1062 hash_map <tree, size_t> label_reps;
1063 size_t current_region = 0, idx = 0;
1065 /* In a first pass, assign an initial region to each statement. Except in
1066 the case of OpenACC loops, each statement simply gets the same region
1067 representative as its predecessor. */
1068 for (gimple_stmt_iterator gsi = gsi_start (seq);
1069 !gsi_end_p (gsi);
1070 gsi_next (&gsi))
1072 gimple *stmt = gsi_stmt (gsi);
1073 gimple *omp_for = top_level_omp_for_in_stmt (stmt);
1074 omp_for_loops.safe_push (omp_for != NULL);
1075 if (omp_for != NULL)
1077 /* Assign a new region to this loop and to its successor. */
1078 current_region = idx;
1079 representatives.safe_push (current_region);
1080 current_region++;
1082 else
1084 representatives.safe_push (current_region);
1085 /* Remember any jumps and labels for the second pass below. */
1086 if (gimple_code (stmt) == GIMPLE_COND
1087 || gimple_code (stmt) == GIMPLE_SWITCH
1088 || gimple_code (stmt) == GIMPLE_GOTO)
1089 control_flow_reps.put (stmt, current_region);
1090 else if (gimple_code (stmt) == GIMPLE_LABEL)
1091 label_reps.put (gimple_label_label (as_a <glabel *> (stmt)),
1092 current_region);
1094 idx++;
1096 gcc_assert (representatives.length () == omp_for_loops.length ());
1098 /* Revisit all the control flow statements and union the region of each
1099 cond, switch, or goto statement with the target labels' regions. */
1100 for (hash_map <gimple *, size_t>::iterator it = control_flow_reps.begin ();
1101 it != control_flow_reps.end ();
1102 ++it)
1104 gimple *stmt = (*it).first;
1105 size_t stmt_rep = (*it).second;
1106 switch (gimple_code (stmt))
1108 tree label;
1109 unsigned int n;
1111 case GIMPLE_COND:
1112 label = gimple_cond_true_label (as_a <gcond *> (stmt));
1113 union_reps (stmt_rep, *label_reps.get (label));
1114 label = gimple_cond_false_label (as_a <gcond *> (stmt));
1115 union_reps (stmt_rep, *label_reps.get (label));
1116 break;
1118 case GIMPLE_SWITCH:
1119 n = gimple_switch_num_labels (as_a <gswitch *> (stmt));
1120 for (unsigned int i = 0; i < n; i++)
1122 tree switch_case
1123 = gimple_switch_label (as_a <gswitch *> (stmt), i);
1124 label = CASE_LABEL (switch_case);
1125 union_reps (stmt_rep, *label_reps.get (label));
1127 break;
1129 case GIMPLE_GOTO:
1130 label = gimple_goto_dest (stmt);
1131 union_reps (stmt_rep, *label_reps.get (label));
1132 break;
1134 default:
1135 gcc_unreachable ();
1140 /* Decompose the body of the KERNELS_REGION, which was originally annotated
1141 with the KERNELS_CLAUSES, into a series of compute constructs. */
1143 static gimple *
1144 decompose_kernels_region_body (gimple *kernels_region, tree kernels_clauses)
1146 location_t loc = gimple_location (kernels_region);
1148 /* The kernels clauses will be propagated to the child clauses unmodified,
1149 except that the 'num_gangs', 'num_workers', and 'vector_length' clauses
1150 will only be added to loop regions. The other regions are "gang-single"
1151 and get an explicit 'num_gangs (1)' clause. So separate out the
1152 'num_gangs', 'num_workers', and 'vector_length' clauses here.
1153 Also check for the presence of an 'async' clause but do not remove it from
1154 the 'kernels' clauses. */
1155 tree num_gangs_clause = NULL, num_workers_clause = NULL,
1156 vector_length_clause = NULL;
1157 tree async_clause = NULL;
1158 tree prev_clause = NULL, next_clause = NULL;
1159 tree parallel_clauses = kernels_clauses;
1160 for (tree c = parallel_clauses; c; c = next_clause)
1162 /* Preserve this here, as we might NULL it later. */
1163 next_clause = OMP_CLAUSE_CHAIN (c);
1165 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_GANGS
1166 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_WORKERS
1167 || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_VECTOR_LENGTH)
1169 /* Cut this clause out of the chain. */
1170 if (prev_clause != NULL)
1171 OMP_CLAUSE_CHAIN (prev_clause) = OMP_CLAUSE_CHAIN (c);
1172 else
1173 kernels_clauses = OMP_CLAUSE_CHAIN (c);
1174 OMP_CLAUSE_CHAIN (c) = NULL;
1175 switch (OMP_CLAUSE_CODE (c))
1177 case OMP_CLAUSE_NUM_GANGS:
1178 num_gangs_clause = c;
1179 break;
1180 case OMP_CLAUSE_NUM_WORKERS:
1181 num_workers_clause = c;
1182 break;
1183 case OMP_CLAUSE_VECTOR_LENGTH:
1184 vector_length_clause = c;
1185 break;
1186 default:
1187 gcc_unreachable ();
1190 else
1191 prev_clause = c;
1192 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_ASYNC)
1193 async_clause = c;
1196 gimple *kernels_body = gimple_omp_body (kernels_region);
1197 gbind *kernels_bind = as_a <gbind *> (kernels_body);
1199 /* The body of the region may contain other nested binds declaring inner
1200 local variables. Collapse all these binds into one to ensure that we
1201 have a single sequence of statements to iterate over; also, collect all
1202 inner variables. */
1203 tree inner_bind_vars = flatten_binds (kernels_bind);
1204 gimple_seq body_sequence = gimple_bind_body (kernels_bind);
1206 /* All these inner variables will get allocated on the device (below, by
1207 calling maybe_build_inner_data_region). Here we create 'present'
1208 clauses for them and add these clauses to the list of clauses to be
1209 attached to each inner compute construct. */
1210 tree present_clauses = kernels_clauses;
1211 for (tree var = inner_bind_vars; var; var = TREE_CHAIN (var))
1213 if (!DECL_ARTIFICIAL (var) && TREE_CODE (var) != CONST_DECL)
1215 tree present_clause = build_omp_clause (loc, OMP_CLAUSE_MAP);
1216 OMP_CLAUSE_SET_MAP_KIND (present_clause, GOMP_MAP_FORCE_PRESENT);
1217 OMP_CLAUSE_DECL (present_clause) = var;
1218 OMP_CLAUSE_SIZE (present_clause) = DECL_SIZE_UNIT (var);
1219 OMP_CLAUSE_CHAIN (present_clause) = present_clauses;
1220 present_clauses = present_clause;
1223 kernels_clauses = present_clauses;
1225 /* In addition to nested binds, the "real" body of the region may be
1226 nested inside a try-finally block. Find its cleanup block, which
1227 contains code to clobber the local variables that must be clobbered. */
1228 gimple *inner_cleanup = NULL;
1229 if (body_sequence != NULL && gimple_code (body_sequence) == GIMPLE_TRY)
1231 if (gimple_seq_singleton_p (body_sequence))
1233 /* The try statement is the only thing inside the bind. */
1234 inner_cleanup = gimple_try_cleanup (body_sequence);
1235 body_sequence = gimple_try_eval (body_sequence);
1237 else
1239 /* The bind's body starts with a try statement, but it is followed
1240 by other things. */
1241 gimple_stmt_iterator gsi = gsi_start (body_sequence);
1242 gimple *try_stmt = gsi_stmt (gsi);
1243 inner_cleanup = gimple_try_cleanup (try_stmt);
1244 gimple *try_body = gimple_try_eval (try_stmt);
1246 gsi_remove (&gsi, false);
1247 /* Now gsi indicates the sequence of statements after the try
1248 statement in the bind. Append the statement in the try body and
1249 the trailing statements from gsi. */
1250 gsi_insert_seq_before (&gsi, try_body, GSI_CONTINUE_LINKING);
1251 body_sequence = gsi_stmt (gsi);
1255 /* This sequence will collect all the top-level statements in the body of
1256 the data region we are about to construct. */
1257 gimple_seq region_body = NULL;
1258 /* This sequence will collect consecutive statements to be put into a
1259 gang-single region. */
1260 gimple_seq gang_single_seq = NULL;
1261 /* Flag recording whether the gang_single_seq only contains copies to
1262 local variables. These may be loop setup code that should not be
1263 separated from the loop. */
1264 bool only_simple_assignments = true;
1266 /* Precompute the control flow region information to determine whether an
1267 OpenACC loop is executed conditionally or unconditionally. */
1268 control_flow_regions cf_regions (body_sequence);
1270 /* Iterate over the statements in the kernels region's body. */
1271 size_t idx = 0;
1272 gimple_stmt_iterator gsi, gsi_n;
1273 for (gsi = gsi_start (body_sequence); !gsi_end_p (gsi); gsi = gsi_n, idx++)
1275 /* Advance the iterator here because otherwise it would be invalidated
1276 by moving statements below. */
1277 gsi_n = gsi;
1278 gsi_next (&gsi_n);
1280 gimple *stmt = gsi_stmt (gsi);
1281 if (gimple_code (stmt) == GIMPLE_DEBUG)
1283 if (flag_compare_debug_opt || flag_compare_debug)
1284 /* Let the usual '-fcompare-debug' analysis bail out, as
1285 necessary. */
1287 else
1288 sorry_at (loc, "%qs not yet supported",
1289 gimple_code_name[gimple_code (stmt)]);
1291 gimple *omp_for = top_level_omp_for_in_stmt (stmt);
1292 bool is_unconditional_oacc_for_loop = false;
1293 if (omp_for != NULL)
1294 is_unconditional_oacc_for_loop
1295 = cf_regions.is_unconditional_oacc_for_loop (idx);
1296 if (omp_for != NULL
1297 && is_unconditional_oacc_for_loop)
1299 /* This is an OMP for statement, put it into a separate region.
1300 But first, construct a gang-single region containing any
1301 complex sequential statements we may have seen. */
1302 if (gang_single_seq != NULL && !only_simple_assignments)
1304 gimple *single_region
1305 = make_region_seq (loc, gang_single_seq,
1306 num_gangs_clause,
1307 num_workers_clause,
1308 vector_length_clause,
1309 kernels_clauses);
1310 gimple_seq_add_stmt (&region_body, single_region);
1312 else if (gang_single_seq != NULL && only_simple_assignments)
1314 /* There is a sequence of sequential statements preceding this
1315 loop, but they are all simple assignments. This is
1316 probably setup code for the loop; in particular, Fortran DO
1317 loops are preceded by code to copy the loop limit variable
1318 to a temporary. Group this code together with the loop
1319 itself. */
1320 gimple_seq_add_stmt (&gang_single_seq, stmt);
1321 stmt = gimple_build_bind (NULL, gang_single_seq,
1322 make_node (BLOCK));
1324 gang_single_seq = NULL;
1325 only_simple_assignments = true;
1327 gimple_seq parallel_seq = NULL;
1328 gimple_seq_add_stmt (&parallel_seq, stmt);
1329 gimple *parallel_region
1330 = make_region_loop_nest (omp_for, parallel_seq,
1331 num_gangs_clause,
1332 num_workers_clause,
1333 vector_length_clause,
1334 kernels_clauses);
1335 gimple_seq_add_stmt (&region_body, parallel_region);
1337 else
1339 if (omp_for != NULL)
1341 gcc_checking_assert (!is_unconditional_oacc_for_loop);
1342 if (dump_enabled_p ())
1343 dump_printf_loc (MSG_MISSED_OPTIMIZATION, omp_for,
1344 "unparallelized loop nest"
1345 " in OpenACC %<kernels%> region:"
1346 " it's executed conditionally\n");
1349 /* This is not an unconditional OMP for statement, so it will be
1350 put into a gang-single region. */
1351 gimple_seq_add_stmt (&gang_single_seq, stmt);
1352 /* Is this a simple assignment? We call it simple if it is an
1353 assignment to an artificial local variable. This captures
1354 Fortran loop setup code computing loop bounds and offsets. */
1355 bool is_simple_assignment
1356 = (gimple_code (stmt) == GIMPLE_ASSIGN
1357 && TREE_CODE (gimple_assign_lhs (stmt)) == VAR_DECL
1358 && DECL_ARTIFICIAL (gimple_assign_lhs (stmt)));
1359 if (!is_simple_assignment)
1360 only_simple_assignments = false;
1364 /* If we did not emit a new region, and are not going to emit one now
1365 (that is, the original region was empty), prepare to emit a dummy so as
1366 to preserve the original construct, which other processing (at least
1367 test cases) depend on. */
1368 if (region_body == NULL && gang_single_seq == NULL)
1370 gimple *stmt = gimple_build_nop ();
1371 gimple_set_location (stmt, loc);
1372 gimple_seq_add_stmt (&gang_single_seq, stmt);
1375 /* Gather up any remaining gang-single statements. */
1376 if (gang_single_seq != NULL)
1378 gimple *single_region
1379 = make_region_seq (loc, gang_single_seq,
1380 num_gangs_clause,
1381 num_workers_clause,
1382 vector_length_clause,
1383 kernels_clauses);
1384 gimple_seq_add_stmt (&region_body, single_region);
1387 /* We want to launch these kernels asynchronously. If the original
1388 kernels region had an async clause, this is done automatically because
1389 that async clause was copied to the individual regions we created.
1390 Otherwise, add an async clause to each newly created region, as well as
1391 a wait directive at the end. */
1392 if (async_clause == NULL)
1393 add_async_clauses_and_wait (loc, &region_body);
1394 else
1395 /* !!! If we have asynchronous parallel blocks inside a (synchronous) data
1396 region, then target memory will get unmapped at the point the data
1397 region ends, even if the inner asynchronous parallels have not yet
1398 completed. For kernels marked "async", we might want to use "enter data
1399 async(...)" and "exit data async(...)" instead, or asynchronous data
1400 regions (see also <https://gcc.gnu.org/PR97390>
1401 "[OpenACC] 'async' clause on 'data' construct",
1402 which is to share the same implementation).
1403 For now, insert a (synchronous) wait at the end of the block. */
1404 add_wait (loc, &region_body);
1406 tree kernels_locals = gimple_bind_vars (as_a <gbind *> (kernels_body));
1407 gimple *body = gimple_build_bind (kernels_locals, region_body,
1408 make_node (BLOCK));
1410 /* If we found variables declared in nested scopes, build a data region to
1411 map them to the device. */
1412 body = maybe_build_inner_data_region (loc, body, inner_bind_vars,
1413 inner_cleanup);
1415 return body;
1418 /* Decompose one OpenACC 'kernels' construct into an OpenACC 'data' construct
1419 containing the original OpenACC 'kernels' construct's region cut up into a
1420 sequence of compute constructs. */
1422 static gimple *
1423 omp_oacc_kernels_decompose_1 (gimple *kernels_stmt)
1425 gcc_checking_assert (gimple_omp_target_kind (kernels_stmt)
1426 == GF_OMP_TARGET_KIND_OACC_KERNELS);
1427 location_t loc = gimple_location (kernels_stmt);
1429 /* Collect the data clauses of the OpenACC 'kernels' directive and create a
1430 new OpenACC 'data' construct with those clauses. */
1431 tree kernels_clauses = gimple_omp_target_clauses (kernels_stmt);
1432 tree data_clauses = NULL;
1433 for (tree c = kernels_clauses; c; c = OMP_CLAUSE_CHAIN (c))
1435 /* Certain clauses are copied to the enclosing OpenACC 'data'. Other
1436 clauses remain on the OpenACC 'kernels'. */
1437 if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP)
1439 tree decl = OMP_CLAUSE_DECL (c);
1440 HOST_WIDE_INT map_kind = OMP_CLAUSE_MAP_KIND (c);
1441 switch (map_kind)
1443 default:
1444 if (map_kind == GOMP_MAP_ALLOC
1445 && integer_zerop (OMP_CLAUSE_SIZE (c)))
1446 /* ??? This is an alloc clause for mapping a pointer whose
1447 target is already mapped. We leave these on the inner
1448 compute constructs because moving them to the outer data
1449 region causes runtime errors. */
1450 break;
1452 /* For non-artificial variables, and for non-declaration
1453 expressions like A[0:n], copy the clause to the data
1454 region. */
1455 if ((DECL_P (decl) && !DECL_ARTIFICIAL (decl))
1456 || !DECL_P (decl))
1458 tree new_clause = build_omp_clause (OMP_CLAUSE_LOCATION (c),
1459 OMP_CLAUSE_MAP);
1460 OMP_CLAUSE_SET_MAP_KIND (new_clause, map_kind);
1461 /* This must be unshared here to avoid "incorrect sharing
1462 of tree nodes" errors from verify_gimple. */
1463 OMP_CLAUSE_DECL (new_clause) = unshare_expr (decl);
1464 OMP_CLAUSE_SIZE (new_clause) = OMP_CLAUSE_SIZE (c);
1465 OMP_CLAUSE_CHAIN (new_clause) = data_clauses;
1466 data_clauses = new_clause;
1468 /* Now that this data is mapped, turn the data clause on the
1469 inner OpenACC 'kernels' into a 'present' clause. */
1470 OMP_CLAUSE_SET_MAP_KIND (c, GOMP_MAP_FORCE_PRESENT);
1472 break;
1474 case GOMP_MAP_POINTER:
1475 case GOMP_MAP_TO_PSET:
1476 case GOMP_MAP_FORCE_TOFROM:
1477 case GOMP_MAP_FIRSTPRIVATE_POINTER:
1478 case GOMP_MAP_FIRSTPRIVATE_REFERENCE:
1479 /* ??? Copying these map kinds leads to internal compiler
1480 errors in later passes. */
1481 break;
1484 else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IF)
1486 /* If there is an 'if' clause, it must be duplicated to the
1487 enclosing data region. Temporarily remove the if clause's
1488 chain to avoid copying it. */
1489 tree saved_chain = OMP_CLAUSE_CHAIN (c);
1490 OMP_CLAUSE_CHAIN (c) = NULL;
1491 tree new_if_clause = unshare_expr (c);
1492 OMP_CLAUSE_CHAIN (c) = saved_chain;
1493 OMP_CLAUSE_CHAIN (new_if_clause) = data_clauses;
1494 data_clauses = new_if_clause;
1497 /* Restore the original order of the clauses. */
1498 data_clauses = nreverse (data_clauses);
1500 gimple *data_region
1501 = gimple_build_omp_target (NULL, GF_OMP_TARGET_KIND_OACC_DATA_KERNELS,
1502 data_clauses);
1503 gimple_set_location (data_region, loc);
1505 /* Transform the body of the kernels region into a sequence of compute
1506 constructs. */
1507 gimple *body = decompose_kernels_region_body (kernels_stmt,
1508 kernels_clauses);
1510 /* Put the transformed pieces together. The entire body of the region is
1511 wrapped in a try-finally statement that calls __builtin_GOACC_data_end
1512 for cleanup. */
1513 gimple *try_stmt = make_data_region_try_statement (loc, body);
1514 gimple_omp_set_body (data_region, try_stmt);
1516 return data_region;
1520 /* Decompose OpenACC 'kernels' constructs in the current function. */
1522 static tree
1523 omp_oacc_kernels_decompose_callback_stmt (gimple_stmt_iterator *gsi_p,
1524 bool *handled_ops_p,
1525 struct walk_stmt_info *)
1527 gimple *stmt = gsi_stmt (*gsi_p);
1529 if ((gimple_code (stmt) == GIMPLE_OMP_TARGET)
1530 && gimple_omp_target_kind (stmt) == GF_OMP_TARGET_KIND_OACC_KERNELS)
1532 gimple *stmt_new = omp_oacc_kernels_decompose_1 (stmt);
1533 gsi_replace (gsi_p, stmt_new, false);
1534 *handled_ops_p = true;
1536 else
1537 *handled_ops_p = false;
1539 return NULL;
1542 static unsigned int
1543 omp_oacc_kernels_decompose (void)
1545 gimple_seq body = gimple_body (current_function_decl);
1547 struct walk_stmt_info wi;
1548 memset (&wi, 0, sizeof (wi));
1549 walk_gimple_seq_mod (&body, omp_oacc_kernels_decompose_callback_stmt, NULL,
1550 &wi);
1552 gimple_set_body (current_function_decl, body);
1554 return 0;
1558 namespace {
1560 const pass_data pass_data_omp_oacc_kernels_decompose =
1562 GIMPLE_PASS, /* type */
1563 "omp_oacc_kernels_decompose", /* name */
1564 OPTGROUP_OMP, /* optinfo_flags */
1565 TV_NONE, /* tv_id */
1566 PROP_gimple_any, /* properties_required */
1567 0, /* properties_provided */
1568 0, /* properties_destroyed */
1569 0, /* todo_flags_start */
1570 0, /* todo_flags_finish */
1573 class pass_omp_oacc_kernels_decompose : public gimple_opt_pass
1575 public:
1576 pass_omp_oacc_kernels_decompose (gcc::context *ctxt)
1577 : gimple_opt_pass (pass_data_omp_oacc_kernels_decompose, ctxt)
1580 /* opt_pass methods: */
1581 virtual bool gate (function *)
1583 return (flag_openacc
1584 && param_openacc_kernels == OPENACC_KERNELS_DECOMPOSE);
1586 virtual unsigned int execute (function *)
1588 return omp_oacc_kernels_decompose ();
1591 }; // class pass_omp_oacc_kernels_decompose
1593 } // anon namespace
1595 gimple_opt_pass *
1596 make_pass_omp_oacc_kernels_decompose (gcc::context *ctxt)
1598 return new pass_omp_oacc_kernels_decompose (ctxt);