Fix try_transform_to_exit_first_loop_alt
[official-gcc.git] / gcc / tree-parloops.c
blobc4b83fe9635b9e5e05e2a0827b1b7376946981cd
1 /* Loop autoparallelization.
2 Copyright (C) 2006-2015 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <pop@cri.ensmp.fr>
4 Zdenek Dvorak <dvorakz@suse.cz> and Razya Ladelsky <razya@il.ibm.com>.
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 "hash-set.h"
26 #include "vec.h"
27 #include "input.h"
28 #include "alias.h"
29 #include "symtab.h"
30 #include "options.h"
31 #include "inchash.h"
32 #include "tree.h"
33 #include "fold-const.h"
34 #include "predict.h"
35 #include "tm.h"
36 #include "hard-reg-set.h"
37 #include "input.h"
38 #include "function.h"
39 #include "dominance.h"
40 #include "cfg.h"
41 #include "basic-block.h"
42 #include "tree-ssa-alias.h"
43 #include "internal-fn.h"
44 #include "gimple-expr.h"
45 #include "is-a.h"
46 #include "gimple.h"
47 #include "gimplify.h"
48 #include "gimple-iterator.h"
49 #include "gimplify-me.h"
50 #include "gimple-walk.h"
51 #include "stor-layout.h"
52 #include "tree-nested.h"
53 #include "gimple-ssa.h"
54 #include "tree-cfg.h"
55 #include "tree-phinodes.h"
56 #include "ssa-iterators.h"
57 #include "stringpool.h"
58 #include "tree-ssanames.h"
59 #include "tree-ssa-loop-ivopts.h"
60 #include "tree-ssa-loop-manip.h"
61 #include "tree-ssa-loop-niter.h"
62 #include "tree-ssa-loop.h"
63 #include "tree-into-ssa.h"
64 #include "cfgloop.h"
65 #include "tree-data-ref.h"
66 #include "tree-scalar-evolution.h"
67 #include "gimple-pretty-print.h"
68 #include "tree-pass.h"
69 #include "langhooks.h"
70 #include "tree-vectorizer.h"
71 #include "tree-hasher.h"
72 #include "tree-parloops.h"
73 #include "omp-low.h"
74 #include "tree-nested.h"
75 #include "plugin-api.h"
76 #include "ipa-ref.h"
77 #include "cgraph.h"
78 #include "tree-ssa.h"
80 /* This pass tries to distribute iterations of loops into several threads.
81 The implementation is straightforward -- for each loop we test whether its
82 iterations are independent, and if it is the case (and some additional
83 conditions regarding profitability and correctness are satisfied), we
84 add GIMPLE_OMP_PARALLEL and GIMPLE_OMP_FOR codes and let omp expansion
85 machinery do its job.
87 The most of the complexity is in bringing the code into shape expected
88 by the omp expanders:
89 -- for GIMPLE_OMP_FOR, ensuring that the loop has only one induction
90 variable and that the exit test is at the start of the loop body
91 -- for GIMPLE_OMP_PARALLEL, replacing the references to local addressable
92 variables by accesses through pointers, and breaking up ssa chains
93 by storing the values incoming to the parallelized loop to a structure
94 passed to the new function as an argument (something similar is done
95 in omp gimplification, unfortunately only a small part of the code
96 can be shared).
98 TODO:
99 -- if there are several parallelizable loops in a function, it may be
100 possible to generate the threads just once (using synchronization to
101 ensure that cross-loop dependences are obeyed).
102 -- handling of common reduction patterns for outer loops.
104 More info can also be found at http://gcc.gnu.org/wiki/AutoParInGCC */
106 Reduction handling:
107 currently we use vect_force_simple_reduction() to detect reduction patterns.
108 The code transformation will be introduced by an example.
111 parloop
113 int sum=1;
115 for (i = 0; i < N; i++)
117 x[i] = i + 3;
118 sum+=x[i];
122 gimple-like code:
123 header_bb:
125 # sum_29 = PHI <sum_11(5), 1(3)>
126 # i_28 = PHI <i_12(5), 0(3)>
127 D.1795_8 = i_28 + 3;
128 x[i_28] = D.1795_8;
129 sum_11 = D.1795_8 + sum_29;
130 i_12 = i_28 + 1;
131 if (N_6(D) > i_12)
132 goto header_bb;
135 exit_bb:
137 # sum_21 = PHI <sum_11(4)>
138 printf (&"%d"[0], sum_21);
141 after reduction transformation (only relevant parts):
143 parloop
146 ....
149 # Storing the initial value given by the user. #
151 .paral_data_store.32.sum.27 = 1;
153 #pragma omp parallel num_threads(4)
155 #pragma omp for schedule(static)
157 # The neutral element corresponding to the particular
158 reduction's operation, e.g. 0 for PLUS_EXPR,
159 1 for MULT_EXPR, etc. replaces the user's initial value. #
161 # sum.27_29 = PHI <sum.27_11, 0>
163 sum.27_11 = D.1827_8 + sum.27_29;
165 GIMPLE_OMP_CONTINUE
167 # Adding this reduction phi is done at create_phi_for_local_result() #
168 # sum.27_56 = PHI <sum.27_11, 0>
169 GIMPLE_OMP_RETURN
171 # Creating the atomic operation is done at
172 create_call_for_reduction_1() #
174 #pragma omp atomic_load
175 D.1839_59 = *&.paral_data_load.33_51->reduction.23;
176 D.1840_60 = sum.27_56 + D.1839_59;
177 #pragma omp atomic_store (D.1840_60);
179 GIMPLE_OMP_RETURN
181 # collecting the result after the join of the threads is done at
182 create_loads_for_reductions().
183 The value computed by the threads is loaded from the
184 shared struct. #
187 .paral_data_load.33_52 = &.paral_data_store.32;
188 sum_37 = .paral_data_load.33_52->sum.27;
189 sum_43 = D.1795_41 + sum_37;
191 exit bb:
192 # sum_21 = PHI <sum_43, sum_26>
193 printf (&"%d"[0], sum_21);
201 /* Minimal number of iterations of a loop that should be executed in each
202 thread. */
203 #define MIN_PER_THREAD 100
205 /* Element of the hashtable, representing a
206 reduction in the current loop. */
207 struct reduction_info
209 gimple reduc_stmt; /* reduction statement. */
210 gimple reduc_phi; /* The phi node defining the reduction. */
211 enum tree_code reduction_code;/* code for the reduction operation. */
212 unsigned reduc_version; /* SSA_NAME_VERSION of original reduc_phi
213 result. */
214 gphi *keep_res; /* The PHI_RESULT of this phi is the resulting value
215 of the reduction variable when existing the loop. */
216 tree initial_value; /* The initial value of the reduction var before entering the loop. */
217 tree field; /* the name of the field in the parloop data structure intended for reduction. */
218 tree init; /* reduction initialization value. */
219 gphi *new_phi; /* (helper field) Newly created phi node whose result
220 will be passed to the atomic operation. Represents
221 the local result each thread computed for the reduction
222 operation. */
225 /* Reduction info hashtable helpers. */
227 struct reduction_hasher : typed_free_remove <reduction_info>
229 typedef reduction_info *value_type;
230 typedef reduction_info *compare_type;
231 static inline hashval_t hash (const reduction_info *);
232 static inline bool equal (const reduction_info *, const reduction_info *);
235 /* Equality and hash functions for hashtab code. */
237 inline bool
238 reduction_hasher::equal (const reduction_info *a, const reduction_info *b)
240 return (a->reduc_phi == b->reduc_phi);
243 inline hashval_t
244 reduction_hasher::hash (const reduction_info *a)
246 return a->reduc_version;
249 typedef hash_table<reduction_hasher> reduction_info_table_type;
252 static struct reduction_info *
253 reduction_phi (reduction_info_table_type *reduction_list, gimple phi)
255 struct reduction_info tmpred, *red;
257 if (reduction_list->elements () == 0 || phi == NULL)
258 return NULL;
260 tmpred.reduc_phi = phi;
261 tmpred.reduc_version = gimple_uid (phi);
262 red = reduction_list->find (&tmpred);
264 return red;
267 /* Element of hashtable of names to copy. */
269 struct name_to_copy_elt
271 unsigned version; /* The version of the name to copy. */
272 tree new_name; /* The new name used in the copy. */
273 tree field; /* The field of the structure used to pass the
274 value. */
277 /* Name copies hashtable helpers. */
279 struct name_to_copy_hasher : typed_free_remove <name_to_copy_elt>
281 typedef name_to_copy_elt *value_type;
282 typedef name_to_copy_elt *compare_type;
283 static inline hashval_t hash (const name_to_copy_elt *);
284 static inline bool equal (const name_to_copy_elt *, const name_to_copy_elt *);
287 /* Equality and hash functions for hashtab code. */
289 inline bool
290 name_to_copy_hasher::equal (const name_to_copy_elt *a, const name_to_copy_elt *b)
292 return a->version == b->version;
295 inline hashval_t
296 name_to_copy_hasher::hash (const name_to_copy_elt *a)
298 return (hashval_t) a->version;
301 typedef hash_table<name_to_copy_hasher> name_to_copy_table_type;
303 /* A transformation matrix, which is a self-contained ROWSIZE x COLSIZE
304 matrix. Rather than use floats, we simply keep a single DENOMINATOR that
305 represents the denominator for every element in the matrix. */
306 typedef struct lambda_trans_matrix_s
308 lambda_matrix matrix;
309 int rowsize;
310 int colsize;
311 int denominator;
312 } *lambda_trans_matrix;
313 #define LTM_MATRIX(T) ((T)->matrix)
314 #define LTM_ROWSIZE(T) ((T)->rowsize)
315 #define LTM_COLSIZE(T) ((T)->colsize)
316 #define LTM_DENOMINATOR(T) ((T)->denominator)
318 /* Allocate a new transformation matrix. */
320 static lambda_trans_matrix
321 lambda_trans_matrix_new (int colsize, int rowsize,
322 struct obstack * lambda_obstack)
324 lambda_trans_matrix ret;
326 ret = (lambda_trans_matrix)
327 obstack_alloc (lambda_obstack, sizeof (struct lambda_trans_matrix_s));
328 LTM_MATRIX (ret) = lambda_matrix_new (rowsize, colsize, lambda_obstack);
329 LTM_ROWSIZE (ret) = rowsize;
330 LTM_COLSIZE (ret) = colsize;
331 LTM_DENOMINATOR (ret) = 1;
332 return ret;
335 /* Multiply a vector VEC by a matrix MAT.
336 MAT is an M*N matrix, and VEC is a vector with length N. The result
337 is stored in DEST which must be a vector of length M. */
339 static void
340 lambda_matrix_vector_mult (lambda_matrix matrix, int m, int n,
341 lambda_vector vec, lambda_vector dest)
343 int i, j;
345 lambda_vector_clear (dest, m);
346 for (i = 0; i < m; i++)
347 for (j = 0; j < n; j++)
348 dest[i] += matrix[i][j] * vec[j];
351 /* Return true if TRANS is a legal transformation matrix that respects
352 the dependence vectors in DISTS and DIRS. The conservative answer
353 is false.
355 "Wolfe proves that a unimodular transformation represented by the
356 matrix T is legal when applied to a loop nest with a set of
357 lexicographically non-negative distance vectors RDG if and only if
358 for each vector d in RDG, (T.d >= 0) is lexicographically positive.
359 i.e.: if and only if it transforms the lexicographically positive
360 distance vectors to lexicographically positive vectors. Note that
361 a unimodular matrix must transform the zero vector (and only it) to
362 the zero vector." S.Muchnick. */
364 static bool
365 lambda_transform_legal_p (lambda_trans_matrix trans,
366 int nb_loops,
367 vec<ddr_p> dependence_relations)
369 unsigned int i, j;
370 lambda_vector distres;
371 struct data_dependence_relation *ddr;
373 gcc_assert (LTM_COLSIZE (trans) == nb_loops
374 && LTM_ROWSIZE (trans) == nb_loops);
376 /* When there are no dependences, the transformation is correct. */
377 if (dependence_relations.length () == 0)
378 return true;
380 ddr = dependence_relations[0];
381 if (ddr == NULL)
382 return true;
384 /* When there is an unknown relation in the dependence_relations, we
385 know that it is no worth looking at this loop nest: give up. */
386 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
387 return false;
389 distres = lambda_vector_new (nb_loops);
391 /* For each distance vector in the dependence graph. */
392 FOR_EACH_VEC_ELT (dependence_relations, i, ddr)
394 /* Don't care about relations for which we know that there is no
395 dependence, nor about read-read (aka. output-dependences):
396 these data accesses can happen in any order. */
397 if (DDR_ARE_DEPENDENT (ddr) == chrec_known
398 || (DR_IS_READ (DDR_A (ddr)) && DR_IS_READ (DDR_B (ddr))))
399 continue;
401 /* Conservatively answer: "this transformation is not valid". */
402 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
403 return false;
405 /* If the dependence could not be captured by a distance vector,
406 conservatively answer that the transform is not valid. */
407 if (DDR_NUM_DIST_VECTS (ddr) == 0)
408 return false;
410 /* Compute trans.dist_vect */
411 for (j = 0; j < DDR_NUM_DIST_VECTS (ddr); j++)
413 lambda_matrix_vector_mult (LTM_MATRIX (trans), nb_loops, nb_loops,
414 DDR_DIST_VECT (ddr, j), distres);
416 if (!lambda_vector_lexico_pos (distres, nb_loops))
417 return false;
420 return true;
423 /* Data dependency analysis. Returns true if the iterations of LOOP
424 are independent on each other (that is, if we can execute them
425 in parallel). */
427 static bool
428 loop_parallel_p (struct loop *loop, struct obstack * parloop_obstack)
430 vec<ddr_p> dependence_relations;
431 vec<data_reference_p> datarefs;
432 lambda_trans_matrix trans;
433 bool ret = false;
435 if (dump_file && (dump_flags & TDF_DETAILS))
437 fprintf (dump_file, "Considering loop %d\n", loop->num);
438 if (!loop->inner)
439 fprintf (dump_file, "loop is innermost\n");
440 else
441 fprintf (dump_file, "loop NOT innermost\n");
444 /* Check for problems with dependences. If the loop can be reversed,
445 the iterations are independent. */
446 auto_vec<loop_p, 3> loop_nest;
447 datarefs.create (10);
448 dependence_relations.create (100);
449 if (! compute_data_dependences_for_loop (loop, true, &loop_nest, &datarefs,
450 &dependence_relations))
452 if (dump_file && (dump_flags & TDF_DETAILS))
453 fprintf (dump_file, " FAILED: cannot analyze data dependencies\n");
454 ret = false;
455 goto end;
457 if (dump_file && (dump_flags & TDF_DETAILS))
458 dump_data_dependence_relations (dump_file, dependence_relations);
460 trans = lambda_trans_matrix_new (1, 1, parloop_obstack);
461 LTM_MATRIX (trans)[0][0] = -1;
463 if (lambda_transform_legal_p (trans, 1, dependence_relations))
465 ret = true;
466 if (dump_file && (dump_flags & TDF_DETAILS))
467 fprintf (dump_file, " SUCCESS: may be parallelized\n");
469 else if (dump_file && (dump_flags & TDF_DETAILS))
470 fprintf (dump_file,
471 " FAILED: data dependencies exist across iterations\n");
473 end:
474 free_dependence_relations (dependence_relations);
475 free_data_refs (datarefs);
477 return ret;
480 /* Return true when LOOP contains basic blocks marked with the
481 BB_IRREDUCIBLE_LOOP flag. */
483 static inline bool
484 loop_has_blocks_with_irreducible_flag (struct loop *loop)
486 unsigned i;
487 basic_block *bbs = get_loop_body_in_dom_order (loop);
488 bool res = true;
490 for (i = 0; i < loop->num_nodes; i++)
491 if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP)
492 goto end;
494 res = false;
495 end:
496 free (bbs);
497 return res;
500 /* Assigns the address of OBJ in TYPE to an ssa name, and returns this name.
501 The assignment statement is placed on edge ENTRY. DECL_ADDRESS maps decls
502 to their addresses that can be reused. The address of OBJ is known to
503 be invariant in the whole function. Other needed statements are placed
504 right before GSI. */
506 static tree
507 take_address_of (tree obj, tree type, edge entry,
508 int_tree_htab_type *decl_address, gimple_stmt_iterator *gsi)
510 int uid;
511 tree *var_p, name, addr;
512 gassign *stmt;
513 gimple_seq stmts;
515 /* Since the address of OBJ is invariant, the trees may be shared.
516 Avoid rewriting unrelated parts of the code. */
517 obj = unshare_expr (obj);
518 for (var_p = &obj;
519 handled_component_p (*var_p);
520 var_p = &TREE_OPERAND (*var_p, 0))
521 continue;
523 /* Canonicalize the access to base on a MEM_REF. */
524 if (DECL_P (*var_p))
525 *var_p = build_simple_mem_ref (build_fold_addr_expr (*var_p));
527 /* Assign a canonical SSA name to the address of the base decl used
528 in the address and share it for all accesses and addresses based
529 on it. */
530 uid = DECL_UID (TREE_OPERAND (TREE_OPERAND (*var_p, 0), 0));
531 int_tree_map elt;
532 elt.uid = uid;
533 int_tree_map *slot = decl_address->find_slot (elt, INSERT);
534 if (!slot->to)
536 if (gsi == NULL)
537 return NULL;
538 addr = TREE_OPERAND (*var_p, 0);
539 const char *obj_name
540 = get_name (TREE_OPERAND (TREE_OPERAND (*var_p, 0), 0));
541 if (obj_name)
542 name = make_temp_ssa_name (TREE_TYPE (addr), NULL, obj_name);
543 else
544 name = make_ssa_name (TREE_TYPE (addr));
545 stmt = gimple_build_assign (name, addr);
546 gsi_insert_on_edge_immediate (entry, stmt);
548 slot->uid = uid;
549 slot->to = name;
551 else
552 name = slot->to;
554 /* Express the address in terms of the canonical SSA name. */
555 TREE_OPERAND (*var_p, 0) = name;
556 if (gsi == NULL)
557 return build_fold_addr_expr_with_type (obj, type);
559 name = force_gimple_operand (build_addr (obj, current_function_decl),
560 &stmts, true, NULL_TREE);
561 if (!gimple_seq_empty_p (stmts))
562 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
564 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
566 name = force_gimple_operand (fold_convert (type, name), &stmts, true,
567 NULL_TREE);
568 if (!gimple_seq_empty_p (stmts))
569 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
572 return name;
575 /* Callback for htab_traverse. Create the initialization statement
576 for reduction described in SLOT, and place it at the preheader of
577 the loop described in DATA. */
580 initialize_reductions (reduction_info **slot, struct loop *loop)
582 tree init, c;
583 tree bvar, type, arg;
584 edge e;
586 struct reduction_info *const reduc = *slot;
588 /* Create initialization in preheader:
589 reduction_variable = initialization value of reduction. */
591 /* In the phi node at the header, replace the argument coming
592 from the preheader with the reduction initialization value. */
594 /* Create a new variable to initialize the reduction. */
595 type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
596 bvar = create_tmp_var (type, "reduction");
598 c = build_omp_clause (gimple_location (reduc->reduc_stmt),
599 OMP_CLAUSE_REDUCTION);
600 OMP_CLAUSE_REDUCTION_CODE (c) = reduc->reduction_code;
601 OMP_CLAUSE_DECL (c) = SSA_NAME_VAR (gimple_assign_lhs (reduc->reduc_stmt));
603 init = omp_reduction_init (c, TREE_TYPE (bvar));
604 reduc->init = init;
606 /* Replace the argument representing the initialization value
607 with the initialization value for the reduction (neutral
608 element for the particular operation, e.g. 0 for PLUS_EXPR,
609 1 for MULT_EXPR, etc).
610 Keep the old value in a new variable "reduction_initial",
611 that will be taken in consideration after the parallel
612 computing is done. */
614 e = loop_preheader_edge (loop);
615 arg = PHI_ARG_DEF_FROM_EDGE (reduc->reduc_phi, e);
616 /* Create new variable to hold the initial value. */
618 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE
619 (reduc->reduc_phi, loop_preheader_edge (loop)), init);
620 reduc->initial_value = arg;
621 return 1;
624 struct elv_data
626 struct walk_stmt_info info;
627 edge entry;
628 int_tree_htab_type *decl_address;
629 gimple_stmt_iterator *gsi;
630 bool changed;
631 bool reset;
634 /* Eliminates references to local variables in *TP out of the single
635 entry single exit region starting at DTA->ENTRY.
636 DECL_ADDRESS contains addresses of the references that had their
637 address taken already. If the expression is changed, CHANGED is
638 set to true. Callback for walk_tree. */
640 static tree
641 eliminate_local_variables_1 (tree *tp, int *walk_subtrees, void *data)
643 struct elv_data *const dta = (struct elv_data *) data;
644 tree t = *tp, var, addr, addr_type, type, obj;
646 if (DECL_P (t))
648 *walk_subtrees = 0;
650 if (!SSA_VAR_P (t) || DECL_EXTERNAL (t))
651 return NULL_TREE;
653 type = TREE_TYPE (t);
654 addr_type = build_pointer_type (type);
655 addr = take_address_of (t, addr_type, dta->entry, dta->decl_address,
656 dta->gsi);
657 if (dta->gsi == NULL && addr == NULL_TREE)
659 dta->reset = true;
660 return NULL_TREE;
663 *tp = build_simple_mem_ref (addr);
665 dta->changed = true;
666 return NULL_TREE;
669 if (TREE_CODE (t) == ADDR_EXPR)
671 /* ADDR_EXPR may appear in two contexts:
672 -- as a gimple operand, when the address taken is a function invariant
673 -- as gimple rhs, when the resulting address in not a function
674 invariant
675 We do not need to do anything special in the latter case (the base of
676 the memory reference whose address is taken may be replaced in the
677 DECL_P case). The former case is more complicated, as we need to
678 ensure that the new address is still a gimple operand. Thus, it
679 is not sufficient to replace just the base of the memory reference --
680 we need to move the whole computation of the address out of the
681 loop. */
682 if (!is_gimple_val (t))
683 return NULL_TREE;
685 *walk_subtrees = 0;
686 obj = TREE_OPERAND (t, 0);
687 var = get_base_address (obj);
688 if (!var || !SSA_VAR_P (var) || DECL_EXTERNAL (var))
689 return NULL_TREE;
691 addr_type = TREE_TYPE (t);
692 addr = take_address_of (obj, addr_type, dta->entry, dta->decl_address,
693 dta->gsi);
694 if (dta->gsi == NULL && addr == NULL_TREE)
696 dta->reset = true;
697 return NULL_TREE;
699 *tp = addr;
701 dta->changed = true;
702 return NULL_TREE;
705 if (!EXPR_P (t))
706 *walk_subtrees = 0;
708 return NULL_TREE;
711 /* Moves the references to local variables in STMT at *GSI out of the single
712 entry single exit region starting at ENTRY. DECL_ADDRESS contains
713 addresses of the references that had their address taken
714 already. */
716 static void
717 eliminate_local_variables_stmt (edge entry, gimple_stmt_iterator *gsi,
718 int_tree_htab_type *decl_address)
720 struct elv_data dta;
721 gimple stmt = gsi_stmt (*gsi);
723 memset (&dta.info, '\0', sizeof (dta.info));
724 dta.entry = entry;
725 dta.decl_address = decl_address;
726 dta.changed = false;
727 dta.reset = false;
729 if (gimple_debug_bind_p (stmt))
731 dta.gsi = NULL;
732 walk_tree (gimple_debug_bind_get_value_ptr (stmt),
733 eliminate_local_variables_1, &dta.info, NULL);
734 if (dta.reset)
736 gimple_debug_bind_reset_value (stmt);
737 dta.changed = true;
740 else if (gimple_clobber_p (stmt))
742 stmt = gimple_build_nop ();
743 gsi_replace (gsi, stmt, false);
744 dta.changed = true;
746 else
748 dta.gsi = gsi;
749 walk_gimple_op (stmt, eliminate_local_variables_1, &dta.info);
752 if (dta.changed)
753 update_stmt (stmt);
756 /* Eliminates the references to local variables from the single entry
757 single exit region between the ENTRY and EXIT edges.
759 This includes:
760 1) Taking address of a local variable -- these are moved out of the
761 region (and temporary variable is created to hold the address if
762 necessary).
764 2) Dereferencing a local variable -- these are replaced with indirect
765 references. */
767 static void
768 eliminate_local_variables (edge entry, edge exit)
770 basic_block bb;
771 auto_vec<basic_block, 3> body;
772 unsigned i;
773 gimple_stmt_iterator gsi;
774 bool has_debug_stmt = false;
775 int_tree_htab_type decl_address (10);
776 basic_block entry_bb = entry->src;
777 basic_block exit_bb = exit->dest;
779 gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
781 FOR_EACH_VEC_ELT (body, i, bb)
782 if (bb != entry_bb && bb != exit_bb)
783 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
784 if (is_gimple_debug (gsi_stmt (gsi)))
786 if (gimple_debug_bind_p (gsi_stmt (gsi)))
787 has_debug_stmt = true;
789 else
790 eliminate_local_variables_stmt (entry, &gsi, &decl_address);
792 if (has_debug_stmt)
793 FOR_EACH_VEC_ELT (body, i, bb)
794 if (bb != entry_bb && bb != exit_bb)
795 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
796 if (gimple_debug_bind_p (gsi_stmt (gsi)))
797 eliminate_local_variables_stmt (entry, &gsi, &decl_address);
800 /* Returns true if expression EXPR is not defined between ENTRY and
801 EXIT, i.e. if all its operands are defined outside of the region. */
803 static bool
804 expr_invariant_in_region_p (edge entry, edge exit, tree expr)
806 basic_block entry_bb = entry->src;
807 basic_block exit_bb = exit->dest;
808 basic_block def_bb;
810 if (is_gimple_min_invariant (expr))
811 return true;
813 if (TREE_CODE (expr) == SSA_NAME)
815 def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
816 if (def_bb
817 && dominated_by_p (CDI_DOMINATORS, def_bb, entry_bb)
818 && !dominated_by_p (CDI_DOMINATORS, def_bb, exit_bb))
819 return false;
821 return true;
824 return false;
827 /* If COPY_NAME_P is true, creates and returns a duplicate of NAME.
828 The copies are stored to NAME_COPIES, if NAME was already duplicated,
829 its duplicate stored in NAME_COPIES is returned.
831 Regardless of COPY_NAME_P, the decl used as a base of the ssa name is also
832 duplicated, storing the copies in DECL_COPIES. */
834 static tree
835 separate_decls_in_region_name (tree name, name_to_copy_table_type *name_copies,
836 int_tree_htab_type *decl_copies,
837 bool copy_name_p)
839 tree copy, var, var_copy;
840 unsigned idx, uid, nuid;
841 struct int_tree_map ielt;
842 struct name_to_copy_elt elt, *nelt;
843 name_to_copy_elt **slot;
844 int_tree_map *dslot;
846 if (TREE_CODE (name) != SSA_NAME)
847 return name;
849 idx = SSA_NAME_VERSION (name);
850 elt.version = idx;
851 slot = name_copies->find_slot_with_hash (&elt, idx,
852 copy_name_p ? INSERT : NO_INSERT);
853 if (slot && *slot)
854 return (*slot)->new_name;
856 if (copy_name_p)
858 copy = duplicate_ssa_name (name, NULL);
859 nelt = XNEW (struct name_to_copy_elt);
860 nelt->version = idx;
861 nelt->new_name = copy;
862 nelt->field = NULL_TREE;
863 *slot = nelt;
865 else
867 gcc_assert (!slot);
868 copy = name;
871 var = SSA_NAME_VAR (name);
872 if (!var)
873 return copy;
875 uid = DECL_UID (var);
876 ielt.uid = uid;
877 dslot = decl_copies->find_slot_with_hash (ielt, uid, INSERT);
878 if (!dslot->to)
880 var_copy = create_tmp_var (TREE_TYPE (var), get_name (var));
881 DECL_GIMPLE_REG_P (var_copy) = DECL_GIMPLE_REG_P (var);
882 dslot->uid = uid;
883 dslot->to = var_copy;
885 /* Ensure that when we meet this decl next time, we won't duplicate
886 it again. */
887 nuid = DECL_UID (var_copy);
888 ielt.uid = nuid;
889 dslot = decl_copies->find_slot_with_hash (ielt, nuid, INSERT);
890 gcc_assert (!dslot->to);
891 dslot->uid = nuid;
892 dslot->to = var_copy;
894 else
895 var_copy = dslot->to;
897 replace_ssa_name_symbol (copy, var_copy);
898 return copy;
901 /* Finds the ssa names used in STMT that are defined outside the
902 region between ENTRY and EXIT and replaces such ssa names with
903 their duplicates. The duplicates are stored to NAME_COPIES. Base
904 decls of all ssa names used in STMT (including those defined in
905 LOOP) are replaced with the new temporary variables; the
906 replacement decls are stored in DECL_COPIES. */
908 static void
909 separate_decls_in_region_stmt (edge entry, edge exit, gimple stmt,
910 name_to_copy_table_type *name_copies,
911 int_tree_htab_type *decl_copies)
913 use_operand_p use;
914 def_operand_p def;
915 ssa_op_iter oi;
916 tree name, copy;
917 bool copy_name_p;
919 FOR_EACH_PHI_OR_STMT_DEF (def, stmt, oi, SSA_OP_DEF)
921 name = DEF_FROM_PTR (def);
922 gcc_assert (TREE_CODE (name) == SSA_NAME);
923 copy = separate_decls_in_region_name (name, name_copies, decl_copies,
924 false);
925 gcc_assert (copy == name);
928 FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
930 name = USE_FROM_PTR (use);
931 if (TREE_CODE (name) != SSA_NAME)
932 continue;
934 copy_name_p = expr_invariant_in_region_p (entry, exit, name);
935 copy = separate_decls_in_region_name (name, name_copies, decl_copies,
936 copy_name_p);
937 SET_USE (use, copy);
941 /* Finds the ssa names used in STMT that are defined outside the
942 region between ENTRY and EXIT and replaces such ssa names with
943 their duplicates. The duplicates are stored to NAME_COPIES. Base
944 decls of all ssa names used in STMT (including those defined in
945 LOOP) are replaced with the new temporary variables; the
946 replacement decls are stored in DECL_COPIES. */
948 static bool
949 separate_decls_in_region_debug (gimple stmt,
950 name_to_copy_table_type *name_copies,
951 int_tree_htab_type *decl_copies)
953 use_operand_p use;
954 ssa_op_iter oi;
955 tree var, name;
956 struct int_tree_map ielt;
957 struct name_to_copy_elt elt;
958 name_to_copy_elt **slot;
959 int_tree_map *dslot;
961 if (gimple_debug_bind_p (stmt))
962 var = gimple_debug_bind_get_var (stmt);
963 else if (gimple_debug_source_bind_p (stmt))
964 var = gimple_debug_source_bind_get_var (stmt);
965 else
966 return true;
967 if (TREE_CODE (var) == DEBUG_EXPR_DECL || TREE_CODE (var) == LABEL_DECL)
968 return true;
969 gcc_assert (DECL_P (var) && SSA_VAR_P (var));
970 ielt.uid = DECL_UID (var);
971 dslot = decl_copies->find_slot_with_hash (ielt, ielt.uid, NO_INSERT);
972 if (!dslot)
973 return true;
974 if (gimple_debug_bind_p (stmt))
975 gimple_debug_bind_set_var (stmt, dslot->to);
976 else if (gimple_debug_source_bind_p (stmt))
977 gimple_debug_source_bind_set_var (stmt, dslot->to);
979 FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
981 name = USE_FROM_PTR (use);
982 if (TREE_CODE (name) != SSA_NAME)
983 continue;
985 elt.version = SSA_NAME_VERSION (name);
986 slot = name_copies->find_slot_with_hash (&elt, elt.version, NO_INSERT);
987 if (!slot)
989 gimple_debug_bind_reset_value (stmt);
990 update_stmt (stmt);
991 break;
994 SET_USE (use, (*slot)->new_name);
997 return false;
1000 /* Callback for htab_traverse. Adds a field corresponding to the reduction
1001 specified in SLOT. The type is passed in DATA. */
1004 add_field_for_reduction (reduction_info **slot, tree type)
1007 struct reduction_info *const red = *slot;
1008 tree var = gimple_assign_lhs (red->reduc_stmt);
1009 tree field = build_decl (gimple_location (red->reduc_stmt), FIELD_DECL,
1010 SSA_NAME_IDENTIFIER (var), TREE_TYPE (var));
1012 insert_field_into_struct (type, field);
1014 red->field = field;
1016 return 1;
1019 /* Callback for htab_traverse. Adds a field corresponding to a ssa name
1020 described in SLOT. The type is passed in DATA. */
1023 add_field_for_name (name_to_copy_elt **slot, tree type)
1025 struct name_to_copy_elt *const elt = *slot;
1026 tree name = ssa_name (elt->version);
1027 tree field = build_decl (UNKNOWN_LOCATION,
1028 FIELD_DECL, SSA_NAME_IDENTIFIER (name),
1029 TREE_TYPE (name));
1031 insert_field_into_struct (type, field);
1032 elt->field = field;
1034 return 1;
1037 /* Callback for htab_traverse. A local result is the intermediate result
1038 computed by a single
1039 thread, or the initial value in case no iteration was executed.
1040 This function creates a phi node reflecting these values.
1041 The phi's result will be stored in NEW_PHI field of the
1042 reduction's data structure. */
1045 create_phi_for_local_result (reduction_info **slot, struct loop *loop)
1047 struct reduction_info *const reduc = *slot;
1048 edge e;
1049 gphi *new_phi;
1050 basic_block store_bb;
1051 tree local_res;
1052 source_location locus;
1054 /* STORE_BB is the block where the phi
1055 should be stored. It is the destination of the loop exit.
1056 (Find the fallthru edge from GIMPLE_OMP_CONTINUE). */
1057 store_bb = FALLTHRU_EDGE (loop->latch)->dest;
1059 /* STORE_BB has two predecessors. One coming from the loop
1060 (the reduction's result is computed at the loop),
1061 and another coming from a block preceding the loop,
1062 when no iterations
1063 are executed (the initial value should be taken). */
1064 if (EDGE_PRED (store_bb, 0) == FALLTHRU_EDGE (loop->latch))
1065 e = EDGE_PRED (store_bb, 1);
1066 else
1067 e = EDGE_PRED (store_bb, 0);
1068 local_res = copy_ssa_name (gimple_assign_lhs (reduc->reduc_stmt));
1069 locus = gimple_location (reduc->reduc_stmt);
1070 new_phi = create_phi_node (local_res, store_bb);
1071 add_phi_arg (new_phi, reduc->init, e, locus);
1072 add_phi_arg (new_phi, gimple_assign_lhs (reduc->reduc_stmt),
1073 FALLTHRU_EDGE (loop->latch), locus);
1074 reduc->new_phi = new_phi;
1076 return 1;
1079 struct clsn_data
1081 tree store;
1082 tree load;
1084 basic_block store_bb;
1085 basic_block load_bb;
1088 /* Callback for htab_traverse. Create an atomic instruction for the
1089 reduction described in SLOT.
1090 DATA annotates the place in memory the atomic operation relates to,
1091 and the basic block it needs to be generated in. */
1094 create_call_for_reduction_1 (reduction_info **slot, struct clsn_data *clsn_data)
1096 struct reduction_info *const reduc = *slot;
1097 gimple_stmt_iterator gsi;
1098 tree type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
1099 tree load_struct;
1100 basic_block bb;
1101 basic_block new_bb;
1102 edge e;
1103 tree t, addr, ref, x;
1104 tree tmp_load, name;
1105 gimple load;
1107 load_struct = build_simple_mem_ref (clsn_data->load);
1108 t = build3 (COMPONENT_REF, type, load_struct, reduc->field, NULL_TREE);
1110 addr = build_addr (t, current_function_decl);
1112 /* Create phi node. */
1113 bb = clsn_data->load_bb;
1115 gsi = gsi_last_bb (bb);
1116 e = split_block (bb, gsi_stmt (gsi));
1117 new_bb = e->dest;
1119 tmp_load = create_tmp_var (TREE_TYPE (TREE_TYPE (addr)));
1120 tmp_load = make_ssa_name (tmp_load);
1121 load = gimple_build_omp_atomic_load (tmp_load, addr);
1122 SSA_NAME_DEF_STMT (tmp_load) = load;
1123 gsi = gsi_start_bb (new_bb);
1124 gsi_insert_after (&gsi, load, GSI_NEW_STMT);
1126 e = split_block (new_bb, load);
1127 new_bb = e->dest;
1128 gsi = gsi_start_bb (new_bb);
1129 ref = tmp_load;
1130 x = fold_build2 (reduc->reduction_code,
1131 TREE_TYPE (PHI_RESULT (reduc->new_phi)), ref,
1132 PHI_RESULT (reduc->new_phi));
1134 name = force_gimple_operand_gsi (&gsi, x, true, NULL_TREE, true,
1135 GSI_CONTINUE_LINKING);
1137 gsi_insert_after (&gsi, gimple_build_omp_atomic_store (name), GSI_NEW_STMT);
1138 return 1;
1141 /* Create the atomic operation at the join point of the threads.
1142 REDUCTION_LIST describes the reductions in the LOOP.
1143 LD_ST_DATA describes the shared data structure where
1144 shared data is stored in and loaded from. */
1145 static void
1146 create_call_for_reduction (struct loop *loop,
1147 reduction_info_table_type *reduction_list,
1148 struct clsn_data *ld_st_data)
1150 reduction_list->traverse <struct loop *, create_phi_for_local_result> (loop);
1151 /* Find the fallthru edge from GIMPLE_OMP_CONTINUE. */
1152 ld_st_data->load_bb = FALLTHRU_EDGE (loop->latch)->dest;
1153 reduction_list
1154 ->traverse <struct clsn_data *, create_call_for_reduction_1> (ld_st_data);
1157 /* Callback for htab_traverse. Loads the final reduction value at the
1158 join point of all threads, and inserts it in the right place. */
1161 create_loads_for_reductions (reduction_info **slot, struct clsn_data *clsn_data)
1163 struct reduction_info *const red = *slot;
1164 gimple stmt;
1165 gimple_stmt_iterator gsi;
1166 tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
1167 tree load_struct;
1168 tree name;
1169 tree x;
1171 gsi = gsi_after_labels (clsn_data->load_bb);
1172 load_struct = build_simple_mem_ref (clsn_data->load);
1173 load_struct = build3 (COMPONENT_REF, type, load_struct, red->field,
1174 NULL_TREE);
1176 x = load_struct;
1177 name = PHI_RESULT (red->keep_res);
1178 stmt = gimple_build_assign (name, x);
1180 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1182 for (gsi = gsi_start_phis (gimple_bb (red->keep_res));
1183 !gsi_end_p (gsi); gsi_next (&gsi))
1184 if (gsi_stmt (gsi) == red->keep_res)
1186 remove_phi_node (&gsi, false);
1187 return 1;
1189 gcc_unreachable ();
1192 /* Load the reduction result that was stored in LD_ST_DATA.
1193 REDUCTION_LIST describes the list of reductions that the
1194 loads should be generated for. */
1195 static void
1196 create_final_loads_for_reduction (reduction_info_table_type *reduction_list,
1197 struct clsn_data *ld_st_data)
1199 gimple_stmt_iterator gsi;
1200 tree t;
1201 gimple stmt;
1203 gsi = gsi_after_labels (ld_st_data->load_bb);
1204 t = build_fold_addr_expr (ld_st_data->store);
1205 stmt = gimple_build_assign (ld_st_data->load, t);
1207 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1209 reduction_list
1210 ->traverse <struct clsn_data *, create_loads_for_reductions> (ld_st_data);
1214 /* Callback for htab_traverse. Store the neutral value for the
1215 particular reduction's operation, e.g. 0 for PLUS_EXPR,
1216 1 for MULT_EXPR, etc. into the reduction field.
1217 The reduction is specified in SLOT. The store information is
1218 passed in DATA. */
1221 create_stores_for_reduction (reduction_info **slot, struct clsn_data *clsn_data)
1223 struct reduction_info *const red = *slot;
1224 tree t;
1225 gimple stmt;
1226 gimple_stmt_iterator gsi;
1227 tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
1229 gsi = gsi_last_bb (clsn_data->store_bb);
1230 t = build3 (COMPONENT_REF, type, clsn_data->store, red->field, NULL_TREE);
1231 stmt = gimple_build_assign (t, red->initial_value);
1232 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1234 return 1;
1237 /* Callback for htab_traverse. Creates loads to a field of LOAD in LOAD_BB and
1238 store to a field of STORE in STORE_BB for the ssa name and its duplicate
1239 specified in SLOT. */
1242 create_loads_and_stores_for_name (name_to_copy_elt **slot,
1243 struct clsn_data *clsn_data)
1245 struct name_to_copy_elt *const elt = *slot;
1246 tree t;
1247 gimple stmt;
1248 gimple_stmt_iterator gsi;
1249 tree type = TREE_TYPE (elt->new_name);
1250 tree load_struct;
1252 gsi = gsi_last_bb (clsn_data->store_bb);
1253 t = build3 (COMPONENT_REF, type, clsn_data->store, elt->field, NULL_TREE);
1254 stmt = gimple_build_assign (t, ssa_name (elt->version));
1255 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1257 gsi = gsi_last_bb (clsn_data->load_bb);
1258 load_struct = build_simple_mem_ref (clsn_data->load);
1259 t = build3 (COMPONENT_REF, type, load_struct, elt->field, NULL_TREE);
1260 stmt = gimple_build_assign (elt->new_name, t);
1261 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1263 return 1;
1266 /* Moves all the variables used in LOOP and defined outside of it (including
1267 the initial values of loop phi nodes, and *PER_THREAD if it is a ssa
1268 name) to a structure created for this purpose. The code
1270 while (1)
1272 use (a);
1273 use (b);
1276 is transformed this way:
1278 bb0:
1279 old.a = a;
1280 old.b = b;
1282 bb1:
1283 a' = new->a;
1284 b' = new->b;
1285 while (1)
1287 use (a');
1288 use (b');
1291 `old' is stored to *ARG_STRUCT and `new' is stored to NEW_ARG_STRUCT. The
1292 pointer `new' is intentionally not initialized (the loop will be split to a
1293 separate function later, and `new' will be initialized from its arguments).
1294 LD_ST_DATA holds information about the shared data structure used to pass
1295 information among the threads. It is initialized here, and
1296 gen_parallel_loop will pass it to create_call_for_reduction that
1297 needs this information. REDUCTION_LIST describes the reductions
1298 in LOOP. */
1300 static void
1301 separate_decls_in_region (edge entry, edge exit,
1302 reduction_info_table_type *reduction_list,
1303 tree *arg_struct, tree *new_arg_struct,
1304 struct clsn_data *ld_st_data)
1307 basic_block bb1 = split_edge (entry);
1308 basic_block bb0 = single_pred (bb1);
1309 name_to_copy_table_type name_copies (10);
1310 int_tree_htab_type decl_copies (10);
1311 unsigned i;
1312 tree type, type_name, nvar;
1313 gimple_stmt_iterator gsi;
1314 struct clsn_data clsn_data;
1315 auto_vec<basic_block, 3> body;
1316 basic_block bb;
1317 basic_block entry_bb = bb1;
1318 basic_block exit_bb = exit->dest;
1319 bool has_debug_stmt = false;
1321 entry = single_succ_edge (entry_bb);
1322 gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
1324 FOR_EACH_VEC_ELT (body, i, bb)
1326 if (bb != entry_bb && bb != exit_bb)
1328 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1329 separate_decls_in_region_stmt (entry, exit, gsi_stmt (gsi),
1330 &name_copies, &decl_copies);
1332 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1334 gimple stmt = gsi_stmt (gsi);
1336 if (is_gimple_debug (stmt))
1337 has_debug_stmt = true;
1338 else
1339 separate_decls_in_region_stmt (entry, exit, stmt,
1340 &name_copies, &decl_copies);
1345 /* Now process debug bind stmts. We must not create decls while
1346 processing debug stmts, so we defer their processing so as to
1347 make sure we will have debug info for as many variables as
1348 possible (all of those that were dealt with in the loop above),
1349 and discard those for which we know there's nothing we can
1350 do. */
1351 if (has_debug_stmt)
1352 FOR_EACH_VEC_ELT (body, i, bb)
1353 if (bb != entry_bb && bb != exit_bb)
1355 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
1357 gimple stmt = gsi_stmt (gsi);
1359 if (is_gimple_debug (stmt))
1361 if (separate_decls_in_region_debug (stmt, &name_copies,
1362 &decl_copies))
1364 gsi_remove (&gsi, true);
1365 continue;
1369 gsi_next (&gsi);
1373 if (name_copies.elements () == 0 && reduction_list->elements () == 0)
1375 /* It may happen that there is nothing to copy (if there are only
1376 loop carried and external variables in the loop). */
1377 *arg_struct = NULL;
1378 *new_arg_struct = NULL;
1380 else
1382 /* Create the type for the structure to store the ssa names to. */
1383 type = lang_hooks.types.make_type (RECORD_TYPE);
1384 type_name = build_decl (UNKNOWN_LOCATION,
1385 TYPE_DECL, create_tmp_var_name (".paral_data"),
1386 type);
1387 TYPE_NAME (type) = type_name;
1389 name_copies.traverse <tree, add_field_for_name> (type);
1390 if (reduction_list && reduction_list->elements () > 0)
1392 /* Create the fields for reductions. */
1393 reduction_list->traverse <tree, add_field_for_reduction> (type);
1395 layout_type (type);
1397 /* Create the loads and stores. */
1398 *arg_struct = create_tmp_var (type, ".paral_data_store");
1399 nvar = create_tmp_var (build_pointer_type (type), ".paral_data_load");
1400 *new_arg_struct = make_ssa_name (nvar);
1402 ld_st_data->store = *arg_struct;
1403 ld_st_data->load = *new_arg_struct;
1404 ld_st_data->store_bb = bb0;
1405 ld_st_data->load_bb = bb1;
1407 name_copies
1408 .traverse <struct clsn_data *, create_loads_and_stores_for_name>
1409 (ld_st_data);
1411 /* Load the calculation from memory (after the join of the threads). */
1413 if (reduction_list && reduction_list->elements () > 0)
1415 reduction_list
1416 ->traverse <struct clsn_data *, create_stores_for_reduction>
1417 (ld_st_data);
1418 clsn_data.load = make_ssa_name (nvar);
1419 clsn_data.load_bb = exit->dest;
1420 clsn_data.store = ld_st_data->store;
1421 create_final_loads_for_reduction (reduction_list, &clsn_data);
1426 /* Returns true if FN was created to run in parallel. */
1428 bool
1429 parallelized_function_p (tree fndecl)
1431 cgraph_node *node = cgraph_node::get (fndecl);
1432 gcc_assert (node != NULL);
1433 return node->parallelized_function;
1436 /* Creates and returns an empty function that will receive the body of
1437 a parallelized loop. */
1439 static tree
1440 create_loop_fn (location_t loc)
1442 char buf[100];
1443 char *tname;
1444 tree decl, type, name, t;
1445 struct function *act_cfun = cfun;
1446 static unsigned loopfn_num;
1448 loc = LOCATION_LOCUS (loc);
1449 snprintf (buf, 100, "%s.$loopfn", current_function_name ());
1450 ASM_FORMAT_PRIVATE_NAME (tname, buf, loopfn_num++);
1451 clean_symbol_name (tname);
1452 name = get_identifier (tname);
1453 type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
1455 decl = build_decl (loc, FUNCTION_DECL, name, type);
1456 TREE_STATIC (decl) = 1;
1457 TREE_USED (decl) = 1;
1458 DECL_ARTIFICIAL (decl) = 1;
1459 DECL_IGNORED_P (decl) = 0;
1460 TREE_PUBLIC (decl) = 0;
1461 DECL_UNINLINABLE (decl) = 1;
1462 DECL_EXTERNAL (decl) = 0;
1463 DECL_CONTEXT (decl) = NULL_TREE;
1464 DECL_INITIAL (decl) = make_node (BLOCK);
1466 t = build_decl (loc, RESULT_DECL, NULL_TREE, void_type_node);
1467 DECL_ARTIFICIAL (t) = 1;
1468 DECL_IGNORED_P (t) = 1;
1469 DECL_RESULT (decl) = t;
1471 t = build_decl (loc, PARM_DECL, get_identifier (".paral_data_param"),
1472 ptr_type_node);
1473 DECL_ARTIFICIAL (t) = 1;
1474 DECL_ARG_TYPE (t) = ptr_type_node;
1475 DECL_CONTEXT (t) = decl;
1476 TREE_USED (t) = 1;
1477 DECL_ARGUMENTS (decl) = t;
1479 allocate_struct_function (decl, false);
1481 /* The call to allocate_struct_function clobbers CFUN, so we need to restore
1482 it. */
1483 set_cfun (act_cfun);
1485 return decl;
1488 /* Replace uses of NAME by VAL in block BB. */
1490 static void
1491 replace_uses_in_bb_by (tree name, tree val, basic_block bb)
1493 gimple use_stmt;
1494 imm_use_iterator imm_iter;
1496 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, name)
1498 if (gimple_bb (use_stmt) != bb)
1499 continue;
1501 use_operand_p use_p;
1502 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
1503 SET_USE (use_p, val);
1507 /* Replace uses of NAME by VAL in blocks BBS. */
1509 static void
1510 replace_uses_in_bbs_by (tree name, tree val, bitmap bbs)
1512 gimple use_stmt;
1513 imm_use_iterator imm_iter;
1515 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, name)
1517 if (!bitmap_bit_p (bbs, gimple_bb (use_stmt)->index))
1518 continue;
1520 use_operand_p use_p;
1521 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
1522 SET_USE (use_p, val);
1526 /* Do transformation from:
1528 <bb preheader>:
1530 goto <bb header>
1532 <bb header>:
1533 ivtmp_a = PHI <ivtmp_init (preheader), ivtmp_b (latch)>
1534 sum_a = PHI <sum_init (preheader), sum_b (latch)>
1536 use (ivtmp_a)
1538 sum_b = sum_a + sum_update
1540 if (ivtmp_a < n)
1541 goto <bb latch>;
1542 else
1543 goto <bb exit>;
1545 <bb latch>:
1546 ivtmp_b = ivtmp_a + 1;
1547 goto <bb header>
1549 <bb exit>:
1550 sum_z = PHI <sum_b (cond[1])>
1552 [1] Where <bb cond> is single_pred (bb latch); In the simplest case,
1553 that's <bb header>.
1557 <bb preheader>:
1559 goto <bb newheader>
1561 <bb header>:
1562 ivtmp_a = PHI <ivtmp_c (latch)>
1563 sum_a = PHI <sum_c (latch)>
1565 use (ivtmp_a)
1567 sum_b = sum_a + sum_update
1569 goto <bb latch>;
1571 <bb newheader>:
1572 ivtmp_c = PHI <ivtmp_init (preheader), ivtmp_b (latch)>
1573 sum_c = PHI <sum_init (preheader), sum_b (latch)>
1574 if (ivtmp_c < n + 1)
1575 goto <bb header>;
1576 else
1577 goto <bb exit>;
1579 <bb latch>:
1580 ivtmp_b = ivtmp_a + 1;
1581 goto <bb newheader>
1583 <bb exit>:
1584 sum_z = PHI <sum_c (newheader)>
1587 In unified diff format:
1589 <bb preheader>:
1591 - goto <bb header>
1592 + goto <bb newheader>
1594 <bb header>:
1595 - ivtmp_a = PHI <ivtmp_init (preheader), ivtmp_b (latch)>
1596 - sum_a = PHI <sum_init (preheader), sum_b (latch)>
1597 + ivtmp_a = PHI <ivtmp_c (latch)>
1598 + sum_a = PHI <sum_c (latch)>
1600 use (ivtmp_a)
1602 sum_b = sum_a + sum_update
1604 - if (ivtmp_a < n)
1605 - goto <bb latch>;
1606 + goto <bb latch>;
1608 + <bb newheader>:
1609 + ivtmp_c = PHI <ivtmp_init (preheader), ivtmp_b (latch)>
1610 + sum_c = PHI <sum_init (preheader), sum_b (latch)>
1611 + if (ivtmp_c < n + 1)
1612 + goto <bb header>;
1613 else
1614 goto <bb exit>;
1616 <bb latch>:
1617 ivtmp_b = ivtmp_a + 1;
1618 - goto <bb header>
1619 + goto <bb newheader>
1621 <bb exit>:
1622 - sum_z = PHI <sum_b (cond[1])>
1623 + sum_z = PHI <sum_c (newheader)>
1625 Note: the example does not show any virtual phis, but these are handled more
1626 or less as reductions.
1629 Moves the exit condition of LOOP to the beginning of its header.
1630 REDUCTION_LIST describes the reductions in LOOP. BOUND is the new loop
1631 bound. */
1633 static void
1634 transform_to_exit_first_loop_alt (struct loop *loop,
1635 reduction_info_table_type *reduction_list,
1636 tree bound)
1638 basic_block header = loop->header;
1639 basic_block latch = loop->latch;
1640 edge exit = single_dom_exit (loop);
1641 basic_block exit_block = exit->dest;
1642 gcond *cond_stmt = as_a <gcond *> (last_stmt (exit->src));
1643 tree control = gimple_cond_lhs (cond_stmt);
1644 edge e;
1646 /* Gather the bbs dominated by the exit block. */
1647 bitmap exit_dominated = BITMAP_ALLOC (NULL);
1648 bitmap_set_bit (exit_dominated, exit_block->index);
1649 vec<basic_block> exit_dominated_vec
1650 = get_dominated_by (CDI_DOMINATORS, exit_block);
1652 int i;
1653 basic_block dom_bb;
1654 FOR_EACH_VEC_ELT (exit_dominated_vec, i, dom_bb)
1655 bitmap_set_bit (exit_dominated, dom_bb->index);
1657 exit_dominated_vec.release ();
1659 /* Create the new_header block. */
1660 basic_block new_header = split_block_before_cond_jump (exit->src);
1661 edge split_edge = single_pred_edge (new_header);
1663 /* Redirect entry edge to new_header. */
1664 edge entry = loop_preheader_edge (loop);
1665 e = redirect_edge_and_branch (entry, new_header);
1666 gcc_assert (e == entry);
1668 /* Redirect post_inc_edge to new_header. */
1669 edge post_inc_edge = single_succ_edge (latch);
1670 e = redirect_edge_and_branch (post_inc_edge, new_header);
1671 gcc_assert (e == post_inc_edge);
1673 /* Redirect post_cond_edge to header. */
1674 edge post_cond_edge = single_pred_edge (latch);
1675 e = redirect_edge_and_branch (post_cond_edge, header);
1676 gcc_assert (e == post_cond_edge);
1678 /* Redirect split_edge to latch. */
1679 e = redirect_edge_and_branch (split_edge, latch);
1680 gcc_assert (e == split_edge);
1682 /* Set the new loop bound. */
1683 gimple_cond_set_rhs (cond_stmt, bound);
1685 /* Repair the ssa. */
1686 vec<edge_var_map> *v = redirect_edge_var_map_vector (post_inc_edge);
1687 edge_var_map *vm;
1688 gphi_iterator gsi;
1689 for (gsi = gsi_start_phis (header), i = 0;
1690 !gsi_end_p (gsi) && v->iterate (i, &vm);
1691 gsi_next (&gsi), i++)
1693 gphi *phi = gsi.phi ();
1694 tree res_a = PHI_RESULT (phi);
1696 /* Create new phi. */
1697 tree res_c = copy_ssa_name (res_a, phi);
1698 gphi *nphi = create_phi_node (res_c, new_header);
1700 /* Replace ivtmp_a with ivtmp_c in condition 'if (ivtmp_a < n)'. */
1701 replace_uses_in_bb_by (res_a, res_c, new_header);
1703 /* Replace ivtmp/sum_b with ivtmp/sum_c in header phi. */
1704 add_phi_arg (phi, res_c, post_cond_edge, UNKNOWN_LOCATION);
1706 /* Replace sum_b with sum_c in exit phi. Loop-closed ssa does not hold
1707 for virtuals, so we cannot get away with exit_block only. */
1708 tree res_b = redirect_edge_var_map_def (vm);
1709 replace_uses_in_bbs_by (res_b, res_c, exit_dominated);
1711 struct reduction_info *red = reduction_phi (reduction_list, phi);
1712 gcc_assert (virtual_operand_p (res_a)
1713 || res_a == control
1714 || red != NULL);
1716 if (red)
1718 /* Register the new reduction phi. */
1719 red->reduc_phi = nphi;
1720 gimple_set_uid (red->reduc_phi, red->reduc_version);
1723 gcc_assert (gsi_end_p (gsi) && !v->iterate (i, &vm));
1724 BITMAP_FREE (exit_dominated);
1726 /* Set the preheader argument of the new phis to ivtmp/sum_init. */
1727 flush_pending_stmts (entry);
1729 /* Set the latch arguments of the new phis to ivtmp/sum_b. */
1730 flush_pending_stmts (post_inc_edge);
1732 /* Register the reduction exit phis. */
1733 for (gphi_iterator gsi = gsi_start_phis (exit_block);
1734 !gsi_end_p (gsi);
1735 gsi_next (&gsi))
1737 gphi *phi = gsi.phi ();
1738 tree res_z = PHI_RESULT (phi);
1739 if (virtual_operand_p (res_z))
1740 continue;
1742 tree res_c = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1743 gimple reduc_phi = SSA_NAME_DEF_STMT (res_c);
1744 struct reduction_info *red = reduction_phi (reduction_list, reduc_phi);
1745 if (red != NULL)
1746 red->keep_res = phi;
1749 /* We're going to cancel the loop at the end of gen_parallel_loop, but until
1750 then we're still using some fields, so only bother about fields that are
1751 still used: header and latch.
1752 The loop has a new header bb, so we update it. The latch bb stays the
1753 same. */
1754 loop->header = new_header;
1756 /* Recalculate dominance info. */
1757 free_dominance_info (CDI_DOMINATORS);
1758 calculate_dominance_info (CDI_DOMINATORS);
1761 /* Tries to moves the exit condition of LOOP to the beginning of its header
1762 without duplication of the loop body. NIT is the number of iterations of the
1763 loop. REDUCTION_LIST describes the reductions in LOOP. Return true if
1764 transformation is successful. */
1766 static bool
1767 try_transform_to_exit_first_loop_alt (struct loop *loop,
1768 reduction_info_table_type *reduction_list,
1769 tree nit)
1771 /* Check whether the latch contains a single statement. */
1772 if (!gimple_seq_nondebug_singleton_p (bb_seq (loop->latch)))
1773 return false;
1775 /* Check whether the latch contains the loop iv increment. */
1776 edge back = single_succ_edge (loop->latch);
1777 edge exit = single_dom_exit (loop);
1778 gcond *cond_stmt = as_a <gcond *> (last_stmt (exit->src));
1779 tree control = gimple_cond_lhs (cond_stmt);
1780 gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (control));
1781 tree inc_res = gimple_phi_arg_def (phi, back->dest_idx);
1782 if (gimple_bb (SSA_NAME_DEF_STMT (inc_res)) != loop->latch)
1783 return false;
1785 /* Check whether there's no code between the loop condition and the latch. */
1786 if (!single_pred_p (loop->latch)
1787 || single_pred (loop->latch) != exit->src)
1788 return false;
1790 tree alt_bound = NULL_TREE;
1791 tree nit_type = TREE_TYPE (nit);
1793 /* Figure out whether nit + 1 overflows. */
1794 if (TREE_CODE (nit) == INTEGER_CST)
1796 if (!tree_int_cst_equal (nit, TYPE_MAXVAL (nit_type)))
1798 alt_bound = fold_build2_loc (UNKNOWN_LOCATION, PLUS_EXPR, nit_type,
1799 nit, build_one_cst (nit_type));
1801 gcc_assert (TREE_CODE (alt_bound) == INTEGER_CST);
1803 else
1805 /* Todo: Figure out if we can trigger this, if it's worth to handle
1806 optimally, and if we can handle it optimally. */
1809 else
1811 gcc_assert (TREE_CODE (nit) == SSA_NAME);
1813 gimple def = SSA_NAME_DEF_STMT (nit);
1815 if (def
1816 && is_gimple_assign (def)
1817 && gimple_assign_rhs_code (def) == PLUS_EXPR)
1819 tree op1 = gimple_assign_rhs1 (def);
1820 tree op2 = gimple_assign_rhs2 (def);
1821 if (integer_minus_onep (op1))
1822 alt_bound = op2;
1823 else if (integer_minus_onep (op2))
1824 alt_bound = op1;
1827 /* There is a number of test-cases for which we don't get an alt_bound
1828 here: they're listed here, with the lhs of the last stmt as the nit:
1830 libgomp.graphite/force-parallel-1.c:
1831 _21 = (signed long) N_6(D);
1832 _19 = _21 + -1;
1833 _7 = (unsigned long) _19;
1835 libgomp.graphite/force-parallel-2.c:
1836 _33 = (signed long) N_9(D);
1837 _16 = _33 + -1;
1838 _37 = (unsigned long) _16;
1840 libgomp.graphite/force-parallel-5.c:
1841 <bb 6>:
1842 # graphite_IV.5_46 = PHI <0(5), graphite_IV.5_47(11)>
1843 <bb 7>:
1844 _33 = (unsigned long) graphite_IV.5_46;
1846 g++.dg/tree-ssa/pr34355.C:
1847 _2 = (unsigned int) i_9;
1848 _3 = 4 - _2;
1850 gcc.dg/pr53849.c:
1851 _5 = d.0_11 + -2;
1852 _18 = (unsigned int) _5;
1854 We will be able to handle some of these cases, if we can determine when
1855 it's safe to look past casts. */
1858 if (alt_bound == NULL_TREE)
1859 return false;
1861 transform_to_exit_first_loop_alt (loop, reduction_list, alt_bound);
1862 return true;
1865 /* Moves the exit condition of LOOP to the beginning of its header. NIT is the
1866 number of iterations of the loop. REDUCTION_LIST describes the reductions in
1867 LOOP. */
1869 static void
1870 transform_to_exit_first_loop (struct loop *loop,
1871 reduction_info_table_type *reduction_list,
1872 tree nit)
1874 basic_block *bbs, *nbbs, ex_bb, orig_header;
1875 unsigned n;
1876 bool ok;
1877 edge exit = single_dom_exit (loop), hpred;
1878 tree control, control_name, res, t;
1879 gphi *phi, *nphi;
1880 gassign *stmt;
1881 gcond *cond_stmt, *cond_nit;
1882 tree nit_1;
1884 split_block_after_labels (loop->header);
1885 orig_header = single_succ (loop->header);
1886 hpred = single_succ_edge (loop->header);
1888 cond_stmt = as_a <gcond *> (last_stmt (exit->src));
1889 control = gimple_cond_lhs (cond_stmt);
1890 gcc_assert (gimple_cond_rhs (cond_stmt) == nit);
1892 /* Make sure that we have phi nodes on exit for all loop header phis
1893 (create_parallel_loop requires that). */
1894 for (gphi_iterator gsi = gsi_start_phis (loop->header);
1895 !gsi_end_p (gsi);
1896 gsi_next (&gsi))
1898 phi = gsi.phi ();
1899 res = PHI_RESULT (phi);
1900 t = copy_ssa_name (res, phi);
1901 SET_PHI_RESULT (phi, t);
1902 nphi = create_phi_node (res, orig_header);
1903 add_phi_arg (nphi, t, hpred, UNKNOWN_LOCATION);
1905 if (res == control)
1907 gimple_cond_set_lhs (cond_stmt, t);
1908 update_stmt (cond_stmt);
1909 control = t;
1913 bbs = get_loop_body_in_dom_order (loop);
1915 for (n = 0; bbs[n] != exit->src; n++)
1916 continue;
1917 nbbs = XNEWVEC (basic_block, n);
1918 ok = gimple_duplicate_sese_tail (single_succ_edge (loop->header), exit,
1919 bbs + 1, n, nbbs);
1920 gcc_assert (ok);
1921 free (bbs);
1922 ex_bb = nbbs[0];
1923 free (nbbs);
1925 /* Other than reductions, the only gimple reg that should be copied
1926 out of the loop is the control variable. */
1927 exit = single_dom_exit (loop);
1928 control_name = NULL_TREE;
1929 for (gphi_iterator gsi = gsi_start_phis (ex_bb);
1930 !gsi_end_p (gsi); )
1932 phi = gsi.phi ();
1933 res = PHI_RESULT (phi);
1934 if (virtual_operand_p (res))
1936 gsi_next (&gsi);
1937 continue;
1940 /* Check if it is a part of reduction. If it is,
1941 keep the phi at the reduction's keep_res field. The
1942 PHI_RESULT of this phi is the resulting value of the reduction
1943 variable when exiting the loop. */
1945 if (reduction_list->elements () > 0)
1947 struct reduction_info *red;
1949 tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1950 red = reduction_phi (reduction_list, SSA_NAME_DEF_STMT (val));
1951 if (red)
1953 red->keep_res = phi;
1954 gsi_next (&gsi);
1955 continue;
1958 gcc_assert (control_name == NULL_TREE
1959 && SSA_NAME_VAR (res) == SSA_NAME_VAR (control));
1960 control_name = res;
1961 remove_phi_node (&gsi, false);
1963 gcc_assert (control_name != NULL_TREE);
1965 /* Initialize the control variable to number of iterations
1966 according to the rhs of the exit condition. */
1967 gimple_stmt_iterator gsi = gsi_after_labels (ex_bb);
1968 cond_nit = as_a <gcond *> (last_stmt (exit->src));
1969 nit_1 = gimple_cond_rhs (cond_nit);
1970 nit_1 = force_gimple_operand_gsi (&gsi,
1971 fold_convert (TREE_TYPE (control_name), nit_1),
1972 false, NULL_TREE, false, GSI_SAME_STMT);
1973 stmt = gimple_build_assign (control_name, nit_1);
1974 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1977 /* Create the parallel constructs for LOOP as described in gen_parallel_loop.
1978 LOOP_FN and DATA are the arguments of GIMPLE_OMP_PARALLEL.
1979 NEW_DATA is the variable that should be initialized from the argument
1980 of LOOP_FN. N_THREADS is the requested number of threads. Returns the
1981 basic block containing GIMPLE_OMP_PARALLEL tree. */
1983 static basic_block
1984 create_parallel_loop (struct loop *loop, tree loop_fn, tree data,
1985 tree new_data, unsigned n_threads, location_t loc)
1987 gimple_stmt_iterator gsi;
1988 basic_block bb, paral_bb, for_bb, ex_bb;
1989 tree t, param;
1990 gomp_parallel *omp_par_stmt;
1991 gimple omp_return_stmt1, omp_return_stmt2;
1992 gimple phi;
1993 gcond *cond_stmt;
1994 gomp_for *for_stmt;
1995 gomp_continue *omp_cont_stmt;
1996 tree cvar, cvar_init, initvar, cvar_next, cvar_base, type;
1997 edge exit, nexit, guard, end, e;
1999 /* Prepare the GIMPLE_OMP_PARALLEL statement. */
2000 bb = loop_preheader_edge (loop)->src;
2001 paral_bb = single_pred (bb);
2002 gsi = gsi_last_bb (paral_bb);
2004 t = build_omp_clause (loc, OMP_CLAUSE_NUM_THREADS);
2005 OMP_CLAUSE_NUM_THREADS_EXPR (t)
2006 = build_int_cst (integer_type_node, n_threads);
2007 omp_par_stmt = gimple_build_omp_parallel (NULL, t, loop_fn, data);
2008 gimple_set_location (omp_par_stmt, loc);
2010 gsi_insert_after (&gsi, omp_par_stmt, GSI_NEW_STMT);
2012 /* Initialize NEW_DATA. */
2013 if (data)
2015 gassign *assign_stmt;
2017 gsi = gsi_after_labels (bb);
2019 param = make_ssa_name (DECL_ARGUMENTS (loop_fn));
2020 assign_stmt = gimple_build_assign (param, build_fold_addr_expr (data));
2021 gsi_insert_before (&gsi, assign_stmt, GSI_SAME_STMT);
2023 assign_stmt = gimple_build_assign (new_data,
2024 fold_convert (TREE_TYPE (new_data), param));
2025 gsi_insert_before (&gsi, assign_stmt, GSI_SAME_STMT);
2028 /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_PARALLEL. */
2029 bb = split_loop_exit_edge (single_dom_exit (loop));
2030 gsi = gsi_last_bb (bb);
2031 omp_return_stmt1 = gimple_build_omp_return (false);
2032 gimple_set_location (omp_return_stmt1, loc);
2033 gsi_insert_after (&gsi, omp_return_stmt1, GSI_NEW_STMT);
2035 /* Extract data for GIMPLE_OMP_FOR. */
2036 gcc_assert (loop->header == single_dom_exit (loop)->src);
2037 cond_stmt = as_a <gcond *> (last_stmt (loop->header));
2039 cvar = gimple_cond_lhs (cond_stmt);
2040 cvar_base = SSA_NAME_VAR (cvar);
2041 phi = SSA_NAME_DEF_STMT (cvar);
2042 cvar_init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2043 initvar = copy_ssa_name (cvar);
2044 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (phi, loop_preheader_edge (loop)),
2045 initvar);
2046 cvar_next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2048 gsi = gsi_last_nondebug_bb (loop->latch);
2049 gcc_assert (gsi_stmt (gsi) == SSA_NAME_DEF_STMT (cvar_next));
2050 gsi_remove (&gsi, true);
2052 /* Prepare cfg. */
2053 for_bb = split_edge (loop_preheader_edge (loop));
2054 ex_bb = split_loop_exit_edge (single_dom_exit (loop));
2055 extract_true_false_edges_from_block (loop->header, &nexit, &exit);
2056 gcc_assert (exit == single_dom_exit (loop));
2058 guard = make_edge (for_bb, ex_bb, 0);
2059 single_succ_edge (loop->latch)->flags = 0;
2060 end = make_edge (loop->latch, ex_bb, EDGE_FALLTHRU);
2061 for (gphi_iterator gpi = gsi_start_phis (ex_bb);
2062 !gsi_end_p (gpi); gsi_next (&gpi))
2064 source_location locus;
2065 tree def;
2066 gphi *phi = gpi.phi ();
2067 gphi *stmt;
2069 stmt = as_a <gphi *> (
2070 SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, exit)));
2072 def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_preheader_edge (loop));
2073 locus = gimple_phi_arg_location_from_edge (stmt,
2074 loop_preheader_edge (loop));
2075 add_phi_arg (phi, def, guard, locus);
2077 def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_latch_edge (loop));
2078 locus = gimple_phi_arg_location_from_edge (stmt, loop_latch_edge (loop));
2079 add_phi_arg (phi, def, end, locus);
2081 e = redirect_edge_and_branch (exit, nexit->dest);
2082 PENDING_STMT (e) = NULL;
2084 /* Emit GIMPLE_OMP_FOR. */
2085 gimple_cond_set_lhs (cond_stmt, cvar_base);
2086 type = TREE_TYPE (cvar);
2087 t = build_omp_clause (loc, OMP_CLAUSE_SCHEDULE);
2088 OMP_CLAUSE_SCHEDULE_KIND (t) = OMP_CLAUSE_SCHEDULE_STATIC;
2090 for_stmt = gimple_build_omp_for (NULL, GF_OMP_FOR_KIND_FOR, t, 1, NULL);
2091 gimple_set_location (for_stmt, loc);
2092 gimple_omp_for_set_index (for_stmt, 0, initvar);
2093 gimple_omp_for_set_initial (for_stmt, 0, cvar_init);
2094 gimple_omp_for_set_final (for_stmt, 0, gimple_cond_rhs (cond_stmt));
2095 gimple_omp_for_set_cond (for_stmt, 0, gimple_cond_code (cond_stmt));
2096 gimple_omp_for_set_incr (for_stmt, 0, build2 (PLUS_EXPR, type,
2097 cvar_base,
2098 build_int_cst (type, 1)));
2100 gsi = gsi_last_bb (for_bb);
2101 gsi_insert_after (&gsi, for_stmt, GSI_NEW_STMT);
2102 SSA_NAME_DEF_STMT (initvar) = for_stmt;
2104 /* Emit GIMPLE_OMP_CONTINUE. */
2105 gsi = gsi_last_bb (loop->latch);
2106 omp_cont_stmt = gimple_build_omp_continue (cvar_next, cvar);
2107 gimple_set_location (omp_cont_stmt, loc);
2108 gsi_insert_after (&gsi, omp_cont_stmt, GSI_NEW_STMT);
2109 SSA_NAME_DEF_STMT (cvar_next) = omp_cont_stmt;
2111 /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_FOR. */
2112 gsi = gsi_last_bb (ex_bb);
2113 omp_return_stmt2 = gimple_build_omp_return (true);
2114 gimple_set_location (omp_return_stmt2, loc);
2115 gsi_insert_after (&gsi, omp_return_stmt2, GSI_NEW_STMT);
2117 /* After the above dom info is hosed. Re-compute it. */
2118 free_dominance_info (CDI_DOMINATORS);
2119 calculate_dominance_info (CDI_DOMINATORS);
2121 return paral_bb;
2124 /* Generates code to execute the iterations of LOOP in N_THREADS
2125 threads in parallel.
2127 NITER describes number of iterations of LOOP.
2128 REDUCTION_LIST describes the reductions existent in the LOOP. */
2130 static void
2131 gen_parallel_loop (struct loop *loop,
2132 reduction_info_table_type *reduction_list,
2133 unsigned n_threads, struct tree_niter_desc *niter)
2135 tree many_iterations_cond, type, nit;
2136 tree arg_struct, new_arg_struct;
2137 gimple_seq stmts;
2138 edge entry, exit;
2139 struct clsn_data clsn_data;
2140 unsigned prob;
2141 location_t loc;
2142 gimple cond_stmt;
2143 unsigned int m_p_thread=2;
2145 /* From
2147 ---------------------------------------------------------------------
2148 loop
2150 IV = phi (INIT, IV + STEP)
2151 BODY1;
2152 if (COND)
2153 break;
2154 BODY2;
2156 ---------------------------------------------------------------------
2158 with # of iterations NITER (possibly with MAY_BE_ZERO assumption),
2159 we generate the following code:
2161 ---------------------------------------------------------------------
2163 if (MAY_BE_ZERO
2164 || NITER < MIN_PER_THREAD * N_THREADS)
2165 goto original;
2167 BODY1;
2168 store all local loop-invariant variables used in body of the loop to DATA.
2169 GIMPLE_OMP_PARALLEL (OMP_CLAUSE_NUM_THREADS (N_THREADS), LOOPFN, DATA);
2170 load the variables from DATA.
2171 GIMPLE_OMP_FOR (IV = INIT; COND; IV += STEP) (OMP_CLAUSE_SCHEDULE (static))
2172 BODY2;
2173 BODY1;
2174 GIMPLE_OMP_CONTINUE;
2175 GIMPLE_OMP_RETURN -- GIMPLE_OMP_FOR
2176 GIMPLE_OMP_RETURN -- GIMPLE_OMP_PARALLEL
2177 goto end;
2179 original:
2180 loop
2182 IV = phi (INIT, IV + STEP)
2183 BODY1;
2184 if (COND)
2185 break;
2186 BODY2;
2189 end:
2193 /* Create two versions of the loop -- in the old one, we know that the
2194 number of iterations is large enough, and we will transform it into the
2195 loop that will be split to loop_fn, the new one will be used for the
2196 remaining iterations. */
2198 /* We should compute a better number-of-iterations value for outer loops.
2199 That is, if we have
2201 for (i = 0; i < n; ++i)
2202 for (j = 0; j < m; ++j)
2205 we should compute nit = n * m, not nit = n.
2206 Also may_be_zero handling would need to be adjusted. */
2208 type = TREE_TYPE (niter->niter);
2209 nit = force_gimple_operand (unshare_expr (niter->niter), &stmts, true,
2210 NULL_TREE);
2211 if (stmts)
2212 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
2214 if (loop->inner)
2215 m_p_thread=2;
2216 else
2217 m_p_thread=MIN_PER_THREAD;
2219 many_iterations_cond =
2220 fold_build2 (GE_EXPR, boolean_type_node,
2221 nit, build_int_cst (type, m_p_thread * n_threads));
2223 many_iterations_cond
2224 = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
2225 invert_truthvalue (unshare_expr (niter->may_be_zero)),
2226 many_iterations_cond);
2227 many_iterations_cond
2228 = force_gimple_operand (many_iterations_cond, &stmts, false, NULL_TREE);
2229 if (stmts)
2230 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
2231 if (!is_gimple_condexpr (many_iterations_cond))
2233 many_iterations_cond
2234 = force_gimple_operand (many_iterations_cond, &stmts,
2235 true, NULL_TREE);
2236 if (stmts)
2237 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
2240 initialize_original_copy_tables ();
2242 /* We assume that the loop usually iterates a lot. */
2243 prob = 4 * REG_BR_PROB_BASE / 5;
2244 loop_version (loop, many_iterations_cond, NULL,
2245 prob, prob, REG_BR_PROB_BASE - prob, true);
2246 update_ssa (TODO_update_ssa);
2247 free_original_copy_tables ();
2249 /* Base all the induction variables in LOOP on a single control one. */
2250 canonicalize_loop_ivs (loop, &nit, true);
2252 /* Ensure that the exit condition is the first statement in the loop.
2253 The common case is that latch of the loop is empty (apart from the
2254 increment) and immediately follows the loop exit test. Attempt to move the
2255 entry of the loop directly before the exit check and increase the number of
2256 iterations of the loop by one. */
2257 if (!try_transform_to_exit_first_loop_alt (loop, reduction_list, nit))
2259 /* Fall back on the method that handles more cases, but duplicates the
2260 loop body: move the exit condition of LOOP to the beginning of its
2261 header, and duplicate the part of the last iteration that gets disabled
2262 to the exit of the loop. */
2263 transform_to_exit_first_loop (loop, reduction_list, nit);
2266 /* Generate initializations for reductions. */
2267 if (reduction_list->elements () > 0)
2268 reduction_list->traverse <struct loop *, initialize_reductions> (loop);
2270 /* Eliminate the references to local variables from the loop. */
2271 gcc_assert (single_exit (loop));
2272 entry = loop_preheader_edge (loop);
2273 exit = single_dom_exit (loop);
2275 eliminate_local_variables (entry, exit);
2276 /* In the old loop, move all variables non-local to the loop to a structure
2277 and back, and create separate decls for the variables used in loop. */
2278 separate_decls_in_region (entry, exit, reduction_list, &arg_struct,
2279 &new_arg_struct, &clsn_data);
2281 /* Create the parallel constructs. */
2282 loc = UNKNOWN_LOCATION;
2283 cond_stmt = last_stmt (loop->header);
2284 if (cond_stmt)
2285 loc = gimple_location (cond_stmt);
2286 create_parallel_loop (loop, create_loop_fn (loc), arg_struct,
2287 new_arg_struct, n_threads, loc);
2288 if (reduction_list->elements () > 0)
2289 create_call_for_reduction (loop, reduction_list, &clsn_data);
2291 scev_reset ();
2293 /* Cancel the loop (it is simpler to do it here rather than to teach the
2294 expander to do it). */
2295 cancel_loop_tree (loop);
2297 /* Free loop bound estimations that could contain references to
2298 removed statements. */
2299 FOR_EACH_LOOP (loop, 0)
2300 free_numbers_of_iterations_estimates_loop (loop);
2303 /* Returns true when LOOP contains vector phi nodes. */
2305 static bool
2306 loop_has_vector_phi_nodes (struct loop *loop ATTRIBUTE_UNUSED)
2308 unsigned i;
2309 basic_block *bbs = get_loop_body_in_dom_order (loop);
2310 gphi_iterator gsi;
2311 bool res = true;
2313 for (i = 0; i < loop->num_nodes; i++)
2314 for (gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi); gsi_next (&gsi))
2315 if (TREE_CODE (TREE_TYPE (PHI_RESULT (gsi.phi ()))) == VECTOR_TYPE)
2316 goto end;
2318 res = false;
2319 end:
2320 free (bbs);
2321 return res;
2324 /* Create a reduction_info struct, initialize it with REDUC_STMT
2325 and PHI, insert it to the REDUCTION_LIST. */
2327 static void
2328 build_new_reduction (reduction_info_table_type *reduction_list,
2329 gimple reduc_stmt, gphi *phi)
2331 reduction_info **slot;
2332 struct reduction_info *new_reduction;
2334 gcc_assert (reduc_stmt);
2336 if (dump_file && (dump_flags & TDF_DETAILS))
2338 fprintf (dump_file,
2339 "Detected reduction. reduction stmt is: \n");
2340 print_gimple_stmt (dump_file, reduc_stmt, 0, 0);
2341 fprintf (dump_file, "\n");
2344 new_reduction = XCNEW (struct reduction_info);
2346 new_reduction->reduc_stmt = reduc_stmt;
2347 new_reduction->reduc_phi = phi;
2348 new_reduction->reduc_version = SSA_NAME_VERSION (gimple_phi_result (phi));
2349 new_reduction->reduction_code = gimple_assign_rhs_code (reduc_stmt);
2350 slot = reduction_list->find_slot (new_reduction, INSERT);
2351 *slot = new_reduction;
2354 /* Callback for htab_traverse. Sets gimple_uid of reduc_phi stmts. */
2357 set_reduc_phi_uids (reduction_info **slot, void *data ATTRIBUTE_UNUSED)
2359 struct reduction_info *const red = *slot;
2360 gimple_set_uid (red->reduc_phi, red->reduc_version);
2361 return 1;
2364 /* Detect all reductions in the LOOP, insert them into REDUCTION_LIST. */
2366 static void
2367 gather_scalar_reductions (loop_p loop, reduction_info_table_type *reduction_list)
2369 gphi_iterator gsi;
2370 loop_vec_info simple_loop_info;
2372 simple_loop_info = vect_analyze_loop_form (loop);
2374 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
2376 gphi *phi = gsi.phi ();
2377 affine_iv iv;
2378 tree res = PHI_RESULT (phi);
2379 bool double_reduc;
2381 if (virtual_operand_p (res))
2382 continue;
2384 if (!simple_iv (loop, loop, res, &iv, true)
2385 && simple_loop_info)
2387 gimple reduc_stmt = vect_force_simple_reduction (simple_loop_info,
2388 phi, true,
2389 &double_reduc);
2390 if (reduc_stmt && !double_reduc)
2391 build_new_reduction (reduction_list, reduc_stmt, phi);
2394 destroy_loop_vec_info (simple_loop_info, true);
2396 /* As gimple_uid is used by the vectorizer in between vect_analyze_loop_form
2397 and destroy_loop_vec_info, we can set gimple_uid of reduc_phi stmts
2398 only now. */
2399 reduction_list->traverse <void *, set_reduc_phi_uids> (NULL);
2402 /* Try to initialize NITER for code generation part. */
2404 static bool
2405 try_get_loop_niter (loop_p loop, struct tree_niter_desc *niter)
2407 edge exit = single_dom_exit (loop);
2409 gcc_assert (exit);
2411 /* We need to know # of iterations, and there should be no uses of values
2412 defined inside loop outside of it, unless the values are invariants of
2413 the loop. */
2414 if (!number_of_iterations_exit (loop, exit, niter, false))
2416 if (dump_file && (dump_flags & TDF_DETAILS))
2417 fprintf (dump_file, " FAILED: number of iterations not known\n");
2418 return false;
2421 return true;
2424 /* Try to initialize REDUCTION_LIST for code generation part.
2425 REDUCTION_LIST describes the reductions. */
2427 static bool
2428 try_create_reduction_list (loop_p loop,
2429 reduction_info_table_type *reduction_list)
2431 edge exit = single_dom_exit (loop);
2432 gphi_iterator gsi;
2434 gcc_assert (exit);
2436 gather_scalar_reductions (loop, reduction_list);
2439 for (gsi = gsi_start_phis (exit->dest); !gsi_end_p (gsi); gsi_next (&gsi))
2441 gphi *phi = gsi.phi ();
2442 struct reduction_info *red;
2443 imm_use_iterator imm_iter;
2444 use_operand_p use_p;
2445 gimple reduc_phi;
2446 tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
2448 if (!virtual_operand_p (val))
2450 if (dump_file && (dump_flags & TDF_DETAILS))
2452 fprintf (dump_file, "phi is ");
2453 print_gimple_stmt (dump_file, phi, 0, 0);
2454 fprintf (dump_file, "arg of phi to exit: value ");
2455 print_generic_expr (dump_file, val, 0);
2456 fprintf (dump_file, " used outside loop\n");
2457 fprintf (dump_file,
2458 " checking if it a part of reduction pattern: \n");
2460 if (reduction_list->elements () == 0)
2462 if (dump_file && (dump_flags & TDF_DETAILS))
2463 fprintf (dump_file,
2464 " FAILED: it is not a part of reduction.\n");
2465 return false;
2467 reduc_phi = NULL;
2468 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, val)
2470 if (!gimple_debug_bind_p (USE_STMT (use_p))
2471 && flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
2473 reduc_phi = USE_STMT (use_p);
2474 break;
2477 red = reduction_phi (reduction_list, reduc_phi);
2478 if (red == NULL)
2480 if (dump_file && (dump_flags & TDF_DETAILS))
2481 fprintf (dump_file,
2482 " FAILED: it is not a part of reduction.\n");
2483 return false;
2485 if (dump_file && (dump_flags & TDF_DETAILS))
2487 fprintf (dump_file, "reduction phi is ");
2488 print_gimple_stmt (dump_file, red->reduc_phi, 0, 0);
2489 fprintf (dump_file, "reduction stmt is ");
2490 print_gimple_stmt (dump_file, red->reduc_stmt, 0, 0);
2495 /* The iterations of the loop may communicate only through bivs whose
2496 iteration space can be distributed efficiently. */
2497 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
2499 gphi *phi = gsi.phi ();
2500 tree def = PHI_RESULT (phi);
2501 affine_iv iv;
2503 if (!virtual_operand_p (def) && !simple_iv (loop, loop, def, &iv, true))
2505 struct reduction_info *red;
2507 red = reduction_phi (reduction_list, phi);
2508 if (red == NULL)
2510 if (dump_file && (dump_flags & TDF_DETAILS))
2511 fprintf (dump_file,
2512 " FAILED: scalar dependency between iterations\n");
2513 return false;
2519 return true;
2522 /* Detect parallel loops and generate parallel code using libgomp
2523 primitives. Returns true if some loop was parallelized, false
2524 otherwise. */
2526 static bool
2527 parallelize_loops (void)
2529 unsigned n_threads = flag_tree_parallelize_loops;
2530 bool changed = false;
2531 struct loop *loop;
2532 struct tree_niter_desc niter_desc;
2533 struct obstack parloop_obstack;
2534 HOST_WIDE_INT estimated;
2535 source_location loop_loc;
2537 /* Do not parallelize loops in the functions created by parallelization. */
2538 if (parallelized_function_p (cfun->decl))
2539 return false;
2540 if (cfun->has_nonlocal_label)
2541 return false;
2543 gcc_obstack_init (&parloop_obstack);
2544 reduction_info_table_type reduction_list (10);
2545 init_stmt_vec_info_vec ();
2547 FOR_EACH_LOOP (loop, 0)
2549 reduction_list.empty ();
2550 if (dump_file && (dump_flags & TDF_DETAILS))
2552 fprintf (dump_file, "Trying loop %d as candidate\n",loop->num);
2553 if (loop->inner)
2554 fprintf (dump_file, "loop %d is not innermost\n",loop->num);
2555 else
2556 fprintf (dump_file, "loop %d is innermost\n",loop->num);
2559 /* If we use autopar in graphite pass, we use its marked dependency
2560 checking results. */
2561 if (flag_loop_parallelize_all && !loop->can_be_parallel)
2563 if (dump_file && (dump_flags & TDF_DETAILS))
2564 fprintf (dump_file, "loop is not parallel according to graphite\n");
2565 continue;
2568 if (!single_dom_exit (loop))
2571 if (dump_file && (dump_flags & TDF_DETAILS))
2572 fprintf (dump_file, "loop is !single_dom_exit\n");
2574 continue;
2577 if (/* And of course, the loop must be parallelizable. */
2578 !can_duplicate_loop_p (loop)
2579 || loop_has_blocks_with_irreducible_flag (loop)
2580 || (loop_preheader_edge (loop)->src->flags & BB_IRREDUCIBLE_LOOP)
2581 /* FIXME: the check for vector phi nodes could be removed. */
2582 || loop_has_vector_phi_nodes (loop))
2583 continue;
2585 estimated = estimated_stmt_executions_int (loop);
2586 if (estimated == -1)
2587 estimated = max_stmt_executions_int (loop);
2588 /* FIXME: Bypass this check as graphite doesn't update the
2589 count and frequency correctly now. */
2590 if (!flag_loop_parallelize_all
2591 && ((estimated != -1
2592 && estimated <= (HOST_WIDE_INT) n_threads * MIN_PER_THREAD)
2593 /* Do not bother with loops in cold areas. */
2594 || optimize_loop_nest_for_size_p (loop)))
2595 continue;
2597 if (!try_get_loop_niter (loop, &niter_desc))
2598 continue;
2600 if (!try_create_reduction_list (loop, &reduction_list))
2601 continue;
2603 if (!flag_loop_parallelize_all
2604 && !loop_parallel_p (loop, &parloop_obstack))
2605 continue;
2607 changed = true;
2608 if (dump_file && (dump_flags & TDF_DETAILS))
2610 if (loop->inner)
2611 fprintf (dump_file, "parallelizing outer loop %d\n",loop->header->index);
2612 else
2613 fprintf (dump_file, "parallelizing inner loop %d\n",loop->header->index);
2614 loop_loc = find_loop_location (loop);
2615 if (loop_loc != UNKNOWN_LOCATION)
2616 fprintf (dump_file, "\nloop at %s:%d: ",
2617 LOCATION_FILE (loop_loc), LOCATION_LINE (loop_loc));
2619 gen_parallel_loop (loop, &reduction_list,
2620 n_threads, &niter_desc);
2623 free_stmt_vec_info_vec ();
2624 obstack_free (&parloop_obstack, NULL);
2626 /* Parallelization will cause new function calls to be inserted through
2627 which local variables will escape. Reset the points-to solution
2628 for ESCAPED. */
2629 if (changed)
2630 pt_solution_reset (&cfun->gimple_df->escaped);
2632 return changed;
2635 /* Parallelization. */
2637 namespace {
2639 const pass_data pass_data_parallelize_loops =
2641 GIMPLE_PASS, /* type */
2642 "parloops", /* name */
2643 OPTGROUP_LOOP, /* optinfo_flags */
2644 TV_TREE_PARALLELIZE_LOOPS, /* tv_id */
2645 ( PROP_cfg | PROP_ssa ), /* properties_required */
2646 0, /* properties_provided */
2647 0, /* properties_destroyed */
2648 0, /* todo_flags_start */
2649 0, /* todo_flags_finish */
2652 class pass_parallelize_loops : public gimple_opt_pass
2654 public:
2655 pass_parallelize_loops (gcc::context *ctxt)
2656 : gimple_opt_pass (pass_data_parallelize_loops, ctxt)
2659 /* opt_pass methods: */
2660 virtual bool gate (function *) { return flag_tree_parallelize_loops > 1; }
2661 virtual unsigned int execute (function *);
2663 }; // class pass_parallelize_loops
2665 unsigned
2666 pass_parallelize_loops::execute (function *fun)
2668 if (number_of_loops (fun) <= 1)
2669 return 0;
2671 if (parallelize_loops ())
2673 fun->curr_properties &= ~(PROP_gimple_eomp);
2674 return TODO_update_ssa;
2677 return 0;
2680 } // anon namespace
2682 gimple_opt_pass *
2683 make_pass_parallelize_loops (gcc::context *ctxt)
2685 return new pass_parallelize_loops (ctxt);