OSDN Git Service

PR tree-optimization/32087
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-manip.c
1 /* High-level loop manipulation functions.
2    Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
3    
4 This file is part of GCC.
5    
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10    
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15    
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "rtl.h"
26 #include "tm_p.h"
27 #include "hard-reg-set.h"
28 #include "basic-block.h"
29 #include "output.h"
30 #include "diagnostic.h"
31 #include "tree-flow.h"
32 #include "tree-dump.h"
33 #include "timevar.h"
34 #include "cfgloop.h"
35 #include "tree-pass.h"
36 #include "cfglayout.h"
37 #include "tree-scalar-evolution.h"
38 #include "params.h"
39 #include "tree-inline.h"
40
41 /* Creates an induction variable with value BASE + STEP * iteration in LOOP.
42    It is expected that neither BASE nor STEP are shared with other expressions
43    (unless the sharing rules allow this).  Use VAR as a base var_decl for it
44    (if NULL, a new temporary will be created).  The increment will occur at
45    INCR_POS (after it if AFTER is true, before it otherwise).  INCR_POS and 
46    AFTER can be computed using standard_iv_increment_position.  The ssa versions
47    of the variable before and after increment will be stored in VAR_BEFORE and
48    VAR_AFTER (unless they are NULL).  */
49
50 void
51 create_iv (tree base, tree step, tree var, struct loop *loop,
52            block_stmt_iterator *incr_pos, bool after,
53            tree *var_before, tree *var_after)
54 {
55   tree stmt, initial, step1, stmts;
56   tree vb, va;
57   enum tree_code incr_op = PLUS_EXPR;
58   edge pe = loop_preheader_edge (loop);
59
60   if (!var)
61     {
62       var = create_tmp_var (TREE_TYPE (base), "ivtmp");
63       add_referenced_var (var);
64     }
65
66   vb = make_ssa_name (var, NULL_TREE);
67   if (var_before)
68     *var_before = vb;
69   va = make_ssa_name (var, NULL_TREE);
70   if (var_after)
71     *var_after = va;
72
73   /* For easier readability of the created code, produce MINUS_EXPRs
74      when suitable.  */
75   if (TREE_CODE (step) == INTEGER_CST)
76     {
77       if (TYPE_UNSIGNED (TREE_TYPE (step)))
78         {
79           step1 = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
80           if (tree_int_cst_lt (step1, step))
81             {
82               incr_op = MINUS_EXPR;
83               step = step1;
84             }
85         }
86       else
87         {
88           bool ovf;
89
90           if (!tree_expr_nonnegative_warnv_p (step, &ovf)
91               && may_negate_without_overflow_p (step))
92             {
93               incr_op = MINUS_EXPR;
94               step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
95             }
96         }
97     }
98   if (POINTER_TYPE_P (TREE_TYPE (base)))
99     {
100       step = fold_convert (sizetype, step);
101       if (incr_op == MINUS_EXPR)
102         step = fold_build1 (NEGATE_EXPR, sizetype, step);
103       incr_op = POINTER_PLUS_EXPR;
104     }
105   /* Gimplify the step if necessary.  We put the computations in front of the
106      loop (i.e. the step should be loop invariant).  */
107   step = force_gimple_operand (step, &stmts, true, var);
108   if (stmts)
109     bsi_insert_on_edge_immediate (pe, stmts);
110
111   stmt = build_gimple_modify_stmt (va,
112                                    build2 (incr_op, TREE_TYPE (base),
113                                            vb, step));
114   SSA_NAME_DEF_STMT (va) = stmt;
115   if (after)
116     bsi_insert_after (incr_pos, stmt, BSI_NEW_STMT);
117   else
118     bsi_insert_before (incr_pos, stmt, BSI_NEW_STMT);
119
120   initial = force_gimple_operand (base, &stmts, true, var);
121   if (stmts)
122     bsi_insert_on_edge_immediate (pe, stmts);
123
124   stmt = create_phi_node (vb, loop->header);
125   SSA_NAME_DEF_STMT (vb) = stmt;
126   add_phi_arg (stmt, initial, loop_preheader_edge (loop));
127   add_phi_arg (stmt, va, loop_latch_edge (loop));
128 }
129
130 /* Add exit phis for the USE on EXIT.  */
131
132 static void
133 add_exit_phis_edge (basic_block exit, tree use)
134 {
135   tree phi, def_stmt = SSA_NAME_DEF_STMT (use);
136   basic_block def_bb = bb_for_stmt (def_stmt);
137   struct loop *def_loop;
138   edge e;
139   edge_iterator ei;
140
141   /* Check that some of the edges entering the EXIT block exits a loop in
142      that USE is defined.  */
143   FOR_EACH_EDGE (e, ei, exit->preds)
144     {
145       def_loop = find_common_loop (def_bb->loop_father, e->src->loop_father);
146       if (!flow_bb_inside_loop_p (def_loop, e->dest))
147         break;
148     }
149
150   if (!e)
151     return;
152
153   phi = create_phi_node (use, exit);
154   create_new_def_for (PHI_RESULT (phi), phi, PHI_RESULT_PTR (phi));
155   FOR_EACH_EDGE (e, ei, exit->preds)
156     add_phi_arg (phi, use, e);
157 }
158
159 /* Add exit phis for VAR that is used in LIVEIN.
160    Exits of the loops are stored in EXITS.  */
161
162 static void
163 add_exit_phis_var (tree var, bitmap livein, bitmap exits)
164 {
165   bitmap def;
166   unsigned index;
167   basic_block def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (var));
168   bitmap_iterator bi;
169
170   if (is_gimple_reg (var))
171     bitmap_clear_bit (livein, def_bb->index);
172   else
173     bitmap_set_bit (livein, def_bb->index);
174
175   def = BITMAP_ALLOC (NULL);
176   bitmap_set_bit (def, def_bb->index);
177   compute_global_livein (livein, def);
178   BITMAP_FREE (def);
179
180   EXECUTE_IF_AND_IN_BITMAP (exits, livein, 0, index, bi)
181     {
182       add_exit_phis_edge (BASIC_BLOCK (index), var);
183     }
184 }
185
186 /* Add exit phis for the names marked in NAMES_TO_RENAME.
187    Exits of the loops are stored in EXITS.  Sets of blocks where the ssa
188    names are used are stored in USE_BLOCKS.  */
189
190 static void
191 add_exit_phis (bitmap names_to_rename, bitmap *use_blocks, bitmap loop_exits)
192 {
193   unsigned i;
194   bitmap_iterator bi;
195
196   EXECUTE_IF_SET_IN_BITMAP (names_to_rename, 0, i, bi)
197     {
198       add_exit_phis_var (ssa_name (i), use_blocks[i], loop_exits);
199     }
200 }
201
202 /* Returns a bitmap of all loop exit edge targets.  */
203
204 static bitmap
205 get_loops_exits (void)
206 {
207   bitmap exits = BITMAP_ALLOC (NULL);
208   basic_block bb;
209   edge e;
210   edge_iterator ei;
211
212   FOR_EACH_BB (bb)
213     {
214       FOR_EACH_EDGE (e, ei, bb->preds)
215         if (e->src != ENTRY_BLOCK_PTR
216             && !flow_bb_inside_loop_p (e->src->loop_father, bb))
217           {
218             bitmap_set_bit (exits, bb->index);
219             break;
220           }
221     }
222
223   return exits;
224 }
225
226 /* For USE in BB, if it is used outside of the loop it is defined in,
227    mark it for rewrite.  Record basic block BB where it is used
228    to USE_BLOCKS.  Record the ssa name index to NEED_PHIS bitmap.  */
229
230 static void
231 find_uses_to_rename_use (basic_block bb, tree use, bitmap *use_blocks,
232                          bitmap need_phis)
233 {
234   unsigned ver;
235   basic_block def_bb;
236   struct loop *def_loop;
237
238   if (TREE_CODE (use) != SSA_NAME)
239     return;
240
241   /* We don't need to keep virtual operands in loop-closed form.  */
242   if (!is_gimple_reg (use))
243     return;
244
245   ver = SSA_NAME_VERSION (use);
246   def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (use));
247   if (!def_bb)
248     return;
249   def_loop = def_bb->loop_father;
250
251   /* If the definition is not inside loop, it is not interesting.  */
252   if (!loop_outer (def_loop))
253     return;
254
255   if (!use_blocks[ver])
256     use_blocks[ver] = BITMAP_ALLOC (NULL);
257   bitmap_set_bit (use_blocks[ver], bb->index);
258
259   bitmap_set_bit (need_phis, ver);
260 }
261
262 /* For uses in STMT, mark names that are used outside of the loop they are
263    defined to rewrite.  Record the set of blocks in that the ssa
264    names are defined to USE_BLOCKS and the ssa names themselves to
265    NEED_PHIS.  */
266
267 static void
268 find_uses_to_rename_stmt (tree stmt, bitmap *use_blocks, bitmap need_phis)
269 {
270   ssa_op_iter iter;
271   tree var;
272   basic_block bb = bb_for_stmt (stmt);
273
274   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
275     find_uses_to_rename_use (bb, var, use_blocks, need_phis);
276 }
277
278 /* Marks names that are used in BB and outside of the loop they are
279    defined in for rewrite.  Records the set of blocks in that the ssa
280    names are defined to USE_BLOCKS.  Record the SSA names that will
281    need exit PHIs in NEED_PHIS.  */
282
283 static void
284 find_uses_to_rename_bb (basic_block bb, bitmap *use_blocks, bitmap need_phis)
285 {
286   block_stmt_iterator bsi;
287   edge e;
288   edge_iterator ei;
289   tree phi;
290
291   FOR_EACH_EDGE (e, ei, bb->succs)
292     for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
293       find_uses_to_rename_use (bb, PHI_ARG_DEF_FROM_EDGE (phi, e),
294                                use_blocks, need_phis);
295  
296   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
297     find_uses_to_rename_stmt (bsi_stmt (bsi), use_blocks, need_phis);
298 }
299      
300 /* Marks names that are used outside of the loop they are defined in
301    for rewrite.  Records the set of blocks in that the ssa
302    names are defined to USE_BLOCKS.  If CHANGED_BBS is not NULL,
303    scan only blocks in this set.  */
304
305 static void
306 find_uses_to_rename (bitmap changed_bbs, bitmap *use_blocks, bitmap need_phis)
307 {
308   basic_block bb;
309   unsigned index;
310   bitmap_iterator bi;
311
312   if (changed_bbs && !bitmap_empty_p (changed_bbs))
313     {
314       EXECUTE_IF_SET_IN_BITMAP (changed_bbs, 0, index, bi)
315         {
316           find_uses_to_rename_bb (BASIC_BLOCK (index), use_blocks, need_phis);
317         }
318     }
319   else
320     {
321       FOR_EACH_BB (bb)
322         {
323           find_uses_to_rename_bb (bb, use_blocks, need_phis);
324         }
325     }
326 }
327
328 /* Rewrites the program into a loop closed ssa form -- i.e. inserts extra
329    phi nodes to ensure that no variable is used outside the loop it is
330    defined in.
331
332    This strengthening of the basic ssa form has several advantages:
333
334    1) Updating it during unrolling/peeling/versioning is trivial, since
335       we do not need to care about the uses outside of the loop.
336    2) The behavior of all uses of an induction variable is the same.
337       Without this, you need to distinguish the case when the variable
338       is used outside of the loop it is defined in, for example
339
340       for (i = 0; i < 100; i++)
341         {
342           for (j = 0; j < 100; j++)
343             {
344               k = i + j;
345               use1 (k);
346             }
347           use2 (k);
348         }
349
350       Looking from the outer loop with the normal SSA form, the first use of k
351       is not well-behaved, while the second one is an induction variable with
352       base 99 and step 1.
353       
354       If CHANGED_BBS is not NULL, we look for uses outside loops only in
355       the basic blocks in this set.
356
357       UPDATE_FLAG is used in the call to update_ssa.  See
358       TODO_update_ssa* for documentation.  */
359
360 void
361 rewrite_into_loop_closed_ssa (bitmap changed_bbs, unsigned update_flag)
362 {
363   bitmap loop_exits;
364   bitmap *use_blocks;
365   unsigned i, old_num_ssa_names;
366   bitmap names_to_rename;
367
368   current_loops->state |= LOOP_CLOSED_SSA;
369   if (number_of_loops () <= 1)
370     return;
371
372   loop_exits = get_loops_exits ();
373   names_to_rename = BITMAP_ALLOC (NULL);
374
375   /* If the pass has caused the SSA form to be out-of-date, update it
376      now.  */
377   update_ssa (update_flag);
378
379   old_num_ssa_names = num_ssa_names;
380   use_blocks = XCNEWVEC (bitmap, old_num_ssa_names);
381
382   /* Find the uses outside loops.  */
383   find_uses_to_rename (changed_bbs, use_blocks, names_to_rename);
384
385   /* Add the PHI nodes on exits of the loops for the names we need to
386      rewrite.  */
387   add_exit_phis (names_to_rename, use_blocks, loop_exits);
388
389   for (i = 0; i < old_num_ssa_names; i++)
390     BITMAP_FREE (use_blocks[i]);
391   free (use_blocks);
392   BITMAP_FREE (loop_exits);
393   BITMAP_FREE (names_to_rename);
394
395   /* Fix up all the names found to be used outside their original
396      loops.  */
397   update_ssa (TODO_update_ssa);
398 }
399
400 /* Check invariants of the loop closed ssa form for the USE in BB.  */
401
402 static void
403 check_loop_closed_ssa_use (basic_block bb, tree use)
404 {
405   tree def;
406   basic_block def_bb;
407   
408   if (TREE_CODE (use) != SSA_NAME || !is_gimple_reg (use))
409     return;
410
411   def = SSA_NAME_DEF_STMT (use);
412   def_bb = bb_for_stmt (def);
413   gcc_assert (!def_bb
414               || flow_bb_inside_loop_p (def_bb->loop_father, bb));
415 }
416
417 /* Checks invariants of loop closed ssa form in statement STMT in BB.  */
418
419 static void
420 check_loop_closed_ssa_stmt (basic_block bb, tree stmt)
421 {
422   ssa_op_iter iter;
423   tree var;
424
425   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
426     check_loop_closed_ssa_use (bb, var);
427 }
428
429 /* Checks that invariants of the loop closed ssa form are preserved.  */
430
431 void
432 verify_loop_closed_ssa (void)
433 {
434   basic_block bb;
435   block_stmt_iterator bsi;
436   tree phi;
437   unsigned i;
438
439   if (number_of_loops () <= 1)
440     return;
441
442   verify_ssa (false);
443
444   FOR_EACH_BB (bb)
445     {
446       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
447         for (i = 0; i < (unsigned) PHI_NUM_ARGS (phi); i++)
448           check_loop_closed_ssa_use (PHI_ARG_EDGE (phi, i)->src,
449                                      PHI_ARG_DEF (phi, i));
450
451       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
452         check_loop_closed_ssa_stmt (bb, bsi_stmt (bsi));
453     }
454 }
455
456 /* Split loop exit edge EXIT.  The things are a bit complicated by a need to
457    preserve the loop closed ssa form.  */
458
459 void
460 split_loop_exit_edge (edge exit)
461 {
462   basic_block dest = exit->dest;
463   basic_block bb = split_edge (exit);
464   tree phi, new_phi, new_name, name;
465   use_operand_p op_p;
466
467   for (phi = phi_nodes (dest); phi; phi = PHI_CHAIN (phi))
468     {
469       op_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, single_succ_edge (bb));
470
471       name = USE_FROM_PTR (op_p);
472
473       /* If the argument of the PHI node is a constant, we do not need
474          to keep it inside loop.  */
475       if (TREE_CODE (name) != SSA_NAME)
476         continue;
477
478       /* Otherwise create an auxiliary phi node that will copy the value
479          of the SSA name out of the loop.  */
480       new_name = duplicate_ssa_name (name, NULL);
481       new_phi = create_phi_node (new_name, bb);
482       SSA_NAME_DEF_STMT (new_name) = new_phi;
483       add_phi_arg (new_phi, name, exit);
484       SET_USE (op_p, new_name);
485     }
486 }
487
488 /* Returns the basic block in that statements should be emitted for induction
489    variables incremented at the end of the LOOP.  */
490
491 basic_block
492 ip_end_pos (struct loop *loop)
493 {
494   return loop->latch;
495 }
496
497 /* Returns the basic block in that statements should be emitted for induction
498    variables incremented just before exit condition of a LOOP.  */
499
500 basic_block
501 ip_normal_pos (struct loop *loop)
502 {
503   tree last;
504   basic_block bb;
505   edge exit;
506
507   if (!single_pred_p (loop->latch))
508     return NULL;
509
510   bb = single_pred (loop->latch);
511   last = last_stmt (bb);
512   if (!last
513       || TREE_CODE (last) != COND_EXPR)
514     return NULL;
515
516   exit = EDGE_SUCC (bb, 0);
517   if (exit->dest == loop->latch)
518     exit = EDGE_SUCC (bb, 1);
519
520   if (flow_bb_inside_loop_p (loop, exit->dest))
521     return NULL;
522
523   return bb;
524 }
525
526 /* Stores the standard position for induction variable increment in LOOP
527    (just before the exit condition if it is available and latch block is empty,
528    end of the latch block otherwise) to BSI.  INSERT_AFTER is set to true if
529    the increment should be inserted after *BSI.  */
530
531 void
532 standard_iv_increment_position (struct loop *loop, block_stmt_iterator *bsi,
533                                 bool *insert_after)
534 {
535   basic_block bb = ip_normal_pos (loop), latch = ip_end_pos (loop);
536   tree last = last_stmt (latch);
537
538   if (!bb
539       || (last && TREE_CODE (last) != LABEL_EXPR))
540     {
541       *bsi = bsi_last (latch);
542       *insert_after = true;
543     }
544   else
545     {
546       *bsi = bsi_last (bb);
547       *insert_after = false;
548     }
549 }
550
551 /* Copies phi node arguments for duplicated blocks.  The index of the first
552    duplicated block is FIRST_NEW_BLOCK.  */
553
554 static void
555 copy_phi_node_args (unsigned first_new_block)
556 {
557   unsigned i;
558
559   for (i = first_new_block; i < (unsigned) last_basic_block; i++)
560     BASIC_BLOCK (i)->flags |= BB_DUPLICATED;
561
562   for (i = first_new_block; i < (unsigned) last_basic_block; i++)
563     add_phi_args_after_copy_bb (BASIC_BLOCK (i));
564
565   for (i = first_new_block; i < (unsigned) last_basic_block; i++)
566     BASIC_BLOCK (i)->flags &= ~BB_DUPLICATED;
567 }
568
569
570 /* The same as cfgloopmanip.c:duplicate_loop_to_header_edge, but also
571    updates the PHI nodes at start of the copied region.  In order to
572    achieve this, only loops whose exits all lead to the same location
573    are handled.
574
575    Notice that we do not completely update the SSA web after
576    duplication.  The caller is responsible for calling update_ssa
577    after the loop has been duplicated.  */
578
579 bool
580 tree_duplicate_loop_to_header_edge (struct loop *loop, edge e,
581                                     unsigned int ndupl, sbitmap wont_exit,
582                                     edge orig, VEC (edge, heap) **to_remove,
583                                     int flags)
584 {
585   unsigned first_new_block;
586
587   if (!(current_loops->state & LOOPS_HAVE_SIMPLE_LATCHES))
588     return false;
589   if (!(current_loops->state & LOOPS_HAVE_PREHEADERS))
590     return false;
591
592 #ifdef ENABLE_CHECKING
593   verify_loop_closed_ssa ();
594 #endif
595
596   first_new_block = last_basic_block;
597   if (!duplicate_loop_to_header_edge (loop, e, ndupl, wont_exit,
598                                       orig, to_remove, flags))
599     return false;
600
601   /* Readd the removed phi args for e.  */
602   flush_pending_stmts (e);
603
604   /* Copy the phi node arguments.  */
605   copy_phi_node_args (first_new_block);
606
607   scev_reset ();
608
609   return true;
610 }
611
612 /* Returns true if we can unroll LOOP FACTOR times.  Number
613    of iterations of the loop is returned in NITER.  */
614
615 bool
616 can_unroll_loop_p (struct loop *loop, unsigned factor,
617                    struct tree_niter_desc *niter)
618 {
619   edge exit;
620
621   /* Check whether unrolling is possible.  We only want to unroll loops
622      for that we are able to determine number of iterations.  We also
623      want to split the extra iterations of the loop from its end,
624      therefore we require that the loop has precisely one
625      exit.  */
626
627   exit = single_dom_exit (loop);
628   if (!exit)
629     return false;
630
631   if (!number_of_iterations_exit (loop, exit, niter, false)
632       || niter->cmp == ERROR_MARK
633       /* Scalar evolutions analysis might have copy propagated
634          the abnormal ssa names into these expressions, hence
635          emitting the computations based on them during loop
636          unrolling might create overlapping life ranges for
637          them, and failures in out-of-ssa.  */
638       || contains_abnormal_ssa_name_p (niter->may_be_zero)
639       || contains_abnormal_ssa_name_p (niter->control.base)
640       || contains_abnormal_ssa_name_p (niter->control.step)
641       || contains_abnormal_ssa_name_p (niter->bound))
642     return false;
643
644   /* And of course, we must be able to duplicate the loop.  */
645   if (!can_duplicate_loop_p (loop))
646     return false;
647
648   /* The final loop should be small enough.  */
649   if (tree_num_loop_insns (loop, &eni_size_weights) * factor
650       > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS))
651     return false;
652
653   return true;
654 }
655
656 /* Determines the conditions that control execution of LOOP unrolled FACTOR
657    times.  DESC is number of iterations of LOOP.  ENTER_COND is set to
658    condition that must be true if the main loop can be entered.
659    EXIT_BASE, EXIT_STEP, EXIT_CMP and EXIT_BOUND are set to values describing
660    how the exit from the unrolled loop should be controlled.  */
661
662 static void
663 determine_exit_conditions (struct loop *loop, struct tree_niter_desc *desc,
664                            unsigned factor, tree *enter_cond,
665                            tree *exit_base, tree *exit_step,
666                            enum tree_code *exit_cmp, tree *exit_bound)
667 {
668   tree stmts;
669   tree base = desc->control.base;
670   tree step = desc->control.step;
671   tree bound = desc->bound;
672   tree type = TREE_TYPE (step);
673   tree bigstep, delta;
674   tree min = lower_bound_in_type (type, type);
675   tree max = upper_bound_in_type (type, type);
676   enum tree_code cmp = desc->cmp;
677   tree cond = boolean_true_node, assum;
678
679   /* For pointers, do the arithmetics in the type of step (sizetype).  */
680   base = fold_convert (type, base);
681   bound = fold_convert (type, bound);
682
683   *enter_cond = boolean_false_node;
684   *exit_base = NULL_TREE;
685   *exit_step = NULL_TREE;
686   *exit_cmp = ERROR_MARK;
687   *exit_bound = NULL_TREE;
688   gcc_assert (cmp != ERROR_MARK);
689
690   /* We only need to be correct when we answer question
691      "Do at least FACTOR more iterations remain?" in the unrolled loop.
692      Thus, transforming BASE + STEP * i <> BOUND to
693      BASE + STEP * i < BOUND is ok.  */
694   if (cmp == NE_EXPR)
695     {
696       if (tree_int_cst_sign_bit (step))
697         cmp = GT_EXPR;
698       else
699         cmp = LT_EXPR;
700     }
701   else if (cmp == LT_EXPR)
702     {
703       gcc_assert (!tree_int_cst_sign_bit (step));
704     }
705   else if (cmp == GT_EXPR)
706     {
707       gcc_assert (tree_int_cst_sign_bit (step));
708     }
709   else
710     gcc_unreachable ();
711
712   /* The main body of the loop may be entered iff:
713
714      1) desc->may_be_zero is false.
715      2) it is possible to check that there are at least FACTOR iterations
716         of the loop, i.e., BOUND - step * FACTOR does not overflow.
717      3) # of iterations is at least FACTOR  */
718
719   if (!integer_zerop (desc->may_be_zero))
720     cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
721                         invert_truthvalue (desc->may_be_zero),
722                         cond);
723
724   bigstep = fold_build2 (MULT_EXPR, type, step,
725                          build_int_cst_type (type, factor));
726   delta = fold_build2 (MINUS_EXPR, type, bigstep, step);
727   if (cmp == LT_EXPR)
728     assum = fold_build2 (GE_EXPR, boolean_type_node,
729                          bound,
730                          fold_build2 (PLUS_EXPR, type, min, delta));
731   else
732     assum = fold_build2 (LE_EXPR, boolean_type_node,
733                          bound,
734                          fold_build2 (PLUS_EXPR, type, max, delta));
735   cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
736
737   bound = fold_build2 (MINUS_EXPR, type, bound, delta);
738   assum = fold_build2 (cmp, boolean_type_node, base, bound);
739   cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
740
741   cond = force_gimple_operand (unshare_expr (cond), &stmts, false, NULL_TREE);
742   if (stmts)
743     bsi_insert_on_edge_immediate (loop_preheader_edge (loop), stmts);
744   /* cond now may be a gimple comparison, which would be OK, but also any
745      other gimple rhs (say a && b).  In this case we need to force it to
746      operand.  */
747   if (!is_gimple_condexpr (cond))
748     {
749       cond = force_gimple_operand (cond, &stmts, true, NULL_TREE);
750       if (stmts)
751         bsi_insert_on_edge_immediate (loop_preheader_edge (loop), stmts);
752     }
753   *enter_cond = cond;
754
755   base = force_gimple_operand (unshare_expr (base), &stmts, true, NULL_TREE);
756   if (stmts)
757     bsi_insert_on_edge_immediate (loop_preheader_edge (loop), stmts);
758   bound = force_gimple_operand (unshare_expr (bound), &stmts, true, NULL_TREE);
759   if (stmts)
760     bsi_insert_on_edge_immediate (loop_preheader_edge (loop), stmts);
761
762   *exit_base = base;
763   *exit_step = bigstep;
764   *exit_cmp = cmp;
765   *exit_bound = bound;
766 }
767
768 /* Scales the frequencies of all basic blocks in LOOP that are strictly
769    dominated by BB by NUM/DEN.  */
770
771 static void
772 scale_dominated_blocks_in_loop (struct loop *loop, basic_block bb,
773                                 int num, int den)
774 {
775   basic_block son;
776
777   if (den == 0)
778     return;
779
780   for (son = first_dom_son (CDI_DOMINATORS, bb);
781        son;
782        son = next_dom_son (CDI_DOMINATORS, son))
783     {
784       if (!flow_bb_inside_loop_p (loop, son))
785         continue;
786       scale_bbs_frequencies_int (&son, 1, num, den);
787       scale_dominated_blocks_in_loop (loop, son, num, den);
788     }
789 }
790
791 /* Unroll LOOP FACTOR times.  DESC describes number of iterations of LOOP.
792    EXIT is the exit of the loop to that DESC corresponds.
793
794    If N is number of iterations of the loop and MAY_BE_ZERO is the condition
795    under that loop exits in the first iteration even if N != 0,
796    
797    while (1)
798      {
799        x = phi (init, next);
800
801        pre;
802        if (st)
803          break;
804        post;
805      }
806
807    becomes (with possibly the exit conditions formulated a bit differently,
808    avoiding the need to create a new iv):
809    
810    if (MAY_BE_ZERO || N < FACTOR)
811      goto rest;
812
813    do
814      {
815        x = phi (init, next);
816
817        pre;
818        post;
819        pre;
820        post;
821        ...
822        pre;
823        post;
824        N -= FACTOR;
825        
826      } while (N >= FACTOR);
827
828    rest:
829      init' = phi (init, x);
830
831    while (1)
832      {
833        x = phi (init', next);
834
835        pre;
836        if (st)
837          break;
838        post;
839      }
840  
841    Before the loop is unrolled, TRANSFORM is called for it (only for the
842    unrolled loop, but not for its versioned copy).  DATA is passed to
843    TRANSFORM.  */
844
845 /* Probability in % that the unrolled loop is entered.  Just a guess.  */
846 #define PROB_UNROLLED_LOOP_ENTERED 90
847
848 void
849 tree_transform_and_unroll_loop (struct loop *loop, unsigned factor,
850                                 edge exit, struct tree_niter_desc *desc,
851                                 transform_callback transform,
852                                 void *data)
853 {
854   tree  exit_if, ctr_before, ctr_after;
855   tree enter_main_cond, exit_base, exit_step, exit_bound;
856   enum tree_code exit_cmp;
857   tree phi_old_loop, phi_new_loop, phi_rest, init, next, new_init, var;
858   struct loop *new_loop;
859   basic_block rest, exit_bb;
860   edge old_entry, new_entry, old_latch, precond_edge, new_exit;
861   edge new_nonexit, e;
862   block_stmt_iterator bsi;
863   use_operand_p op;
864   bool ok;
865   unsigned est_niter, prob_entry, scale_unrolled, scale_rest, freq_e, freq_h;
866   unsigned new_est_niter, i, prob;
867   unsigned irr = loop_preheader_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP;
868   sbitmap wont_exit;
869   VEC (edge, heap) *to_remove = NULL;
870
871   est_niter = expected_loop_iterations (loop);
872   determine_exit_conditions (loop, desc, factor,
873                              &enter_main_cond, &exit_base, &exit_step,
874                              &exit_cmp, &exit_bound);
875
876   /* Let us assume that the unrolled loop is quite likely to be entered.  */
877   if (integer_nonzerop (enter_main_cond))
878     prob_entry = REG_BR_PROB_BASE;
879   else
880     prob_entry = PROB_UNROLLED_LOOP_ENTERED * REG_BR_PROB_BASE / 100;
881
882   /* The values for scales should keep profile consistent, and somewhat close
883      to correct.
884
885      TODO: The current value of SCALE_REST makes it appear that the loop that
886      is created by splitting the remaining iterations of the unrolled loop is
887      executed the same number of times as the original loop, and with the same
888      frequencies, which is obviously wrong.  This does not appear to cause
889      problems, so we do not bother with fixing it for now.  To make the profile
890      correct, we would need to change the probability of the exit edge of the
891      loop, and recompute the distribution of frequencies in its body because
892      of this change (scale the frequencies of blocks before and after the exit
893      by appropriate factors).  */
894   scale_unrolled = prob_entry;
895   scale_rest = REG_BR_PROB_BASE;
896
897   new_loop = loop_version (loop, enter_main_cond, NULL,
898                            prob_entry, scale_unrolled, scale_rest, true);
899   gcc_assert (new_loop != NULL);
900   update_ssa (TODO_update_ssa);
901
902   /* Determine the probability of the exit edge of the unrolled loop.  */
903   new_est_niter = est_niter / factor;
904
905   /* Without profile feedback, loops for that we do not know a better estimate
906      are assumed to roll 10 times.  When we unroll such loop, it appears to
907      roll too little, and it may even seem to be cold.  To avoid this, we
908      ensure that the created loop appears to roll at least 5 times (but at
909      most as many times as before unrolling).  */
910   if (new_est_niter < 5)
911     {
912       if (est_niter < 5)
913         new_est_niter = est_niter;
914       else
915         new_est_niter = 5;
916     }
917
918   /* Prepare the cfg and update the phi nodes.  Move the loop exit to the
919      loop latch (and make its condition dummy, for the moment).  */
920   rest = loop_preheader_edge (new_loop)->src;
921   precond_edge = single_pred_edge (rest);
922   split_edge (loop_latch_edge (loop));
923   exit_bb = single_pred (loop->latch);
924
925   /* Since the exit edge will be removed, the frequency of all the blocks
926      in the loop that are dominated by it must be scaled by
927      1 / (1 - exit->probability).  */
928   scale_dominated_blocks_in_loop (loop, exit->src,
929                                   REG_BR_PROB_BASE,
930                                   REG_BR_PROB_BASE - exit->probability);
931
932   bsi = bsi_last (exit_bb);
933   exit_if = build3 (COND_EXPR, void_type_node, boolean_true_node,
934                     NULL_TREE, NULL_TREE);
935
936   bsi_insert_after (&bsi, exit_if, BSI_NEW_STMT);
937   new_exit = make_edge (exit_bb, rest, EDGE_FALSE_VALUE | irr);
938   rescan_loop_exit (new_exit, true, false);
939
940   /* Set the probability of new exit to the same of the old one.  Fix
941      the frequency of the latch block, by scaling it back by
942      1 - exit->probability.  */
943   new_exit->count = exit->count;
944   new_exit->probability = exit->probability;
945   new_nonexit = single_pred_edge (loop->latch);
946   new_nonexit->probability = REG_BR_PROB_BASE - exit->probability;
947   new_nonexit->flags = EDGE_TRUE_VALUE;
948   new_nonexit->count -= exit->count;
949   if (new_nonexit->count < 0)
950     new_nonexit->count = 0;
951   scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
952                              REG_BR_PROB_BASE);
953
954   old_entry = loop_preheader_edge (loop);
955   new_entry = loop_preheader_edge (new_loop);
956   old_latch = loop_latch_edge (loop);
957   for (phi_old_loop = phi_nodes (loop->header),
958        phi_new_loop = phi_nodes (new_loop->header);
959        phi_old_loop;
960        phi_old_loop = PHI_CHAIN (phi_old_loop),
961        phi_new_loop = PHI_CHAIN (phi_new_loop))
962     {
963       init = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_entry);
964       op = PHI_ARG_DEF_PTR_FROM_EDGE (phi_new_loop, new_entry);
965       gcc_assert (operand_equal_for_phi_arg_p (init, USE_FROM_PTR (op)));
966       next = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_latch);
967
968       /* Prefer using original variable as a base for the new ssa name.
969          This is necessary for virtual ops, and useful in order to avoid
970          losing debug info for real ops.  */
971       if (TREE_CODE (next) == SSA_NAME)
972         var = SSA_NAME_VAR (next);
973       else if (TREE_CODE (init) == SSA_NAME)
974         var = SSA_NAME_VAR (init);
975       else
976         {
977           var = create_tmp_var (TREE_TYPE (init), "unrinittmp");
978           add_referenced_var (var);
979         }
980
981       new_init = make_ssa_name (var, NULL_TREE);
982       phi_rest = create_phi_node (new_init, rest);
983       SSA_NAME_DEF_STMT (new_init) = phi_rest;
984
985       add_phi_arg (phi_rest, init, precond_edge);
986       add_phi_arg (phi_rest, next, new_exit);
987       SET_USE (op, new_init);
988     }
989
990   remove_path (exit);
991
992   /* Transform the loop.  */
993   if (transform)
994     (*transform) (loop, data);
995
996   /* Unroll the loop and remove the exits in all iterations except for the
997      last one.  */
998   wont_exit = sbitmap_alloc (factor);
999   sbitmap_ones (wont_exit);
1000   RESET_BIT (wont_exit, factor - 1);
1001
1002   ok = tree_duplicate_loop_to_header_edge
1003           (loop, loop_latch_edge (loop), factor - 1,
1004            wont_exit, new_exit, &to_remove, DLTHE_FLAG_UPDATE_FREQ);
1005   free (wont_exit);
1006   gcc_assert (ok);
1007
1008   for (i = 0; VEC_iterate (edge, to_remove, i, e); i++)
1009     {
1010       ok = remove_path (e);
1011       gcc_assert (ok);
1012     }
1013   VEC_free (edge, heap, to_remove);
1014   update_ssa (TODO_update_ssa);
1015
1016   /* Ensure that the frequencies in the loop match the new estimated
1017      number of iterations, and change the probability of the new
1018      exit edge.  */
1019   freq_h = loop->header->frequency;
1020   freq_e = EDGE_FREQUENCY (loop_preheader_edge (loop));
1021   if (freq_h != 0)
1022     scale_loop_frequencies (loop, freq_e * (new_est_niter + 1), freq_h);
1023
1024   exit_bb = single_pred (loop->latch);
1025   new_exit = find_edge (exit_bb, rest);
1026   new_exit->count = loop_preheader_edge (loop)->count;
1027   new_exit->probability = REG_BR_PROB_BASE / (new_est_niter + 1);
1028
1029   rest->count += new_exit->count;
1030   rest->frequency += EDGE_FREQUENCY (new_exit);
1031
1032   new_nonexit = single_pred_edge (loop->latch);
1033   prob = new_nonexit->probability;
1034   new_nonexit->probability = REG_BR_PROB_BASE - new_exit->probability;
1035   new_nonexit->count = exit_bb->count - new_exit->count;
1036   if (new_nonexit->count < 0)
1037     new_nonexit->count = 0;
1038   if (prob > 0)
1039     scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
1040                                prob);
1041
1042   /* Finally create the new counter for number of iterations and add the new
1043      exit instruction.  */
1044   bsi = bsi_last (exit_bb);
1045   exit_if = bsi_stmt (bsi);
1046   create_iv (exit_base, exit_step, NULL_TREE, loop,
1047              &bsi, false, &ctr_before, &ctr_after);
1048   COND_EXPR_COND (exit_if) = build2 (exit_cmp, boolean_type_node, ctr_after,
1049                                      exit_bound);
1050   update_stmt (exit_if);
1051
1052 #ifdef ENABLE_CHECKING
1053   verify_flow_info ();
1054   verify_dominators (CDI_DOMINATORS);
1055   verify_loop_structure ();
1056   verify_loop_closed_ssa ();
1057 #endif
1058 }
1059
1060 /* Wrapper over tree_transform_and_unroll_loop for case we do not
1061    want to transform the loop before unrolling.  The meaning
1062    of the arguments is the same as for tree_transform_and_unroll_loop.  */
1063
1064 void
1065 tree_unroll_loop (struct loop *loop, unsigned factor,
1066                   edge exit, struct tree_niter_desc *desc)
1067 {
1068   tree_transform_and_unroll_loop (loop, factor, exit, desc,
1069                                   NULL, NULL);
1070 }