re PR tree-optimization/56541 (vectorizaton fails in conditional assignment of a...
[platform/upstream/gcc.git] / gcc / tree-if-conv.c
1 /* If-conversion for vectorizer.
2    Copyright (C) 2004-2016 Free Software Foundation, Inc.
3    Contributed by Devang Patel <dpatel@apple.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 /* This pass implements a tree level if-conversion of loops.  Its
22    initial goal is to help the vectorizer to vectorize loops with
23    conditions.
24
25    A short description of if-conversion:
26
27      o Decide if a loop is if-convertible or not.
28      o Walk all loop basic blocks in breadth first order (BFS order).
29        o Remove conditional statements (at the end of basic block)
30          and propagate condition into destination basic blocks'
31          predicate list.
32        o Replace modify expression with conditional modify expression
33          using current basic block's condition.
34      o Merge all basic blocks
35        o Replace phi nodes with conditional modify expr
36        o Merge all basic blocks into header
37
38      Sample transformation:
39
40      INPUT
41      -----
42
43      # i_23 = PHI <0(0), i_18(10)>;
44      <L0>:;
45      j_15 = A[i_23];
46      if (j_15 > 41) goto <L1>; else goto <L17>;
47
48      <L17>:;
49      goto <bb 3> (<L3>);
50
51      <L1>:;
52
53      # iftmp.2_4 = PHI <0(8), 42(2)>;
54      <L3>:;
55      A[i_23] = iftmp.2_4;
56      i_18 = i_23 + 1;
57      if (i_18 <= 15) goto <L19>; else goto <L18>;
58
59      <L19>:;
60      goto <bb 1> (<L0>);
61
62      <L18>:;
63
64      OUTPUT
65      ------
66
67      # i_23 = PHI <0(0), i_18(10)>;
68      <L0>:;
69      j_15 = A[i_23];
70
71      <L3>:;
72      iftmp.2_4 = j_15 > 41 ? 42 : 0;
73      A[i_23] = iftmp.2_4;
74      i_18 = i_23 + 1;
75      if (i_18 <= 15) goto <L19>; else goto <L18>;
76
77      <L19>:;
78      goto <bb 1> (<L0>);
79
80      <L18>:;
81 */
82
83 #include "config.h"
84 #include "system.h"
85 #include "coretypes.h"
86 #include "backend.h"
87 #include "rtl.h"
88 #include "tree.h"
89 #include "gimple.h"
90 #include "cfghooks.h"
91 #include "tree-pass.h"
92 #include "ssa.h"
93 #include "expmed.h"
94 #include "optabs-query.h"
95 #include "gimple-pretty-print.h"
96 #include "alias.h"
97 #include "fold-const.h"
98 #include "stor-layout.h"
99 #include "gimple-fold.h"
100 #include "gimplify.h"
101 #include "gimple-iterator.h"
102 #include "gimplify-me.h"
103 #include "tree-cfg.h"
104 #include "tree-into-ssa.h"
105 #include "tree-ssa.h"
106 #include "cfgloop.h"
107 #include "tree-data-ref.h"
108 #include "tree-scalar-evolution.h"
109 #include "tree-ssa-loop-ivopts.h"
110 #include "tree-ssa-address.h"
111 #include "dbgcnt.h"
112 #include "tree-hash-traits.h"
113 #include "varasm.h"
114 #include "builtins.h"
115 #include "params.h"
116
117 /* Only handle PHIs with no more arguments unless we are asked to by
118    simd pragma.  */
119 #define MAX_PHI_ARG_NUM \
120   ((unsigned) PARAM_VALUE (PARAM_MAX_TREE_IF_CONVERSION_PHI_ARGS))
121
122 /* Indicate if new load/store that needs to be predicated is introduced
123    during if conversion.  */
124 static bool any_pred_load_store;
125
126 /* Indicate if there are any complicated PHIs that need to be handled in
127    if-conversion.  Complicated PHI has more than two arguments and can't
128    be degenerated to two arguments PHI.  See more information in comment
129    before phi_convertible_by_degenerating_args.  */
130 static bool any_complicated_phi;
131
132 /* Hash for struct innermost_loop_behavior.  It depends on the user to
133    free the memory.  */
134
135 struct innermost_loop_behavior_hash : nofree_ptr_hash <innermost_loop_behavior>
136 {
137   static inline hashval_t hash (const value_type &);
138   static inline bool equal (const value_type &,
139                             const compare_type &);
140 };
141
142 inline hashval_t
143 innermost_loop_behavior_hash::hash (const value_type &e)
144 {
145   hashval_t hash;
146
147   hash = iterative_hash_expr (e->base_address, 0);
148   hash = iterative_hash_expr (e->offset, hash);
149   hash = iterative_hash_expr (e->init, hash);
150   return iterative_hash_expr (e->step, hash);
151 }
152
153 inline bool
154 innermost_loop_behavior_hash::equal (const value_type &e1,
155                                      const compare_type &e2)
156 {
157   if ((e1->base_address && !e2->base_address)
158       || (!e1->base_address && e2->base_address)
159       || (!e1->offset && e2->offset)
160       || (e1->offset && !e2->offset)
161       || (!e1->init && e2->init)
162       || (e1->init && !e2->init)
163       || (!e1->step && e2->step)
164       || (e1->step && !e2->step))
165     return false;
166
167   if (e1->base_address && e2->base_address
168       && !operand_equal_p (e1->base_address, e2->base_address, 0))
169     return false;
170   if (e1->offset && e2->offset
171       && !operand_equal_p (e1->offset, e2->offset, 0))
172     return false;
173   if (e1->init && e2->init
174       && !operand_equal_p (e1->init, e2->init, 0))
175     return false;
176   if (e1->step && e2->step
177       && !operand_equal_p (e1->step, e2->step, 0))
178     return false;
179
180   return true;
181 }
182
183 /* List of basic blocks in if-conversion-suitable order.  */
184 static basic_block *ifc_bbs;
185
186 /* Hash table to store <DR's innermost loop behavior, DR> pairs.  */
187 static hash_map<innermost_loop_behavior_hash,
188                 data_reference_p> *innermost_DR_map;
189
190 /* Hash table to store <base reference, DR> pairs.  */
191 static hash_map<tree_operand_hash, data_reference_p> *baseref_DR_map;
192
193 /* Structure used to predicate basic blocks.  This is attached to the
194    ->aux field of the BBs in the loop to be if-converted.  */
195 struct bb_predicate {
196
197   /* The condition under which this basic block is executed.  */
198   tree predicate;
199
200   /* PREDICATE is gimplified, and the sequence of statements is
201      recorded here, in order to avoid the duplication of computations
202      that occur in previous conditions.  See PR44483.  */
203   gimple_seq predicate_gimplified_stmts;
204 };
205
206 /* Returns true when the basic block BB has a predicate.  */
207
208 static inline bool
209 bb_has_predicate (basic_block bb)
210 {
211   return bb->aux != NULL;
212 }
213
214 /* Returns the gimplified predicate for basic block BB.  */
215
216 static inline tree
217 bb_predicate (basic_block bb)
218 {
219   return ((struct bb_predicate *) bb->aux)->predicate;
220 }
221
222 /* Sets the gimplified predicate COND for basic block BB.  */
223
224 static inline void
225 set_bb_predicate (basic_block bb, tree cond)
226 {
227   gcc_assert ((TREE_CODE (cond) == TRUTH_NOT_EXPR
228                && is_gimple_condexpr (TREE_OPERAND (cond, 0)))
229               || is_gimple_condexpr (cond));
230   ((struct bb_predicate *) bb->aux)->predicate = cond;
231 }
232
233 /* Returns the sequence of statements of the gimplification of the
234    predicate for basic block BB.  */
235
236 static inline gimple_seq
237 bb_predicate_gimplified_stmts (basic_block bb)
238 {
239   return ((struct bb_predicate *) bb->aux)->predicate_gimplified_stmts;
240 }
241
242 /* Sets the sequence of statements STMTS of the gimplification of the
243    predicate for basic block BB.  */
244
245 static inline void
246 set_bb_predicate_gimplified_stmts (basic_block bb, gimple_seq stmts)
247 {
248   ((struct bb_predicate *) bb->aux)->predicate_gimplified_stmts = stmts;
249 }
250
251 /* Adds the sequence of statements STMTS to the sequence of statements
252    of the predicate for basic block BB.  */
253
254 static inline void
255 add_bb_predicate_gimplified_stmts (basic_block bb, gimple_seq stmts)
256 {
257   gimple_seq_add_seq
258     (&(((struct bb_predicate *) bb->aux)->predicate_gimplified_stmts), stmts);
259 }
260
261 /* Initializes to TRUE the predicate of basic block BB.  */
262
263 static inline void
264 init_bb_predicate (basic_block bb)
265 {
266   bb->aux = XNEW (struct bb_predicate);
267   set_bb_predicate_gimplified_stmts (bb, NULL);
268   set_bb_predicate (bb, boolean_true_node);
269 }
270
271 /* Release the SSA_NAMEs associated with the predicate of basic block BB,
272    but don't actually free it.  */
273
274 static inline void
275 release_bb_predicate (basic_block bb)
276 {
277   gimple_seq stmts = bb_predicate_gimplified_stmts (bb);
278   if (stmts)
279     {
280       gimple_stmt_iterator i;
281
282       for (i = gsi_start (stmts); !gsi_end_p (i); gsi_next (&i))
283         free_stmt_operands (cfun, gsi_stmt (i));
284       set_bb_predicate_gimplified_stmts (bb, NULL);
285     }
286 }
287
288 /* Free the predicate of basic block BB.  */
289
290 static inline void
291 free_bb_predicate (basic_block bb)
292 {
293   if (!bb_has_predicate (bb))
294     return;
295
296   release_bb_predicate (bb);
297   free (bb->aux);
298   bb->aux = NULL;
299 }
300
301 /* Reinitialize predicate of BB with the true predicate.  */
302
303 static inline void
304 reset_bb_predicate (basic_block bb)
305 {
306   if (!bb_has_predicate (bb))
307     init_bb_predicate (bb);
308   else
309     {
310       release_bb_predicate (bb);
311       set_bb_predicate (bb, boolean_true_node);
312     }
313 }
314
315 /* Returns a new SSA_NAME of type TYPE that is assigned the value of
316    the expression EXPR.  Inserts the statement created for this
317    computation before GSI and leaves the iterator GSI at the same
318    statement.  */
319
320 static tree
321 ifc_temp_var (tree type, tree expr, gimple_stmt_iterator *gsi)
322 {
323   tree new_name = make_temp_ssa_name (type, NULL, "_ifc_");
324   gimple *stmt = gimple_build_assign (new_name, expr);
325   gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
326   return new_name;
327 }
328
329 /* Return true when COND is a false predicate.  */
330
331 static inline bool
332 is_false_predicate (tree cond)
333 {
334   return (cond != NULL_TREE
335           && (cond == boolean_false_node
336               || integer_zerop (cond)));
337 }
338
339 /* Return true when COND is a true predicate.  */
340
341 static inline bool
342 is_true_predicate (tree cond)
343 {
344   return (cond == NULL_TREE
345           || cond == boolean_true_node
346           || integer_onep (cond));
347 }
348
349 /* Returns true when BB has a predicate that is not trivial: true or
350    NULL_TREE.  */
351
352 static inline bool
353 is_predicated (basic_block bb)
354 {
355   return !is_true_predicate (bb_predicate (bb));
356 }
357
358 /* Parses the predicate COND and returns its comparison code and
359    operands OP0 and OP1.  */
360
361 static enum tree_code
362 parse_predicate (tree cond, tree *op0, tree *op1)
363 {
364   gimple *s;
365
366   if (TREE_CODE (cond) == SSA_NAME
367       && is_gimple_assign (s = SSA_NAME_DEF_STMT (cond)))
368     {
369       if (TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
370         {
371           *op0 = gimple_assign_rhs1 (s);
372           *op1 = gimple_assign_rhs2 (s);
373           return gimple_assign_rhs_code (s);
374         }
375
376       else if (gimple_assign_rhs_code (s) == TRUTH_NOT_EXPR)
377         {
378           tree op = gimple_assign_rhs1 (s);
379           tree type = TREE_TYPE (op);
380           enum tree_code code = parse_predicate (op, op0, op1);
381
382           return code == ERROR_MARK ? ERROR_MARK
383             : invert_tree_comparison (code, HONOR_NANS (type));
384         }
385
386       return ERROR_MARK;
387     }
388
389   if (COMPARISON_CLASS_P (cond))
390     {
391       *op0 = TREE_OPERAND (cond, 0);
392       *op1 = TREE_OPERAND (cond, 1);
393       return TREE_CODE (cond);
394     }
395
396   return ERROR_MARK;
397 }
398
399 /* Returns the fold of predicate C1 OR C2 at location LOC.  */
400
401 static tree
402 fold_or_predicates (location_t loc, tree c1, tree c2)
403 {
404   tree op1a, op1b, op2a, op2b;
405   enum tree_code code1 = parse_predicate (c1, &op1a, &op1b);
406   enum tree_code code2 = parse_predicate (c2, &op2a, &op2b);
407
408   if (code1 != ERROR_MARK && code2 != ERROR_MARK)
409     {
410       tree t = maybe_fold_or_comparisons (code1, op1a, op1b,
411                                           code2, op2a, op2b);
412       if (t)
413         return t;
414     }
415
416   return fold_build2_loc (loc, TRUTH_OR_EXPR, boolean_type_node, c1, c2);
417 }
418
419 /* Returns true if N is either a constant or a SSA_NAME.  */
420
421 static bool
422 constant_or_ssa_name (tree n)
423 {
424   switch (TREE_CODE (n))
425     {
426       case SSA_NAME:
427       case INTEGER_CST:
428       case REAL_CST:
429       case COMPLEX_CST:
430       case VECTOR_CST:
431         return true;
432       default:
433         return false;
434     }
435 }
436
437 /* Returns either a COND_EXPR or the folded expression if the folded
438    expression is a MIN_EXPR, a MAX_EXPR, an ABS_EXPR,
439    a constant or a SSA_NAME. */
440
441 static tree
442 fold_build_cond_expr (tree type, tree cond, tree rhs, tree lhs)
443 {
444   tree rhs1, lhs1, cond_expr;
445
446   /* If COND is comparison r != 0 and r has boolean type, convert COND
447      to SSA_NAME to accept by vect bool pattern.  */
448   if (TREE_CODE (cond) == NE_EXPR)
449     {
450       tree op0 = TREE_OPERAND (cond, 0);
451       tree op1 = TREE_OPERAND (cond, 1);
452       if (TREE_CODE (op0) == SSA_NAME
453           && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
454           && (integer_zerop (op1)))
455         cond = op0;
456     }
457   cond_expr = fold_ternary (COND_EXPR, type, cond,
458                             rhs, lhs);
459
460   if (cond_expr == NULL_TREE)
461     return build3 (COND_EXPR, type, cond, rhs, lhs);
462
463   STRIP_USELESS_TYPE_CONVERSION (cond_expr);
464
465   if (constant_or_ssa_name (cond_expr))
466     return cond_expr;
467
468   if (TREE_CODE (cond_expr) == ABS_EXPR)
469     {
470       rhs1 = TREE_OPERAND (cond_expr, 1);
471       STRIP_USELESS_TYPE_CONVERSION (rhs1);
472       if (constant_or_ssa_name (rhs1))
473         return build1 (ABS_EXPR, type, rhs1);
474     }
475
476   if (TREE_CODE (cond_expr) == MIN_EXPR
477       || TREE_CODE (cond_expr) == MAX_EXPR)
478     {
479       lhs1 = TREE_OPERAND (cond_expr, 0);
480       STRIP_USELESS_TYPE_CONVERSION (lhs1);
481       rhs1 = TREE_OPERAND (cond_expr, 1);
482       STRIP_USELESS_TYPE_CONVERSION (rhs1);
483       if (constant_or_ssa_name (rhs1)
484           && constant_or_ssa_name (lhs1))
485         return build2 (TREE_CODE (cond_expr), type, lhs1, rhs1);
486     }
487   return build3 (COND_EXPR, type, cond, rhs, lhs);
488 }
489
490 /* Add condition NC to the predicate list of basic block BB.  LOOP is
491    the loop to be if-converted. Use predicate of cd-equivalent block
492    for join bb if it exists: we call basic blocks bb1 and bb2 
493    cd-equivalent if they are executed under the same condition.  */
494
495 static inline void
496 add_to_predicate_list (struct loop *loop, basic_block bb, tree nc)
497 {
498   tree bc, *tp;
499   basic_block dom_bb;
500
501   if (is_true_predicate (nc))
502     return;
503
504   /* If dominance tells us this basic block is always executed,
505      don't record any predicates for it.  */
506   if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
507     return;
508
509   dom_bb = get_immediate_dominator (CDI_DOMINATORS, bb);
510   /* We use notion of cd equivalence to get simpler predicate for
511      join block, e.g. if join block has 2 predecessors with predicates
512      p1 & p2 and p1 & !p2, we'd like to get p1 for it instead of
513      p1 & p2 | p1 & !p2.  */
514   if (dom_bb != loop->header
515       && get_immediate_dominator (CDI_POST_DOMINATORS, dom_bb) == bb)
516     {
517       gcc_assert (flow_bb_inside_loop_p (loop, dom_bb));
518       bc = bb_predicate (dom_bb);
519       if (!is_true_predicate (bc))
520         set_bb_predicate (bb, bc);
521       else
522         gcc_assert (is_true_predicate (bb_predicate (bb)));
523       if (dump_file && (dump_flags & TDF_DETAILS))
524         fprintf (dump_file, "Use predicate of bb#%d for bb#%d\n",
525                  dom_bb->index, bb->index);
526       return;
527     }
528
529   if (!is_predicated (bb))
530     bc = nc;
531   else
532     {
533       bc = bb_predicate (bb);
534       bc = fold_or_predicates (EXPR_LOCATION (bc), nc, bc);
535       if (is_true_predicate (bc))
536         {
537           reset_bb_predicate (bb);
538           return;
539         }
540     }
541
542   /* Allow a TRUTH_NOT_EXPR around the main predicate.  */
543   if (TREE_CODE (bc) == TRUTH_NOT_EXPR)
544     tp = &TREE_OPERAND (bc, 0);
545   else
546     tp = &bc;
547   if (!is_gimple_condexpr (*tp))
548     {
549       gimple_seq stmts;
550       *tp = force_gimple_operand_1 (*tp, &stmts, is_gimple_condexpr, NULL_TREE);
551       add_bb_predicate_gimplified_stmts (bb, stmts);
552     }
553   set_bb_predicate (bb, bc);
554 }
555
556 /* Add the condition COND to the previous condition PREV_COND, and add
557    this to the predicate list of the destination of edge E.  LOOP is
558    the loop to be if-converted.  */
559
560 static void
561 add_to_dst_predicate_list (struct loop *loop, edge e,
562                            tree prev_cond, tree cond)
563 {
564   if (!flow_bb_inside_loop_p (loop, e->dest))
565     return;
566
567   if (!is_true_predicate (prev_cond))
568     cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
569                         prev_cond, cond);
570
571   if (!dominated_by_p (CDI_DOMINATORS, loop->latch, e->dest))
572     add_to_predicate_list (loop, e->dest, cond);
573 }
574
575 /* Return true if one of the successor edges of BB exits LOOP.  */
576
577 static bool
578 bb_with_exit_edge_p (struct loop *loop, basic_block bb)
579 {
580   edge e;
581   edge_iterator ei;
582
583   FOR_EACH_EDGE (e, ei, bb->succs)
584     if (loop_exit_edge_p (loop, e))
585       return true;
586
587   return false;
588 }
589
590 /* Given PHI which has more than two arguments, this function checks if
591    it's if-convertible by degenerating its arguments.  Specifically, if
592    below two conditions are satisfied:
593
594      1) Number of PHI arguments with different values equals to 2 and one
595         argument has the only occurrence.
596      2) The edge corresponding to the unique argument isn't critical edge.
597
598    Such PHI can be handled as PHIs have only two arguments.  For example,
599    below PHI:
600
601      res = PHI <A_1(e1), A_1(e2), A_2(e3)>;
602
603    can be transformed into:
604
605      res = (predicate of e3) ? A_2 : A_1;
606
607    Return TRUE if it is the case, FALSE otherwise.  */
608
609 static bool
610 phi_convertible_by_degenerating_args (gphi *phi)
611 {
612   edge e;
613   tree arg, t1 = NULL, t2 = NULL;
614   unsigned int i, i1 = 0, i2 = 0, n1 = 0, n2 = 0;
615   unsigned int num_args = gimple_phi_num_args (phi);
616
617   gcc_assert (num_args > 2);
618
619   for (i = 0; i < num_args; i++)
620     {
621       arg = gimple_phi_arg_def (phi, i);
622       if (t1 == NULL || operand_equal_p (t1, arg, 0))
623         {
624           n1++;
625           i1 = i;
626           t1 = arg;
627         }
628       else if (t2 == NULL || operand_equal_p (t2, arg, 0))
629         {
630           n2++;
631           i2 = i;
632           t2 = arg;
633         }
634       else
635         return false;
636     }
637
638   if (n1 != 1 && n2 != 1)
639     return false;
640
641   /* Check if the edge corresponding to the unique arg is critical.  */
642   e = gimple_phi_arg_edge (phi, (n1 == 1) ? i1 : i2);
643   if (EDGE_COUNT (e->src->succs) > 1)
644     return false;
645
646   return true;
647 }
648
649 /* Return true when PHI is if-convertible.  PHI is part of loop LOOP
650    and it belongs to basic block BB.  Note at this point, it is sure
651    that PHI is if-convertible.  This function updates global variable
652    ANY_COMPLICATED_PHI if PHI is complicated.  */
653
654 static bool
655 if_convertible_phi_p (struct loop *loop, basic_block bb, gphi *phi)
656 {
657   if (dump_file && (dump_flags & TDF_DETAILS))
658     {
659       fprintf (dump_file, "-------------------------\n");
660       print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
661     }
662
663   if (bb != loop->header
664       && gimple_phi_num_args (phi) > 2
665       && !phi_convertible_by_degenerating_args (phi))
666     any_complicated_phi = true;
667
668   return true;
669 }
670
671 /* Records the status of a data reference.  This struct is attached to
672    each DR->aux field.  */
673
674 struct ifc_dr {
675   bool rw_unconditionally;
676   bool w_unconditionally;
677   bool written_at_least_once;
678
679   tree rw_predicate;
680   tree w_predicate;
681   tree base_w_predicate;
682 };
683
684 #define IFC_DR(DR) ((struct ifc_dr *) (DR)->aux)
685 #define DR_BASE_W_UNCONDITIONALLY(DR) (IFC_DR (DR)->written_at_least_once)
686 #define DR_RW_UNCONDITIONALLY(DR) (IFC_DR (DR)->rw_unconditionally)
687 #define DR_W_UNCONDITIONALLY(DR) (IFC_DR (DR)->w_unconditionally)
688
689 /* Iterates over DR's and stores refs, DR and base refs, DR pairs in
690    HASH tables.  While storing them in HASH table, it checks if the
691    reference is unconditionally read or written and stores that as a flag
692    information.  For base reference it checks if it is written atlest once
693    unconditionally and stores it as flag information along with DR.
694    In other words for every data reference A in STMT there exist other
695    accesses to a data reference with the same base with predicates that
696    add up (OR-up) to the true predicate: this ensures that the data
697    reference A is touched (read or written) on every iteration of the
698    if-converted loop.  */
699 static void
700 hash_memrefs_baserefs_and_store_DRs_read_written_info (data_reference_p a)
701 {
702
703   data_reference_p *master_dr, *base_master_dr;
704   tree base_ref = DR_BASE_OBJECT (a);
705   innermost_loop_behavior *innermost = &DR_INNERMOST (a);
706   tree ca = bb_predicate (gimple_bb (DR_STMT (a)));
707   bool exist1, exist2;
708
709   master_dr = &innermost_DR_map->get_or_insert (innermost, &exist1);
710   if (!exist1)
711     *master_dr = a;
712
713   if (DR_IS_WRITE (a))
714     {
715       IFC_DR (*master_dr)->w_predicate
716         = fold_or_predicates (UNKNOWN_LOCATION, ca,
717                               IFC_DR (*master_dr)->w_predicate);
718       if (is_true_predicate (IFC_DR (*master_dr)->w_predicate))
719         DR_W_UNCONDITIONALLY (*master_dr) = true;
720     }
721   IFC_DR (*master_dr)->rw_predicate
722     = fold_or_predicates (UNKNOWN_LOCATION, ca,
723                           IFC_DR (*master_dr)->rw_predicate);
724   if (is_true_predicate (IFC_DR (*master_dr)->rw_predicate))
725     DR_RW_UNCONDITIONALLY (*master_dr) = true;
726
727   if (DR_IS_WRITE (a))
728     {
729       base_master_dr = &baseref_DR_map->get_or_insert (base_ref, &exist2);
730       if (!exist2)
731         *base_master_dr = a;
732       IFC_DR (*base_master_dr)->base_w_predicate
733         = fold_or_predicates (UNKNOWN_LOCATION, ca,
734                               IFC_DR (*base_master_dr)->base_w_predicate);
735       if (is_true_predicate (IFC_DR (*base_master_dr)->base_w_predicate))
736         DR_BASE_W_UNCONDITIONALLY (*base_master_dr) = true;
737     }
738 }
739
740 /* Return true when the memory references of STMT won't trap in the
741    if-converted code.  There are two things that we have to check for:
742
743    - writes to memory occur to writable memory: if-conversion of
744    memory writes transforms the conditional memory writes into
745    unconditional writes, i.e. "if (cond) A[i] = foo" is transformed
746    into "A[i] = cond ? foo : A[i]", and as the write to memory may not
747    be executed at all in the original code, it may be a readonly
748    memory.  To check that A is not const-qualified, we check that
749    there exists at least an unconditional write to A in the current
750    function.
751
752    - reads or writes to memory are valid memory accesses for every
753    iteration.  To check that the memory accesses are correctly formed
754    and that we are allowed to read and write in these locations, we
755    check that the memory accesses to be if-converted occur at every
756    iteration unconditionally.
757
758    Returns true for the memory reference in STMT, same memory reference
759    is read or written unconditionally atleast once and the base memory
760    reference is written unconditionally once.  This is to check reference
761    will not write fault.  Also retuns true if the memory reference is
762    unconditionally read once then we are conditionally writing to memory
763    which is defined as read and write and is bound to the definition
764    we are seeing.  */
765 static bool
766 ifcvt_memrefs_wont_trap (gimple *stmt, vec<data_reference_p> drs)
767 {
768   data_reference_p *master_dr, *base_master_dr;
769   data_reference_p a = drs[gimple_uid (stmt) - 1];
770
771   tree base = DR_BASE_OBJECT (a);
772   innermost_loop_behavior *innermost = &DR_INNERMOST (a);
773
774   gcc_assert (DR_STMT (a) == stmt);
775   gcc_assert (DR_BASE_ADDRESS (a) || DR_OFFSET (a)
776               || DR_INIT (a) || DR_STEP (a));
777
778   master_dr = innermost_DR_map->get (innermost);
779   gcc_assert (master_dr != NULL);
780
781   base_master_dr = baseref_DR_map->get (base);
782
783   /* If a is unconditionally written to it doesn't trap.  */
784   if (DR_W_UNCONDITIONALLY (*master_dr))
785     return true;
786
787   /* If a is unconditionally accessed then ... */
788   if (DR_RW_UNCONDITIONALLY (*master_dr))
789     {
790       /* an unconditional read won't trap.  */
791       if (DR_IS_READ (a))
792         return true;
793
794       /* an unconditionaly write won't trap if the base is written
795          to unconditionally.  */
796       if (base_master_dr
797           && DR_BASE_W_UNCONDITIONALLY (*base_master_dr))
798         return PARAM_VALUE (PARAM_ALLOW_STORE_DATA_RACES);
799       else
800         {
801           /* or the base is know to be not readonly.  */
802           tree base_tree = get_base_address (DR_REF (a));
803           if (DECL_P (base_tree)
804               && decl_binds_to_current_def_p (base_tree)
805               && ! TREE_READONLY (base_tree))
806             return PARAM_VALUE (PARAM_ALLOW_STORE_DATA_RACES);
807         }
808     }
809   return false;
810 }
811
812 /* Return true if STMT could be converted into a masked load or store
813    (conditional load or store based on a mask computed from bb predicate).  */
814
815 static bool
816 ifcvt_can_use_mask_load_store (gimple *stmt)
817 {
818   tree lhs, ref;
819   machine_mode mode;
820   basic_block bb = gimple_bb (stmt);
821   bool is_load;
822
823   if (!(flag_tree_loop_vectorize || bb->loop_father->force_vectorize)
824       || bb->loop_father->dont_vectorize
825       || !gimple_assign_single_p (stmt)
826       || gimple_has_volatile_ops (stmt))
827     return false;
828
829   /* Check whether this is a load or store.  */
830   lhs = gimple_assign_lhs (stmt);
831   if (gimple_store_p (stmt))
832     {
833       if (!is_gimple_val (gimple_assign_rhs1 (stmt)))
834         return false;
835       is_load = false;
836       ref = lhs;
837     }
838   else if (gimple_assign_load_p (stmt))
839     {
840       is_load = true;
841       ref = gimple_assign_rhs1 (stmt);
842     }
843   else
844     return false;
845
846   if (may_be_nonaddressable_p (ref))
847     return false;
848
849   /* Mask should be integer mode of the same size as the load/store
850      mode.  */
851   mode = TYPE_MODE (TREE_TYPE (lhs));
852   if (int_mode_for_mode (mode) == BLKmode
853       || VECTOR_MODE_P (mode))
854     return false;
855
856   if (can_vec_mask_load_store_p (mode, VOIDmode, is_load))
857     return true;
858
859   return false;
860 }
861
862 /* Return true when STMT is if-convertible.
863
864    GIMPLE_ASSIGN statement is not if-convertible if,
865    - it is not movable,
866    - it could trap,
867    - LHS is not var decl.  */
868
869 static bool
870 if_convertible_gimple_assign_stmt_p (gimple *stmt,
871                                      vec<data_reference_p> refs)
872 {
873   tree lhs = gimple_assign_lhs (stmt);
874
875   if (dump_file && (dump_flags & TDF_DETAILS))
876     {
877       fprintf (dump_file, "-------------------------\n");
878       print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
879     }
880
881   if (!is_gimple_reg_type (TREE_TYPE (lhs)))
882     return false;
883
884   /* Some of these constrains might be too conservative.  */
885   if (stmt_ends_bb_p (stmt)
886       || gimple_has_volatile_ops (stmt)
887       || (TREE_CODE (lhs) == SSA_NAME
888           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
889       || gimple_has_side_effects (stmt))
890     {
891       if (dump_file && (dump_flags & TDF_DETAILS))
892         fprintf (dump_file, "stmt not suitable for ifcvt\n");
893       return false;
894     }
895
896   /* tree-into-ssa.c uses GF_PLF_1, so avoid it, because
897      in between if_convertible_loop_p and combine_blocks
898      we can perform loop versioning.  */
899   gimple_set_plf (stmt, GF_PLF_2, false);
900
901   if ((! gimple_vuse (stmt)
902        || gimple_could_trap_p_1 (stmt, false, false)
903        || ! ifcvt_memrefs_wont_trap (stmt, refs))
904       && gimple_could_trap_p (stmt))
905     {
906       if (ifcvt_can_use_mask_load_store (stmt))
907         {
908           gimple_set_plf (stmt, GF_PLF_2, true);
909           any_pred_load_store = true;
910           return true;
911         }
912       if (dump_file && (dump_flags & TDF_DETAILS))
913         fprintf (dump_file, "tree could trap...\n");
914       return false;
915     }
916
917   /* When if-converting stores force versioning, likewise if we
918      ended up generating store data races.  */
919   if (gimple_vdef (stmt))
920     any_pred_load_store = true;
921
922   return true;
923 }
924
925 /* Return true when STMT is if-convertible.
926
927    A statement is if-convertible if:
928    - it is an if-convertible GIMPLE_ASSIGN,
929    - it is a GIMPLE_LABEL or a GIMPLE_COND,
930    - it is builtins call.  */
931
932 static bool
933 if_convertible_stmt_p (gimple *stmt, vec<data_reference_p> refs)
934 {
935   switch (gimple_code (stmt))
936     {
937     case GIMPLE_LABEL:
938     case GIMPLE_DEBUG:
939     case GIMPLE_COND:
940       return true;
941
942     case GIMPLE_ASSIGN:
943       return if_convertible_gimple_assign_stmt_p (stmt, refs);
944
945     case GIMPLE_CALL:
946       {
947         tree fndecl = gimple_call_fndecl (stmt);
948         if (fndecl)
949           {
950             int flags = gimple_call_flags (stmt);
951             if ((flags & ECF_CONST)
952                 && !(flags & ECF_LOOPING_CONST_OR_PURE)
953                 /* We can only vectorize some builtins at the moment,
954                    so restrict if-conversion to those.  */
955                 && DECL_BUILT_IN (fndecl))
956               return true;
957           }
958         return false;
959       }
960
961     default:
962       /* Don't know what to do with 'em so don't do anything.  */
963       if (dump_file && (dump_flags & TDF_DETAILS))
964         {
965           fprintf (dump_file, "don't know what to do\n");
966           print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
967         }
968       return false;
969       break;
970     }
971
972   return true;
973 }
974
975 /* Assumes that BB has more than 1 predecessors.
976    Returns false if at least one successor is not on critical edge
977    and true otherwise.  */
978
979 static inline bool
980 all_preds_critical_p (basic_block bb)
981 {
982   edge e;
983   edge_iterator ei;
984
985   FOR_EACH_EDGE (e, ei, bb->preds)
986     if (EDGE_COUNT (e->src->succs) == 1)
987       return false;
988   return true;
989 }
990
991 /* Returns true if at least one successor in on critical edge.  */
992 static inline bool
993 has_pred_critical_p (basic_block bb)
994 {
995   edge e;
996   edge_iterator ei;
997
998   FOR_EACH_EDGE (e, ei, bb->preds)
999     if (EDGE_COUNT (e->src->succs) > 1)
1000       return true;
1001   return false;
1002 }
1003
1004 /* Return true when BB is if-convertible.  This routine does not check
1005    basic block's statements and phis.
1006
1007    A basic block is not if-convertible if:
1008    - it is non-empty and it is after the exit block (in BFS order),
1009    - it is after the exit block but before the latch,
1010    - its edges are not normal.
1011
1012    EXIT_BB is the basic block containing the exit of the LOOP.  BB is
1013    inside LOOP.  */
1014
1015 static bool
1016 if_convertible_bb_p (struct loop *loop, basic_block bb, basic_block exit_bb)
1017 {
1018   edge e;
1019   edge_iterator ei;
1020
1021   if (dump_file && (dump_flags & TDF_DETAILS))
1022     fprintf (dump_file, "----------[%d]-------------\n", bb->index);
1023
1024   if (EDGE_COUNT (bb->succs) > 2)
1025     return false;
1026
1027   if (exit_bb)
1028     {
1029       if (bb != loop->latch)
1030         {
1031           if (dump_file && (dump_flags & TDF_DETAILS))
1032             fprintf (dump_file, "basic block after exit bb but before latch\n");
1033           return false;
1034         }
1035       else if (!empty_block_p (bb))
1036         {
1037           if (dump_file && (dump_flags & TDF_DETAILS))
1038             fprintf (dump_file, "non empty basic block after exit bb\n");
1039           return false;
1040         }
1041       else if (bb == loop->latch
1042                && bb != exit_bb
1043                && !dominated_by_p (CDI_DOMINATORS, bb, exit_bb))
1044           {
1045             if (dump_file && (dump_flags & TDF_DETAILS))
1046               fprintf (dump_file, "latch is not dominated by exit_block\n");
1047             return false;
1048           }
1049     }
1050
1051   /* Be less adventurous and handle only normal edges.  */
1052   FOR_EACH_EDGE (e, ei, bb->succs)
1053     if (e->flags & (EDGE_EH | EDGE_ABNORMAL | EDGE_IRREDUCIBLE_LOOP))
1054       {
1055         if (dump_file && (dump_flags & TDF_DETAILS))
1056           fprintf (dump_file, "Difficult to handle edges\n");
1057         return false;
1058       }
1059
1060   return true;
1061 }
1062
1063 /* Return true when all predecessor blocks of BB are visited.  The
1064    VISITED bitmap keeps track of the visited blocks.  */
1065
1066 static bool
1067 pred_blocks_visited_p (basic_block bb, bitmap *visited)
1068 {
1069   edge e;
1070   edge_iterator ei;
1071   FOR_EACH_EDGE (e, ei, bb->preds)
1072     if (!bitmap_bit_p (*visited, e->src->index))
1073       return false;
1074
1075   return true;
1076 }
1077
1078 /* Get body of a LOOP in suitable order for if-conversion.  It is
1079    caller's responsibility to deallocate basic block list.
1080    If-conversion suitable order is, breadth first sort (BFS) order
1081    with an additional constraint: select a block only if all its
1082    predecessors are already selected.  */
1083
1084 static basic_block *
1085 get_loop_body_in_if_conv_order (const struct loop *loop)
1086 {
1087   basic_block *blocks, *blocks_in_bfs_order;
1088   basic_block bb;
1089   bitmap visited;
1090   unsigned int index = 0;
1091   unsigned int visited_count = 0;
1092
1093   gcc_assert (loop->num_nodes);
1094   gcc_assert (loop->latch != EXIT_BLOCK_PTR_FOR_FN (cfun));
1095
1096   blocks = XCNEWVEC (basic_block, loop->num_nodes);
1097   visited = BITMAP_ALLOC (NULL);
1098
1099   blocks_in_bfs_order = get_loop_body_in_bfs_order (loop);
1100
1101   index = 0;
1102   while (index < loop->num_nodes)
1103     {
1104       bb = blocks_in_bfs_order [index];
1105
1106       if (bb->flags & BB_IRREDUCIBLE_LOOP)
1107         {
1108           free (blocks_in_bfs_order);
1109           BITMAP_FREE (visited);
1110           free (blocks);
1111           return NULL;
1112         }
1113
1114       if (!bitmap_bit_p (visited, bb->index))
1115         {
1116           if (pred_blocks_visited_p (bb, &visited)
1117               || bb == loop->header)
1118             {
1119               /* This block is now visited.  */
1120               bitmap_set_bit (visited, bb->index);
1121               blocks[visited_count++] = bb;
1122             }
1123         }
1124
1125       index++;
1126
1127       if (index == loop->num_nodes
1128           && visited_count != loop->num_nodes)
1129         /* Not done yet.  */
1130         index = 0;
1131     }
1132   free (blocks_in_bfs_order);
1133   BITMAP_FREE (visited);
1134   return blocks;
1135 }
1136
1137 /* Returns true when the analysis of the predicates for all the basic
1138    blocks in LOOP succeeded.
1139
1140    predicate_bbs first allocates the predicates of the basic blocks.
1141    These fields are then initialized with the tree expressions
1142    representing the predicates under which a basic block is executed
1143    in the LOOP.  As the loop->header is executed at each iteration, it
1144    has the "true" predicate.  Other statements executed under a
1145    condition are predicated with that condition, for example
1146
1147    | if (x)
1148    |   S1;
1149    | else
1150    |   S2;
1151
1152    S1 will be predicated with "x", and
1153    S2 will be predicated with "!x".  */
1154
1155 static void
1156 predicate_bbs (loop_p loop)
1157 {
1158   unsigned int i;
1159
1160   for (i = 0; i < loop->num_nodes; i++)
1161     init_bb_predicate (ifc_bbs[i]);
1162
1163   for (i = 0; i < loop->num_nodes; i++)
1164     {
1165       basic_block bb = ifc_bbs[i];
1166       tree cond;
1167       gimple *stmt;
1168
1169       /* The loop latch and loop exit block are always executed and
1170          have no extra conditions to be processed: skip them.  */
1171       if (bb == loop->latch
1172           || bb_with_exit_edge_p (loop, bb))
1173         {
1174           reset_bb_predicate (bb);
1175           continue;
1176         }
1177
1178       cond = bb_predicate (bb);
1179       stmt = last_stmt (bb);
1180       if (stmt && gimple_code (stmt) == GIMPLE_COND)
1181         {
1182           tree c2;
1183           edge true_edge, false_edge;
1184           location_t loc = gimple_location (stmt);
1185           tree c = build2_loc (loc, gimple_cond_code (stmt),
1186                                     boolean_type_node,
1187                                     gimple_cond_lhs (stmt),
1188                                     gimple_cond_rhs (stmt));
1189
1190           /* Add new condition into destination's predicate list.  */
1191           extract_true_false_edges_from_block (gimple_bb (stmt),
1192                                                &true_edge, &false_edge);
1193
1194           /* If C is true, then TRUE_EDGE is taken.  */
1195           add_to_dst_predicate_list (loop, true_edge, unshare_expr (cond),
1196                                      unshare_expr (c));
1197
1198           /* If C is false, then FALSE_EDGE is taken.  */
1199           c2 = build1_loc (loc, TRUTH_NOT_EXPR, boolean_type_node,
1200                            unshare_expr (c));
1201           add_to_dst_predicate_list (loop, false_edge,
1202                                      unshare_expr (cond), c2);
1203
1204           cond = NULL_TREE;
1205         }
1206
1207       /* If current bb has only one successor, then consider it as an
1208          unconditional goto.  */
1209       if (single_succ_p (bb))
1210         {
1211           basic_block bb_n = single_succ (bb);
1212
1213           /* The successor bb inherits the predicate of its
1214              predecessor.  If there is no predicate in the predecessor
1215              bb, then consider the successor bb as always executed.  */
1216           if (cond == NULL_TREE)
1217             cond = boolean_true_node;
1218
1219           add_to_predicate_list (loop, bb_n, cond);
1220         }
1221     }
1222
1223   /* The loop header is always executed.  */
1224   reset_bb_predicate (loop->header);
1225   gcc_assert (bb_predicate_gimplified_stmts (loop->header) == NULL
1226               && bb_predicate_gimplified_stmts (loop->latch) == NULL);
1227 }
1228
1229 /* Return true when LOOP is if-convertible.  This is a helper function
1230    for if_convertible_loop_p.  REFS and DDRS are initialized and freed
1231    in if_convertible_loop_p.  */
1232
1233 static bool
1234 if_convertible_loop_p_1 (struct loop *loop, vec<data_reference_p> *refs)
1235 {
1236   unsigned int i;
1237   basic_block exit_bb = NULL;
1238
1239   if (find_data_references_in_loop (loop, refs) == chrec_dont_know)
1240     return false;
1241
1242   calculate_dominance_info (CDI_DOMINATORS);
1243   calculate_dominance_info (CDI_POST_DOMINATORS);
1244
1245   /* Allow statements that can be handled during if-conversion.  */
1246   ifc_bbs = get_loop_body_in_if_conv_order (loop);
1247   if (!ifc_bbs)
1248     {
1249       if (dump_file && (dump_flags & TDF_DETAILS))
1250         fprintf (dump_file, "Irreducible loop\n");
1251       return false;
1252     }
1253
1254   for (i = 0; i < loop->num_nodes; i++)
1255     {
1256       basic_block bb = ifc_bbs[i];
1257
1258       if (!if_convertible_bb_p (loop, bb, exit_bb))
1259         return false;
1260
1261       if (bb_with_exit_edge_p (loop, bb))
1262         exit_bb = bb;
1263     }
1264
1265   for (i = 0; i < loop->num_nodes; i++)
1266     {
1267       basic_block bb = ifc_bbs[i];
1268       gimple_stmt_iterator gsi;
1269
1270       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1271         switch (gimple_code (gsi_stmt (gsi)))
1272           {
1273           case GIMPLE_LABEL:
1274           case GIMPLE_ASSIGN:
1275           case GIMPLE_CALL:
1276           case GIMPLE_DEBUG:
1277           case GIMPLE_COND:
1278             gimple_set_uid (gsi_stmt (gsi), 0);
1279             break;
1280           default:
1281             return false;
1282           }
1283     }
1284
1285   data_reference_p dr;
1286
1287   innermost_DR_map
1288           = new hash_map<innermost_loop_behavior_hash, data_reference_p>;
1289   baseref_DR_map = new hash_map<tree_operand_hash, data_reference_p>;
1290
1291   predicate_bbs (loop);
1292
1293   for (i = 0; refs->iterate (i, &dr); i++)
1294     {
1295       tree ref = DR_REF (dr);
1296
1297       dr->aux = XNEW (struct ifc_dr);
1298       DR_BASE_W_UNCONDITIONALLY (dr) = false;
1299       DR_RW_UNCONDITIONALLY (dr) = false;
1300       DR_W_UNCONDITIONALLY (dr) = false;
1301       IFC_DR (dr)->rw_predicate = boolean_false_node;
1302       IFC_DR (dr)->w_predicate = boolean_false_node;
1303       IFC_DR (dr)->base_w_predicate = boolean_false_node;
1304       if (gimple_uid (DR_STMT (dr)) == 0)
1305         gimple_set_uid (DR_STMT (dr), i + 1);
1306
1307       /* If DR doesn't have innermost loop behavior or it's a compound
1308          memory reference, we synthesize its innermost loop behavior
1309          for hashing.  */
1310       if (TREE_CODE (ref) == COMPONENT_REF
1311           || TREE_CODE (ref) == IMAGPART_EXPR
1312           || TREE_CODE (ref) == REALPART_EXPR
1313           || !(DR_BASE_ADDRESS (dr) || DR_OFFSET (dr)
1314                || DR_INIT (dr) || DR_STEP (dr)))
1315         {
1316           while (TREE_CODE (ref) == COMPONENT_REF
1317                  || TREE_CODE (ref) == IMAGPART_EXPR
1318                  || TREE_CODE (ref) == REALPART_EXPR)
1319             ref = TREE_OPERAND (ref, 0);
1320
1321           DR_BASE_ADDRESS (dr) = ref;
1322           DR_OFFSET (dr) = NULL;
1323           DR_INIT (dr) = NULL;
1324           DR_STEP (dr) = NULL;
1325           DR_ALIGNED_TO (dr) = NULL;
1326         }
1327       hash_memrefs_baserefs_and_store_DRs_read_written_info (dr);
1328     }
1329
1330   for (i = 0; i < loop->num_nodes; i++)
1331     {
1332       basic_block bb = ifc_bbs[i];
1333       gimple_stmt_iterator itr;
1334
1335       /* Check the if-convertibility of statements in predicated BBs.  */
1336       if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
1337         for (itr = gsi_start_bb (bb); !gsi_end_p (itr); gsi_next (&itr))
1338           if (!if_convertible_stmt_p (gsi_stmt (itr), *refs))
1339             return false;
1340     }
1341
1342   for (i = 0; i < loop->num_nodes; i++)
1343     free_bb_predicate (ifc_bbs[i]);
1344
1345   /* Checking PHIs needs to be done after stmts, as the fact whether there
1346      are any masked loads or stores affects the tests.  */
1347   for (i = 0; i < loop->num_nodes; i++)
1348     {
1349       basic_block bb = ifc_bbs[i];
1350       gphi_iterator itr;
1351
1352       for (itr = gsi_start_phis (bb); !gsi_end_p (itr); gsi_next (&itr))
1353         if (!if_convertible_phi_p (loop, bb, itr.phi ()))
1354           return false;
1355     }
1356
1357   if (dump_file)
1358     fprintf (dump_file, "Applying if-conversion\n");
1359
1360   return true;
1361 }
1362
1363 /* Return true when LOOP is if-convertible.
1364    LOOP is if-convertible if:
1365    - it is innermost,
1366    - it has two or more basic blocks,
1367    - it has only one exit,
1368    - loop header is not the exit edge,
1369    - if its basic blocks and phi nodes are if convertible.  */
1370
1371 static bool
1372 if_convertible_loop_p (struct loop *loop)
1373 {
1374   edge e;
1375   edge_iterator ei;
1376   bool res = false;
1377   vec<data_reference_p> refs;
1378
1379   /* Handle only innermost loop.  */
1380   if (!loop || loop->inner)
1381     {
1382       if (dump_file && (dump_flags & TDF_DETAILS))
1383         fprintf (dump_file, "not innermost loop\n");
1384       return false;
1385     }
1386
1387   /* If only one block, no need for if-conversion.  */
1388   if (loop->num_nodes <= 2)
1389     {
1390       if (dump_file && (dump_flags & TDF_DETAILS))
1391         fprintf (dump_file, "less than 2 basic blocks\n");
1392       return false;
1393     }
1394
1395   /* More than one loop exit is too much to handle.  */
1396   if (!single_exit (loop))
1397     {
1398       if (dump_file && (dump_flags & TDF_DETAILS))
1399         fprintf (dump_file, "multiple exits\n");
1400       return false;
1401     }
1402
1403   /* If one of the loop header's edge is an exit edge then do not
1404      apply if-conversion.  */
1405   FOR_EACH_EDGE (e, ei, loop->header->succs)
1406     if (loop_exit_edge_p (loop, e))
1407       return false;
1408
1409   refs.create (5);
1410   res = if_convertible_loop_p_1 (loop, &refs);
1411
1412   data_reference_p dr;
1413   unsigned int i;
1414   for (i = 0; refs.iterate (i, &dr); i++)
1415     free (dr->aux);
1416
1417   free_data_refs (refs);
1418
1419   delete innermost_DR_map;
1420   innermost_DR_map = NULL;
1421
1422   delete baseref_DR_map;
1423   baseref_DR_map = NULL;
1424
1425   return res;
1426 }
1427
1428 /* Returns true if def-stmt for phi argument ARG is simple increment/decrement
1429    which is in predicated basic block.
1430    In fact, the following PHI pattern is searching:
1431       loop-header:
1432         reduc_1 = PHI <..., reduc_2>
1433       ...
1434         if (...)
1435           reduc_3 = ...
1436         reduc_2 = PHI <reduc_1, reduc_3>
1437
1438    ARG_0 and ARG_1 are correspondent PHI arguments.
1439    REDUC, OP0 and OP1 contain reduction stmt and its operands.
1440    EXTENDED is true if PHI has > 2 arguments.  */
1441
1442 static bool
1443 is_cond_scalar_reduction (gimple *phi, gimple **reduc, tree arg_0, tree arg_1,
1444                           tree *op0, tree *op1, bool extended)
1445 {
1446   tree lhs, r_op1, r_op2;
1447   gimple *stmt;
1448   gimple *header_phi = NULL;
1449   enum tree_code reduction_op;
1450   basic_block bb = gimple_bb (phi);
1451   struct loop *loop = bb->loop_father;
1452   edge latch_e = loop_latch_edge (loop);
1453   imm_use_iterator imm_iter;
1454   use_operand_p use_p;
1455   edge e;
1456   edge_iterator ei;
1457   bool result = false;
1458   if (TREE_CODE (arg_0) != SSA_NAME || TREE_CODE (arg_1) != SSA_NAME)
1459     return false;
1460
1461   if (!extended && gimple_code (SSA_NAME_DEF_STMT (arg_0)) == GIMPLE_PHI)
1462     {
1463       lhs = arg_1;
1464       header_phi = SSA_NAME_DEF_STMT (arg_0);
1465       stmt = SSA_NAME_DEF_STMT (arg_1);
1466     }
1467   else if (gimple_code (SSA_NAME_DEF_STMT (arg_1)) == GIMPLE_PHI)
1468     {
1469       lhs = arg_0;
1470       header_phi = SSA_NAME_DEF_STMT (arg_1);
1471       stmt = SSA_NAME_DEF_STMT (arg_0);
1472     }
1473   else
1474     return false;
1475   if (gimple_bb (header_phi) != loop->header)
1476     return false;
1477
1478   if (PHI_ARG_DEF_FROM_EDGE (header_phi, latch_e) != PHI_RESULT (phi))
1479     return false;
1480
1481   if (gimple_code (stmt) != GIMPLE_ASSIGN
1482       || gimple_has_volatile_ops (stmt))
1483     return false;
1484
1485   if (!flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
1486     return false;
1487
1488   if (!is_predicated (gimple_bb (stmt)))
1489     return false;
1490
1491   /* Check that stmt-block is predecessor of phi-block.  */
1492   FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
1493     if (e->dest == bb)
1494       {
1495         result = true;
1496         break;
1497       }
1498   if (!result)
1499     return false;
1500
1501   if (!has_single_use (lhs))
1502     return false;
1503
1504   reduction_op = gimple_assign_rhs_code (stmt);
1505   if (reduction_op != PLUS_EXPR && reduction_op != MINUS_EXPR)
1506     return false;
1507   r_op1 = gimple_assign_rhs1 (stmt);
1508   r_op2 = gimple_assign_rhs2 (stmt);
1509
1510   /* Make R_OP1 to hold reduction variable.  */
1511   if (r_op2 == PHI_RESULT (header_phi)
1512       && reduction_op == PLUS_EXPR)
1513     std::swap (r_op1, r_op2);
1514   else if (r_op1 != PHI_RESULT (header_phi))
1515     return false;
1516
1517   /* Check that R_OP1 is used in reduction stmt or in PHI only.  */
1518   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, r_op1)
1519     {
1520       gimple *use_stmt = USE_STMT (use_p);
1521       if (is_gimple_debug (use_stmt))
1522         continue;
1523       if (use_stmt == stmt)
1524         continue;
1525       if (gimple_code (use_stmt) != GIMPLE_PHI)
1526         return false;
1527     }
1528
1529   *op0 = r_op1; *op1 = r_op2;
1530   *reduc = stmt;
1531   return true;
1532 }
1533
1534 /* Converts conditional scalar reduction into unconditional form, e.g.
1535      bb_4
1536        if (_5 != 0) goto bb_5 else goto bb_6
1537      end_bb_4
1538      bb_5
1539        res_6 = res_13 + 1;
1540      end_bb_5
1541      bb_6
1542        # res_2 = PHI <res_13(4), res_6(5)>
1543      end_bb_6
1544
1545    will be converted into sequence
1546     _ifc__1 = _5 != 0 ? 1 : 0;
1547     res_2 = res_13 + _ifc__1;
1548   Argument SWAP tells that arguments of conditional expression should be
1549   swapped.
1550   Returns rhs of resulting PHI assignment.  */
1551
1552 static tree
1553 convert_scalar_cond_reduction (gimple *reduc, gimple_stmt_iterator *gsi,
1554                                tree cond, tree op0, tree op1, bool swap)
1555 {
1556   gimple_stmt_iterator stmt_it;
1557   gimple *new_assign;
1558   tree rhs;
1559   tree rhs1 = gimple_assign_rhs1 (reduc);
1560   tree tmp = make_temp_ssa_name (TREE_TYPE (rhs1), NULL, "_ifc_");
1561   tree c;
1562   tree zero = build_zero_cst (TREE_TYPE (rhs1));
1563
1564   if (dump_file && (dump_flags & TDF_DETAILS))
1565     {
1566       fprintf (dump_file, "Found cond scalar reduction.\n");
1567       print_gimple_stmt (dump_file, reduc, 0, TDF_SLIM);
1568     }
1569
1570   /* Build cond expression using COND and constant operand
1571      of reduction rhs.  */
1572   c = fold_build_cond_expr (TREE_TYPE (rhs1),
1573                             unshare_expr (cond),
1574                             swap ? zero : op1,
1575                             swap ? op1 : zero);
1576
1577   /* Create assignment stmt and insert it at GSI.  */
1578   new_assign = gimple_build_assign (tmp, c);
1579   gsi_insert_before (gsi, new_assign, GSI_SAME_STMT);
1580   /* Build rhs for unconditional increment/decrement.  */
1581   rhs = fold_build2 (gimple_assign_rhs_code (reduc),
1582                      TREE_TYPE (rhs1), op0, tmp);
1583
1584   /* Delete original reduction stmt.  */
1585   stmt_it = gsi_for_stmt (reduc);
1586   gsi_remove (&stmt_it, true);
1587   release_defs (reduc);
1588   return rhs;
1589 }
1590
1591 /* Produce condition for all occurrences of ARG in PHI node.  */
1592
1593 static tree
1594 gen_phi_arg_condition (gphi *phi, vec<int> *occur,
1595                        gimple_stmt_iterator *gsi)
1596 {
1597   int len;
1598   int i;
1599   tree cond = NULL_TREE;
1600   tree c;
1601   edge e;
1602
1603   len = occur->length ();
1604   gcc_assert (len > 0);
1605   for (i = 0; i < len; i++)
1606     {
1607       e = gimple_phi_arg_edge (phi, (*occur)[i]);
1608       c = bb_predicate (e->src);
1609       if (is_true_predicate (c))
1610         continue;
1611       c = force_gimple_operand_gsi_1 (gsi, unshare_expr (c),
1612                                       is_gimple_condexpr, NULL_TREE,
1613                                       true, GSI_SAME_STMT);
1614       if (cond != NULL_TREE)
1615         {
1616           /* Must build OR expression.  */
1617           cond = fold_or_predicates (EXPR_LOCATION (c), c, cond);
1618           cond = force_gimple_operand_gsi_1 (gsi, unshare_expr (cond),
1619                                              is_gimple_condexpr, NULL_TREE,
1620                                              true, GSI_SAME_STMT);
1621         }
1622       else
1623         cond = c;
1624     }
1625   gcc_assert (cond != NULL_TREE);
1626   return cond;
1627 }
1628
1629 /* Replace a scalar PHI node with a COND_EXPR using COND as condition.
1630    This routine can handle PHI nodes with more than two arguments.
1631
1632    For example,
1633      S1: A = PHI <x1(1), x2(5)>
1634    is converted into,
1635      S2: A = cond ? x1 : x2;
1636
1637    The generated code is inserted at GSI that points to the top of
1638    basic block's statement list.
1639    If PHI node has more than two arguments a chain of conditional
1640    expression is produced.  */
1641
1642
1643 static void
1644 predicate_scalar_phi (gphi *phi, gimple_stmt_iterator *gsi)
1645 {
1646   gimple *new_stmt = NULL, *reduc;
1647   tree rhs, res, arg0, arg1, op0, op1, scev;
1648   tree cond;
1649   unsigned int index0;
1650   unsigned int max, args_len;
1651   edge e;
1652   basic_block bb;
1653   unsigned int i;
1654
1655   res = gimple_phi_result (phi);
1656   if (virtual_operand_p (res))
1657     return;
1658
1659   if ((rhs = degenerate_phi_result (phi))
1660       || ((scev = analyze_scalar_evolution (gimple_bb (phi)->loop_father,
1661                                             res))
1662           && !chrec_contains_undetermined (scev)
1663           && scev != res
1664           && (rhs = gimple_phi_arg_def (phi, 0))))
1665     {
1666       if (dump_file && (dump_flags & TDF_DETAILS))
1667         {
1668           fprintf (dump_file, "Degenerate phi!\n");
1669           print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
1670         }
1671       new_stmt = gimple_build_assign (res, rhs);
1672       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1673       update_stmt (new_stmt);
1674       return;
1675     }
1676
1677   bb = gimple_bb (phi);
1678   if (EDGE_COUNT (bb->preds) == 2)
1679     {
1680       /* Predicate ordinary PHI node with 2 arguments.  */
1681       edge first_edge, second_edge;
1682       basic_block true_bb;
1683       first_edge = EDGE_PRED (bb, 0);
1684       second_edge = EDGE_PRED (bb, 1);
1685       cond = bb_predicate (first_edge->src);
1686       if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1687         std::swap (first_edge, second_edge);
1688       if (EDGE_COUNT (first_edge->src->succs) > 1)
1689         {
1690           cond = bb_predicate (second_edge->src);
1691           if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1692             cond = TREE_OPERAND (cond, 0);
1693           else
1694             first_edge = second_edge;
1695         }
1696       else
1697         cond = bb_predicate (first_edge->src);
1698       /* Gimplify the condition to a valid cond-expr conditonal operand.  */
1699       cond = force_gimple_operand_gsi_1 (gsi, unshare_expr (cond),
1700                                          is_gimple_condexpr, NULL_TREE,
1701                                          true, GSI_SAME_STMT);
1702       true_bb = first_edge->src;
1703       if (EDGE_PRED (bb, 1)->src == true_bb)
1704         {
1705           arg0 = gimple_phi_arg_def (phi, 1);
1706           arg1 = gimple_phi_arg_def (phi, 0);
1707         }
1708       else
1709         {
1710           arg0 = gimple_phi_arg_def (phi, 0);
1711           arg1 = gimple_phi_arg_def (phi, 1);
1712         }
1713       if (is_cond_scalar_reduction (phi, &reduc, arg0, arg1,
1714                                     &op0, &op1, false))
1715         /* Convert reduction stmt into vectorizable form.  */
1716         rhs = convert_scalar_cond_reduction (reduc, gsi, cond, op0, op1,
1717                                              true_bb != gimple_bb (reduc));
1718       else
1719         /* Build new RHS using selected condition and arguments.  */
1720         rhs = fold_build_cond_expr (TREE_TYPE (res), unshare_expr (cond),
1721                                     arg0, arg1);
1722       new_stmt = gimple_build_assign (res, rhs);
1723       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1724       update_stmt (new_stmt);
1725
1726       if (dump_file && (dump_flags & TDF_DETAILS))
1727         {
1728           fprintf (dump_file, "new phi replacement stmt\n");
1729           print_gimple_stmt (dump_file, new_stmt, 0, TDF_SLIM);
1730         }
1731       return;
1732     }
1733
1734   /* Create hashmap for PHI node which contain vector of argument indexes
1735      having the same value.  */
1736   bool swap = false;
1737   hash_map<tree_operand_hash, auto_vec<int> > phi_arg_map;
1738   unsigned int num_args = gimple_phi_num_args (phi);
1739   int max_ind = -1;
1740   /* Vector of different PHI argument values.  */
1741   auto_vec<tree> args (num_args);
1742
1743   /* Compute phi_arg_map.  */
1744   for (i = 0; i < num_args; i++)
1745     {
1746       tree arg;
1747
1748       arg = gimple_phi_arg_def (phi, i);
1749       if (!phi_arg_map.get (arg))
1750         args.quick_push (arg);
1751       phi_arg_map.get_or_insert (arg).safe_push (i);
1752     }
1753
1754   /* Determine element with max number of occurrences.  */
1755   max_ind = -1;
1756   max = 1;
1757   args_len = args.length ();
1758   for (i = 0; i < args_len; i++)
1759     {
1760       unsigned int len;
1761       if ((len = phi_arg_map.get (args[i])->length ()) > max)
1762         {
1763           max_ind = (int) i;
1764           max = len;
1765         }
1766     }
1767
1768   /* Put element with max number of occurences to the end of ARGS.  */
1769   if (max_ind != -1 && max_ind +1 != (int) args_len)
1770     std::swap (args[args_len - 1], args[max_ind]);
1771
1772   /* Handle one special case when number of arguments with different values
1773      is equal 2 and one argument has the only occurrence.  Such PHI can be
1774      handled as if would have only 2 arguments.  */
1775   if (args_len == 2 && phi_arg_map.get (args[0])->length () == 1)
1776     {
1777       vec<int> *indexes;
1778       indexes = phi_arg_map.get (args[0]);
1779       index0 = (*indexes)[0];
1780       arg0 = args[0];
1781       arg1 = args[1];
1782       e = gimple_phi_arg_edge (phi, index0);
1783       cond = bb_predicate (e->src);
1784       if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1785         {
1786           swap = true;
1787           cond = TREE_OPERAND (cond, 0);
1788         }
1789       /* Gimplify the condition to a valid cond-expr conditonal operand.  */
1790       cond = force_gimple_operand_gsi_1 (gsi, unshare_expr (cond),
1791                                          is_gimple_condexpr, NULL_TREE,
1792                                          true, GSI_SAME_STMT);
1793       if (!(is_cond_scalar_reduction (phi, &reduc, arg0 , arg1,
1794                                       &op0, &op1, true)))
1795         rhs = fold_build_cond_expr (TREE_TYPE (res), unshare_expr (cond),
1796                                     swap? arg1 : arg0,
1797                                     swap? arg0 : arg1);
1798       else
1799         /* Convert reduction stmt into vectorizable form.  */
1800         rhs = convert_scalar_cond_reduction (reduc, gsi, cond, op0, op1,
1801                                              swap);
1802       new_stmt = gimple_build_assign (res, rhs);
1803       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1804       update_stmt (new_stmt);
1805     }
1806   else
1807     {
1808       /* Common case.  */
1809       vec<int> *indexes;
1810       tree type = TREE_TYPE (gimple_phi_result (phi));
1811       tree lhs;
1812       arg1 = args[1];
1813       for (i = 0; i < args_len; i++)
1814         {
1815           arg0 = args[i];
1816           indexes = phi_arg_map.get (args[i]);
1817           if (i != args_len - 1)
1818             lhs = make_temp_ssa_name (type, NULL, "_ifc_");
1819           else
1820             lhs = res;
1821           cond = gen_phi_arg_condition (phi, indexes, gsi);
1822           rhs = fold_build_cond_expr (type, unshare_expr (cond),
1823                                       arg0, arg1);
1824           new_stmt = gimple_build_assign (lhs, rhs);
1825           gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1826           update_stmt (new_stmt);
1827           arg1 = lhs;
1828         }
1829     }
1830
1831   if (dump_file && (dump_flags & TDF_DETAILS))
1832     {
1833       fprintf (dump_file, "new extended phi replacement stmt\n");
1834       print_gimple_stmt (dump_file, new_stmt, 0, TDF_SLIM);
1835     }
1836 }
1837
1838 /* Replaces in LOOP all the scalar phi nodes other than those in the
1839    LOOP->header block with conditional modify expressions.  */
1840
1841 static void
1842 predicate_all_scalar_phis (struct loop *loop)
1843 {
1844   basic_block bb;
1845   unsigned int orig_loop_num_nodes = loop->num_nodes;
1846   unsigned int i;
1847
1848   for (i = 1; i < orig_loop_num_nodes; i++)
1849     {
1850       gphi *phi;
1851       gimple_stmt_iterator gsi;
1852       gphi_iterator phi_gsi;
1853       bb = ifc_bbs[i];
1854
1855       if (bb == loop->header)
1856         continue;
1857
1858       phi_gsi = gsi_start_phis (bb);
1859       if (gsi_end_p (phi_gsi))
1860         continue;
1861
1862       gsi = gsi_after_labels (bb);
1863       while (!gsi_end_p (phi_gsi))
1864         {
1865           phi = phi_gsi.phi ();
1866           predicate_scalar_phi (phi, &gsi);
1867           release_phi_node (phi);
1868           gsi_next (&phi_gsi);
1869         }
1870
1871       set_phi_nodes (bb, NULL);
1872     }
1873 }
1874
1875 /* Insert in each basic block of LOOP the statements produced by the
1876    gimplification of the predicates.  */
1877
1878 static void
1879 insert_gimplified_predicates (loop_p loop)
1880 {
1881   unsigned int i;
1882
1883   for (i = 0; i < loop->num_nodes; i++)
1884     {
1885       basic_block bb = ifc_bbs[i];
1886       gimple_seq stmts;
1887       if (!is_predicated (bb))
1888         gcc_assert (bb_predicate_gimplified_stmts (bb) == NULL);
1889       if (!is_predicated (bb))
1890         {
1891           /* Do not insert statements for a basic block that is not
1892              predicated.  Also make sure that the predicate of the
1893              basic block is set to true.  */
1894           reset_bb_predicate (bb);
1895           continue;
1896         }
1897
1898       stmts = bb_predicate_gimplified_stmts (bb);
1899       if (stmts)
1900         {
1901           if (any_pred_load_store)
1902             {
1903               /* Insert the predicate of the BB just after the label,
1904                  as the if-conversion of memory writes will use this
1905                  predicate.  */
1906               gimple_stmt_iterator gsi = gsi_after_labels (bb);
1907               gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
1908             }
1909           else
1910             {
1911               /* Insert the predicate of the BB at the end of the BB
1912                  as this would reduce the register pressure: the only
1913                  use of this predicate will be in successor BBs.  */
1914               gimple_stmt_iterator gsi = gsi_last_bb (bb);
1915
1916               if (gsi_end_p (gsi)
1917                   || stmt_ends_bb_p (gsi_stmt (gsi)))
1918                 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
1919               else
1920                 gsi_insert_seq_after (&gsi, stmts, GSI_SAME_STMT);
1921             }
1922
1923           /* Once the sequence is code generated, set it to NULL.  */
1924           set_bb_predicate_gimplified_stmts (bb, NULL);
1925         }
1926     }
1927 }
1928
1929 /* Helper function for predicate_mem_writes. Returns index of existent
1930    mask if it was created for given SIZE and -1 otherwise.  */
1931
1932 static int
1933 mask_exists (int size, vec<int> vec)
1934 {
1935   unsigned int ix;
1936   int v;
1937   FOR_EACH_VEC_ELT (vec, ix, v)
1938     if (v == size)
1939       return (int) ix;
1940   return -1;
1941 }
1942
1943 /* Predicate each write to memory in LOOP.
1944
1945    This function transforms control flow constructs containing memory
1946    writes of the form:
1947
1948    | for (i = 0; i < N; i++)
1949    |   if (cond)
1950    |     A[i] = expr;
1951
1952    into the following form that does not contain control flow:
1953
1954    | for (i = 0; i < N; i++)
1955    |   A[i] = cond ? expr : A[i];
1956
1957    The original CFG looks like this:
1958
1959    | bb_0
1960    |   i = 0
1961    | end_bb_0
1962    |
1963    | bb_1
1964    |   if (i < N) goto bb_5 else goto bb_2
1965    | end_bb_1
1966    |
1967    | bb_2
1968    |   cond = some_computation;
1969    |   if (cond) goto bb_3 else goto bb_4
1970    | end_bb_2
1971    |
1972    | bb_3
1973    |   A[i] = expr;
1974    |   goto bb_4
1975    | end_bb_3
1976    |
1977    | bb_4
1978    |   goto bb_1
1979    | end_bb_4
1980
1981    insert_gimplified_predicates inserts the computation of the COND
1982    expression at the beginning of the destination basic block:
1983
1984    | bb_0
1985    |   i = 0
1986    | end_bb_0
1987    |
1988    | bb_1
1989    |   if (i < N) goto bb_5 else goto bb_2
1990    | end_bb_1
1991    |
1992    | bb_2
1993    |   cond = some_computation;
1994    |   if (cond) goto bb_3 else goto bb_4
1995    | end_bb_2
1996    |
1997    | bb_3
1998    |   cond = some_computation;
1999    |   A[i] = expr;
2000    |   goto bb_4
2001    | end_bb_3
2002    |
2003    | bb_4
2004    |   goto bb_1
2005    | end_bb_4
2006
2007    predicate_mem_writes is then predicating the memory write as follows:
2008
2009    | bb_0
2010    |   i = 0
2011    | end_bb_0
2012    |
2013    | bb_1
2014    |   if (i < N) goto bb_5 else goto bb_2
2015    | end_bb_1
2016    |
2017    | bb_2
2018    |   if (cond) goto bb_3 else goto bb_4
2019    | end_bb_2
2020    |
2021    | bb_3
2022    |   cond = some_computation;
2023    |   A[i] = cond ? expr : A[i];
2024    |   goto bb_4
2025    | end_bb_3
2026    |
2027    | bb_4
2028    |   goto bb_1
2029    | end_bb_4
2030
2031    and finally combine_blocks removes the basic block boundaries making
2032    the loop vectorizable:
2033
2034    | bb_0
2035    |   i = 0
2036    |   if (i < N) goto bb_5 else goto bb_1
2037    | end_bb_0
2038    |
2039    | bb_1
2040    |   cond = some_computation;
2041    |   A[i] = cond ? expr : A[i];
2042    |   if (i < N) goto bb_5 else goto bb_4
2043    | end_bb_1
2044    |
2045    | bb_4
2046    |   goto bb_1
2047    | end_bb_4
2048 */
2049
2050 static void
2051 predicate_mem_writes (loop_p loop)
2052 {
2053   unsigned int i, orig_loop_num_nodes = loop->num_nodes;
2054   auto_vec<int, 1> vect_sizes;
2055   auto_vec<tree, 1> vect_masks;
2056
2057   for (i = 1; i < orig_loop_num_nodes; i++)
2058     {
2059       gimple_stmt_iterator gsi;
2060       basic_block bb = ifc_bbs[i];
2061       tree cond = bb_predicate (bb);
2062       bool swap;
2063       gimple *stmt;
2064       int index;
2065
2066       if (is_true_predicate (cond) || is_false_predicate (cond))
2067         continue;
2068
2069       swap = false;
2070       if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
2071         {
2072           swap = true;
2073           cond = TREE_OPERAND (cond, 0);
2074         }
2075
2076       vect_sizes.truncate (0);
2077       vect_masks.truncate (0);
2078
2079       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2080         if (!gimple_assign_single_p (stmt = gsi_stmt (gsi)))
2081           continue;
2082         else if (gimple_plf (stmt, GF_PLF_2))
2083           {
2084             tree lhs = gimple_assign_lhs (stmt);
2085             tree rhs = gimple_assign_rhs1 (stmt);
2086             tree ref, addr, ptr, mask;
2087             gimple *new_stmt;
2088             gimple_seq stmts = NULL;
2089             int bitsize = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (lhs)));
2090             ref = TREE_CODE (lhs) == SSA_NAME ? rhs : lhs;
2091             mark_addressable (ref);
2092             addr = force_gimple_operand_gsi (&gsi, build_fold_addr_expr (ref),
2093                                              true, NULL_TREE, true,
2094                                              GSI_SAME_STMT);
2095             if (!vect_sizes.is_empty ()
2096                 && (index = mask_exists (bitsize, vect_sizes)) != -1)
2097               /* Use created mask.  */
2098               mask = vect_masks[index];
2099             else
2100               {
2101                 if (COMPARISON_CLASS_P (cond))
2102                   mask = gimple_build (&stmts, TREE_CODE (cond),
2103                                        boolean_type_node,
2104                                        TREE_OPERAND (cond, 0),
2105                                        TREE_OPERAND (cond, 1));
2106                 else
2107                   {
2108                     gcc_assert (TREE_CODE (cond) == SSA_NAME);
2109                     mask = cond;
2110                   }
2111
2112                 if (swap)
2113                   {
2114                     tree true_val
2115                       = constant_boolean_node (true, TREE_TYPE (mask));
2116                     mask = gimple_build (&stmts, BIT_XOR_EXPR,
2117                                          TREE_TYPE (mask), mask, true_val);
2118                   }
2119                 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
2120
2121                 mask = ifc_temp_var (TREE_TYPE (mask), mask, &gsi);
2122                 /* Save mask and its size for further use.  */
2123                 vect_sizes.safe_push (bitsize);
2124                 vect_masks.safe_push (mask);
2125               }
2126             ptr = build_int_cst (reference_alias_ptr_type (ref),
2127                                  get_object_alignment (ref));
2128             /* Copy points-to info if possible.  */
2129             if (TREE_CODE (addr) == SSA_NAME && !SSA_NAME_PTR_INFO (addr))
2130               copy_ref_info (build2 (MEM_REF, TREE_TYPE (ref), addr, ptr),
2131                              ref);
2132             if (TREE_CODE (lhs) == SSA_NAME)
2133               {
2134                 new_stmt
2135                   = gimple_build_call_internal (IFN_MASK_LOAD, 3, addr,
2136                                                 ptr, mask);
2137                 gimple_call_set_lhs (new_stmt, lhs);
2138               }
2139             else
2140               new_stmt
2141                 = gimple_build_call_internal (IFN_MASK_STORE, 4, addr, ptr,
2142                                               mask, rhs);
2143             gsi_replace (&gsi, new_stmt, true);
2144           }
2145         else if (gimple_vdef (stmt))
2146           {
2147             tree lhs = gimple_assign_lhs (stmt);
2148             tree rhs = gimple_assign_rhs1 (stmt);
2149             tree type = TREE_TYPE (lhs);
2150
2151             lhs = ifc_temp_var (type, unshare_expr (lhs), &gsi);
2152             rhs = ifc_temp_var (type, unshare_expr (rhs), &gsi);
2153             if (swap)
2154               std::swap (lhs, rhs);
2155             cond = force_gimple_operand_gsi_1 (&gsi, unshare_expr (cond),
2156                                                is_gimple_condexpr, NULL_TREE,
2157                                                true, GSI_SAME_STMT);
2158             rhs = fold_build_cond_expr (type, unshare_expr (cond), rhs, lhs);
2159             gimple_assign_set_rhs1 (stmt, ifc_temp_var (type, rhs, &gsi));
2160             update_stmt (stmt);
2161           }
2162     }
2163 }
2164
2165 /* Remove all GIMPLE_CONDs and GIMPLE_LABELs of all the basic blocks
2166    other than the exit and latch of the LOOP.  Also resets the
2167    GIMPLE_DEBUG information.  */
2168
2169 static void
2170 remove_conditions_and_labels (loop_p loop)
2171 {
2172   gimple_stmt_iterator gsi;
2173   unsigned int i;
2174
2175   for (i = 0; i < loop->num_nodes; i++)
2176     {
2177       basic_block bb = ifc_bbs[i];
2178
2179       if (bb_with_exit_edge_p (loop, bb)
2180         || bb == loop->latch)
2181       continue;
2182
2183       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2184         switch (gimple_code (gsi_stmt (gsi)))
2185           {
2186           case GIMPLE_COND:
2187           case GIMPLE_LABEL:
2188             gsi_remove (&gsi, true);
2189             break;
2190
2191           case GIMPLE_DEBUG:
2192             /* ??? Should there be conditional GIMPLE_DEBUG_BINDs?  */
2193             if (gimple_debug_bind_p (gsi_stmt (gsi)))
2194               {
2195                 gimple_debug_bind_reset_value (gsi_stmt (gsi));
2196                 update_stmt (gsi_stmt (gsi));
2197               }
2198             gsi_next (&gsi);
2199             break;
2200
2201           default:
2202             gsi_next (&gsi);
2203           }
2204     }
2205 }
2206
2207 /* Combine all the basic blocks from LOOP into one or two super basic
2208    blocks.  Replace PHI nodes with conditional modify expressions.  */
2209
2210 static void
2211 combine_blocks (struct loop *loop)
2212 {
2213   basic_block bb, exit_bb, merge_target_bb;
2214   unsigned int orig_loop_num_nodes = loop->num_nodes;
2215   unsigned int i;
2216   edge e;
2217   edge_iterator ei;
2218
2219   predicate_bbs (loop);
2220   remove_conditions_and_labels (loop);
2221   insert_gimplified_predicates (loop);
2222   predicate_all_scalar_phis (loop);
2223
2224   if (any_pred_load_store)
2225     predicate_mem_writes (loop);
2226
2227   /* Merge basic blocks: first remove all the edges in the loop,
2228      except for those from the exit block.  */
2229   exit_bb = NULL;
2230   bool *predicated = XNEWVEC (bool, orig_loop_num_nodes);
2231   for (i = 0; i < orig_loop_num_nodes; i++)
2232     {
2233       bb = ifc_bbs[i];
2234       predicated[i] = !is_true_predicate (bb_predicate (bb));
2235       free_bb_predicate (bb);
2236       if (bb_with_exit_edge_p (loop, bb))
2237         {
2238           gcc_assert (exit_bb == NULL);
2239           exit_bb = bb;
2240         }
2241     }
2242   gcc_assert (exit_bb != loop->latch);
2243
2244   for (i = 1; i < orig_loop_num_nodes; i++)
2245     {
2246       bb = ifc_bbs[i];
2247
2248       for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei));)
2249         {
2250           if (e->src == exit_bb)
2251             ei_next (&ei);
2252           else
2253             remove_edge (e);
2254         }
2255     }
2256
2257   if (exit_bb != NULL)
2258     {
2259       if (exit_bb != loop->header)
2260         {
2261           /* Connect this node to loop header.  */
2262           make_edge (loop->header, exit_bb, EDGE_FALLTHRU);
2263           set_immediate_dominator (CDI_DOMINATORS, exit_bb, loop->header);
2264         }
2265
2266       /* Redirect non-exit edges to loop->latch.  */
2267       FOR_EACH_EDGE (e, ei, exit_bb->succs)
2268         {
2269           if (!loop_exit_edge_p (loop, e))
2270             redirect_edge_and_branch (e, loop->latch);
2271         }
2272       set_immediate_dominator (CDI_DOMINATORS, loop->latch, exit_bb);
2273     }
2274   else
2275     {
2276       /* If the loop does not have an exit, reconnect header and latch.  */
2277       make_edge (loop->header, loop->latch, EDGE_FALLTHRU);
2278       set_immediate_dominator (CDI_DOMINATORS, loop->latch, loop->header);
2279     }
2280
2281   merge_target_bb = loop->header;
2282   for (i = 1; i < orig_loop_num_nodes; i++)
2283     {
2284       gimple_stmt_iterator gsi;
2285       gimple_stmt_iterator last;
2286
2287       bb = ifc_bbs[i];
2288
2289       if (bb == exit_bb || bb == loop->latch)
2290         continue;
2291
2292       /* Make stmts member of loop->header and clear range info from all stmts
2293          in BB which is now no longer executed conditional on a predicate we
2294          could have derived it from.  */
2295       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2296         {
2297           gimple *stmt = gsi_stmt (gsi);
2298           gimple_set_bb (stmt, merge_target_bb);
2299           if (predicated[i])
2300             {
2301               ssa_op_iter i;
2302               tree op;
2303               FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
2304                 reset_flow_sensitive_info (op);
2305             }
2306         }
2307
2308       /* Update stmt list.  */
2309       last = gsi_last_bb (merge_target_bb);
2310       gsi_insert_seq_after (&last, bb_seq (bb), GSI_NEW_STMT);
2311       set_bb_seq (bb, NULL);
2312
2313       delete_basic_block (bb);
2314     }
2315
2316   /* If possible, merge loop header to the block with the exit edge.
2317      This reduces the number of basic blocks to two, to please the
2318      vectorizer that handles only loops with two nodes.  */
2319   if (exit_bb
2320       && exit_bb != loop->header
2321       && can_merge_blocks_p (loop->header, exit_bb))
2322     merge_blocks (loop->header, exit_bb);
2323
2324   free (ifc_bbs);
2325   ifc_bbs = NULL;
2326   free (predicated);
2327 }
2328
2329 /* Version LOOP before if-converting it; the original loop
2330    will be if-converted, the new copy of the loop will not,
2331    and the LOOP_VECTORIZED internal call will be guarding which
2332    loop to execute.  The vectorizer pass will fold this
2333    internal call into either true or false.  */
2334
2335 static bool
2336 version_loop_for_if_conversion (struct loop *loop)
2337 {
2338   basic_block cond_bb;
2339   tree cond = make_ssa_name (boolean_type_node);
2340   struct loop *new_loop;
2341   gimple *g;
2342   gimple_stmt_iterator gsi;
2343
2344   g = gimple_build_call_internal (IFN_LOOP_VECTORIZED, 2,
2345                                   build_int_cst (integer_type_node, loop->num),
2346                                   integer_zero_node);
2347   gimple_call_set_lhs (g, cond);
2348
2349   initialize_original_copy_tables ();
2350   new_loop = loop_version (loop, cond, &cond_bb,
2351                            REG_BR_PROB_BASE, REG_BR_PROB_BASE,
2352                            REG_BR_PROB_BASE, true);
2353   free_original_copy_tables ();
2354   if (new_loop == NULL)
2355     return false;
2356   new_loop->dont_vectorize = true;
2357   new_loop->force_vectorize = false;
2358   gsi = gsi_last_bb (cond_bb);
2359   gimple_call_set_arg (g, 1, build_int_cst (integer_type_node, new_loop->num));
2360   gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2361   update_ssa (TODO_update_ssa);
2362   return true;
2363 }
2364
2365 /* Performs splitting of critical edges.  Skip splitting and return false
2366    if LOOP will not be converted because:
2367
2368      - LOOP is not well formed.
2369      - LOOP has PHI with more than MAX_PHI_ARG_NUM arguments.
2370
2371    Last restriction is valid only if AGGRESSIVE_IF_CONV is false.  */
2372
2373 static bool
2374 ifcvt_split_critical_edges (struct loop *loop, bool aggressive_if_conv)
2375 {
2376   basic_block *body;
2377   basic_block bb;
2378   unsigned int num = loop->num_nodes;
2379   unsigned int i;
2380   gimple *stmt;
2381   edge e;
2382   edge_iterator ei;
2383   vec<edge> critical_edges = vNULL;
2384
2385   /* Loop is not well formed.  */
2386   if (num <= 2 || loop->inner || !single_exit (loop))
2387     return false;
2388
2389   body = get_loop_body (loop);
2390   for (i = 0; i < num; i++)
2391     {
2392       bb = body[i];
2393       if (!aggressive_if_conv
2394           && phi_nodes (bb)
2395           && EDGE_COUNT (bb->preds) > MAX_PHI_ARG_NUM)
2396         {
2397           if (dump_file && (dump_flags & TDF_DETAILS))
2398             fprintf (dump_file,
2399                      "BB %d has complicated PHI with more than %u args.\n",
2400                      bb->index, MAX_PHI_ARG_NUM);
2401
2402           free (body);
2403           critical_edges.release ();
2404           return false;
2405         }
2406       if (bb == loop->latch || bb_with_exit_edge_p (loop, bb))
2407         continue;
2408
2409       stmt = last_stmt (bb);
2410       /* Skip basic blocks not ending with conditional branch.  */
2411       if (!stmt || gimple_code (stmt) != GIMPLE_COND)
2412         continue;
2413
2414       FOR_EACH_EDGE (e, ei, bb->succs)
2415         if (EDGE_CRITICAL_P (e) && e->dest->loop_father == loop)
2416           critical_edges.safe_push (e);
2417     }
2418   free (body);
2419
2420   while (critical_edges.length () > 0)
2421     {
2422       e = critical_edges.pop ();
2423       /* Don't split if bb can be predicated along non-critical edge.  */
2424       if (EDGE_COUNT (e->dest->preds) > 2 || all_preds_critical_p (e->dest))
2425         split_edge (e);
2426     }
2427
2428   return true;
2429 }
2430
2431 /* Assumes that lhs of DEF_STMT have multiple uses.
2432    Delete one use by (1) creation of copy DEF_STMT with
2433    unique lhs; (2) change original use of lhs in one
2434    use statement with newly created lhs.  */
2435
2436 static void
2437 ifcvt_split_def_stmt (gimple *def_stmt, gimple *use_stmt)
2438 {
2439   tree var;
2440   tree lhs;
2441   gimple *copy_stmt;
2442   gimple_stmt_iterator gsi;
2443   use_operand_p use_p;
2444   imm_use_iterator imm_iter;
2445
2446   var = gimple_assign_lhs (def_stmt);
2447   copy_stmt = gimple_copy (def_stmt);
2448   lhs = make_temp_ssa_name (TREE_TYPE (var), NULL, "_ifc_");
2449   gimple_assign_set_lhs (copy_stmt, lhs);
2450   SSA_NAME_DEF_STMT (lhs) = copy_stmt;
2451   /* Insert copy of DEF_STMT.  */
2452   gsi = gsi_for_stmt (def_stmt);
2453   gsi_insert_after (&gsi, copy_stmt, GSI_SAME_STMT);
2454   /* Change use of var to lhs in use_stmt.  */
2455   if (dump_file && (dump_flags & TDF_DETAILS))
2456     {
2457       fprintf (dump_file, "Change use of var  ");
2458       print_generic_expr (dump_file, var, TDF_SLIM);
2459       fprintf (dump_file, " to ");
2460       print_generic_expr (dump_file, lhs, TDF_SLIM);
2461       fprintf (dump_file, "\n");
2462     }
2463   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, var)
2464     {
2465       if (USE_STMT (use_p) != use_stmt)
2466         continue;
2467       SET_USE (use_p, lhs);
2468       break;
2469     }
2470 }
2471
2472 /* Traverse bool pattern recursively starting from VAR.
2473    Save its def and use statements to defuse_list if VAR does
2474    not have single use.  */
2475
2476 static void
2477 ifcvt_walk_pattern_tree (tree var, vec<gimple *> *defuse_list,
2478                          gimple *use_stmt)
2479 {
2480   tree rhs1, rhs2;
2481   enum tree_code code;
2482   gimple *def_stmt;
2483
2484   def_stmt = SSA_NAME_DEF_STMT (var);
2485   if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2486     return;
2487   if (!has_single_use (var))
2488     {
2489       /* Put def and use stmts into defuse_list.  */
2490       defuse_list->safe_push (def_stmt);
2491       defuse_list->safe_push (use_stmt);
2492       if (dump_file && (dump_flags & TDF_DETAILS))
2493         {
2494           fprintf (dump_file, "Multiple lhs uses in stmt\n");
2495           print_gimple_stmt (dump_file, def_stmt, 0, TDF_SLIM);
2496         }
2497     }
2498   rhs1 = gimple_assign_rhs1 (def_stmt);
2499   code = gimple_assign_rhs_code (def_stmt);
2500   switch (code)
2501     {
2502     case SSA_NAME:
2503       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2504       break;
2505     CASE_CONVERT:
2506       if ((TYPE_PRECISION (TREE_TYPE (rhs1)) != 1
2507            || !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
2508           && TREE_CODE (TREE_TYPE (rhs1)) != BOOLEAN_TYPE)
2509         break;
2510       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2511       break;
2512     case BIT_NOT_EXPR:
2513       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2514       break;
2515     case BIT_AND_EXPR:
2516     case BIT_IOR_EXPR:
2517     case BIT_XOR_EXPR:
2518       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2519       rhs2 = gimple_assign_rhs2 (def_stmt);
2520       ifcvt_walk_pattern_tree (rhs2, defuse_list, def_stmt);
2521       break;
2522     default:
2523       break;
2524     }
2525   return;
2526 }
2527
2528 /* Returns true if STMT can be a root of bool pattern applied
2529    by vectorizer.  */
2530
2531 static bool
2532 stmt_is_root_of_bool_pattern (gimple *stmt)
2533 {
2534   enum tree_code code;
2535   tree lhs, rhs;
2536
2537   code = gimple_assign_rhs_code (stmt);
2538   if (CONVERT_EXPR_CODE_P (code))
2539     {
2540       lhs = gimple_assign_lhs (stmt);
2541       rhs = gimple_assign_rhs1 (stmt);
2542       if (TREE_CODE (TREE_TYPE (rhs)) != BOOLEAN_TYPE)
2543         return false;
2544       if (TREE_CODE (TREE_TYPE (lhs)) == BOOLEAN_TYPE)
2545         return false;
2546       return true;
2547     }
2548   else if (code == COND_EXPR)
2549     {
2550       rhs = gimple_assign_rhs1 (stmt);
2551       if (TREE_CODE (rhs) != SSA_NAME)
2552         return false;
2553       return true;
2554     }
2555   return false;
2556 }
2557
2558 /*  Traverse all statements in BB which correspond to loop header to
2559     find out all statements which can start bool pattern applied by
2560     vectorizer and convert multiple uses in it to conform pattern
2561     restrictions.  Such case can occur if the same predicate is used both
2562     for phi node conversion and load/store mask.  */
2563
2564 static void
2565 ifcvt_repair_bool_pattern (basic_block bb)
2566 {
2567   tree rhs;
2568   gimple *stmt;
2569   gimple_stmt_iterator gsi;
2570   vec<gimple *> defuse_list = vNULL;
2571   vec<gimple *> pattern_roots = vNULL;
2572   bool repeat = true;
2573   int niter = 0;
2574   unsigned int ix;
2575
2576   /* Collect all root pattern statements.  */
2577   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2578     {
2579       stmt = gsi_stmt (gsi);
2580       if (gimple_code (stmt) != GIMPLE_ASSIGN)
2581         continue;
2582       if (!stmt_is_root_of_bool_pattern (stmt))
2583         continue;
2584       pattern_roots.safe_push (stmt);
2585     }
2586
2587   if (pattern_roots.is_empty ())
2588     return;
2589
2590   /* Split all statements with multiple uses iteratively since splitting
2591      may create new multiple uses.  */
2592   while (repeat)
2593     {
2594       repeat = false;
2595       niter++;
2596       FOR_EACH_VEC_ELT (pattern_roots, ix, stmt)
2597         {
2598           rhs = gimple_assign_rhs1 (stmt);
2599           ifcvt_walk_pattern_tree (rhs, &defuse_list, stmt);
2600           while (defuse_list.length () > 0)
2601             {
2602               repeat = true;
2603               gimple *def_stmt, *use_stmt;
2604               use_stmt = defuse_list.pop ();
2605               def_stmt = defuse_list.pop ();
2606               ifcvt_split_def_stmt (def_stmt, use_stmt);
2607             }
2608
2609         }
2610     }
2611   if (dump_file && (dump_flags & TDF_DETAILS))
2612     fprintf (dump_file, "Repair bool pattern takes %d iterations. \n",
2613              niter);
2614 }
2615
2616 /* Delete redundant statements produced by predication which prevents
2617    loop vectorization.  */
2618
2619 static void
2620 ifcvt_local_dce (basic_block bb)
2621 {
2622   gimple *stmt;
2623   gimple *stmt1;
2624   gimple *phi;
2625   gimple_stmt_iterator gsi;
2626   auto_vec<gimple *> worklist;
2627   enum gimple_code code;
2628   use_operand_p use_p;
2629   imm_use_iterator imm_iter;
2630
2631   worklist.create (64);
2632   /* Consider all phi as live statements.  */
2633   for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2634     {
2635       phi = gsi_stmt (gsi);
2636       gimple_set_plf (phi, GF_PLF_2, true);
2637       worklist.safe_push (phi);
2638     }
2639   /* Consider load/store statements, CALL and COND as live.  */
2640   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2641     {
2642       stmt = gsi_stmt (gsi);
2643       if (gimple_store_p (stmt)
2644           || gimple_assign_load_p (stmt)
2645           || is_gimple_debug (stmt))
2646         {
2647           gimple_set_plf (stmt, GF_PLF_2, true);
2648           worklist.safe_push (stmt);
2649           continue;
2650         }
2651       code = gimple_code (stmt);
2652       if (code == GIMPLE_COND || code == GIMPLE_CALL)
2653         {
2654           gimple_set_plf (stmt, GF_PLF_2, true);
2655           worklist.safe_push (stmt);
2656           continue;
2657         }
2658       gimple_set_plf (stmt, GF_PLF_2, false);
2659
2660       if (code == GIMPLE_ASSIGN)
2661         {
2662           tree lhs = gimple_assign_lhs (stmt);
2663           FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
2664             {
2665               stmt1 = USE_STMT (use_p);
2666               if (gimple_bb (stmt1) != bb)
2667                 {
2668                   gimple_set_plf (stmt, GF_PLF_2, true);
2669                   worklist.safe_push (stmt);
2670                   break;
2671                 }
2672             }
2673         }
2674     }
2675   /* Propagate liveness through arguments of live stmt.  */
2676   while (worklist.length () > 0)
2677     {
2678       ssa_op_iter iter;
2679       use_operand_p use_p;
2680       tree use;
2681
2682       stmt = worklist.pop ();
2683       FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
2684         {
2685           use = USE_FROM_PTR (use_p);
2686           if (TREE_CODE (use) != SSA_NAME)
2687             continue;
2688           stmt1 = SSA_NAME_DEF_STMT (use);
2689           if (gimple_bb (stmt1) != bb
2690               || gimple_plf (stmt1, GF_PLF_2))
2691             continue;
2692           gimple_set_plf (stmt1, GF_PLF_2, true);
2693           worklist.safe_push (stmt1);
2694         }
2695     }
2696   /* Delete dead statements.  */
2697   gsi = gsi_start_bb (bb);
2698   while (!gsi_end_p (gsi))
2699     {
2700       stmt = gsi_stmt (gsi);
2701       if (gimple_plf (stmt, GF_PLF_2))
2702         {
2703           gsi_next (&gsi);
2704           continue;
2705         }
2706       if (dump_file && (dump_flags & TDF_DETAILS))
2707         {
2708           fprintf (dump_file, "Delete dead stmt in bb#%d\n", bb->index);
2709           print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2710         }
2711       gsi_remove (&gsi, true);
2712       release_defs (stmt);
2713     }
2714 }
2715
2716 /* If-convert LOOP when it is legal.  For the moment this pass has no
2717    profitability analysis.  Returns non-zero todo flags when something
2718    changed.  */
2719
2720 static unsigned int
2721 tree_if_conversion (struct loop *loop)
2722 {
2723   unsigned int todo = 0;
2724   bool aggressive_if_conv;
2725
2726   ifc_bbs = NULL;
2727   any_pred_load_store = false;
2728   any_complicated_phi = false;
2729
2730   /* Apply more aggressive if-conversion when loop or its outer loop were
2731      marked with simd pragma.  When that's the case, we try to if-convert
2732      loop containing PHIs with more than MAX_PHI_ARG_NUM arguments.  */
2733   aggressive_if_conv = loop->force_vectorize;
2734   if (!aggressive_if_conv)
2735     {
2736       struct loop *outer_loop = loop_outer (loop);
2737       if (outer_loop && outer_loop->force_vectorize)
2738         aggressive_if_conv = true;
2739     }
2740
2741   if (!ifcvt_split_critical_edges (loop, aggressive_if_conv))
2742     goto cleanup;
2743
2744   if (!if_convertible_loop_p (loop)
2745       || !dbg_cnt (if_conversion_tree))
2746     goto cleanup;
2747
2748   if ((any_pred_load_store || any_complicated_phi)
2749       && ((!flag_tree_loop_vectorize && !loop->force_vectorize)
2750           || loop->dont_vectorize))
2751     goto cleanup;
2752
2753   if ((any_pred_load_store || any_complicated_phi)
2754       && !version_loop_for_if_conversion (loop))
2755     goto cleanup;
2756
2757   /* Now all statements are if-convertible.  Combine all the basic
2758      blocks into one huge basic block doing the if-conversion
2759      on-the-fly.  */
2760   combine_blocks (loop);
2761
2762   /* Delete dead predicate computations and repair tree correspondent
2763      to bool pattern to delete multiple uses of predicates.  */
2764   ifcvt_local_dce (loop->header);
2765   ifcvt_repair_bool_pattern (loop->header);
2766
2767   todo |= TODO_cleanup_cfg;
2768   mark_virtual_operands_for_renaming (cfun);
2769   todo |= TODO_update_ssa_only_virtuals;
2770
2771  cleanup:
2772   if (ifc_bbs)
2773     {
2774       unsigned int i;
2775
2776       for (i = 0; i < loop->num_nodes; i++)
2777         free_bb_predicate (ifc_bbs[i]);
2778
2779       free (ifc_bbs);
2780       ifc_bbs = NULL;
2781     }
2782   free_dominance_info (CDI_POST_DOMINATORS);
2783
2784   return todo;
2785 }
2786
2787 /* Tree if-conversion pass management.  */
2788
2789 namespace {
2790
2791 const pass_data pass_data_if_conversion =
2792 {
2793   GIMPLE_PASS, /* type */
2794   "ifcvt", /* name */
2795   OPTGROUP_NONE, /* optinfo_flags */
2796   TV_NONE, /* tv_id */
2797   ( PROP_cfg | PROP_ssa ), /* properties_required */
2798   0, /* properties_provided */
2799   0, /* properties_destroyed */
2800   0, /* todo_flags_start */
2801   0, /* todo_flags_finish */
2802 };
2803
2804 class pass_if_conversion : public gimple_opt_pass
2805 {
2806 public:
2807   pass_if_conversion (gcc::context *ctxt)
2808     : gimple_opt_pass (pass_data_if_conversion, ctxt)
2809   {}
2810
2811   /* opt_pass methods: */
2812   virtual bool gate (function *);
2813   virtual unsigned int execute (function *);
2814
2815 }; // class pass_if_conversion
2816
2817 bool
2818 pass_if_conversion::gate (function *fun)
2819 {
2820   return (((flag_tree_loop_vectorize || fun->has_force_vectorize_loops)
2821            && flag_tree_loop_if_convert != 0)
2822           || flag_tree_loop_if_convert == 1
2823           || flag_tree_loop_if_convert_stores == 1);
2824 }
2825
2826 unsigned int
2827 pass_if_conversion::execute (function *fun)
2828 {
2829   struct loop *loop;
2830   unsigned todo = 0;
2831
2832   if (number_of_loops (fun) <= 1)
2833     return 0;
2834
2835   FOR_EACH_LOOP (loop, 0)
2836     if (flag_tree_loop_if_convert == 1
2837         || flag_tree_loop_if_convert_stores == 1
2838         || ((flag_tree_loop_vectorize || loop->force_vectorize)
2839             && !loop->dont_vectorize))
2840       todo |= tree_if_conversion (loop);
2841
2842   if (flag_checking)
2843     {
2844       basic_block bb;
2845       FOR_EACH_BB_FN (bb, fun)
2846         gcc_assert (!bb->aux);
2847     }
2848
2849   return todo;
2850 }
2851
2852 } // anon namespace
2853
2854 gimple_opt_pass *
2855 make_pass_if_conversion (gcc::context *ctxt)
2856 {
2857   return new pass_if_conversion (ctxt);
2858 }