OSDN Git Service

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