OSDN Git Service

3c9a1d2826ad30862ed39d9f625d01b84481856f
[pf3gnuchains/gcc-fork.git] / gcc / tree-parloops.c
1 /* Loop autoparallelization.
2    Copyright (C) 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Sebastian Pop <pop@cri.ensmp.fr> and
5    Zdenek Dvorak <dvorakz@suse.cz>.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "tree.h"
28 #include "tree-flow.h"
29 #include "cfgloop.h"
30 #include "tree-data-ref.h"
31 #include "diagnostic.h"
32 #include "tree-pass.h"
33 #include "tree-scalar-evolution.h"
34 #include "hashtab.h"
35 #include "langhooks.h"
36 #include "tree-vectorizer.h"
37
38 /* This pass tries to distribute iterations of loops into several threads.
39    The implementation is straightforward -- for each loop we test whether its
40    iterations are independent, and if it is the case (and some additional
41    conditions regarding profitability and correctness are satisfied), we
42    add GIMPLE_OMP_PARALLEL and GIMPLE_OMP_FOR codes and let omp expansion
43    machinery do its job.
44
45    The most of the complexity is in bringing the code into shape expected
46    by the omp expanders:
47    -- for GIMPLE_OMP_FOR, ensuring that the loop has only one induction
48       variable and that the exit test is at the start of the loop body
49    -- for GIMPLE_OMP_PARALLEL, replacing the references to local addressable
50       variables by accesses through pointers, and breaking up ssa chains
51       by storing the values incoming to the parallelized loop to a structure
52       passed to the new function as an argument (something similar is done
53       in omp gimplification, unfortunately only a small part of the code
54       can be shared).
55
56    TODO:
57    -- if there are several parallelizable loops in a function, it may be
58       possible to generate the threads just once (using synchronization to
59       ensure that cross-loop dependences are obeyed).
60    -- handling of common scalar dependence patterns (accumulation, ...)
61    -- handling of non-innermost loops  */
62
63 /*
64   Reduction handling:
65   currently we use vect_force_simple_reduction() to detect reduction patterns.
66   The code transformation will be introduced by an example.
67
68
69 parloop
70 {
71   int sum=1;
72
73   for (i = 0; i < N; i++)
74    {
75     x[i] = i + 3;
76     sum+=x[i];
77    }
78 }
79
80 gimple-like code:
81 header_bb:
82
83   # sum_29 = PHI <sum_11(5), 1(3)>
84   # i_28 = PHI <i_12(5), 0(3)>
85   D.1795_8 = i_28 + 3;
86   x[i_28] = D.1795_8;
87   sum_11 = D.1795_8 + sum_29;
88   i_12 = i_28 + 1;
89   if (N_6(D) > i_12)
90     goto header_bb;
91
92
93 exit_bb:
94
95   # sum_21 = PHI <sum_11(4)>
96   printf (&"%d"[0], sum_21);
97
98
99 after reduction transformation (only relevant parts):
100
101 parloop
102 {
103
104 ....
105
106
107   # Storing the initial value given by the user.  #
108
109   .paral_data_store.32.sum.27 = 1;
110
111   #pragma omp parallel num_threads(4)
112
113   #pragma omp for schedule(static)
114
115   # The neutral element corresponding to the particular
116   reduction's operation, e.g. 0 for PLUS_EXPR,
117   1 for MULT_EXPR, etc. replaces the user's initial value.  #
118
119   # sum.27_29 = PHI <sum.27_11, 0>
120
121   sum.27_11 = D.1827_8 + sum.27_29;
122
123   GIMPLE_OMP_CONTINUE
124
125   # Adding this reduction phi is done at create_phi_for_local_result() #
126   # sum.27_56 = PHI <sum.27_11, 0>
127   GIMPLE_OMP_RETURN
128
129   # Creating the atomic operation is done at
130   create_call_for_reduction_1()  #
131
132   #pragma omp atomic_load
133   D.1839_59 = *&.paral_data_load.33_51->reduction.23;
134   D.1840_60 = sum.27_56 + D.1839_59;
135   #pragma omp atomic_store (D.1840_60);
136
137   GIMPLE_OMP_RETURN
138
139  # collecting the result after the join of the threads is done at
140   create_loads_for_reductions().
141   The value computed by the threads is loaded from the
142   shared struct.  #
143
144
145   .paral_data_load.33_52 = &.paral_data_store.32;
146   sum_37 =  .paral_data_load.33_52->sum.27;
147   sum_43 = D.1795_41 + sum_37;
148
149   exit bb:
150   # sum_21 = PHI <sum_43, sum_26>
151   printf (&"%d"[0], sum_21);
152
153 ...
154
155 }
156
157 */
158
159 /* Minimal number of iterations of a loop that should be executed in each
160    thread.  */
161 #define MIN_PER_THREAD 100
162
163 /* Element of the hashtable, representing a
164    reduction in the current loop.  */
165 struct reduction_info
166 {
167   gimple reduc_stmt;            /* reduction statement.  */
168   gimple reduc_phi;             /* The phi node defining the reduction.  */
169   enum tree_code reduction_code;/* code for the reduction operation.  */
170   gimple keep_res;              /* The PHI_RESULT of this phi is the resulting value
171                                    of the reduction variable when existing the loop. */
172   tree initial_value;           /* The initial value of the reduction var before entering the loop.  */
173   tree field;                   /*  the name of the field in the parloop data structure intended for reduction.  */
174   tree init;                    /* reduction initialization value.  */
175   gimple new_phi;               /* (helper field) Newly created phi node whose result
176                                    will be passed to the atomic operation.  Represents
177                                    the local result each thread computed for the reduction
178                                    operation.  */
179 };
180
181 /* Equality and hash functions for hashtab code.  */
182
183 static int
184 reduction_info_eq (const void *aa, const void *bb)
185 {
186   const struct reduction_info *a = (const struct reduction_info *) aa;
187   const struct reduction_info *b = (const struct reduction_info *) bb;
188
189   return (a->reduc_phi == b->reduc_phi);
190 }
191
192 static hashval_t
193 reduction_info_hash (const void *aa)
194 {
195   const struct reduction_info *a = (const struct reduction_info *) aa;
196
197   return htab_hash_pointer (a->reduc_phi);
198 }
199
200 static struct reduction_info *
201 reduction_phi (htab_t reduction_list, gimple phi)
202 {
203   struct reduction_info tmpred, *red;
204
205   if (htab_elements (reduction_list) == 0)
206     return NULL;
207
208   tmpred.reduc_phi = phi;
209   red = (struct reduction_info *) htab_find (reduction_list, &tmpred);
210
211   return red;
212 }
213
214 /* Element of hashtable of names to copy.  */
215
216 struct name_to_copy_elt
217 {
218   unsigned version;     /* The version of the name to copy.  */
219   tree new_name;        /* The new name used in the copy.  */
220   tree field;           /* The field of the structure used to pass the
221                            value.  */
222 };
223
224 /* Equality and hash functions for hashtab code.  */
225
226 static int
227 name_to_copy_elt_eq (const void *aa, const void *bb)
228 {
229   const struct name_to_copy_elt *a = (const struct name_to_copy_elt *) aa;
230   const struct name_to_copy_elt *b = (const struct name_to_copy_elt *) bb;
231
232   return a->version == b->version;
233 }
234
235 static hashval_t
236 name_to_copy_elt_hash (const void *aa)
237 {
238   const struct name_to_copy_elt *a = (const struct name_to_copy_elt *) aa;
239
240   return (hashval_t) a->version;
241 }
242
243
244 /* Data dependency analysis. Returns true if the iterations of LOOP
245    are independent on each other (that is, if we can execute them
246    in parallel).  */
247
248 static bool
249 loop_parallel_p (struct loop *loop, struct obstack * parloop_obstack)
250 {
251   VEC (ddr_p, heap) * dependence_relations;
252   VEC (data_reference_p, heap) *datarefs;
253   lambda_trans_matrix trans;
254   bool ret = false;
255
256   if (dump_file && (dump_flags & TDF_DETAILS))
257   {
258     fprintf (dump_file, "Considering loop %d\n", loop->num);
259     if (!loop->inner)
260       fprintf (dump_file, "loop is innermost\n");
261     else
262       fprintf (dump_file, "loop NOT innermost\n");
263    }
264
265   /* Check for problems with dependences.  If the loop can be reversed,
266      the iterations are independent.  */
267   datarefs = VEC_alloc (data_reference_p, heap, 10);
268   dependence_relations = VEC_alloc (ddr_p, heap, 10 * 10);
269   compute_data_dependences_for_loop (loop, true, &datarefs,
270                                      &dependence_relations);
271   if (dump_file && (dump_flags & TDF_DETAILS))
272     dump_data_dependence_relations (dump_file, dependence_relations);
273
274   trans = lambda_trans_matrix_new (1, 1, parloop_obstack);
275   LTM_MATRIX (trans)[0][0] = -1;
276
277   if (lambda_transform_legal_p (trans, 1, dependence_relations))
278     {
279       ret = true;
280       if (dump_file && (dump_flags & TDF_DETAILS))
281         fprintf (dump_file, "  SUCCESS: may be parallelized\n");
282     }
283   else if (dump_file && (dump_flags & TDF_DETAILS))
284     fprintf (dump_file,
285              "  FAILED: data dependencies exist across iterations\n");
286
287   free_dependence_relations (dependence_relations);
288   free_data_refs (datarefs);
289
290   return ret;
291 }
292
293 /* Return true when LOOP contains basic blocks marked with the
294    BB_IRREDUCIBLE_LOOP flag.  */
295
296 static inline bool
297 loop_has_blocks_with_irreducible_flag (struct loop *loop)
298 {
299   unsigned i;
300   basic_block *bbs = get_loop_body_in_dom_order (loop);
301   bool res = true;
302
303   for (i = 0; i < loop->num_nodes; i++)
304     if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP)
305       goto end;
306
307   res = false;
308  end:
309   free (bbs);
310   return res;
311 }
312
313 /* Assigns the address of OBJ in TYPE to an ssa name, and returns this name.
314    The assignment statement is placed on edge ENTRY.  DECL_ADDRESS maps decls
315    to their addresses that can be reused.  The address of OBJ is known to
316    be invariant in the whole function.  */
317
318 static tree
319 take_address_of (tree obj, tree type, edge entry, htab_t decl_address)
320 {
321   int uid;
322   void **dslot;
323   struct int_tree_map ielt, *nielt;
324   tree *var_p, name, bvar, addr;
325   gimple stmt;
326   gimple_seq stmts;
327
328   /* Since the address of OBJ is invariant, the trees may be shared.
329      Avoid rewriting unrelated parts of the code.  */
330   obj = unshare_expr (obj);
331   for (var_p = &obj;
332        handled_component_p (*var_p);
333        var_p = &TREE_OPERAND (*var_p, 0))
334     continue;
335   uid = DECL_UID (*var_p);
336
337   ielt.uid = uid;
338   dslot = htab_find_slot_with_hash (decl_address, &ielt, uid, INSERT);
339   if (!*dslot)
340     {
341       addr = build_addr (*var_p, current_function_decl);
342       bvar = create_tmp_var (TREE_TYPE (addr), get_name (*var_p));
343       add_referenced_var (bvar);
344       stmt = gimple_build_assign (bvar, addr);
345       name = make_ssa_name (bvar, stmt);
346       gimple_assign_set_lhs (stmt, name);
347       gsi_insert_on_edge_immediate (entry, stmt);
348
349       nielt = XNEW (struct int_tree_map);
350       nielt->uid = uid;
351       nielt->to = name;
352       *dslot = nielt;
353     }
354   else
355     name = ((struct int_tree_map *) *dslot)->to;
356
357   if (var_p != &obj)
358     {
359       *var_p = build1 (INDIRECT_REF, TREE_TYPE (*var_p), name);
360       name = force_gimple_operand (build_addr (obj, current_function_decl),
361                                    &stmts, true, NULL_TREE);
362       if (!gimple_seq_empty_p (stmts))
363         gsi_insert_seq_on_edge_immediate (entry, stmts);
364     }
365
366   if (TREE_TYPE (name) != type)
367     {
368       name = force_gimple_operand (fold_convert (type, name), &stmts, true,
369                                    NULL_TREE);
370       if (!gimple_seq_empty_p (stmts))
371         gsi_insert_seq_on_edge_immediate (entry, stmts);
372     }
373
374   return name;
375 }
376
377 /* Callback for htab_traverse.  Create the initialization statement
378    for reduction described in SLOT, and place it at the preheader of
379    the loop described in DATA.  */
380
381 static int
382 initialize_reductions (void **slot, void *data)
383 {
384   tree init, c;
385   tree bvar, type, arg;
386   edge e;
387
388   struct reduction_info *const reduc = (struct reduction_info *) *slot;
389   struct loop *loop = (struct loop *) data;
390
391   /* Create initialization in preheader:
392      reduction_variable = initialization value of reduction.  */
393
394   /* In the phi node at the header, replace the argument coming
395      from the preheader with the reduction initialization value.  */
396
397   /* Create a new variable to initialize the reduction.  */
398   type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
399   bvar = create_tmp_var (type, "reduction");
400   add_referenced_var (bvar);
401
402   c = build_omp_clause (gimple_location (reduc->reduc_stmt),
403                         OMP_CLAUSE_REDUCTION);
404   OMP_CLAUSE_REDUCTION_CODE (c) = reduc->reduction_code;
405   OMP_CLAUSE_DECL (c) = SSA_NAME_VAR (gimple_assign_lhs (reduc->reduc_stmt));
406
407   init = omp_reduction_init (c, TREE_TYPE (bvar));
408   reduc->init = init;
409
410   /* Replace the argument representing the initialization value
411      with the initialization value for the reduction (neutral
412      element for the particular operation, e.g. 0 for PLUS_EXPR,
413      1 for MULT_EXPR, etc).
414      Keep the old value in a new variable "reduction_initial",
415      that will be taken in consideration after the parallel
416      computing is done.  */
417
418   e = loop_preheader_edge (loop);
419   arg = PHI_ARG_DEF_FROM_EDGE (reduc->reduc_phi, e);
420   /* Create new variable to hold the initial value.  */
421
422   SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE
423            (reduc->reduc_phi, loop_preheader_edge (loop)), init);
424   reduc->initial_value = arg;
425   return 1;
426 }
427
428 struct elv_data
429 {
430   struct walk_stmt_info info;
431   edge entry;
432   htab_t decl_address;
433   bool changed;
434 };
435
436 /* Eliminates references to local variables in *TP out of the single
437    entry single exit region starting at DTA->ENTRY.
438    DECL_ADDRESS contains addresses of the references that had their
439    address taken already.  If the expression is changed, CHANGED is
440    set to true.  Callback for walk_tree.  */
441
442 static tree
443 eliminate_local_variables_1 (tree *tp, int *walk_subtrees, void *data)
444 {
445   struct elv_data *const dta = (struct elv_data *) data;
446   tree t = *tp, var, addr, addr_type, type, obj;
447
448   if (DECL_P (t))
449     {
450       *walk_subtrees = 0;
451
452       if (!SSA_VAR_P (t) || DECL_EXTERNAL (t))
453         return NULL_TREE;
454
455       type = TREE_TYPE (t);
456       addr_type = build_pointer_type (type);
457       addr = take_address_of (t, addr_type, dta->entry, dta->decl_address);
458       *tp = build1 (INDIRECT_REF, TREE_TYPE (*tp), addr);
459
460       dta->changed = true;
461       return NULL_TREE;
462     }
463
464   if (TREE_CODE (t) == ADDR_EXPR)
465     {
466       /* ADDR_EXPR may appear in two contexts:
467          -- as a gimple operand, when the address taken is a function invariant
468          -- as gimple rhs, when the resulting address in not a function
469             invariant
470          We do not need to do anything special in the latter case (the base of
471          the memory reference whose address is taken may be replaced in the
472          DECL_P case).  The former case is more complicated, as we need to
473          ensure that the new address is still a gimple operand.  Thus, it
474          is not sufficient to replace just the base of the memory reference --
475          we need to move the whole computation of the address out of the
476          loop.  */
477       if (!is_gimple_val (t))
478         return NULL_TREE;
479
480       *walk_subtrees = 0;
481       obj = TREE_OPERAND (t, 0);
482       var = get_base_address (obj);
483       if (!var || !SSA_VAR_P (var) || DECL_EXTERNAL (var))
484         return NULL_TREE;
485
486       addr_type = TREE_TYPE (t);
487       addr = take_address_of (obj, addr_type, dta->entry, dta->decl_address);
488       *tp = addr;
489
490       dta->changed = true;
491       return NULL_TREE;
492     }
493
494   if (!EXPR_P (t))
495     *walk_subtrees = 0;
496
497   return NULL_TREE;
498 }
499
500 /* Moves the references to local variables in STMT out of the single
501    entry single exit region starting at ENTRY.  DECL_ADDRESS contains
502    addresses of the references that had their address taken
503    already.  */
504
505 static void
506 eliminate_local_variables_stmt (edge entry, gimple stmt,
507                                 htab_t decl_address)
508 {
509   struct elv_data dta;
510
511   memset (&dta.info, '\0', sizeof (dta.info));
512   dta.entry = entry;
513   dta.decl_address = decl_address;
514   dta.changed = false;
515
516   if (gimple_debug_bind_p (stmt))
517     walk_tree (gimple_debug_bind_get_value_ptr (stmt),
518                eliminate_local_variables_1, &dta.info, NULL);
519   else
520     walk_gimple_op (stmt, eliminate_local_variables_1, &dta.info);
521
522   if (dta.changed)
523     update_stmt (stmt);
524 }
525
526 /* Eliminates the references to local variables from the single entry
527    single exit region between the ENTRY and EXIT edges.
528
529    This includes:
530    1) Taking address of a local variable -- these are moved out of the
531    region (and temporary variable is created to hold the address if
532    necessary).
533
534    2) Dereferencing a local variable -- these are replaced with indirect
535    references.  */
536
537 static void
538 eliminate_local_variables (edge entry, edge exit)
539 {
540   basic_block bb;
541   VEC (basic_block, heap) *body = VEC_alloc (basic_block, heap, 3);
542   unsigned i;
543   gimple_stmt_iterator gsi;
544   htab_t decl_address = htab_create (10, int_tree_map_hash, int_tree_map_eq,
545                                      free);
546   basic_block entry_bb = entry->src;
547   basic_block exit_bb = exit->dest;
548
549   gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
550
551   for (i = 0; VEC_iterate (basic_block, body, i, bb); i++)
552     if (bb != entry_bb && bb != exit_bb)
553       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
554         eliminate_local_variables_stmt (entry, gsi_stmt (gsi),
555                                         decl_address);
556
557   htab_delete (decl_address);
558   VEC_free (basic_block, heap, body);
559 }
560
561 /* Returns true if expression EXPR is not defined between ENTRY and
562    EXIT, i.e. if all its operands are defined outside of the region.  */
563
564 static bool
565 expr_invariant_in_region_p (edge entry, edge exit, tree expr)
566 {
567   basic_block entry_bb = entry->src;
568   basic_block exit_bb = exit->dest;
569   basic_block def_bb;
570
571   if (is_gimple_min_invariant (expr))
572     return true;
573
574   if (TREE_CODE (expr) == SSA_NAME)
575     {
576       def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
577       if (def_bb
578           && dominated_by_p (CDI_DOMINATORS, def_bb, entry_bb)
579           && !dominated_by_p (CDI_DOMINATORS, def_bb, exit_bb))
580         return false;
581
582       return true;
583     }
584
585   return false;
586 }
587
588 /* If COPY_NAME_P is true, creates and returns a duplicate of NAME.
589    The copies are stored to NAME_COPIES, if NAME was already duplicated,
590    its duplicate stored in NAME_COPIES is returned.
591
592    Regardless of COPY_NAME_P, the decl used as a base of the ssa name is also
593    duplicated, storing the copies in DECL_COPIES.  */
594
595 static tree
596 separate_decls_in_region_name (tree name,
597                                htab_t name_copies, htab_t decl_copies,
598                                bool copy_name_p)
599 {
600   tree copy, var, var_copy;
601   unsigned idx, uid, nuid;
602   struct int_tree_map ielt, *nielt;
603   struct name_to_copy_elt elt, *nelt;
604   void **slot, **dslot;
605
606   if (TREE_CODE (name) != SSA_NAME)
607     return name;
608
609   idx = SSA_NAME_VERSION (name);
610   elt.version = idx;
611   slot = htab_find_slot_with_hash (name_copies, &elt, idx,
612                                    copy_name_p ? INSERT : NO_INSERT);
613   if (slot && *slot)
614     return ((struct name_to_copy_elt *) *slot)->new_name;
615
616   var = SSA_NAME_VAR (name);
617   uid = DECL_UID (var);
618   ielt.uid = uid;
619   dslot = htab_find_slot_with_hash (decl_copies, &ielt, uid, INSERT);
620   if (!*dslot)
621     {
622       var_copy = create_tmp_var (TREE_TYPE (var), get_name (var));
623       DECL_GIMPLE_REG_P (var_copy) = DECL_GIMPLE_REG_P (var);
624       add_referenced_var (var_copy);
625       nielt = XNEW (struct int_tree_map);
626       nielt->uid = uid;
627       nielt->to = var_copy;
628       *dslot = nielt;
629
630       /* Ensure that when we meet this decl next time, we won't duplicate
631          it again.  */
632       nuid = DECL_UID (var_copy);
633       ielt.uid = nuid;
634       dslot = htab_find_slot_with_hash (decl_copies, &ielt, nuid, INSERT);
635       gcc_assert (!*dslot);
636       nielt = XNEW (struct int_tree_map);
637       nielt->uid = nuid;
638       nielt->to = var_copy;
639       *dslot = nielt;
640     }
641   else
642     var_copy = ((struct int_tree_map *) *dslot)->to;
643
644   if (copy_name_p)
645     {
646       copy = duplicate_ssa_name (name, NULL);
647       nelt = XNEW (struct name_to_copy_elt);
648       nelt->version = idx;
649       nelt->new_name = copy;
650       nelt->field = NULL_TREE;
651       *slot = nelt;
652     }
653   else
654     {
655       gcc_assert (!slot);
656       copy = name;
657     }
658
659   SSA_NAME_VAR (copy) = var_copy;
660   return copy;
661 }
662
663 /* Finds the ssa names used in STMT that are defined outside the
664    region between ENTRY and EXIT and replaces such ssa names with
665    their duplicates.  The duplicates are stored to NAME_COPIES.  Base
666    decls of all ssa names used in STMT (including those defined in
667    LOOP) are replaced with the new temporary variables; the
668    replacement decls are stored in DECL_COPIES.  */
669
670 static void
671 separate_decls_in_region_stmt (edge entry, edge exit, gimple stmt,
672                                htab_t name_copies, htab_t decl_copies)
673 {
674   use_operand_p use;
675   def_operand_p def;
676   ssa_op_iter oi;
677   tree name, copy;
678   bool copy_name_p;
679
680   mark_virtual_ops_for_renaming (stmt);
681
682   FOR_EACH_PHI_OR_STMT_DEF (def, stmt, oi, SSA_OP_DEF)
683   {
684     name = DEF_FROM_PTR (def);
685     gcc_assert (TREE_CODE (name) == SSA_NAME);
686     copy = separate_decls_in_region_name (name, name_copies, decl_copies,
687                                           false);
688     gcc_assert (copy == name);
689   }
690
691   FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
692   {
693     name = USE_FROM_PTR (use);
694     if (TREE_CODE (name) != SSA_NAME)
695       continue;
696
697     copy_name_p = expr_invariant_in_region_p (entry, exit, name);
698     copy = separate_decls_in_region_name (name, name_copies, decl_copies,
699                                           copy_name_p);
700     SET_USE (use, copy);
701   }
702 }
703
704 /* Finds the ssa names used in STMT that are defined outside the
705    region between ENTRY and EXIT and replaces such ssa names with
706    their duplicates.  The duplicates are stored to NAME_COPIES.  Base
707    decls of all ssa names used in STMT (including those defined in
708    LOOP) are replaced with the new temporary variables; the
709    replacement decls are stored in DECL_COPIES.  */
710
711 static bool
712 separate_decls_in_region_debug_bind (gimple stmt,
713                                      htab_t name_copies, htab_t decl_copies)
714 {
715   use_operand_p use;
716   ssa_op_iter oi;
717   tree var, name;
718   struct int_tree_map ielt;
719   struct name_to_copy_elt elt;
720   void **slot, **dslot;
721
722   var = gimple_debug_bind_get_var (stmt);
723   if (TREE_CODE (var) == DEBUG_EXPR_DECL)
724     return true;
725   gcc_assert (DECL_P (var) && SSA_VAR_P (var));
726   ielt.uid = DECL_UID (var);
727   dslot = htab_find_slot_with_hash (decl_copies, &ielt, ielt.uid, NO_INSERT);
728   if (!dslot)
729     return true;
730   gimple_debug_bind_set_var (stmt, ((struct int_tree_map *) *dslot)->to);
731
732   FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
733   {
734     name = USE_FROM_PTR (use);
735     if (TREE_CODE (name) != SSA_NAME)
736       continue;
737
738     elt.version = SSA_NAME_VERSION (name);
739     slot = htab_find_slot_with_hash (name_copies, &elt, elt.version, NO_INSERT);
740     if (!slot)
741       {
742         gimple_debug_bind_reset_value (stmt);
743         update_stmt (stmt);
744         break;
745       }
746
747     SET_USE (use, ((struct name_to_copy_elt *) *slot)->new_name);
748   }
749
750   return false;
751 }
752
753 /* Callback for htab_traverse.  Adds a field corresponding to the reduction
754    specified in SLOT. The type is passed in DATA.  */
755
756 static int
757 add_field_for_reduction (void **slot, void *data)
758 {
759
760   struct reduction_info *const red = (struct reduction_info *) *slot;
761   tree const type = (tree) data;
762   tree var = SSA_NAME_VAR (gimple_assign_lhs (red->reduc_stmt));
763   tree field = build_decl (gimple_location (red->reduc_stmt),
764                            FIELD_DECL, DECL_NAME (var), TREE_TYPE (var));
765
766   insert_field_into_struct (type, field);
767
768   red->field = field;
769
770   return 1;
771 }
772
773 /* Callback for htab_traverse.  Adds a field corresponding to a ssa name
774    described in SLOT. The type is passed in DATA.  */
775
776 static int
777 add_field_for_name (void **slot, void *data)
778 {
779   struct name_to_copy_elt *const elt = (struct name_to_copy_elt *) *slot;
780   tree type = (tree) data;
781   tree name = ssa_name (elt->version);
782   tree var = SSA_NAME_VAR (name);
783   tree field = build_decl (DECL_SOURCE_LOCATION (var),
784                            FIELD_DECL, DECL_NAME (var), TREE_TYPE (var));
785
786   insert_field_into_struct (type, field);
787   elt->field = field;
788
789   return 1;
790 }
791
792 /* Callback for htab_traverse.  A local result is the intermediate result
793    computed by a single
794    thread, or the initial value in case no iteration was executed.
795    This function creates a phi node reflecting these values.
796    The phi's result will be stored in NEW_PHI field of the
797    reduction's data structure.  */
798
799 static int
800 create_phi_for_local_result (void **slot, void *data)
801 {
802   struct reduction_info *const reduc = (struct reduction_info *) *slot;
803   const struct loop *const loop = (const struct loop *) data;
804   edge e;
805   gimple new_phi;
806   basic_block store_bb;
807   tree local_res;
808   source_location locus;
809
810   /* STORE_BB is the block where the phi
811      should be stored.  It is the destination of the loop exit.
812      (Find the fallthru edge from GIMPLE_OMP_CONTINUE).  */
813   store_bb = FALLTHRU_EDGE (loop->latch)->dest;
814
815   /* STORE_BB has two predecessors.  One coming from  the loop
816      (the reduction's result is computed at the loop),
817      and another coming from a block preceding the loop,
818      when no iterations
819      are executed (the initial value should be taken).  */
820   if (EDGE_PRED (store_bb, 0) == FALLTHRU_EDGE (loop->latch))
821     e = EDGE_PRED (store_bb, 1);
822   else
823     e = EDGE_PRED (store_bb, 0);
824   local_res
825     = make_ssa_name (SSA_NAME_VAR (gimple_assign_lhs (reduc->reduc_stmt)),
826                      NULL);
827   locus = gimple_location (reduc->reduc_stmt);
828   new_phi = create_phi_node (local_res, store_bb);
829   SSA_NAME_DEF_STMT (local_res) = new_phi;
830   add_phi_arg (new_phi, reduc->init, e, locus);
831   add_phi_arg (new_phi, gimple_assign_lhs (reduc->reduc_stmt),
832                FALLTHRU_EDGE (loop->latch), locus);
833   reduc->new_phi = new_phi;
834
835   return 1;
836 }
837
838 struct clsn_data
839 {
840   tree store;
841   tree load;
842
843   basic_block store_bb;
844   basic_block load_bb;
845 };
846
847 /* Callback for htab_traverse.  Create an atomic instruction for the
848    reduction described in SLOT.
849    DATA annotates the place in memory the atomic operation relates to,
850    and the basic block it needs to be generated in.  */
851
852 static int
853 create_call_for_reduction_1 (void **slot, void *data)
854 {
855   struct reduction_info *const reduc = (struct reduction_info *) *slot;
856   struct clsn_data *const clsn_data = (struct clsn_data *) data;
857   gimple_stmt_iterator gsi;
858   tree type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
859   tree struct_type = TREE_TYPE (TREE_TYPE (clsn_data->load));
860   tree load_struct;
861   basic_block bb;
862   basic_block new_bb;
863   edge e;
864   tree t, addr, ref, x;
865   tree tmp_load, name;
866   gimple load;
867
868   load_struct = fold_build1 (INDIRECT_REF, struct_type, clsn_data->load);
869   t = build3 (COMPONENT_REF, type, load_struct, reduc->field, NULL_TREE);
870
871   addr = build_addr (t, current_function_decl);
872
873   /* Create phi node.  */
874   bb = clsn_data->load_bb;
875
876   e = split_block (bb, t);
877   new_bb = e->dest;
878
879   tmp_load = create_tmp_var (TREE_TYPE (TREE_TYPE (addr)), NULL);
880   add_referenced_var (tmp_load);
881   tmp_load = make_ssa_name (tmp_load, NULL);
882   load = gimple_build_omp_atomic_load (tmp_load, addr);
883   SSA_NAME_DEF_STMT (tmp_load) = load;
884   gsi = gsi_start_bb (new_bb);
885   gsi_insert_after (&gsi, load, GSI_NEW_STMT);
886
887   e = split_block (new_bb, load);
888   new_bb = e->dest;
889   gsi = gsi_start_bb (new_bb);
890   ref = tmp_load;
891   x = fold_build2 (reduc->reduction_code,
892                    TREE_TYPE (PHI_RESULT (reduc->new_phi)), ref,
893                    PHI_RESULT (reduc->new_phi));
894
895   name = force_gimple_operand_gsi (&gsi, x, true, NULL_TREE, true,
896                                    GSI_CONTINUE_LINKING);
897
898   gsi_insert_after (&gsi, gimple_build_omp_atomic_store (name), GSI_NEW_STMT);
899   return 1;
900 }
901
902 /* Create the atomic operation at the join point of the threads.
903    REDUCTION_LIST describes the reductions in the LOOP.
904    LD_ST_DATA describes the shared data structure where
905    shared data is stored in and loaded from.  */
906 static void
907 create_call_for_reduction (struct loop *loop, htab_t reduction_list,
908                            struct clsn_data *ld_st_data)
909 {
910   htab_traverse (reduction_list, create_phi_for_local_result, loop);
911   /* Find the fallthru edge from GIMPLE_OMP_CONTINUE.  */
912   ld_st_data->load_bb = FALLTHRU_EDGE (loop->latch)->dest;
913   htab_traverse (reduction_list, create_call_for_reduction_1, ld_st_data);
914 }
915
916 /* Callback for htab_traverse.  Loads the final reduction value at the
917    join point of all threads, and inserts it in the right place.  */
918
919 static int
920 create_loads_for_reductions (void **slot, void *data)
921 {
922   struct reduction_info *const red = (struct reduction_info *) *slot;
923   struct clsn_data *const clsn_data = (struct clsn_data *) data;
924   gimple stmt;
925   gimple_stmt_iterator gsi;
926   tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
927   tree struct_type = TREE_TYPE (TREE_TYPE (clsn_data->load));
928   tree load_struct;
929   tree name;
930   tree x;
931
932   gsi = gsi_after_labels (clsn_data->load_bb);
933   load_struct = fold_build1 (INDIRECT_REF, struct_type, clsn_data->load);
934   load_struct = build3 (COMPONENT_REF, type, load_struct, red->field,
935                         NULL_TREE);
936
937   x = load_struct;
938   name = PHI_RESULT (red->keep_res);
939   stmt = gimple_build_assign (name, x);
940   SSA_NAME_DEF_STMT (name) = stmt;
941
942   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
943
944   for (gsi = gsi_start_phis (gimple_bb (red->keep_res));
945        !gsi_end_p (gsi); gsi_next (&gsi))
946     if (gsi_stmt (gsi) == red->keep_res)
947       {
948         remove_phi_node (&gsi, false);
949         return 1;
950       }
951   gcc_unreachable ();
952 }
953
954 /* Load the reduction result that was stored in LD_ST_DATA.
955    REDUCTION_LIST describes the list of reductions that the
956    loads should be generated for.  */
957 static void
958 create_final_loads_for_reduction (htab_t reduction_list,
959                                   struct clsn_data *ld_st_data)
960 {
961   gimple_stmt_iterator gsi;
962   tree t;
963   gimple stmt;
964
965   gsi = gsi_after_labels (ld_st_data->load_bb);
966   t = build_fold_addr_expr (ld_st_data->store);
967   stmt = gimple_build_assign (ld_st_data->load, t);
968
969   gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
970   SSA_NAME_DEF_STMT (ld_st_data->load) = stmt;
971
972   htab_traverse (reduction_list, create_loads_for_reductions, ld_st_data);
973
974 }
975
976 /* Callback for htab_traverse.  Store the neutral value for the
977   particular reduction's operation, e.g. 0 for PLUS_EXPR,
978   1 for MULT_EXPR, etc. into the reduction field.
979   The reduction is specified in SLOT. The store information is
980   passed in DATA.  */
981
982 static int
983 create_stores_for_reduction (void **slot, void *data)
984 {
985   struct reduction_info *const red = (struct reduction_info *) *slot;
986   struct clsn_data *const clsn_data = (struct clsn_data *) data;
987   tree t;
988   gimple stmt;
989   gimple_stmt_iterator gsi;
990   tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
991
992   gsi = gsi_last_bb (clsn_data->store_bb);
993   t = build3 (COMPONENT_REF, type, clsn_data->store, red->field, NULL_TREE);
994   stmt = gimple_build_assign (t, red->initial_value);
995   mark_virtual_ops_for_renaming (stmt);
996   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
997
998   return 1;
999 }
1000
1001 /* Callback for htab_traverse.  Creates loads to a field of LOAD in LOAD_BB and
1002    store to a field of STORE in STORE_BB for the ssa name and its duplicate
1003    specified in SLOT.  */
1004
1005 static int
1006 create_loads_and_stores_for_name (void **slot, void *data)
1007 {
1008   struct name_to_copy_elt *const elt = (struct name_to_copy_elt *) *slot;
1009   struct clsn_data *const clsn_data = (struct clsn_data *) data;
1010   tree t;
1011   gimple stmt;
1012   gimple_stmt_iterator gsi;
1013   tree type = TREE_TYPE (elt->new_name);
1014   tree struct_type = TREE_TYPE (TREE_TYPE (clsn_data->load));
1015   tree load_struct;
1016
1017   gsi = gsi_last_bb (clsn_data->store_bb);
1018   t = build3 (COMPONENT_REF, type, clsn_data->store, elt->field, NULL_TREE);
1019   stmt = gimple_build_assign (t, ssa_name (elt->version));
1020   mark_virtual_ops_for_renaming (stmt);
1021   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1022
1023   gsi = gsi_last_bb (clsn_data->load_bb);
1024   load_struct = fold_build1 (INDIRECT_REF, struct_type, clsn_data->load);
1025   t = build3 (COMPONENT_REF, type, load_struct, elt->field, NULL_TREE);
1026   stmt = gimple_build_assign (elt->new_name, t);
1027   SSA_NAME_DEF_STMT (elt->new_name) = stmt;
1028   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1029
1030   return 1;
1031 }
1032
1033 /* Moves all the variables used in LOOP and defined outside of it (including
1034    the initial values of loop phi nodes, and *PER_THREAD if it is a ssa
1035    name) to a structure created for this purpose.  The code
1036
1037    while (1)
1038      {
1039        use (a);
1040        use (b);
1041      }
1042
1043    is transformed this way:
1044
1045    bb0:
1046    old.a = a;
1047    old.b = b;
1048
1049    bb1:
1050    a' = new->a;
1051    b' = new->b;
1052    while (1)
1053      {
1054        use (a');
1055        use (b');
1056      }
1057
1058    `old' is stored to *ARG_STRUCT and `new' is stored to NEW_ARG_STRUCT.  The
1059    pointer `new' is intentionally not initialized (the loop will be split to a
1060    separate function later, and `new' will be initialized from its arguments).
1061    LD_ST_DATA holds information about the shared data structure used to pass
1062    information among the threads.  It is initialized here, and
1063    gen_parallel_loop will pass it to create_call_for_reduction that
1064    needs this information.  REDUCTION_LIST describes the reductions
1065    in LOOP.  */
1066
1067 static void
1068 separate_decls_in_region (edge entry, edge exit, htab_t reduction_list,
1069                           tree *arg_struct, tree *new_arg_struct,
1070                           struct clsn_data *ld_st_data)
1071
1072 {
1073   basic_block bb1 = split_edge (entry);
1074   basic_block bb0 = single_pred (bb1);
1075   htab_t name_copies = htab_create (10, name_to_copy_elt_hash,
1076                                     name_to_copy_elt_eq, free);
1077   htab_t decl_copies = htab_create (10, int_tree_map_hash, int_tree_map_eq,
1078                                     free);
1079   unsigned i;
1080   tree type, type_name, nvar;
1081   gimple_stmt_iterator gsi;
1082   struct clsn_data clsn_data;
1083   VEC (basic_block, heap) *body = VEC_alloc (basic_block, heap, 3);
1084   basic_block bb;
1085   basic_block entry_bb = bb1;
1086   basic_block exit_bb = exit->dest;
1087   bool has_debug_stmt = false;
1088
1089   entry = single_succ_edge (entry_bb);
1090   gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
1091
1092   for (i = 0; VEC_iterate (basic_block, body, i, bb); i++)
1093     {
1094       if (bb != entry_bb && bb != exit_bb)
1095         {
1096           for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1097             separate_decls_in_region_stmt (entry, exit, gsi_stmt (gsi),
1098                                            name_copies, decl_copies);
1099
1100           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1101             {
1102               gimple stmt = gsi_stmt (gsi);
1103
1104               if (is_gimple_debug (stmt))
1105                 has_debug_stmt = true;
1106               else
1107                 separate_decls_in_region_stmt (entry, exit, stmt,
1108                                                name_copies, decl_copies);
1109             }
1110         }
1111     }
1112
1113   /* Now process debug bind stmts.  We must not create decls while
1114      processing debug stmts, so we defer their processing so as to
1115      make sure we will have debug info for as many variables as
1116      possible (all of those that were dealt with in the loop above),
1117      and discard those for which we know there's nothing we can
1118      do.  */
1119   if (has_debug_stmt)
1120     for (i = 0; VEC_iterate (basic_block, body, i, bb); i++)
1121       if (bb != entry_bb && bb != exit_bb)
1122         {
1123           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
1124             {
1125               gimple stmt = gsi_stmt (gsi);
1126
1127               if (gimple_debug_bind_p (stmt))
1128                 {
1129                   if (separate_decls_in_region_debug_bind (stmt,
1130                                                            name_copies,
1131                                                            decl_copies))
1132                     {
1133                       gsi_remove (&gsi, true);
1134                       continue;
1135                     }
1136                 }
1137
1138               gsi_next (&gsi);
1139             }
1140         }
1141
1142   VEC_free (basic_block, heap, body);
1143
1144   if (htab_elements (name_copies) == 0 && htab_elements (reduction_list) == 0)
1145     {
1146       /* It may happen that there is nothing to copy (if there are only
1147          loop carried and external variables in the loop).  */
1148       *arg_struct = NULL;
1149       *new_arg_struct = NULL;
1150     }
1151   else
1152     {
1153       /* Create the type for the structure to store the ssa names to.  */
1154       type = lang_hooks.types.make_type (RECORD_TYPE);
1155       type_name = build_decl (BUILTINS_LOCATION,
1156                               TYPE_DECL, create_tmp_var_name (".paral_data"),
1157                               type);
1158       TYPE_NAME (type) = type_name;
1159
1160       htab_traverse (name_copies, add_field_for_name, type);
1161       if (reduction_list && htab_elements (reduction_list) > 0)
1162         {
1163           /* Create the fields for reductions.  */
1164           htab_traverse (reduction_list, add_field_for_reduction,
1165                          type);
1166         }
1167       layout_type (type);
1168
1169       /* Create the loads and stores.  */
1170       *arg_struct = create_tmp_var (type, ".paral_data_store");
1171       add_referenced_var (*arg_struct);
1172       nvar = create_tmp_var (build_pointer_type (type), ".paral_data_load");
1173       add_referenced_var (nvar);
1174       *new_arg_struct = make_ssa_name (nvar, NULL);
1175
1176       ld_st_data->store = *arg_struct;
1177       ld_st_data->load = *new_arg_struct;
1178       ld_st_data->store_bb = bb0;
1179       ld_st_data->load_bb = bb1;
1180
1181       htab_traverse (name_copies, create_loads_and_stores_for_name,
1182                      ld_st_data);
1183
1184       /* Load the calculation from memory (after the join of the threads).  */
1185
1186       if (reduction_list && htab_elements (reduction_list) > 0)
1187         {
1188           htab_traverse (reduction_list, create_stores_for_reduction,
1189                         ld_st_data);
1190           clsn_data.load = make_ssa_name (nvar, NULL);
1191           clsn_data.load_bb = exit->dest;
1192           clsn_data.store = ld_st_data->store;
1193           create_final_loads_for_reduction (reduction_list, &clsn_data);
1194         }
1195     }
1196
1197   htab_delete (decl_copies);
1198   htab_delete (name_copies);
1199 }
1200
1201 /* Bitmap containing uids of functions created by parallelization.  We cannot
1202    allocate it from the default obstack, as it must live across compilation
1203    of several functions; we make it gc allocated instead.  */
1204
1205 static GTY(()) bitmap parallelized_functions;
1206
1207 /* Returns true if FN was created by create_loop_fn.  */
1208
1209 static bool
1210 parallelized_function_p (tree fn)
1211 {
1212   if (!parallelized_functions || !DECL_ARTIFICIAL (fn))
1213     return false;
1214
1215   return bitmap_bit_p (parallelized_functions, DECL_UID (fn));
1216 }
1217
1218 /* Creates and returns an empty function that will receive the body of
1219    a parallelized loop.  */
1220
1221 static tree
1222 create_loop_fn (void)
1223 {
1224   char buf[100];
1225   char *tname;
1226   tree decl, type, name, t;
1227   struct function *act_cfun = cfun;
1228   static unsigned loopfn_num;
1229
1230   snprintf (buf, 100, "%s.$loopfn", current_function_name ());
1231   ASM_FORMAT_PRIVATE_NAME (tname, buf, loopfn_num++);
1232   clean_symbol_name (tname);
1233   name = get_identifier (tname);
1234   type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
1235
1236   decl = build_decl (BUILTINS_LOCATION,
1237                      FUNCTION_DECL, name, type);
1238   if (!parallelized_functions)
1239     parallelized_functions = BITMAP_GGC_ALLOC ();
1240   bitmap_set_bit (parallelized_functions, DECL_UID (decl));
1241
1242   TREE_STATIC (decl) = 1;
1243   TREE_USED (decl) = 1;
1244   DECL_ARTIFICIAL (decl) = 1;
1245   DECL_IGNORED_P (decl) = 0;
1246   TREE_PUBLIC (decl) = 0;
1247   DECL_UNINLINABLE (decl) = 1;
1248   DECL_EXTERNAL (decl) = 0;
1249   DECL_CONTEXT (decl) = NULL_TREE;
1250   DECL_INITIAL (decl) = make_node (BLOCK);
1251
1252   t = build_decl (BUILTINS_LOCATION,
1253                   RESULT_DECL, NULL_TREE, void_type_node);
1254   DECL_ARTIFICIAL (t) = 1;
1255   DECL_IGNORED_P (t) = 1;
1256   DECL_RESULT (decl) = t;
1257
1258   t = build_decl (BUILTINS_LOCATION,
1259                   PARM_DECL, get_identifier (".paral_data_param"),
1260                   ptr_type_node);
1261   DECL_ARTIFICIAL (t) = 1;
1262   DECL_ARG_TYPE (t) = ptr_type_node;
1263   DECL_CONTEXT (t) = decl;
1264   TREE_USED (t) = 1;
1265   DECL_ARGUMENTS (decl) = t;
1266
1267   allocate_struct_function (decl, false);
1268
1269   /* The call to allocate_struct_function clobbers CFUN, so we need to restore
1270      it.  */
1271   set_cfun (act_cfun);
1272
1273   return decl;
1274 }
1275
1276 /* Moves the exit condition of LOOP to the beginning of its header, and
1277    duplicates the part of the last iteration that gets disabled to the
1278    exit of the loop.  NIT is the number of iterations of the loop
1279    (used to initialize the variables in the duplicated part).
1280
1281    TODO: the common case is that latch of the loop is empty and immediately
1282    follows the loop exit.  In this case, it would be better not to copy the
1283    body of the loop, but only move the entry of the loop directly before the
1284    exit check and increase the number of iterations of the loop by one.
1285    This may need some additional preconditioning in case NIT = ~0.
1286    REDUCTION_LIST describes the reductions in LOOP.  */
1287
1288 static void
1289 transform_to_exit_first_loop (struct loop *loop, htab_t reduction_list, tree nit)
1290 {
1291   basic_block *bbs, *nbbs, ex_bb, orig_header;
1292   unsigned n;
1293   bool ok;
1294   edge exit = single_dom_exit (loop), hpred;
1295   tree control, control_name, res, t;
1296   gimple phi, nphi, cond_stmt, stmt, cond_nit;
1297   gimple_stmt_iterator gsi;
1298   tree nit_1;
1299
1300   split_block_after_labels (loop->header);
1301   orig_header = single_succ (loop->header);
1302   hpred = single_succ_edge (loop->header);
1303
1304   cond_stmt = last_stmt (exit->src);
1305   control = gimple_cond_lhs (cond_stmt);
1306   gcc_assert (gimple_cond_rhs (cond_stmt) == nit);
1307
1308   /* Make sure that we have phi nodes on exit for all loop header phis
1309      (create_parallel_loop requires that).  */
1310   for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
1311     {
1312       phi = gsi_stmt (gsi);
1313       res = PHI_RESULT (phi);
1314       t = make_ssa_name (SSA_NAME_VAR (res), phi);
1315       SET_PHI_RESULT (phi, t);
1316       nphi = create_phi_node (res, orig_header);
1317       SSA_NAME_DEF_STMT (res) = nphi;
1318       add_phi_arg (nphi, t, hpred, UNKNOWN_LOCATION);
1319
1320       if (res == control)
1321         {
1322           gimple_cond_set_lhs (cond_stmt, t);
1323           update_stmt (cond_stmt);
1324           control = t;
1325         }
1326     }
1327   bbs = get_loop_body_in_dom_order (loop);
1328
1329   for (n = 0; bbs[n] != loop->latch; n++)
1330     continue;
1331   nbbs = XNEWVEC (basic_block, n);
1332   ok = gimple_duplicate_sese_tail (single_succ_edge (loop->header), exit,
1333                                    bbs + 1, n, nbbs);
1334   gcc_assert (ok);
1335   free (bbs);
1336   ex_bb = nbbs[0];
1337   free (nbbs);
1338
1339   /* Other than reductions, the only gimple reg that should be copied
1340      out of the loop is the control variable.  */
1341
1342   control_name = NULL_TREE;
1343   for (gsi = gsi_start_phis (ex_bb); !gsi_end_p (gsi); )
1344     {
1345       phi = gsi_stmt (gsi);
1346       res = PHI_RESULT (phi);
1347       if (!is_gimple_reg (res))
1348         {
1349           gsi_next (&gsi);
1350           continue;
1351         }
1352
1353       /* Check if it is a part of reduction.  If it is,
1354          keep the phi at the reduction's keep_res field.  The
1355          PHI_RESULT of this phi is the resulting value of the reduction
1356          variable when exiting the loop.  */
1357
1358       exit = single_dom_exit (loop);
1359
1360       if (htab_elements (reduction_list) > 0)
1361         {
1362           struct reduction_info *red;
1363
1364           tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1365           red = reduction_phi (reduction_list, SSA_NAME_DEF_STMT (val));
1366           if (red)
1367             {
1368               red->keep_res = phi;
1369               gsi_next (&gsi);
1370               continue;
1371             }
1372         }
1373       gcc_assert (control_name == NULL_TREE
1374                   && SSA_NAME_VAR (res) == SSA_NAME_VAR (control));
1375       control_name = res;
1376       remove_phi_node (&gsi, false);
1377     }
1378   gcc_assert (control_name != NULL_TREE);
1379
1380   /* Initialize the control variable to number of iterations
1381      according to the rhs of the exit condition.  */
1382   gsi = gsi_after_labels (ex_bb);
1383   cond_nit = last_stmt (exit->src);
1384   nit_1 =  gimple_cond_rhs (cond_nit);
1385   nit_1 = force_gimple_operand_gsi (&gsi,
1386                                   fold_convert (TREE_TYPE (control_name), nit_1),
1387                                   false, NULL_TREE, false, GSI_SAME_STMT);
1388   stmt = gimple_build_assign (control_name, nit_1);
1389   gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1390   SSA_NAME_DEF_STMT (control_name) = stmt;
1391 }
1392
1393 /* Create the parallel constructs for LOOP as described in gen_parallel_loop.
1394    LOOP_FN and DATA are the arguments of GIMPLE_OMP_PARALLEL.
1395    NEW_DATA is the variable that should be initialized from the argument
1396    of LOOP_FN.  N_THREADS is the requested number of threads.  Returns the
1397    basic block containing GIMPLE_OMP_PARALLEL tree.  */
1398
1399 static basic_block
1400 create_parallel_loop (struct loop *loop, tree loop_fn, tree data,
1401                       tree new_data, unsigned n_threads)
1402 {
1403   gimple_stmt_iterator gsi;
1404   basic_block bb, paral_bb, for_bb, ex_bb;
1405   tree t, param;
1406   gimple stmt, for_stmt, phi, cond_stmt;
1407   tree cvar, cvar_init, initvar, cvar_next, cvar_base, type;
1408   edge exit, nexit, guard, end, e;
1409
1410   /* Prepare the GIMPLE_OMP_PARALLEL statement.  */
1411   bb = loop_preheader_edge (loop)->src;
1412   paral_bb = single_pred (bb);
1413   gsi = gsi_last_bb (paral_bb);
1414
1415   t = build_omp_clause (BUILTINS_LOCATION, OMP_CLAUSE_NUM_THREADS);
1416   OMP_CLAUSE_NUM_THREADS_EXPR (t)
1417     = build_int_cst (integer_type_node, n_threads);
1418   stmt = gimple_build_omp_parallel (NULL, t, loop_fn, data);
1419
1420   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1421
1422   /* Initialize NEW_DATA.  */
1423   if (data)
1424     {
1425       gsi = gsi_after_labels (bb);
1426
1427       param = make_ssa_name (DECL_ARGUMENTS (loop_fn), NULL);
1428       stmt = gimple_build_assign (param, build_fold_addr_expr (data));
1429       gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1430       SSA_NAME_DEF_STMT (param) = stmt;
1431
1432       stmt = gimple_build_assign (new_data,
1433                                   fold_convert (TREE_TYPE (new_data), param));
1434       gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1435       SSA_NAME_DEF_STMT (new_data) = stmt;
1436     }
1437
1438   /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_PARALLEL.  */
1439   bb = split_loop_exit_edge (single_dom_exit (loop));
1440   gsi = gsi_last_bb (bb);
1441   gsi_insert_after (&gsi, gimple_build_omp_return (false), GSI_NEW_STMT);
1442
1443   /* Extract data for GIMPLE_OMP_FOR.  */
1444   gcc_assert (loop->header == single_dom_exit (loop)->src);
1445   cond_stmt = last_stmt (loop->header);
1446
1447   cvar = gimple_cond_lhs (cond_stmt);
1448   cvar_base = SSA_NAME_VAR (cvar);
1449   phi = SSA_NAME_DEF_STMT (cvar);
1450   cvar_init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1451   initvar = make_ssa_name (cvar_base, NULL);
1452   SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (phi, loop_preheader_edge (loop)),
1453            initvar);
1454   cvar_next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1455
1456   gsi = gsi_last_bb (loop->latch);
1457   gcc_assert (gsi_stmt (gsi) == SSA_NAME_DEF_STMT (cvar_next));
1458   gsi_remove (&gsi, true);
1459
1460   /* Prepare cfg.  */
1461   for_bb = split_edge (loop_preheader_edge (loop));
1462   ex_bb = split_loop_exit_edge (single_dom_exit (loop));
1463   extract_true_false_edges_from_block (loop->header, &nexit, &exit);
1464   gcc_assert (exit == single_dom_exit (loop));
1465
1466   guard = make_edge (for_bb, ex_bb, 0);
1467   single_succ_edge (loop->latch)->flags = 0;
1468   end = make_edge (loop->latch, ex_bb, EDGE_FALLTHRU);
1469   for (gsi = gsi_start_phis (ex_bb); !gsi_end_p (gsi); gsi_next (&gsi))
1470     {
1471       source_location locus;
1472       tree def;
1473       phi = gsi_stmt (gsi);
1474       stmt = SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, exit));
1475
1476       def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_preheader_edge (loop));
1477       locus = gimple_phi_arg_location_from_edge (stmt,
1478                                                  loop_preheader_edge (loop));
1479       add_phi_arg (phi, def, guard, locus);
1480
1481       def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_latch_edge (loop));
1482       locus = gimple_phi_arg_location_from_edge (stmt, loop_latch_edge (loop));
1483       add_phi_arg (phi, def, end, locus);
1484     }
1485   e = redirect_edge_and_branch (exit, nexit->dest);
1486   PENDING_STMT (e) = NULL;
1487
1488   /* Emit GIMPLE_OMP_FOR.  */
1489   gimple_cond_set_lhs (cond_stmt, cvar_base);
1490   type = TREE_TYPE (cvar);
1491   t = build_omp_clause (BUILTINS_LOCATION, OMP_CLAUSE_SCHEDULE);
1492   OMP_CLAUSE_SCHEDULE_KIND (t) = OMP_CLAUSE_SCHEDULE_STATIC;
1493
1494   for_stmt = gimple_build_omp_for (NULL, t, 1, NULL);
1495   gimple_omp_for_set_index (for_stmt, 0, initvar);
1496   gimple_omp_for_set_initial (for_stmt, 0, cvar_init);
1497   gimple_omp_for_set_final (for_stmt, 0, gimple_cond_rhs (cond_stmt));
1498   gimple_omp_for_set_cond (for_stmt, 0, gimple_cond_code (cond_stmt));
1499   gimple_omp_for_set_incr (for_stmt, 0, build2 (PLUS_EXPR, type,
1500                                                 cvar_base,
1501                                                 build_int_cst (type, 1)));
1502
1503   gsi = gsi_last_bb (for_bb);
1504   gsi_insert_after (&gsi, for_stmt, GSI_NEW_STMT);
1505   SSA_NAME_DEF_STMT (initvar) = for_stmt;
1506
1507   /* Emit GIMPLE_OMP_CONTINUE.  */
1508   gsi = gsi_last_bb (loop->latch);
1509   stmt = gimple_build_omp_continue (cvar_next, cvar);
1510   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1511   SSA_NAME_DEF_STMT (cvar_next) = stmt;
1512
1513   /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_FOR.  */
1514   gsi = gsi_last_bb (ex_bb);
1515   gsi_insert_after (&gsi, gimple_build_omp_return (true), GSI_NEW_STMT);
1516
1517   return paral_bb;
1518 }
1519
1520 /* Generates code to execute the iterations of LOOP in N_THREADS
1521    threads in parallel.
1522
1523    NITER describes number of iterations of LOOP.
1524    REDUCTION_LIST describes the reductions existent in the LOOP.  */
1525
1526 static void
1527 gen_parallel_loop (struct loop *loop, htab_t reduction_list,
1528                    unsigned n_threads, struct tree_niter_desc *niter)
1529 {
1530   loop_iterator li;
1531   tree many_iterations_cond, type, nit;
1532   tree arg_struct, new_arg_struct;
1533   gimple_seq stmts;
1534   basic_block parallel_head;
1535   edge entry, exit;
1536   struct clsn_data clsn_data;
1537   unsigned prob;
1538
1539   /* From
1540
1541      ---------------------------------------------------------------------
1542      loop
1543        {
1544          IV = phi (INIT, IV + STEP)
1545          BODY1;
1546          if (COND)
1547            break;
1548          BODY2;
1549        }
1550      ---------------------------------------------------------------------
1551
1552      with # of iterations NITER (possibly with MAY_BE_ZERO assumption),
1553      we generate the following code:
1554
1555      ---------------------------------------------------------------------
1556
1557      if (MAY_BE_ZERO
1558      || NITER < MIN_PER_THREAD * N_THREADS)
1559      goto original;
1560
1561      BODY1;
1562      store all local loop-invariant variables used in body of the loop to DATA.
1563      GIMPLE_OMP_PARALLEL (OMP_CLAUSE_NUM_THREADS (N_THREADS), LOOPFN, DATA);
1564      load the variables from DATA.
1565      GIMPLE_OMP_FOR (IV = INIT; COND; IV += STEP) (OMP_CLAUSE_SCHEDULE (static))
1566      BODY2;
1567      BODY1;
1568      GIMPLE_OMP_CONTINUE;
1569      GIMPLE_OMP_RETURN         -- GIMPLE_OMP_FOR
1570      GIMPLE_OMP_RETURN         -- GIMPLE_OMP_PARALLEL
1571      goto end;
1572
1573      original:
1574      loop
1575        {
1576          IV = phi (INIT, IV + STEP)
1577          BODY1;
1578          if (COND)
1579            break;
1580          BODY2;
1581        }
1582
1583      end:
1584
1585    */
1586
1587   /* Create two versions of the loop -- in the old one, we know that the
1588      number of iterations is large enough, and we will transform it into the
1589      loop that will be split to loop_fn, the new one will be used for the
1590      remaining iterations.  */
1591
1592   type = TREE_TYPE (niter->niter);
1593   nit = force_gimple_operand (unshare_expr (niter->niter), &stmts, true,
1594                               NULL_TREE);
1595   if (stmts)
1596     gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1597
1598   many_iterations_cond =
1599     fold_build2 (GE_EXPR, boolean_type_node,
1600                  nit, build_int_cst (type, MIN_PER_THREAD * n_threads));
1601   many_iterations_cond
1602     = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1603                    invert_truthvalue (unshare_expr (niter->may_be_zero)),
1604                    many_iterations_cond);
1605   many_iterations_cond
1606     = force_gimple_operand (many_iterations_cond, &stmts, false, NULL_TREE);
1607   if (stmts)
1608     gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1609   if (!is_gimple_condexpr (many_iterations_cond))
1610     {
1611       many_iterations_cond
1612         = force_gimple_operand (many_iterations_cond, &stmts,
1613                                 true, NULL_TREE);
1614       if (stmts)
1615         gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1616     }
1617
1618   initialize_original_copy_tables ();
1619
1620   /* We assume that the loop usually iterates a lot.  */
1621   prob = 4 * REG_BR_PROB_BASE / 5;
1622   loop_version (loop, many_iterations_cond, NULL,
1623                 prob, prob, REG_BR_PROB_BASE - prob, true);
1624   update_ssa (TODO_update_ssa);
1625   free_original_copy_tables ();
1626
1627   /* Base all the induction variables in LOOP on a single control one.  */
1628   canonicalize_loop_ivs (loop, &nit, true);
1629
1630   /* Ensure that the exit condition is the first statement in the loop.  */
1631   transform_to_exit_first_loop (loop, reduction_list, nit);
1632
1633   /* Generate initializations for reductions.  */
1634   if (htab_elements (reduction_list) > 0)
1635     htab_traverse (reduction_list, initialize_reductions, loop);
1636
1637   /* Eliminate the references to local variables from the loop.  */
1638   gcc_assert (single_exit (loop));
1639   entry = loop_preheader_edge (loop);
1640   exit = single_dom_exit (loop);
1641
1642   eliminate_local_variables (entry, exit);
1643   /* In the old loop, move all variables non-local to the loop to a structure
1644      and back, and create separate decls for the variables used in loop.  */
1645   separate_decls_in_region (entry, exit, reduction_list, &arg_struct,
1646                             &new_arg_struct, &clsn_data);
1647
1648   /* Create the parallel constructs.  */
1649   parallel_head = create_parallel_loop (loop, create_loop_fn (), arg_struct,
1650                                         new_arg_struct, n_threads);
1651   if (htab_elements (reduction_list) > 0)
1652     create_call_for_reduction (loop, reduction_list, &clsn_data);
1653
1654   scev_reset ();
1655
1656   /* Cancel the loop (it is simpler to do it here rather than to teach the
1657      expander to do it).  */
1658   cancel_loop_tree (loop);
1659
1660   /* Free loop bound estimations that could contain references to
1661      removed statements.  */
1662   FOR_EACH_LOOP (li, loop, 0)
1663     free_numbers_of_iterations_estimates_loop (loop);
1664
1665   /* Expand the parallel constructs.  We do it directly here instead of running
1666      a separate expand_omp pass, since it is more efficient, and less likely to
1667      cause troubles with further analyses not being able to deal with the
1668      OMP trees.  */
1669
1670   omp_expand_local (parallel_head);
1671 }
1672
1673 /* Returns true when LOOP contains vector phi nodes.  */
1674
1675 static bool
1676 loop_has_vector_phi_nodes (struct loop *loop ATTRIBUTE_UNUSED)
1677 {
1678   unsigned i;
1679   basic_block *bbs = get_loop_body_in_dom_order (loop);
1680   gimple_stmt_iterator gsi;
1681   bool res = true;
1682
1683   for (i = 0; i < loop->num_nodes; i++)
1684     for (gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi); gsi_next (&gsi))
1685       if (TREE_CODE (TREE_TYPE (PHI_RESULT (gsi_stmt (gsi)))) == VECTOR_TYPE)
1686         goto end;
1687
1688   res = false;
1689  end:
1690   free (bbs);
1691   return res;
1692 }
1693
1694 /* Create a reduction_info struct, initialize it with REDUC_STMT
1695    and PHI, insert it to the REDUCTION_LIST.  */
1696
1697 static void
1698 build_new_reduction (htab_t reduction_list, gimple reduc_stmt, gimple phi)
1699 {
1700   PTR *slot;
1701   struct reduction_info *new_reduction;
1702
1703   gcc_assert (reduc_stmt);
1704
1705   if (dump_file && (dump_flags & TDF_DETAILS))
1706     {
1707       fprintf (dump_file,
1708                "Detected reduction. reduction stmt is: \n");
1709       print_gimple_stmt (dump_file, reduc_stmt, 0, 0);
1710       fprintf (dump_file, "\n");
1711     }
1712
1713   new_reduction = XCNEW (struct reduction_info);
1714
1715   new_reduction->reduc_stmt = reduc_stmt;
1716   new_reduction->reduc_phi = phi;
1717   new_reduction->reduction_code = gimple_assign_rhs_code (reduc_stmt);
1718   slot = htab_find_slot (reduction_list, new_reduction, INSERT);
1719   *slot = new_reduction;
1720 }
1721
1722 /* Detect all reductions in the LOOP, insert them into REDUCTION_LIST.  */
1723
1724 static void
1725 gather_scalar_reductions (loop_p loop, htab_t reduction_list)
1726 {
1727   gimple_stmt_iterator gsi;
1728   loop_vec_info simple_loop_info;
1729
1730   vect_dump = NULL;
1731   simple_loop_info = vect_analyze_loop_form (loop);
1732
1733   for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
1734     {
1735       gimple phi = gsi_stmt (gsi);
1736       affine_iv iv;
1737       tree res = PHI_RESULT (phi);
1738       bool double_reduc;
1739
1740       if (!is_gimple_reg (res))
1741         continue;
1742
1743       if (!simple_iv (loop, loop, res, &iv, true)
1744         && simple_loop_info)
1745         {
1746            gimple reduc_stmt = vect_force_simple_reduction (simple_loop_info,
1747                                                             phi, true,
1748                                                             &double_reduc);
1749            if (reduc_stmt && !double_reduc)
1750               build_new_reduction (reduction_list, reduc_stmt, phi);
1751         }
1752     }
1753     destroy_loop_vec_info (simple_loop_info, true);
1754 }
1755
1756 /* Try to initialize NITER for code generation part.  */
1757
1758 static bool
1759 try_get_loop_niter (loop_p loop, struct tree_niter_desc *niter)
1760 {
1761   edge exit = single_dom_exit (loop);
1762
1763   gcc_assert (exit);
1764
1765   /* We need to know # of iterations, and there should be no uses of values
1766      defined inside loop outside of it, unless the values are invariants of
1767      the loop.  */
1768   if (!number_of_iterations_exit (loop, exit, niter, false))
1769     {
1770       if (dump_file && (dump_flags & TDF_DETAILS))
1771         fprintf (dump_file, "  FAILED: number of iterations not known\n");
1772       return false;
1773     }
1774
1775   return true;
1776 }
1777
1778 /* Try to initialize REDUCTION_LIST for code generation part.
1779    REDUCTION_LIST describes the reductions.  */
1780
1781 static bool
1782 try_create_reduction_list (loop_p loop, htab_t reduction_list)
1783 {
1784   edge exit = single_dom_exit (loop);
1785   gimple_stmt_iterator gsi;
1786
1787   gcc_assert (exit);
1788
1789   gather_scalar_reductions (loop, reduction_list);
1790
1791
1792   for (gsi = gsi_start_phis (exit->dest); !gsi_end_p (gsi); gsi_next (&gsi))
1793     {
1794       gimple phi = gsi_stmt (gsi);
1795       struct reduction_info *red;
1796       imm_use_iterator imm_iter;
1797       use_operand_p use_p;
1798       gimple reduc_phi;
1799       tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1800
1801       if (is_gimple_reg (val))
1802         {
1803           if (dump_file && (dump_flags & TDF_DETAILS))
1804             {
1805               fprintf (dump_file, "phi is ");
1806               print_gimple_stmt (dump_file, phi, 0, 0);
1807               fprintf (dump_file, "arg of phi to exit:   value ");
1808               print_generic_expr (dump_file, val, 0);
1809               fprintf (dump_file, " used outside loop\n");
1810               fprintf (dump_file,
1811                        "  checking if it a part of reduction pattern:  \n");
1812             }
1813           if (htab_elements (reduction_list) == 0)
1814             {
1815               if (dump_file && (dump_flags & TDF_DETAILS))
1816                 fprintf (dump_file,
1817                          "  FAILED: it is not a part of reduction.\n");
1818               return false;
1819             }
1820           reduc_phi = NULL;
1821           FOR_EACH_IMM_USE_FAST (use_p, imm_iter, val)
1822             {
1823               if (flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
1824                 {
1825                   reduc_phi = USE_STMT (use_p);
1826                   break;
1827                 }
1828             }
1829           red = reduction_phi (reduction_list, reduc_phi);
1830           if (red == NULL)
1831             {
1832               if (dump_file && (dump_flags & TDF_DETAILS))
1833                 fprintf (dump_file,
1834                          "  FAILED: it is not a part of reduction.\n");
1835               return false;
1836             }
1837           if (dump_file && (dump_flags & TDF_DETAILS))
1838             {
1839               fprintf (dump_file, "reduction phi is  ");
1840               print_gimple_stmt (dump_file, red->reduc_phi, 0, 0);
1841               fprintf (dump_file, "reduction stmt is  ");
1842               print_gimple_stmt (dump_file, red->reduc_stmt, 0, 0);
1843             }
1844         }
1845     }
1846
1847   /* The iterations of the loop may communicate only through bivs whose
1848      iteration space can be distributed efficiently.  */
1849   for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
1850     {
1851       gimple phi = gsi_stmt (gsi);
1852       tree def = PHI_RESULT (phi);
1853       affine_iv iv;
1854
1855       if (is_gimple_reg (def) && !simple_iv (loop, loop, def, &iv, true))
1856         {
1857           struct reduction_info *red;
1858
1859           red = reduction_phi (reduction_list, phi);
1860           if (red == NULL)
1861             {
1862               if (dump_file && (dump_flags & TDF_DETAILS))
1863                 fprintf (dump_file,
1864                          "  FAILED: scalar dependency between iterations\n");
1865               return false;
1866             }
1867         }
1868     }
1869
1870
1871   return true;
1872 }
1873
1874 /* Detect parallel loops and generate parallel code using libgomp
1875    primitives.  Returns true if some loop was parallelized, false
1876    otherwise.  */
1877
1878 bool
1879 parallelize_loops (void)
1880 {
1881   unsigned n_threads = flag_tree_parallelize_loops;
1882   bool changed = false;
1883   struct loop *loop;
1884   struct tree_niter_desc niter_desc;
1885   loop_iterator li;
1886   htab_t reduction_list;
1887   struct obstack parloop_obstack;
1888   HOST_WIDE_INT estimated;
1889   LOC loop_loc;
1890
1891   /* Do not parallelize loops in the functions created by parallelization.  */
1892   if (parallelized_function_p (cfun->decl))
1893     return false;
1894   if (cfun->has_nonlocal_label)
1895     return false;
1896
1897   gcc_obstack_init (&parloop_obstack);
1898   reduction_list = htab_create (10, reduction_info_hash,
1899                                      reduction_info_eq, free);
1900   init_stmt_vec_info_vec ();
1901
1902   FOR_EACH_LOOP (li, loop, 0)
1903     {
1904       htab_empty (reduction_list);
1905       if (dump_file && (dump_flags & TDF_DETAILS))
1906       {
1907         fprintf (dump_file, "Trying loop %d as candidate\n",loop->num);
1908         if (loop->inner)
1909           fprintf (dump_file, "loop %d is not innermost\n",loop->num);
1910         else
1911           fprintf (dump_file, "loop %d is innermost\n",loop->num);
1912       }
1913
1914       /* If we use autopar in graphite pass, we use its marked dependency
1915       checking results.  */
1916       if (flag_loop_parallelize_all && !loop->can_be_parallel)
1917       {
1918         if (dump_file && (dump_flags & TDF_DETAILS))
1919            fprintf (dump_file, "loop is not parallel according to graphite\n");
1920         continue;
1921       }
1922
1923       if (!single_dom_exit (loop))
1924       {
1925
1926         if (dump_file && (dump_flags & TDF_DETAILS))
1927           fprintf (dump_file, "loop is !single_dom_exit\n");
1928
1929         continue;
1930       }
1931
1932       if (/* And of course, the loop must be parallelizable.  */
1933           !can_duplicate_loop_p (loop)
1934           || loop_has_blocks_with_irreducible_flag (loop)
1935           || (loop_preheader_edge (loop)->src->flags & BB_IRREDUCIBLE_LOOP)
1936           /* FIXME: the check for vector phi nodes could be removed.  */
1937           || loop_has_vector_phi_nodes (loop))
1938         continue;
1939       estimated = estimated_loop_iterations_int (loop, false);
1940       /* FIXME: Bypass this check as graphite doesn't update the
1941       count and frequency correctly now.  */
1942       if (!flag_loop_parallelize_all
1943           && ((estimated !=-1 
1944              && estimated <= (HOST_WIDE_INT) n_threads * MIN_PER_THREAD)
1945               /* Do not bother with loops in cold areas.  */
1946               || optimize_loop_nest_for_size_p (loop)))
1947         continue;
1948
1949       if (!try_get_loop_niter (loop, &niter_desc))
1950         continue;
1951
1952       if (!try_create_reduction_list (loop, reduction_list))
1953         continue;
1954
1955       if (!flag_loop_parallelize_all
1956           && !loop_parallel_p (loop, &parloop_obstack))
1957         continue;
1958
1959       changed = true;
1960       if (dump_file && (dump_flags & TDF_DETAILS))
1961       {
1962         if (loop->inner)
1963           fprintf (dump_file, "parallelizing outer loop %d\n",loop->header->index);
1964         else
1965           fprintf (dump_file, "parallelizing inner loop %d\n",loop->header->index);
1966         loop_loc = find_loop_location (loop);
1967         if (loop_loc != UNKNOWN_LOC)
1968           fprintf (dump_file, "\nloop at %s:%d: ",
1969                    LOC_FILE (loop_loc), LOC_LINE (loop_loc));
1970       }
1971       gen_parallel_loop (loop, reduction_list,
1972                          n_threads, &niter_desc);
1973       verify_flow_info ();
1974       verify_dominators (CDI_DOMINATORS);
1975       verify_loop_structure ();
1976       verify_loop_closed_ssa (true);
1977     }
1978
1979   free_stmt_vec_info_vec ();
1980   htab_delete (reduction_list);
1981   obstack_free (&parloop_obstack, NULL);
1982
1983   /* Parallelization will cause new function calls to be inserted through
1984      which local variables will escape.  Reset the points-to solution
1985      for ESCAPED.  */
1986   if (changed)
1987     pt_solution_reset (&cfun->gimple_df->escaped);
1988
1989   return changed;
1990 }
1991
1992 #include "gt-tree-parloops.h"