* arm.h (TARGET_CPU_CPP_BUILTINS): Remove Maverick support.
[official-gcc.git] / gcc / tree-ssa-loop-manip.c
blobe2e76058251a13ccbada9c59e3fa6b0142df0922
1 /* High-level loop manipulation functions.
2 Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY 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.
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/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "tm_p.h"
27 #include "basic-block.h"
28 #include "tree-flow.h"
29 #include "tree-dump.h"
30 #include "timevar.h"
31 #include "cfgloop.h"
32 #include "tree-pass.h"
33 #include "tree-scalar-evolution.h"
34 #include "params.h"
35 #include "tree-inline.h"
36 #include "langhooks.h"
38 /* Creates an induction variable with value BASE + STEP * iteration in LOOP.
39 It is expected that neither BASE nor STEP are shared with other expressions
40 (unless the sharing rules allow this). Use VAR as a base var_decl for it
41 (if NULL, a new temporary will be created). The increment will occur at
42 INCR_POS (after it if AFTER is true, before it otherwise). INCR_POS and
43 AFTER can be computed using standard_iv_increment_position. The ssa versions
44 of the variable before and after increment will be stored in VAR_BEFORE and
45 VAR_AFTER (unless they are NULL). */
47 void
48 create_iv (tree base, tree step, tree var, struct loop *loop,
49 gimple_stmt_iterator *incr_pos, bool after,
50 tree *var_before, tree *var_after)
52 gimple stmt;
53 tree initial, step1;
54 gimple_seq stmts;
55 tree vb, va;
56 enum tree_code incr_op = PLUS_EXPR;
57 edge pe = loop_preheader_edge (loop);
59 if (!var)
61 var = create_tmp_var (TREE_TYPE (base), "ivtmp");
62 add_referenced_var (var);
65 vb = make_ssa_name (var, NULL);
66 if (var_before)
67 *var_before = vb;
68 va = make_ssa_name (var, NULL);
69 if (var_after)
70 *var_after = va;
72 /* For easier readability of the created code, produce MINUS_EXPRs
73 when suitable. */
74 if (TREE_CODE (step) == INTEGER_CST)
76 if (TYPE_UNSIGNED (TREE_TYPE (step)))
78 step1 = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
79 if (tree_int_cst_lt (step1, step))
81 incr_op = MINUS_EXPR;
82 step = step1;
85 else
87 bool ovf;
89 if (!tree_expr_nonnegative_warnv_p (step, &ovf)
90 && may_negate_without_overflow_p (step))
92 incr_op = MINUS_EXPR;
93 step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
97 if (POINTER_TYPE_P (TREE_TYPE (base)))
99 if (TREE_CODE (base) == ADDR_EXPR)
100 mark_addressable (TREE_OPERAND (base, 0));
101 step = convert_to_ptrofftype (step);
102 if (incr_op == MINUS_EXPR)
103 step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
104 incr_op = POINTER_PLUS_EXPR;
106 /* Gimplify the step if necessary. We put the computations in front of the
107 loop (i.e. the step should be loop invariant). */
108 step = force_gimple_operand (step, &stmts, true, NULL_TREE);
109 if (stmts)
110 gsi_insert_seq_on_edge_immediate (pe, stmts);
112 stmt = gimple_build_assign_with_ops (incr_op, va, vb, step);
113 if (after)
114 gsi_insert_after (incr_pos, stmt, GSI_NEW_STMT);
115 else
116 gsi_insert_before (incr_pos, stmt, GSI_NEW_STMT);
118 initial = force_gimple_operand (base, &stmts, true, var);
119 if (stmts)
120 gsi_insert_seq_on_edge_immediate (pe, stmts);
122 stmt = create_phi_node (vb, loop->header);
123 SSA_NAME_DEF_STMT (vb) = stmt;
124 add_phi_arg (stmt, initial, loop_preheader_edge (loop), UNKNOWN_LOCATION);
125 add_phi_arg (stmt, va, loop_latch_edge (loop), UNKNOWN_LOCATION);
128 /* Add exit phis for the USE on EXIT. */
130 static void
131 add_exit_phis_edge (basic_block exit, tree use)
133 gimple phi, def_stmt = SSA_NAME_DEF_STMT (use);
134 basic_block def_bb = gimple_bb (def_stmt);
135 struct loop *def_loop;
136 edge e;
137 edge_iterator ei;
139 /* Check that some of the edges entering the EXIT block exits a loop in
140 that USE is defined. */
141 FOR_EACH_EDGE (e, ei, exit->preds)
143 def_loop = find_common_loop (def_bb->loop_father, e->src->loop_father);
144 if (!flow_bb_inside_loop_p (def_loop, e->dest))
145 break;
148 if (!e)
149 return;
151 phi = create_phi_node (use, exit);
152 create_new_def_for (gimple_phi_result (phi), phi,
153 gimple_phi_result_ptr (phi));
154 FOR_EACH_EDGE (e, ei, exit->preds)
155 add_phi_arg (phi, use, e, UNKNOWN_LOCATION);
158 /* Add exit phis for VAR that is used in LIVEIN.
159 Exits of the loops are stored in EXITS. */
161 static void
162 add_exit_phis_var (tree var, bitmap livein, bitmap exits)
164 bitmap def;
165 unsigned index;
166 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
167 bitmap_iterator bi;
169 if (is_gimple_reg (var))
170 bitmap_clear_bit (livein, def_bb->index);
171 else
172 bitmap_set_bit (livein, def_bb->index);
174 def = BITMAP_ALLOC (NULL);
175 bitmap_set_bit (def, def_bb->index);
176 compute_global_livein (livein, def);
177 BITMAP_FREE (def);
179 EXECUTE_IF_AND_IN_BITMAP (exits, livein, 0, index, bi)
181 add_exit_phis_edge (BASIC_BLOCK (index), var);
185 /* Add exit phis for the names marked in NAMES_TO_RENAME.
186 Exits of the loops are stored in EXITS. Sets of blocks where the ssa
187 names are used are stored in USE_BLOCKS. */
189 static void
190 add_exit_phis (bitmap names_to_rename, bitmap *use_blocks, bitmap loop_exits)
192 unsigned i;
193 bitmap_iterator bi;
195 EXECUTE_IF_SET_IN_BITMAP (names_to_rename, 0, i, bi)
197 add_exit_phis_var (ssa_name (i), use_blocks[i], loop_exits);
201 /* Returns a bitmap of all loop exit edge targets. */
203 static bitmap
204 get_loops_exits (void)
206 bitmap exits = BITMAP_ALLOC (NULL);
207 basic_block bb;
208 edge e;
209 edge_iterator ei;
211 FOR_EACH_BB (bb)
213 FOR_EACH_EDGE (e, ei, bb->preds)
214 if (e->src != ENTRY_BLOCK_PTR
215 && !flow_bb_inside_loop_p (e->src->loop_father, bb))
217 bitmap_set_bit (exits, bb->index);
218 break;
222 return exits;
225 /* For USE in BB, if it is used outside of the loop it is defined in,
226 mark it for rewrite. Record basic block BB where it is used
227 to USE_BLOCKS. Record the ssa name index to NEED_PHIS bitmap. */
229 static void
230 find_uses_to_rename_use (basic_block bb, tree use, bitmap *use_blocks,
231 bitmap need_phis)
233 unsigned ver;
234 basic_block def_bb;
235 struct loop *def_loop;
237 if (TREE_CODE (use) != SSA_NAME)
238 return;
240 /* We don't need to keep virtual operands in loop-closed form. */
241 if (!is_gimple_reg (use))
242 return;
244 ver = SSA_NAME_VERSION (use);
245 def_bb = gimple_bb (SSA_NAME_DEF_STMT (use));
246 if (!def_bb)
247 return;
248 def_loop = def_bb->loop_father;
250 /* If the definition is not inside a loop, it is not interesting. */
251 if (!loop_outer (def_loop))
252 return;
254 /* If the use is not outside of the loop it is defined in, it is not
255 interesting. */
256 if (flow_bb_inside_loop_p (def_loop, bb))
257 return;
259 if (!use_blocks[ver])
260 use_blocks[ver] = BITMAP_ALLOC (NULL);
261 bitmap_set_bit (use_blocks[ver], bb->index);
263 bitmap_set_bit (need_phis, ver);
266 /* For uses in STMT, mark names that are used outside of the loop they are
267 defined to rewrite. Record the set of blocks in that the ssa
268 names are defined to USE_BLOCKS and the ssa names themselves to
269 NEED_PHIS. */
271 static void
272 find_uses_to_rename_stmt (gimple stmt, bitmap *use_blocks, bitmap need_phis)
274 ssa_op_iter iter;
275 tree var;
276 basic_block bb = gimple_bb (stmt);
278 if (is_gimple_debug (stmt))
279 return;
281 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
282 find_uses_to_rename_use (bb, var, use_blocks, need_phis);
285 /* Marks names that are used in BB and outside of the loop they are
286 defined in for rewrite. Records the set of blocks in that the ssa
287 names are defined to USE_BLOCKS. Record the SSA names that will
288 need exit PHIs in NEED_PHIS. */
290 static void
291 find_uses_to_rename_bb (basic_block bb, bitmap *use_blocks, bitmap need_phis)
293 gimple_stmt_iterator bsi;
294 edge e;
295 edge_iterator ei;
297 FOR_EACH_EDGE (e, ei, bb->succs)
298 for (bsi = gsi_start_phis (e->dest); !gsi_end_p (bsi); gsi_next (&bsi))
299 find_uses_to_rename_use (bb, PHI_ARG_DEF_FROM_EDGE (gsi_stmt (bsi), e),
300 use_blocks, need_phis);
302 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
303 find_uses_to_rename_stmt (gsi_stmt (bsi), use_blocks, need_phis);
306 /* Marks names that are used outside of the loop they are defined in
307 for rewrite. Records the set of blocks in that the ssa
308 names are defined to USE_BLOCKS. If CHANGED_BBS is not NULL,
309 scan only blocks in this set. */
311 static void
312 find_uses_to_rename (bitmap changed_bbs, bitmap *use_blocks, bitmap need_phis)
314 basic_block bb;
315 unsigned index;
316 bitmap_iterator bi;
318 if (changed_bbs && !bitmap_empty_p (changed_bbs))
320 EXECUTE_IF_SET_IN_BITMAP (changed_bbs, 0, index, bi)
322 find_uses_to_rename_bb (BASIC_BLOCK (index), use_blocks, need_phis);
325 else
327 FOR_EACH_BB (bb)
329 find_uses_to_rename_bb (bb, use_blocks, need_phis);
334 /* Rewrites the program into a loop closed ssa form -- i.e. inserts extra
335 phi nodes to ensure that no variable is used outside the loop it is
336 defined in.
338 This strengthening of the basic ssa form has several advantages:
340 1) Updating it during unrolling/peeling/versioning is trivial, since
341 we do not need to care about the uses outside of the loop.
342 2) The behavior of all uses of an induction variable is the same.
343 Without this, you need to distinguish the case when the variable
344 is used outside of the loop it is defined in, for example
346 for (i = 0; i < 100; i++)
348 for (j = 0; j < 100; j++)
350 k = i + j;
351 use1 (k);
353 use2 (k);
356 Looking from the outer loop with the normal SSA form, the first use of k
357 is not well-behaved, while the second one is an induction variable with
358 base 99 and step 1.
360 If CHANGED_BBS is not NULL, we look for uses outside loops only in
361 the basic blocks in this set.
363 UPDATE_FLAG is used in the call to update_ssa. See
364 TODO_update_ssa* for documentation. */
366 void
367 rewrite_into_loop_closed_ssa (bitmap changed_bbs, unsigned update_flag)
369 bitmap loop_exits;
370 bitmap *use_blocks;
371 unsigned i, old_num_ssa_names;
372 bitmap names_to_rename;
374 loops_state_set (LOOP_CLOSED_SSA);
375 if (number_of_loops () <= 1)
376 return;
378 loop_exits = get_loops_exits ();
379 names_to_rename = BITMAP_ALLOC (NULL);
381 /* If the pass has caused the SSA form to be out-of-date, update it
382 now. */
383 update_ssa (update_flag);
385 old_num_ssa_names = num_ssa_names;
386 use_blocks = XCNEWVEC (bitmap, old_num_ssa_names);
388 /* Find the uses outside loops. */
389 find_uses_to_rename (changed_bbs, use_blocks, names_to_rename);
391 /* Add the PHI nodes on exits of the loops for the names we need to
392 rewrite. */
393 add_exit_phis (names_to_rename, use_blocks, loop_exits);
395 for (i = 0; i < old_num_ssa_names; i++)
396 BITMAP_FREE (use_blocks[i]);
397 free (use_blocks);
398 BITMAP_FREE (loop_exits);
399 BITMAP_FREE (names_to_rename);
401 /* Fix up all the names found to be used outside their original
402 loops. */
403 update_ssa (TODO_update_ssa);
406 /* Check invariants of the loop closed ssa form for the USE in BB. */
408 static void
409 check_loop_closed_ssa_use (basic_block bb, tree use)
411 gimple def;
412 basic_block def_bb;
414 if (TREE_CODE (use) != SSA_NAME || !is_gimple_reg (use))
415 return;
417 def = SSA_NAME_DEF_STMT (use);
418 def_bb = gimple_bb (def);
419 gcc_assert (!def_bb
420 || flow_bb_inside_loop_p (def_bb->loop_father, bb));
423 /* Checks invariants of loop closed ssa form in statement STMT in BB. */
425 static void
426 check_loop_closed_ssa_stmt (basic_block bb, gimple stmt)
428 ssa_op_iter iter;
429 tree var;
431 if (is_gimple_debug (stmt))
432 return;
434 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
435 check_loop_closed_ssa_use (bb, var);
438 /* Checks that invariants of the loop closed ssa form are preserved.
439 Call verify_ssa when VERIFY_SSA_P is true. */
441 DEBUG_FUNCTION void
442 verify_loop_closed_ssa (bool verify_ssa_p)
444 basic_block bb;
445 gimple_stmt_iterator bsi;
446 gimple phi;
447 edge e;
448 edge_iterator ei;
450 if (number_of_loops () <= 1)
451 return;
453 if (verify_ssa_p)
454 verify_ssa (false);
456 timevar_push (TV_VERIFY_LOOP_CLOSED);
458 FOR_EACH_BB (bb)
460 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
462 phi = gsi_stmt (bsi);
463 FOR_EACH_EDGE (e, ei, bb->preds)
464 check_loop_closed_ssa_use (e->src,
465 PHI_ARG_DEF_FROM_EDGE (phi, e));
468 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
469 check_loop_closed_ssa_stmt (bb, gsi_stmt (bsi));
472 timevar_pop (TV_VERIFY_LOOP_CLOSED);
475 /* Split loop exit edge EXIT. The things are a bit complicated by a need to
476 preserve the loop closed ssa form. The newly created block is returned. */
478 basic_block
479 split_loop_exit_edge (edge exit)
481 basic_block dest = exit->dest;
482 basic_block bb = split_edge (exit);
483 gimple phi, new_phi;
484 tree new_name, name;
485 use_operand_p op_p;
486 gimple_stmt_iterator psi;
487 source_location locus;
489 for (psi = gsi_start_phis (dest); !gsi_end_p (psi); gsi_next (&psi))
491 phi = gsi_stmt (psi);
492 op_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, single_succ_edge (bb));
493 locus = gimple_phi_arg_location_from_edge (phi, single_succ_edge (bb));
495 name = USE_FROM_PTR (op_p);
497 /* If the argument of the PHI node is a constant, we do not need
498 to keep it inside loop. */
499 if (TREE_CODE (name) != SSA_NAME)
500 continue;
502 /* Otherwise create an auxiliary phi node that will copy the value
503 of the SSA name out of the loop. */
504 new_name = duplicate_ssa_name (name, NULL);
505 new_phi = create_phi_node (new_name, bb);
506 SSA_NAME_DEF_STMT (new_name) = new_phi;
507 add_phi_arg (new_phi, name, exit, locus);
508 SET_USE (op_p, new_name);
511 return bb;
514 /* Returns the basic block in that statements should be emitted for induction
515 variables incremented at the end of the LOOP. */
517 basic_block
518 ip_end_pos (struct loop *loop)
520 return loop->latch;
523 /* Returns the basic block in that statements should be emitted for induction
524 variables incremented just before exit condition of a LOOP. */
526 basic_block
527 ip_normal_pos (struct loop *loop)
529 gimple last;
530 basic_block bb;
531 edge exit;
533 if (!single_pred_p (loop->latch))
534 return NULL;
536 bb = single_pred (loop->latch);
537 last = last_stmt (bb);
538 if (!last
539 || gimple_code (last) != GIMPLE_COND)
540 return NULL;
542 exit = EDGE_SUCC (bb, 0);
543 if (exit->dest == loop->latch)
544 exit = EDGE_SUCC (bb, 1);
546 if (flow_bb_inside_loop_p (loop, exit->dest))
547 return NULL;
549 return bb;
552 /* Stores the standard position for induction variable increment in LOOP
553 (just before the exit condition if it is available and latch block is empty,
554 end of the latch block otherwise) to BSI. INSERT_AFTER is set to true if
555 the increment should be inserted after *BSI. */
557 void
558 standard_iv_increment_position (struct loop *loop, gimple_stmt_iterator *bsi,
559 bool *insert_after)
561 basic_block bb = ip_normal_pos (loop), latch = ip_end_pos (loop);
562 gimple last = last_stmt (latch);
564 if (!bb
565 || (last && gimple_code (last) != GIMPLE_LABEL))
567 *bsi = gsi_last_bb (latch);
568 *insert_after = true;
570 else
572 *bsi = gsi_last_bb (bb);
573 *insert_after = false;
577 /* Copies phi node arguments for duplicated blocks. The index of the first
578 duplicated block is FIRST_NEW_BLOCK. */
580 static void
581 copy_phi_node_args (unsigned first_new_block)
583 unsigned i;
585 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
586 BASIC_BLOCK (i)->flags |= BB_DUPLICATED;
588 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
589 add_phi_args_after_copy_bb (BASIC_BLOCK (i));
591 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
592 BASIC_BLOCK (i)->flags &= ~BB_DUPLICATED;
596 /* The same as cfgloopmanip.c:duplicate_loop_to_header_edge, but also
597 updates the PHI nodes at start of the copied region. In order to
598 achieve this, only loops whose exits all lead to the same location
599 are handled.
601 Notice that we do not completely update the SSA web after
602 duplication. The caller is responsible for calling update_ssa
603 after the loop has been duplicated. */
605 bool
606 gimple_duplicate_loop_to_header_edge (struct loop *loop, edge e,
607 unsigned int ndupl, sbitmap wont_exit,
608 edge orig, VEC (edge, heap) **to_remove,
609 int flags)
611 unsigned first_new_block;
613 if (!loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
614 return false;
615 if (!loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS))
616 return false;
618 #ifdef ENABLE_CHECKING
619 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
620 verify_loop_closed_ssa (true);
621 #endif
623 first_new_block = last_basic_block;
624 if (!duplicate_loop_to_header_edge (loop, e, ndupl, wont_exit,
625 orig, to_remove, flags))
626 return false;
628 /* Readd the removed phi args for e. */
629 flush_pending_stmts (e);
631 /* Copy the phi node arguments. */
632 copy_phi_node_args (first_new_block);
634 scev_reset ();
636 return true;
639 /* Returns true if we can unroll LOOP FACTOR times. Number
640 of iterations of the loop is returned in NITER. */
642 bool
643 can_unroll_loop_p (struct loop *loop, unsigned factor,
644 struct tree_niter_desc *niter)
646 edge exit;
648 /* Check whether unrolling is possible. We only want to unroll loops
649 for that we are able to determine number of iterations. We also
650 want to split the extra iterations of the loop from its end,
651 therefore we require that the loop has precisely one
652 exit. */
654 exit = single_dom_exit (loop);
655 if (!exit)
656 return false;
658 if (!number_of_iterations_exit (loop, exit, niter, false)
659 || niter->cmp == ERROR_MARK
660 /* Scalar evolutions analysis might have copy propagated
661 the abnormal ssa names into these expressions, hence
662 emitting the computations based on them during loop
663 unrolling might create overlapping life ranges for
664 them, and failures in out-of-ssa. */
665 || contains_abnormal_ssa_name_p (niter->may_be_zero)
666 || contains_abnormal_ssa_name_p (niter->control.base)
667 || contains_abnormal_ssa_name_p (niter->control.step)
668 || contains_abnormal_ssa_name_p (niter->bound))
669 return false;
671 /* And of course, we must be able to duplicate the loop. */
672 if (!can_duplicate_loop_p (loop))
673 return false;
675 /* The final loop should be small enough. */
676 if (tree_num_loop_insns (loop, &eni_size_weights) * factor
677 > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS))
678 return false;
680 return true;
683 /* Determines the conditions that control execution of LOOP unrolled FACTOR
684 times. DESC is number of iterations of LOOP. ENTER_COND is set to
685 condition that must be true if the main loop can be entered.
686 EXIT_BASE, EXIT_STEP, EXIT_CMP and EXIT_BOUND are set to values describing
687 how the exit from the unrolled loop should be controlled. */
689 static void
690 determine_exit_conditions (struct loop *loop, struct tree_niter_desc *desc,
691 unsigned factor, tree *enter_cond,
692 tree *exit_base, tree *exit_step,
693 enum tree_code *exit_cmp, tree *exit_bound)
695 gimple_seq stmts;
696 tree base = desc->control.base;
697 tree step = desc->control.step;
698 tree bound = desc->bound;
699 tree type = TREE_TYPE (step);
700 tree bigstep, delta;
701 tree min = lower_bound_in_type (type, type);
702 tree max = upper_bound_in_type (type, type);
703 enum tree_code cmp = desc->cmp;
704 tree cond = boolean_true_node, assum;
706 /* For pointers, do the arithmetics in the type of step. */
707 base = fold_convert (type, base);
708 bound = fold_convert (type, bound);
710 *enter_cond = boolean_false_node;
711 *exit_base = NULL_TREE;
712 *exit_step = NULL_TREE;
713 *exit_cmp = ERROR_MARK;
714 *exit_bound = NULL_TREE;
715 gcc_assert (cmp != ERROR_MARK);
717 /* We only need to be correct when we answer question
718 "Do at least FACTOR more iterations remain?" in the unrolled loop.
719 Thus, transforming BASE + STEP * i <> BOUND to
720 BASE + STEP * i < BOUND is ok. */
721 if (cmp == NE_EXPR)
723 if (tree_int_cst_sign_bit (step))
724 cmp = GT_EXPR;
725 else
726 cmp = LT_EXPR;
728 else if (cmp == LT_EXPR)
730 gcc_assert (!tree_int_cst_sign_bit (step));
732 else if (cmp == GT_EXPR)
734 gcc_assert (tree_int_cst_sign_bit (step));
736 else
737 gcc_unreachable ();
739 /* The main body of the loop may be entered iff:
741 1) desc->may_be_zero is false.
742 2) it is possible to check that there are at least FACTOR iterations
743 of the loop, i.e., BOUND - step * FACTOR does not overflow.
744 3) # of iterations is at least FACTOR */
746 if (!integer_zerop (desc->may_be_zero))
747 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
748 invert_truthvalue (desc->may_be_zero),
749 cond);
751 bigstep = fold_build2 (MULT_EXPR, type, step,
752 build_int_cst_type (type, factor));
753 delta = fold_build2 (MINUS_EXPR, type, bigstep, step);
754 if (cmp == LT_EXPR)
755 assum = fold_build2 (GE_EXPR, boolean_type_node,
756 bound,
757 fold_build2 (PLUS_EXPR, type, min, delta));
758 else
759 assum = fold_build2 (LE_EXPR, boolean_type_node,
760 bound,
761 fold_build2 (PLUS_EXPR, type, max, delta));
762 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
764 bound = fold_build2 (MINUS_EXPR, type, bound, delta);
765 assum = fold_build2 (cmp, boolean_type_node, base, bound);
766 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
768 cond = force_gimple_operand (unshare_expr (cond), &stmts, false, NULL_TREE);
769 if (stmts)
770 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
771 /* cond now may be a gimple comparison, which would be OK, but also any
772 other gimple rhs (say a && b). In this case we need to force it to
773 operand. */
774 if (!is_gimple_condexpr (cond))
776 cond = force_gimple_operand (cond, &stmts, true, NULL_TREE);
777 if (stmts)
778 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
780 *enter_cond = cond;
782 base = force_gimple_operand (unshare_expr (base), &stmts, true, NULL_TREE);
783 if (stmts)
784 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
785 bound = force_gimple_operand (unshare_expr (bound), &stmts, true, NULL_TREE);
786 if (stmts)
787 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
789 *exit_base = base;
790 *exit_step = bigstep;
791 *exit_cmp = cmp;
792 *exit_bound = bound;
795 /* Scales the frequencies of all basic blocks in LOOP that are strictly
796 dominated by BB by NUM/DEN. */
798 static void
799 scale_dominated_blocks_in_loop (struct loop *loop, basic_block bb,
800 int num, int den)
802 basic_block son;
804 if (den == 0)
805 return;
807 for (son = first_dom_son (CDI_DOMINATORS, bb);
808 son;
809 son = next_dom_son (CDI_DOMINATORS, son))
811 if (!flow_bb_inside_loop_p (loop, son))
812 continue;
813 scale_bbs_frequencies_int (&son, 1, num, den);
814 scale_dominated_blocks_in_loop (loop, son, num, den);
818 /* Unroll LOOP FACTOR times. DESC describes number of iterations of LOOP.
819 EXIT is the exit of the loop to that DESC corresponds.
821 If N is number of iterations of the loop and MAY_BE_ZERO is the condition
822 under that loop exits in the first iteration even if N != 0,
824 while (1)
826 x = phi (init, next);
828 pre;
829 if (st)
830 break;
831 post;
834 becomes (with possibly the exit conditions formulated a bit differently,
835 avoiding the need to create a new iv):
837 if (MAY_BE_ZERO || N < FACTOR)
838 goto rest;
842 x = phi (init, next);
844 pre;
845 post;
846 pre;
847 post;
849 pre;
850 post;
851 N -= FACTOR;
853 } while (N >= FACTOR);
855 rest:
856 init' = phi (init, x);
858 while (1)
860 x = phi (init', next);
862 pre;
863 if (st)
864 break;
865 post;
868 Before the loop is unrolled, TRANSFORM is called for it (only for the
869 unrolled loop, but not for its versioned copy). DATA is passed to
870 TRANSFORM. */
872 /* Probability in % that the unrolled loop is entered. Just a guess. */
873 #define PROB_UNROLLED_LOOP_ENTERED 90
875 void
876 tree_transform_and_unroll_loop (struct loop *loop, unsigned factor,
877 edge exit, struct tree_niter_desc *desc,
878 transform_callback transform,
879 void *data)
881 gimple exit_if;
882 tree ctr_before, ctr_after;
883 tree enter_main_cond, exit_base, exit_step, exit_bound;
884 enum tree_code exit_cmp;
885 gimple phi_old_loop, phi_new_loop, phi_rest;
886 gimple_stmt_iterator psi_old_loop, psi_new_loop;
887 tree init, next, new_init, var;
888 struct loop *new_loop;
889 basic_block rest, exit_bb;
890 edge old_entry, new_entry, old_latch, precond_edge, new_exit;
891 edge new_nonexit, e;
892 gimple_stmt_iterator bsi;
893 use_operand_p op;
894 bool ok;
895 unsigned est_niter, prob_entry, scale_unrolled, scale_rest, freq_e, freq_h;
896 unsigned new_est_niter, i, prob;
897 unsigned irr = loop_preheader_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP;
898 sbitmap wont_exit;
899 VEC (edge, heap) *to_remove = NULL;
901 est_niter = expected_loop_iterations (loop);
902 determine_exit_conditions (loop, desc, factor,
903 &enter_main_cond, &exit_base, &exit_step,
904 &exit_cmp, &exit_bound);
906 /* Let us assume that the unrolled loop is quite likely to be entered. */
907 if (integer_nonzerop (enter_main_cond))
908 prob_entry = REG_BR_PROB_BASE;
909 else
910 prob_entry = PROB_UNROLLED_LOOP_ENTERED * REG_BR_PROB_BASE / 100;
912 /* The values for scales should keep profile consistent, and somewhat close
913 to correct.
915 TODO: The current value of SCALE_REST makes it appear that the loop that
916 is created by splitting the remaining iterations of the unrolled loop is
917 executed the same number of times as the original loop, and with the same
918 frequencies, which is obviously wrong. This does not appear to cause
919 problems, so we do not bother with fixing it for now. To make the profile
920 correct, we would need to change the probability of the exit edge of the
921 loop, and recompute the distribution of frequencies in its body because
922 of this change (scale the frequencies of blocks before and after the exit
923 by appropriate factors). */
924 scale_unrolled = prob_entry;
925 scale_rest = REG_BR_PROB_BASE;
927 new_loop = loop_version (loop, enter_main_cond, NULL,
928 prob_entry, scale_unrolled, scale_rest, true);
929 gcc_assert (new_loop != NULL);
930 update_ssa (TODO_update_ssa);
932 /* Determine the probability of the exit edge of the unrolled loop. */
933 new_est_niter = est_niter / factor;
935 /* Without profile feedback, loops for that we do not know a better estimate
936 are assumed to roll 10 times. When we unroll such loop, it appears to
937 roll too little, and it may even seem to be cold. To avoid this, we
938 ensure that the created loop appears to roll at least 5 times (but at
939 most as many times as before unrolling). */
940 if (new_est_niter < 5)
942 if (est_niter < 5)
943 new_est_niter = est_niter;
944 else
945 new_est_niter = 5;
948 /* Prepare the cfg and update the phi nodes. Move the loop exit to the
949 loop latch (and make its condition dummy, for the moment). */
950 rest = loop_preheader_edge (new_loop)->src;
951 precond_edge = single_pred_edge (rest);
952 split_edge (loop_latch_edge (loop));
953 exit_bb = single_pred (loop->latch);
955 /* Since the exit edge will be removed, the frequency of all the blocks
956 in the loop that are dominated by it must be scaled by
957 1 / (1 - exit->probability). */
958 scale_dominated_blocks_in_loop (loop, exit->src,
959 REG_BR_PROB_BASE,
960 REG_BR_PROB_BASE - exit->probability);
962 bsi = gsi_last_bb (exit_bb);
963 exit_if = gimple_build_cond (EQ_EXPR, integer_zero_node,
964 integer_zero_node,
965 NULL_TREE, NULL_TREE);
967 gsi_insert_after (&bsi, exit_if, GSI_NEW_STMT);
968 new_exit = make_edge (exit_bb, rest, EDGE_FALSE_VALUE | irr);
969 rescan_loop_exit (new_exit, true, false);
971 /* Set the probability of new exit to the same of the old one. Fix
972 the frequency of the latch block, by scaling it back by
973 1 - exit->probability. */
974 new_exit->count = exit->count;
975 new_exit->probability = exit->probability;
976 new_nonexit = single_pred_edge (loop->latch);
977 new_nonexit->probability = REG_BR_PROB_BASE - exit->probability;
978 new_nonexit->flags = EDGE_TRUE_VALUE;
979 new_nonexit->count -= exit->count;
980 if (new_nonexit->count < 0)
981 new_nonexit->count = 0;
982 scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
983 REG_BR_PROB_BASE);
985 old_entry = loop_preheader_edge (loop);
986 new_entry = loop_preheader_edge (new_loop);
987 old_latch = loop_latch_edge (loop);
988 for (psi_old_loop = gsi_start_phis (loop->header),
989 psi_new_loop = gsi_start_phis (new_loop->header);
990 !gsi_end_p (psi_old_loop);
991 gsi_next (&psi_old_loop), gsi_next (&psi_new_loop))
993 phi_old_loop = gsi_stmt (psi_old_loop);
994 phi_new_loop = gsi_stmt (psi_new_loop);
996 init = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_entry);
997 op = PHI_ARG_DEF_PTR_FROM_EDGE (phi_new_loop, new_entry);
998 gcc_assert (operand_equal_for_phi_arg_p (init, USE_FROM_PTR (op)));
999 next = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_latch);
1001 /* Prefer using original variable as a base for the new ssa name.
1002 This is necessary for virtual ops, and useful in order to avoid
1003 losing debug info for real ops. */
1004 if (TREE_CODE (next) == SSA_NAME
1005 && useless_type_conversion_p (TREE_TYPE (next),
1006 TREE_TYPE (init)))
1007 var = SSA_NAME_VAR (next);
1008 else if (TREE_CODE (init) == SSA_NAME
1009 && useless_type_conversion_p (TREE_TYPE (init),
1010 TREE_TYPE (next)))
1011 var = SSA_NAME_VAR (init);
1012 else if (useless_type_conversion_p (TREE_TYPE (next), TREE_TYPE (init)))
1014 var = create_tmp_var (TREE_TYPE (next), "unrinittmp");
1015 add_referenced_var (var);
1017 else
1019 var = create_tmp_var (TREE_TYPE (init), "unrinittmp");
1020 add_referenced_var (var);
1023 new_init = make_ssa_name (var, NULL);
1024 phi_rest = create_phi_node (new_init, rest);
1025 SSA_NAME_DEF_STMT (new_init) = phi_rest;
1027 add_phi_arg (phi_rest, init, precond_edge, UNKNOWN_LOCATION);
1028 add_phi_arg (phi_rest, next, new_exit, UNKNOWN_LOCATION);
1029 SET_USE (op, new_init);
1032 remove_path (exit);
1034 /* Transform the loop. */
1035 if (transform)
1036 (*transform) (loop, data);
1038 /* Unroll the loop and remove the exits in all iterations except for the
1039 last one. */
1040 wont_exit = sbitmap_alloc (factor);
1041 sbitmap_ones (wont_exit);
1042 RESET_BIT (wont_exit, factor - 1);
1044 ok = gimple_duplicate_loop_to_header_edge
1045 (loop, loop_latch_edge (loop), factor - 1,
1046 wont_exit, new_exit, &to_remove, DLTHE_FLAG_UPDATE_FREQ);
1047 free (wont_exit);
1048 gcc_assert (ok);
1050 FOR_EACH_VEC_ELT (edge, to_remove, i, e)
1052 ok = remove_path (e);
1053 gcc_assert (ok);
1055 VEC_free (edge, heap, to_remove);
1056 update_ssa (TODO_update_ssa);
1058 /* Ensure that the frequencies in the loop match the new estimated
1059 number of iterations, and change the probability of the new
1060 exit edge. */
1061 freq_h = loop->header->frequency;
1062 freq_e = EDGE_FREQUENCY (loop_preheader_edge (loop));
1063 if (freq_h != 0)
1064 scale_loop_frequencies (loop, freq_e * (new_est_niter + 1), freq_h);
1066 exit_bb = single_pred (loop->latch);
1067 new_exit = find_edge (exit_bb, rest);
1068 new_exit->count = loop_preheader_edge (loop)->count;
1069 new_exit->probability = REG_BR_PROB_BASE / (new_est_niter + 1);
1071 rest->count += new_exit->count;
1072 rest->frequency += EDGE_FREQUENCY (new_exit);
1074 new_nonexit = single_pred_edge (loop->latch);
1075 prob = new_nonexit->probability;
1076 new_nonexit->probability = REG_BR_PROB_BASE - new_exit->probability;
1077 new_nonexit->count = exit_bb->count - new_exit->count;
1078 if (new_nonexit->count < 0)
1079 new_nonexit->count = 0;
1080 if (prob > 0)
1081 scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
1082 prob);
1084 /* Finally create the new counter for number of iterations and add the new
1085 exit instruction. */
1086 bsi = gsi_last_nondebug_bb (exit_bb);
1087 exit_if = gsi_stmt (bsi);
1088 create_iv (exit_base, exit_step, NULL_TREE, loop,
1089 &bsi, false, &ctr_before, &ctr_after);
1090 gimple_cond_set_code (exit_if, exit_cmp);
1091 gimple_cond_set_lhs (exit_if, ctr_after);
1092 gimple_cond_set_rhs (exit_if, exit_bound);
1093 update_stmt (exit_if);
1095 #ifdef ENABLE_CHECKING
1096 verify_flow_info ();
1097 verify_loop_structure ();
1098 verify_loop_closed_ssa (true);
1099 #endif
1102 /* Wrapper over tree_transform_and_unroll_loop for case we do not
1103 want to transform the loop before unrolling. The meaning
1104 of the arguments is the same as for tree_transform_and_unroll_loop. */
1106 void
1107 tree_unroll_loop (struct loop *loop, unsigned factor,
1108 edge exit, struct tree_niter_desc *desc)
1110 tree_transform_and_unroll_loop (loop, factor, exit, desc,
1111 NULL, NULL);
1114 /* Rewrite the phi node at position PSI in function of the main
1115 induction variable MAIN_IV and insert the generated code at GSI. */
1117 static void
1118 rewrite_phi_with_iv (loop_p loop,
1119 gimple_stmt_iterator *psi,
1120 gimple_stmt_iterator *gsi,
1121 tree main_iv)
1123 affine_iv iv;
1124 gimple stmt, phi = gsi_stmt (*psi);
1125 tree atype, mtype, val, res = PHI_RESULT (phi);
1127 if (!is_gimple_reg (res) || res == main_iv)
1129 gsi_next (psi);
1130 return;
1133 if (!simple_iv (loop, loop, res, &iv, true))
1135 gsi_next (psi);
1136 return;
1139 remove_phi_node (psi, false);
1141 atype = TREE_TYPE (res);
1142 mtype = POINTER_TYPE_P (atype) ? sizetype : atype;
1143 val = fold_build2 (MULT_EXPR, mtype, unshare_expr (iv.step),
1144 fold_convert (mtype, main_iv));
1145 val = fold_build2 (POINTER_TYPE_P (atype)
1146 ? POINTER_PLUS_EXPR : PLUS_EXPR,
1147 atype, unshare_expr (iv.base), val);
1148 val = force_gimple_operand_gsi (gsi, val, false, NULL_TREE, true,
1149 GSI_SAME_STMT);
1150 stmt = gimple_build_assign (res, val);
1151 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1152 SSA_NAME_DEF_STMT (res) = stmt;
1155 /* Rewrite all the phi nodes of LOOP in function of the main induction
1156 variable MAIN_IV. */
1158 static void
1159 rewrite_all_phi_nodes_with_iv (loop_p loop, tree main_iv)
1161 unsigned i;
1162 basic_block *bbs = get_loop_body_in_dom_order (loop);
1163 gimple_stmt_iterator psi;
1165 for (i = 0; i < loop->num_nodes; i++)
1167 basic_block bb = bbs[i];
1168 gimple_stmt_iterator gsi = gsi_after_labels (bb);
1170 if (bb->loop_father != loop)
1171 continue;
1173 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); )
1174 rewrite_phi_with_iv (loop, &psi, &gsi, main_iv);
1177 free (bbs);
1180 /* Bases all the induction variables in LOOP on a single induction
1181 variable (unsigned with base 0 and step 1), whose final value is
1182 compared with *NIT. When the IV type precision has to be larger
1183 than *NIT type precision, *NIT is converted to the larger type, the
1184 conversion code is inserted before the loop, and *NIT is updated to
1185 the new definition. When BUMP_IN_LATCH is true, the induction
1186 variable is incremented in the loop latch, otherwise it is
1187 incremented in the loop header. Return the induction variable that
1188 was created. */
1190 tree
1191 canonicalize_loop_ivs (struct loop *loop, tree *nit, bool bump_in_latch)
1193 unsigned precision = TYPE_PRECISION (TREE_TYPE (*nit));
1194 unsigned original_precision = precision;
1195 tree type, var_before;
1196 gimple_stmt_iterator gsi, psi;
1197 gimple stmt;
1198 edge exit = single_dom_exit (loop);
1199 gimple_seq stmts;
1200 enum machine_mode mode;
1201 bool unsigned_p = false;
1203 for (psi = gsi_start_phis (loop->header);
1204 !gsi_end_p (psi); gsi_next (&psi))
1206 gimple phi = gsi_stmt (psi);
1207 tree res = PHI_RESULT (phi);
1208 bool uns;
1210 type = TREE_TYPE (res);
1211 if (!is_gimple_reg (res)
1212 || (!INTEGRAL_TYPE_P (type)
1213 && !POINTER_TYPE_P (type))
1214 || TYPE_PRECISION (type) < precision)
1215 continue;
1217 uns = POINTER_TYPE_P (type) | TYPE_UNSIGNED (type);
1219 if (TYPE_PRECISION (type) > precision)
1220 unsigned_p = uns;
1221 else
1222 unsigned_p |= uns;
1224 precision = TYPE_PRECISION (type);
1227 mode = smallest_mode_for_size (precision, MODE_INT);
1228 precision = GET_MODE_PRECISION (mode);
1229 type = build_nonstandard_integer_type (precision, unsigned_p);
1231 if (original_precision != precision)
1233 *nit = fold_convert (type, *nit);
1234 *nit = force_gimple_operand (*nit, &stmts, true, NULL_TREE);
1235 if (stmts)
1236 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1239 if (bump_in_latch)
1240 gsi = gsi_last_bb (loop->latch);
1241 else
1242 gsi = gsi_last_nondebug_bb (loop->header);
1243 create_iv (build_int_cst_type (type, 0), build_int_cst (type, 1), NULL_TREE,
1244 loop, &gsi, bump_in_latch, &var_before, NULL);
1246 rewrite_all_phi_nodes_with_iv (loop, var_before);
1248 stmt = last_stmt (exit->src);
1249 /* Make the loop exit if the control condition is not satisfied. */
1250 if (exit->flags & EDGE_TRUE_VALUE)
1252 edge te, fe;
1254 extract_true_false_edges_from_block (exit->src, &te, &fe);
1255 te->flags = EDGE_FALSE_VALUE;
1256 fe->flags = EDGE_TRUE_VALUE;
1258 gimple_cond_set_code (stmt, LT_EXPR);
1259 gimple_cond_set_lhs (stmt, var_before);
1260 gimple_cond_set_rhs (stmt, *nit);
1261 update_stmt (stmt);
1263 return var_before;