cfgexpand.c (expand_used_vars): Use virtual_operand_p.
[gcc.git] / gcc / tree-ssa-loop-manip.c
1 /* High-level loop manipulation functions.
2 Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010
3 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
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.
11
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.
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 #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 "dumpfile.h"
30 #include "cfgloop.h"
31 #include "tree-pass.h" /* ??? for TODO_update_ssa but this isn't a pass. */
32 #include "tree-scalar-evolution.h"
33 #include "params.h"
34 #include "tree-inline.h"
35 #include "langhooks.h"
36
37 /* All bitmaps for rewriting into loop-closed SSA go on this obstack,
38 so that we can free them all at once. */
39 static bitmap_obstack loop_renamer_obstack;
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 gimple_stmt_iterator *incr_pos, bool after,
53 tree *var_before, tree *var_after)
54 {
55 gimple stmt;
56 tree initial, step1;
57 gimple_seq stmts;
58 tree vb, va;
59 enum tree_code incr_op = PLUS_EXPR;
60 edge pe = loop_preheader_edge (loop);
61
62 if (var != NULL_TREE)
63 {
64 vb = make_ssa_name (var, NULL);
65 va = make_ssa_name (var, NULL);
66 }
67 else
68 {
69 vb = make_temp_ssa_name (TREE_TYPE (base), NULL, "ivtmp");
70 va = make_temp_ssa_name (TREE_TYPE (base), NULL, "ivtmp");
71 }
72 if (var_before)
73 *var_before = vb;
74 if (var_after)
75 *var_after = va;
76
77 /* For easier readability of the created code, produce MINUS_EXPRs
78 when suitable. */
79 if (TREE_CODE (step) == INTEGER_CST)
80 {
81 if (TYPE_UNSIGNED (TREE_TYPE (step)))
82 {
83 step1 = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
84 if (tree_int_cst_lt (step1, step))
85 {
86 incr_op = MINUS_EXPR;
87 step = step1;
88 }
89 }
90 else
91 {
92 bool ovf;
93
94 if (!tree_expr_nonnegative_warnv_p (step, &ovf)
95 && may_negate_without_overflow_p (step))
96 {
97 incr_op = MINUS_EXPR;
98 step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
99 }
100 }
101 }
102 if (POINTER_TYPE_P (TREE_TYPE (base)))
103 {
104 if (TREE_CODE (base) == ADDR_EXPR)
105 mark_addressable (TREE_OPERAND (base, 0));
106 step = convert_to_ptrofftype (step);
107 if (incr_op == MINUS_EXPR)
108 step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
109 incr_op = POINTER_PLUS_EXPR;
110 }
111 /* Gimplify the step if necessary. We put the computations in front of the
112 loop (i.e. the step should be loop invariant). */
113 step = force_gimple_operand (step, &stmts, true, NULL_TREE);
114 if (stmts)
115 gsi_insert_seq_on_edge_immediate (pe, stmts);
116
117 stmt = gimple_build_assign_with_ops (incr_op, va, vb, step);
118 if (after)
119 gsi_insert_after (incr_pos, stmt, GSI_NEW_STMT);
120 else
121 gsi_insert_before (incr_pos, stmt, GSI_NEW_STMT);
122
123 initial = force_gimple_operand (base, &stmts, true, var);
124 if (stmts)
125 gsi_insert_seq_on_edge_immediate (pe, stmts);
126
127 stmt = create_phi_node (vb, loop->header);
128 add_phi_arg (stmt, initial, loop_preheader_edge (loop), UNKNOWN_LOCATION);
129 add_phi_arg (stmt, va, loop_latch_edge (loop), UNKNOWN_LOCATION);
130 }
131
132 /* Add exit phis for the USE on EXIT. */
133
134 static void
135 add_exit_phis_edge (basic_block exit, tree use)
136 {
137 gimple phi, def_stmt = SSA_NAME_DEF_STMT (use);
138 basic_block def_bb = gimple_bb (def_stmt);
139 struct loop *def_loop;
140 edge e;
141 edge_iterator ei;
142
143 /* Check that some of the edges entering the EXIT block exits a loop in
144 that USE is defined. */
145 FOR_EACH_EDGE (e, ei, exit->preds)
146 {
147 def_loop = find_common_loop (def_bb->loop_father, e->src->loop_father);
148 if (!flow_bb_inside_loop_p (def_loop, e->dest))
149 break;
150 }
151
152 if (!e)
153 return;
154
155 phi = create_phi_node (NULL_TREE, exit);
156 create_new_def_for (use, phi, gimple_phi_result_ptr (phi));
157 FOR_EACH_EDGE (e, ei, exit->preds)
158 add_phi_arg (phi, use, e, UNKNOWN_LOCATION);
159 }
160
161 /* Add exit phis for VAR that is used in LIVEIN.
162 Exits of the loops are stored in EXITS. */
163
164 static void
165 add_exit_phis_var (tree var, bitmap livein, bitmap exits)
166 {
167 bitmap def;
168 unsigned index;
169 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
170 bitmap_iterator bi;
171
172 gcc_checking_assert (! virtual_operand_p (var));
173 bitmap_clear_bit (livein, def_bb->index);
174
175 def = BITMAP_ALLOC (&loop_renamer_obstack);
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 /* Free the livein bitmap. We'll not be needing it anymore, and
186 it may have grown quite large. No reason to hold on to it. */
187 bitmap_clear (livein);
188 }
189
190 /* Add exit phis for the names marked in NAMES_TO_RENAME.
191 Exits of the loops are stored in EXITS. Sets of blocks where the ssa
192 names are used are stored in USE_BLOCKS. */
193
194 static void
195 add_exit_phis (bitmap names_to_rename, bitmap *use_blocks, bitmap loop_exits)
196 {
197 unsigned i;
198 bitmap_iterator bi;
199
200 EXECUTE_IF_SET_IN_BITMAP (names_to_rename, 0, i, bi)
201 {
202 add_exit_phis_var (ssa_name (i), use_blocks[i], loop_exits);
203 }
204 }
205
206 /* Returns a bitmap of all loop exit edge targets. */
207
208 static bitmap
209 get_loops_exits (void)
210 {
211 bitmap exits = BITMAP_ALLOC (&loop_renamer_obstack);
212 basic_block bb;
213 edge e;
214 edge_iterator ei;
215
216 FOR_EACH_BB (bb)
217 {
218 FOR_EACH_EDGE (e, ei, bb->preds)
219 if (e->src != ENTRY_BLOCK_PTR
220 && !flow_bb_inside_loop_p (e->src->loop_father, bb))
221 {
222 bitmap_set_bit (exits, bb->index);
223 break;
224 }
225 }
226
227 return exits;
228 }
229
230 /* For USE in BB, if it is used outside of the loop it is defined in,
231 mark it for rewrite. Record basic block BB where it is used
232 to USE_BLOCKS. Record the ssa name index to NEED_PHIS bitmap. */
233
234 static void
235 find_uses_to_rename_use (basic_block bb, tree use, bitmap *use_blocks,
236 bitmap need_phis)
237 {
238 unsigned ver;
239 basic_block def_bb;
240 struct loop *def_loop;
241
242 if (TREE_CODE (use) != SSA_NAME)
243 return;
244
245 /* We don't need to keep virtual operands in loop-closed form. */
246 if (virtual_operand_p (use))
247 return;
248
249 ver = SSA_NAME_VERSION (use);
250 def_bb = gimple_bb (SSA_NAME_DEF_STMT (use));
251 if (!def_bb)
252 return;
253 def_loop = def_bb->loop_father;
254
255 /* If the definition is not inside a loop, it is not interesting. */
256 if (!loop_outer (def_loop))
257 return;
258
259 /* If the use is not outside of the loop it is defined in, it is not
260 interesting. */
261 if (flow_bb_inside_loop_p (def_loop, bb))
262 return;
263
264 /* If we're seeing VER for the first time, we still have to allocate
265 a bitmap for its uses. */
266 if (bitmap_set_bit (need_phis, ver))
267 use_blocks[ver] = BITMAP_ALLOC (&loop_renamer_obstack);
268 bitmap_set_bit (use_blocks[ver], bb->index);
269 }
270
271 /* For uses in STMT, mark names that are used outside of the loop they are
272 defined to rewrite. Record the set of blocks in that the ssa
273 names are defined to USE_BLOCKS and the ssa names themselves to
274 NEED_PHIS. */
275
276 static void
277 find_uses_to_rename_stmt (gimple stmt, bitmap *use_blocks, bitmap need_phis)
278 {
279 ssa_op_iter iter;
280 tree var;
281 basic_block bb = gimple_bb (stmt);
282
283 if (is_gimple_debug (stmt))
284 return;
285
286 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_USE)
287 find_uses_to_rename_use (bb, var, use_blocks, need_phis);
288 }
289
290 /* Marks names that are used in BB and outside of the loop they are
291 defined in for rewrite. Records the set of blocks in that the ssa
292 names are defined to USE_BLOCKS. Record the SSA names that will
293 need exit PHIs in NEED_PHIS. */
294
295 static void
296 find_uses_to_rename_bb (basic_block bb, bitmap *use_blocks, bitmap need_phis)
297 {
298 gimple_stmt_iterator bsi;
299 edge e;
300 edge_iterator ei;
301
302 FOR_EACH_EDGE (e, ei, bb->succs)
303 for (bsi = gsi_start_phis (e->dest); !gsi_end_p (bsi); gsi_next (&bsi))
304 find_uses_to_rename_use (bb, PHI_ARG_DEF_FROM_EDGE (gsi_stmt (bsi), e),
305 use_blocks, need_phis);
306
307 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
308 find_uses_to_rename_stmt (gsi_stmt (bsi), use_blocks, need_phis);
309 }
310
311 /* Marks names that are used outside of the loop they are defined in
312 for rewrite. Records the set of blocks in that the ssa
313 names are defined to USE_BLOCKS. If CHANGED_BBS is not NULL,
314 scan only blocks in this set. */
315
316 static void
317 find_uses_to_rename (bitmap changed_bbs, bitmap *use_blocks, bitmap need_phis)
318 {
319 basic_block bb;
320 unsigned index;
321 bitmap_iterator bi;
322
323 /* ??? If CHANGED_BBS is empty we rewrite the whole function -- why? */
324 if (changed_bbs && !bitmap_empty_p (changed_bbs))
325 {
326 EXECUTE_IF_SET_IN_BITMAP (changed_bbs, 0, index, bi)
327 {
328 find_uses_to_rename_bb (BASIC_BLOCK (index), use_blocks, need_phis);
329 }
330 }
331 else
332 {
333 FOR_EACH_BB (bb)
334 {
335 find_uses_to_rename_bb (bb, use_blocks, need_phis);
336 }
337 }
338 }
339
340 /* Rewrites the program into a loop closed ssa form -- i.e. inserts extra
341 phi nodes to ensure that no variable is used outside the loop it is
342 defined in.
343
344 This strengthening of the basic ssa form has several advantages:
345
346 1) Updating it during unrolling/peeling/versioning is trivial, since
347 we do not need to care about the uses outside of the loop.
348 2) The behavior of all uses of an induction variable is the same.
349 Without this, you need to distinguish the case when the variable
350 is used outside of the loop it is defined in, for example
351
352 for (i = 0; i < 100; i++)
353 {
354 for (j = 0; j < 100; j++)
355 {
356 k = i + j;
357 use1 (k);
358 }
359 use2 (k);
360 }
361
362 Looking from the outer loop with the normal SSA form, the first use of k
363 is not well-behaved, while the second one is an induction variable with
364 base 99 and step 1.
365
366 If CHANGED_BBS is not NULL, we look for uses outside loops only in
367 the basic blocks in this set.
368
369 UPDATE_FLAG is used in the call to update_ssa. See
370 TODO_update_ssa* for documentation. */
371
372 void
373 rewrite_into_loop_closed_ssa (bitmap changed_bbs, unsigned update_flag)
374 {
375 bitmap loop_exits;
376 bitmap *use_blocks;
377 bitmap names_to_rename;
378
379 loops_state_set (LOOP_CLOSED_SSA);
380 if (number_of_loops () <= 1)
381 return;
382
383 bitmap_obstack_initialize (&loop_renamer_obstack);
384
385 loop_exits = get_loops_exits ();
386 names_to_rename = BITMAP_ALLOC (&loop_renamer_obstack);
387
388 /* If the pass has caused the SSA form to be out-of-date, update it
389 now. */
390 update_ssa (update_flag);
391
392 /* Uses of names to rename. We don't have to initialize this array,
393 because we know that we will only have entries for the SSA names
394 in NAMES_TO_RENAME. */
395 use_blocks = XNEWVEC (bitmap, num_ssa_names);
396
397 /* Find the uses outside loops. */
398 find_uses_to_rename (changed_bbs, use_blocks, names_to_rename);
399
400 /* Add the PHI nodes on exits of the loops for the names we need to
401 rewrite. */
402 add_exit_phis (names_to_rename, use_blocks, loop_exits);
403
404 bitmap_obstack_release (&loop_renamer_obstack);
405 free (use_blocks);
406
407 /* Fix up all the names found to be used outside their original
408 loops. */
409 update_ssa (TODO_update_ssa);
410 }
411
412 /* Check invariants of the loop closed ssa form for the USE in BB. */
413
414 static void
415 check_loop_closed_ssa_use (basic_block bb, tree use)
416 {
417 gimple def;
418 basic_block def_bb;
419
420 if (TREE_CODE (use) != SSA_NAME || virtual_operand_p (use))
421 return;
422
423 def = SSA_NAME_DEF_STMT (use);
424 def_bb = gimple_bb (def);
425 gcc_assert (!def_bb
426 || flow_bb_inside_loop_p (def_bb->loop_father, bb));
427 }
428
429 /* Checks invariants of loop closed ssa form in statement STMT in BB. */
430
431 static void
432 check_loop_closed_ssa_stmt (basic_block bb, gimple stmt)
433 {
434 ssa_op_iter iter;
435 tree var;
436
437 if (is_gimple_debug (stmt))
438 return;
439
440 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_USE)
441 check_loop_closed_ssa_use (bb, var);
442 }
443
444 /* Checks that invariants of the loop closed ssa form are preserved.
445 Call verify_ssa when VERIFY_SSA_P is true. */
446
447 DEBUG_FUNCTION void
448 verify_loop_closed_ssa (bool verify_ssa_p)
449 {
450 basic_block bb;
451 gimple_stmt_iterator bsi;
452 gimple phi;
453 edge e;
454 edge_iterator ei;
455
456 if (number_of_loops () <= 1)
457 return;
458
459 if (verify_ssa_p)
460 verify_ssa (false);
461
462 timevar_push (TV_VERIFY_LOOP_CLOSED);
463
464 FOR_EACH_BB (bb)
465 {
466 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
467 {
468 phi = gsi_stmt (bsi);
469 FOR_EACH_EDGE (e, ei, bb->preds)
470 check_loop_closed_ssa_use (e->src,
471 PHI_ARG_DEF_FROM_EDGE (phi, e));
472 }
473
474 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
475 check_loop_closed_ssa_stmt (bb, gsi_stmt (bsi));
476 }
477
478 timevar_pop (TV_VERIFY_LOOP_CLOSED);
479 }
480
481 /* Split loop exit edge EXIT. The things are a bit complicated by a need to
482 preserve the loop closed ssa form. The newly created block is returned. */
483
484 basic_block
485 split_loop_exit_edge (edge exit)
486 {
487 basic_block dest = exit->dest;
488 basic_block bb = split_edge (exit);
489 gimple phi, new_phi;
490 tree new_name, name;
491 use_operand_p op_p;
492 gimple_stmt_iterator psi;
493 source_location locus;
494
495 for (psi = gsi_start_phis (dest); !gsi_end_p (psi); gsi_next (&psi))
496 {
497 phi = gsi_stmt (psi);
498 op_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, single_succ_edge (bb));
499 locus = gimple_phi_arg_location_from_edge (phi, single_succ_edge (bb));
500
501 name = USE_FROM_PTR (op_p);
502
503 /* If the argument of the PHI node is a constant, we do not need
504 to keep it inside loop. */
505 if (TREE_CODE (name) != SSA_NAME)
506 continue;
507
508 /* Otherwise create an auxiliary phi node that will copy the value
509 of the SSA name out of the loop. */
510 new_name = duplicate_ssa_name (name, NULL);
511 new_phi = create_phi_node (new_name, bb);
512 add_phi_arg (new_phi, name, exit, locus);
513 SET_USE (op_p, new_name);
514 }
515
516 return bb;
517 }
518
519 /* Returns the basic block in that statements should be emitted for induction
520 variables incremented at the end of the LOOP. */
521
522 basic_block
523 ip_end_pos (struct loop *loop)
524 {
525 return loop->latch;
526 }
527
528 /* Returns the basic block in that statements should be emitted for induction
529 variables incremented just before exit condition of a LOOP. */
530
531 basic_block
532 ip_normal_pos (struct loop *loop)
533 {
534 gimple last;
535 basic_block bb;
536 edge exit;
537
538 if (!single_pred_p (loop->latch))
539 return NULL;
540
541 bb = single_pred (loop->latch);
542 last = last_stmt (bb);
543 if (!last
544 || gimple_code (last) != GIMPLE_COND)
545 return NULL;
546
547 exit = EDGE_SUCC (bb, 0);
548 if (exit->dest == loop->latch)
549 exit = EDGE_SUCC (bb, 1);
550
551 if (flow_bb_inside_loop_p (loop, exit->dest))
552 return NULL;
553
554 return bb;
555 }
556
557 /* Stores the standard position for induction variable increment in LOOP
558 (just before the exit condition if it is available and latch block is empty,
559 end of the latch block otherwise) to BSI. INSERT_AFTER is set to true if
560 the increment should be inserted after *BSI. */
561
562 void
563 standard_iv_increment_position (struct loop *loop, gimple_stmt_iterator *bsi,
564 bool *insert_after)
565 {
566 basic_block bb = ip_normal_pos (loop), latch = ip_end_pos (loop);
567 gimple last = last_stmt (latch);
568
569 if (!bb
570 || (last && gimple_code (last) != GIMPLE_LABEL))
571 {
572 *bsi = gsi_last_bb (latch);
573 *insert_after = true;
574 }
575 else
576 {
577 *bsi = gsi_last_bb (bb);
578 *insert_after = false;
579 }
580 }
581
582 /* Copies phi node arguments for duplicated blocks. The index of the first
583 duplicated block is FIRST_NEW_BLOCK. */
584
585 static void
586 copy_phi_node_args (unsigned first_new_block)
587 {
588 unsigned i;
589
590 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
591 BASIC_BLOCK (i)->flags |= BB_DUPLICATED;
592
593 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
594 add_phi_args_after_copy_bb (BASIC_BLOCK (i));
595
596 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
597 BASIC_BLOCK (i)->flags &= ~BB_DUPLICATED;
598 }
599
600
601 /* The same as cfgloopmanip.c:duplicate_loop_to_header_edge, but also
602 updates the PHI nodes at start of the copied region. In order to
603 achieve this, only loops whose exits all lead to the same location
604 are handled.
605
606 Notice that we do not completely update the SSA web after
607 duplication. The caller is responsible for calling update_ssa
608 after the loop has been duplicated. */
609
610 bool
611 gimple_duplicate_loop_to_header_edge (struct loop *loop, edge e,
612 unsigned int ndupl, sbitmap wont_exit,
613 edge orig, VEC (edge, heap) **to_remove,
614 int flags)
615 {
616 unsigned first_new_block;
617
618 if (!loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
619 return false;
620 if (!loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS))
621 return false;
622
623 #ifdef ENABLE_CHECKING
624 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
625 verify_loop_closed_ssa (true);
626 #endif
627
628 first_new_block = last_basic_block;
629 if (!duplicate_loop_to_header_edge (loop, e, ndupl, wont_exit,
630 orig, to_remove, flags))
631 return false;
632
633 /* Readd the removed phi args for e. */
634 flush_pending_stmts (e);
635
636 /* Copy the phi node arguments. */
637 copy_phi_node_args (first_new_block);
638
639 scev_reset ();
640
641 return true;
642 }
643
644 /* Returns true if we can unroll LOOP FACTOR times. Number
645 of iterations of the loop is returned in NITER. */
646
647 bool
648 can_unroll_loop_p (struct loop *loop, unsigned factor,
649 struct tree_niter_desc *niter)
650 {
651 edge exit;
652
653 /* Check whether unrolling is possible. We only want to unroll loops
654 for that we are able to determine number of iterations. We also
655 want to split the extra iterations of the loop from its end,
656 therefore we require that the loop has precisely one
657 exit. */
658
659 exit = single_dom_exit (loop);
660 if (!exit)
661 return false;
662
663 if (!number_of_iterations_exit (loop, exit, niter, false)
664 || niter->cmp == ERROR_MARK
665 /* Scalar evolutions analysis might have copy propagated
666 the abnormal ssa names into these expressions, hence
667 emitting the computations based on them during loop
668 unrolling might create overlapping life ranges for
669 them, and failures in out-of-ssa. */
670 || contains_abnormal_ssa_name_p (niter->may_be_zero)
671 || contains_abnormal_ssa_name_p (niter->control.base)
672 || contains_abnormal_ssa_name_p (niter->control.step)
673 || contains_abnormal_ssa_name_p (niter->bound))
674 return false;
675
676 /* And of course, we must be able to duplicate the loop. */
677 if (!can_duplicate_loop_p (loop))
678 return false;
679
680 /* The final loop should be small enough. */
681 if (tree_num_loop_insns (loop, &eni_size_weights) * factor
682 > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS))
683 return false;
684
685 return true;
686 }
687
688 /* Determines the conditions that control execution of LOOP unrolled FACTOR
689 times. DESC is number of iterations of LOOP. ENTER_COND is set to
690 condition that must be true if the main loop can be entered.
691 EXIT_BASE, EXIT_STEP, EXIT_CMP and EXIT_BOUND are set to values describing
692 how the exit from the unrolled loop should be controlled. */
693
694 static void
695 determine_exit_conditions (struct loop *loop, struct tree_niter_desc *desc,
696 unsigned factor, tree *enter_cond,
697 tree *exit_base, tree *exit_step,
698 enum tree_code *exit_cmp, tree *exit_bound)
699 {
700 gimple_seq stmts;
701 tree base = desc->control.base;
702 tree step = desc->control.step;
703 tree bound = desc->bound;
704 tree type = TREE_TYPE (step);
705 tree bigstep, delta;
706 tree min = lower_bound_in_type (type, type);
707 tree max = upper_bound_in_type (type, type);
708 enum tree_code cmp = desc->cmp;
709 tree cond = boolean_true_node, assum;
710
711 /* For pointers, do the arithmetics in the type of step. */
712 base = fold_convert (type, base);
713 bound = fold_convert (type, bound);
714
715 *enter_cond = boolean_false_node;
716 *exit_base = NULL_TREE;
717 *exit_step = NULL_TREE;
718 *exit_cmp = ERROR_MARK;
719 *exit_bound = NULL_TREE;
720 gcc_assert (cmp != ERROR_MARK);
721
722 /* We only need to be correct when we answer question
723 "Do at least FACTOR more iterations remain?" in the unrolled loop.
724 Thus, transforming BASE + STEP * i <> BOUND to
725 BASE + STEP * i < BOUND is ok. */
726 if (cmp == NE_EXPR)
727 {
728 if (tree_int_cst_sign_bit (step))
729 cmp = GT_EXPR;
730 else
731 cmp = LT_EXPR;
732 }
733 else if (cmp == LT_EXPR)
734 {
735 gcc_assert (!tree_int_cst_sign_bit (step));
736 }
737 else if (cmp == GT_EXPR)
738 {
739 gcc_assert (tree_int_cst_sign_bit (step));
740 }
741 else
742 gcc_unreachable ();
743
744 /* The main body of the loop may be entered iff:
745
746 1) desc->may_be_zero is false.
747 2) it is possible to check that there are at least FACTOR iterations
748 of the loop, i.e., BOUND - step * FACTOR does not overflow.
749 3) # of iterations is at least FACTOR */
750
751 if (!integer_zerop (desc->may_be_zero))
752 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
753 invert_truthvalue (desc->may_be_zero),
754 cond);
755
756 bigstep = fold_build2 (MULT_EXPR, type, step,
757 build_int_cst_type (type, factor));
758 delta = fold_build2 (MINUS_EXPR, type, bigstep, step);
759 if (cmp == LT_EXPR)
760 assum = fold_build2 (GE_EXPR, boolean_type_node,
761 bound,
762 fold_build2 (PLUS_EXPR, type, min, delta));
763 else
764 assum = fold_build2 (LE_EXPR, boolean_type_node,
765 bound,
766 fold_build2 (PLUS_EXPR, type, max, delta));
767 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
768
769 bound = fold_build2 (MINUS_EXPR, type, bound, delta);
770 assum = fold_build2 (cmp, boolean_type_node, base, bound);
771 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
772
773 cond = force_gimple_operand (unshare_expr (cond), &stmts, false, NULL_TREE);
774 if (stmts)
775 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
776 /* cond now may be a gimple comparison, which would be OK, but also any
777 other gimple rhs (say a && b). In this case we need to force it to
778 operand. */
779 if (!is_gimple_condexpr (cond))
780 {
781 cond = force_gimple_operand (cond, &stmts, true, NULL_TREE);
782 if (stmts)
783 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
784 }
785 *enter_cond = cond;
786
787 base = force_gimple_operand (unshare_expr (base), &stmts, true, NULL_TREE);
788 if (stmts)
789 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
790 bound = force_gimple_operand (unshare_expr (bound), &stmts, true, NULL_TREE);
791 if (stmts)
792 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
793
794 *exit_base = base;
795 *exit_step = bigstep;
796 *exit_cmp = cmp;
797 *exit_bound = bound;
798 }
799
800 /* Scales the frequencies of all basic blocks in LOOP that are strictly
801 dominated by BB by NUM/DEN. */
802
803 static void
804 scale_dominated_blocks_in_loop (struct loop *loop, basic_block bb,
805 int num, int den)
806 {
807 basic_block son;
808
809 if (den == 0)
810 return;
811
812 for (son = first_dom_son (CDI_DOMINATORS, bb);
813 son;
814 son = next_dom_son (CDI_DOMINATORS, son))
815 {
816 if (!flow_bb_inside_loop_p (loop, son))
817 continue;
818 scale_bbs_frequencies_int (&son, 1, num, den);
819 scale_dominated_blocks_in_loop (loop, son, num, den);
820 }
821 }
822
823 /* Unroll LOOP FACTOR times. DESC describes number of iterations of LOOP.
824 EXIT is the exit of the loop to that DESC corresponds.
825
826 If N is number of iterations of the loop and MAY_BE_ZERO is the condition
827 under that loop exits in the first iteration even if N != 0,
828
829 while (1)
830 {
831 x = phi (init, next);
832
833 pre;
834 if (st)
835 break;
836 post;
837 }
838
839 becomes (with possibly the exit conditions formulated a bit differently,
840 avoiding the need to create a new iv):
841
842 if (MAY_BE_ZERO || N < FACTOR)
843 goto rest;
844
845 do
846 {
847 x = phi (init, next);
848
849 pre;
850 post;
851 pre;
852 post;
853 ...
854 pre;
855 post;
856 N -= FACTOR;
857
858 } while (N >= FACTOR);
859
860 rest:
861 init' = phi (init, x);
862
863 while (1)
864 {
865 x = phi (init', next);
866
867 pre;
868 if (st)
869 break;
870 post;
871 }
872
873 Before the loop is unrolled, TRANSFORM is called for it (only for the
874 unrolled loop, but not for its versioned copy). DATA is passed to
875 TRANSFORM. */
876
877 /* Probability in % that the unrolled loop is entered. Just a guess. */
878 #define PROB_UNROLLED_LOOP_ENTERED 90
879
880 void
881 tree_transform_and_unroll_loop (struct loop *loop, unsigned factor,
882 edge exit, struct tree_niter_desc *desc,
883 transform_callback transform,
884 void *data)
885 {
886 gimple exit_if;
887 tree ctr_before, ctr_after;
888 tree enter_main_cond, exit_base, exit_step, exit_bound;
889 enum tree_code exit_cmp;
890 gimple phi_old_loop, phi_new_loop, phi_rest;
891 gimple_stmt_iterator psi_old_loop, psi_new_loop;
892 tree init, next, new_init;
893 struct loop *new_loop;
894 basic_block rest, exit_bb;
895 edge old_entry, new_entry, old_latch, precond_edge, new_exit;
896 edge new_nonexit, e;
897 gimple_stmt_iterator bsi;
898 use_operand_p op;
899 bool ok;
900 unsigned est_niter, prob_entry, scale_unrolled, scale_rest, freq_e, freq_h;
901 unsigned new_est_niter, i, prob;
902 unsigned irr = loop_preheader_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP;
903 sbitmap wont_exit;
904 VEC (edge, heap) *to_remove = NULL;
905
906 est_niter = expected_loop_iterations (loop);
907 determine_exit_conditions (loop, desc, factor,
908 &enter_main_cond, &exit_base, &exit_step,
909 &exit_cmp, &exit_bound);
910
911 /* Let us assume that the unrolled loop is quite likely to be entered. */
912 if (integer_nonzerop (enter_main_cond))
913 prob_entry = REG_BR_PROB_BASE;
914 else
915 prob_entry = PROB_UNROLLED_LOOP_ENTERED * REG_BR_PROB_BASE / 100;
916
917 /* The values for scales should keep profile consistent, and somewhat close
918 to correct.
919
920 TODO: The current value of SCALE_REST makes it appear that the loop that
921 is created by splitting the remaining iterations of the unrolled loop is
922 executed the same number of times as the original loop, and with the same
923 frequencies, which is obviously wrong. This does not appear to cause
924 problems, so we do not bother with fixing it for now. To make the profile
925 correct, we would need to change the probability of the exit edge of the
926 loop, and recompute the distribution of frequencies in its body because
927 of this change (scale the frequencies of blocks before and after the exit
928 by appropriate factors). */
929 scale_unrolled = prob_entry;
930 scale_rest = REG_BR_PROB_BASE;
931
932 new_loop = loop_version (loop, enter_main_cond, NULL,
933 prob_entry, scale_unrolled, scale_rest, true);
934 gcc_assert (new_loop != NULL);
935 update_ssa (TODO_update_ssa);
936
937 /* Determine the probability of the exit edge of the unrolled loop. */
938 new_est_niter = est_niter / factor;
939
940 /* Without profile feedback, loops for that we do not know a better estimate
941 are assumed to roll 10 times. When we unroll such loop, it appears to
942 roll too little, and it may even seem to be cold. To avoid this, we
943 ensure that the created loop appears to roll at least 5 times (but at
944 most as many times as before unrolling). */
945 if (new_est_niter < 5)
946 {
947 if (est_niter < 5)
948 new_est_niter = est_niter;
949 else
950 new_est_niter = 5;
951 }
952
953 /* Prepare the cfg and update the phi nodes. Move the loop exit to the
954 loop latch (and make its condition dummy, for the moment). */
955 rest = loop_preheader_edge (new_loop)->src;
956 precond_edge = single_pred_edge (rest);
957 split_edge (loop_latch_edge (loop));
958 exit_bb = single_pred (loop->latch);
959
960 /* Since the exit edge will be removed, the frequency of all the blocks
961 in the loop that are dominated by it must be scaled by
962 1 / (1 - exit->probability). */
963 scale_dominated_blocks_in_loop (loop, exit->src,
964 REG_BR_PROB_BASE,
965 REG_BR_PROB_BASE - exit->probability);
966
967 bsi = gsi_last_bb (exit_bb);
968 exit_if = gimple_build_cond (EQ_EXPR, integer_zero_node,
969 integer_zero_node,
970 NULL_TREE, NULL_TREE);
971
972 gsi_insert_after (&bsi, exit_if, GSI_NEW_STMT);
973 new_exit = make_edge (exit_bb, rest, EDGE_FALSE_VALUE | irr);
974 rescan_loop_exit (new_exit, true, false);
975
976 /* Set the probability of new exit to the same of the old one. Fix
977 the frequency of the latch block, by scaling it back by
978 1 - exit->probability. */
979 new_exit->count = exit->count;
980 new_exit->probability = exit->probability;
981 new_nonexit = single_pred_edge (loop->latch);
982 new_nonexit->probability = REG_BR_PROB_BASE - exit->probability;
983 new_nonexit->flags = EDGE_TRUE_VALUE;
984 new_nonexit->count -= exit->count;
985 if (new_nonexit->count < 0)
986 new_nonexit->count = 0;
987 scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
988 REG_BR_PROB_BASE);
989
990 old_entry = loop_preheader_edge (loop);
991 new_entry = loop_preheader_edge (new_loop);
992 old_latch = loop_latch_edge (loop);
993 for (psi_old_loop = gsi_start_phis (loop->header),
994 psi_new_loop = gsi_start_phis (new_loop->header);
995 !gsi_end_p (psi_old_loop);
996 gsi_next (&psi_old_loop), gsi_next (&psi_new_loop))
997 {
998 phi_old_loop = gsi_stmt (psi_old_loop);
999 phi_new_loop = gsi_stmt (psi_new_loop);
1000
1001 init = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_entry);
1002 op = PHI_ARG_DEF_PTR_FROM_EDGE (phi_new_loop, new_entry);
1003 gcc_assert (operand_equal_for_phi_arg_p (init, USE_FROM_PTR (op)));
1004 next = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_latch);
1005
1006 /* Prefer using original variable as a base for the new ssa name.
1007 This is necessary for virtual ops, and useful in order to avoid
1008 losing debug info for real ops. */
1009 if (TREE_CODE (next) == SSA_NAME
1010 && useless_type_conversion_p (TREE_TYPE (next),
1011 TREE_TYPE (init)))
1012 new_init = copy_ssa_name (next, NULL);
1013 else if (TREE_CODE (init) == SSA_NAME
1014 && useless_type_conversion_p (TREE_TYPE (init),
1015 TREE_TYPE (next)))
1016 new_init = copy_ssa_name (init, NULL);
1017 else if (useless_type_conversion_p (TREE_TYPE (next), TREE_TYPE (init)))
1018 new_init = make_temp_ssa_name (TREE_TYPE (next), NULL, "unrinittmp");
1019 else
1020 new_init = make_temp_ssa_name (TREE_TYPE (init), NULL, "unrinittmp");
1021
1022 phi_rest = create_phi_node (new_init, rest);
1023
1024 add_phi_arg (phi_rest, init, precond_edge, UNKNOWN_LOCATION);
1025 add_phi_arg (phi_rest, next, new_exit, UNKNOWN_LOCATION);
1026 SET_USE (op, new_init);
1027 }
1028
1029 remove_path (exit);
1030
1031 /* Transform the loop. */
1032 if (transform)
1033 (*transform) (loop, data);
1034
1035 /* Unroll the loop and remove the exits in all iterations except for the
1036 last one. */
1037 wont_exit = sbitmap_alloc (factor);
1038 sbitmap_ones (wont_exit);
1039 RESET_BIT (wont_exit, factor - 1);
1040
1041 ok = gimple_duplicate_loop_to_header_edge
1042 (loop, loop_latch_edge (loop), factor - 1,
1043 wont_exit, new_exit, &to_remove, DLTHE_FLAG_UPDATE_FREQ);
1044 free (wont_exit);
1045 gcc_assert (ok);
1046
1047 FOR_EACH_VEC_ELT (edge, to_remove, i, e)
1048 {
1049 ok = remove_path (e);
1050 gcc_assert (ok);
1051 }
1052 VEC_free (edge, heap, to_remove);
1053 update_ssa (TODO_update_ssa);
1054
1055 /* Ensure that the frequencies in the loop match the new estimated
1056 number of iterations, and change the probability of the new
1057 exit edge. */
1058 freq_h = loop->header->frequency;
1059 freq_e = EDGE_FREQUENCY (loop_preheader_edge (loop));
1060 if (freq_h != 0)
1061 scale_loop_frequencies (loop, freq_e * (new_est_niter + 1), freq_h);
1062
1063 exit_bb = single_pred (loop->latch);
1064 new_exit = find_edge (exit_bb, rest);
1065 new_exit->count = loop_preheader_edge (loop)->count;
1066 new_exit->probability = REG_BR_PROB_BASE / (new_est_niter + 1);
1067
1068 rest->count += new_exit->count;
1069 rest->frequency += EDGE_FREQUENCY (new_exit);
1070
1071 new_nonexit = single_pred_edge (loop->latch);
1072 prob = new_nonexit->probability;
1073 new_nonexit->probability = REG_BR_PROB_BASE - new_exit->probability;
1074 new_nonexit->count = exit_bb->count - new_exit->count;
1075 if (new_nonexit->count < 0)
1076 new_nonexit->count = 0;
1077 if (prob > 0)
1078 scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
1079 prob);
1080
1081 /* Finally create the new counter for number of iterations and add the new
1082 exit instruction. */
1083 bsi = gsi_last_nondebug_bb (exit_bb);
1084 exit_if = gsi_stmt (bsi);
1085 create_iv (exit_base, exit_step, NULL_TREE, loop,
1086 &bsi, false, &ctr_before, &ctr_after);
1087 gimple_cond_set_code (exit_if, exit_cmp);
1088 gimple_cond_set_lhs (exit_if, ctr_after);
1089 gimple_cond_set_rhs (exit_if, exit_bound);
1090 update_stmt (exit_if);
1091
1092 #ifdef ENABLE_CHECKING
1093 verify_flow_info ();
1094 verify_loop_structure ();
1095 verify_loop_closed_ssa (true);
1096 #endif
1097 }
1098
1099 /* Wrapper over tree_transform_and_unroll_loop for case we do not
1100 want to transform the loop before unrolling. The meaning
1101 of the arguments is the same as for tree_transform_and_unroll_loop. */
1102
1103 void
1104 tree_unroll_loop (struct loop *loop, unsigned factor,
1105 edge exit, struct tree_niter_desc *desc)
1106 {
1107 tree_transform_and_unroll_loop (loop, factor, exit, desc,
1108 NULL, NULL);
1109 }
1110
1111 /* Rewrite the phi node at position PSI in function of the main
1112 induction variable MAIN_IV and insert the generated code at GSI. */
1113
1114 static void
1115 rewrite_phi_with_iv (loop_p loop,
1116 gimple_stmt_iterator *psi,
1117 gimple_stmt_iterator *gsi,
1118 tree main_iv)
1119 {
1120 affine_iv iv;
1121 gimple stmt, phi = gsi_stmt (*psi);
1122 tree atype, mtype, val, res = PHI_RESULT (phi);
1123
1124 if (virtual_operand_p (res) || res == main_iv)
1125 {
1126 gsi_next (psi);
1127 return;
1128 }
1129
1130 if (!simple_iv (loop, loop, res, &iv, true))
1131 {
1132 gsi_next (psi);
1133 return;
1134 }
1135
1136 remove_phi_node (psi, false);
1137
1138 atype = TREE_TYPE (res);
1139 mtype = POINTER_TYPE_P (atype) ? sizetype : atype;
1140 val = fold_build2 (MULT_EXPR, mtype, unshare_expr (iv.step),
1141 fold_convert (mtype, main_iv));
1142 val = fold_build2 (POINTER_TYPE_P (atype)
1143 ? POINTER_PLUS_EXPR : PLUS_EXPR,
1144 atype, unshare_expr (iv.base), val);
1145 val = force_gimple_operand_gsi (gsi, val, false, NULL_TREE, true,
1146 GSI_SAME_STMT);
1147 stmt = gimple_build_assign (res, val);
1148 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1149 SSA_NAME_DEF_STMT (res) = stmt;
1150 }
1151
1152 /* Rewrite all the phi nodes of LOOP in function of the main induction
1153 variable MAIN_IV. */
1154
1155 static void
1156 rewrite_all_phi_nodes_with_iv (loop_p loop, tree main_iv)
1157 {
1158 unsigned i;
1159 basic_block *bbs = get_loop_body_in_dom_order (loop);
1160 gimple_stmt_iterator psi;
1161
1162 for (i = 0; i < loop->num_nodes; i++)
1163 {
1164 basic_block bb = bbs[i];
1165 gimple_stmt_iterator gsi = gsi_after_labels (bb);
1166
1167 if (bb->loop_father != loop)
1168 continue;
1169
1170 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); )
1171 rewrite_phi_with_iv (loop, &psi, &gsi, main_iv);
1172 }
1173
1174 free (bbs);
1175 }
1176
1177 /* Bases all the induction variables in LOOP on a single induction
1178 variable (unsigned with base 0 and step 1), whose final value is
1179 compared with *NIT. When the IV type precision has to be larger
1180 than *NIT type precision, *NIT is converted to the larger type, the
1181 conversion code is inserted before the loop, and *NIT is updated to
1182 the new definition. When BUMP_IN_LATCH is true, the induction
1183 variable is incremented in the loop latch, otherwise it is
1184 incremented in the loop header. Return the induction variable that
1185 was created. */
1186
1187 tree
1188 canonicalize_loop_ivs (struct loop *loop, tree *nit, bool bump_in_latch)
1189 {
1190 unsigned precision = TYPE_PRECISION (TREE_TYPE (*nit));
1191 unsigned original_precision = precision;
1192 tree type, var_before;
1193 gimple_stmt_iterator gsi, psi;
1194 gimple stmt;
1195 edge exit = single_dom_exit (loop);
1196 gimple_seq stmts;
1197 enum machine_mode mode;
1198 bool unsigned_p = false;
1199
1200 for (psi = gsi_start_phis (loop->header);
1201 !gsi_end_p (psi); gsi_next (&psi))
1202 {
1203 gimple phi = gsi_stmt (psi);
1204 tree res = PHI_RESULT (phi);
1205 bool uns;
1206
1207 type = TREE_TYPE (res);
1208 if (virtual_operand_p (res)
1209 || (!INTEGRAL_TYPE_P (type)
1210 && !POINTER_TYPE_P (type))
1211 || TYPE_PRECISION (type) < precision)
1212 continue;
1213
1214 uns = POINTER_TYPE_P (type) | TYPE_UNSIGNED (type);
1215
1216 if (TYPE_PRECISION (type) > precision)
1217 unsigned_p = uns;
1218 else
1219 unsigned_p |= uns;
1220
1221 precision = TYPE_PRECISION (type);
1222 }
1223
1224 mode = smallest_mode_for_size (precision, MODE_INT);
1225 precision = GET_MODE_PRECISION (mode);
1226 type = build_nonstandard_integer_type (precision, unsigned_p);
1227
1228 if (original_precision != precision)
1229 {
1230 *nit = fold_convert (type, *nit);
1231 *nit = force_gimple_operand (*nit, &stmts, true, NULL_TREE);
1232 if (stmts)
1233 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1234 }
1235
1236 if (bump_in_latch)
1237 gsi = gsi_last_bb (loop->latch);
1238 else
1239 gsi = gsi_last_nondebug_bb (loop->header);
1240 create_iv (build_int_cst_type (type, 0), build_int_cst (type, 1), NULL_TREE,
1241 loop, &gsi, bump_in_latch, &var_before, NULL);
1242
1243 rewrite_all_phi_nodes_with_iv (loop, var_before);
1244
1245 stmt = last_stmt (exit->src);
1246 /* Make the loop exit if the control condition is not satisfied. */
1247 if (exit->flags & EDGE_TRUE_VALUE)
1248 {
1249 edge te, fe;
1250
1251 extract_true_false_edges_from_block (exit->src, &te, &fe);
1252 te->flags = EDGE_FALSE_VALUE;
1253 fe->flags = EDGE_TRUE_VALUE;
1254 }
1255 gimple_cond_set_code (stmt, LT_EXPR);
1256 gimple_cond_set_lhs (stmt, var_before);
1257 gimple_cond_set_rhs (stmt, *nit);
1258 update_stmt (stmt);
1259
1260 return var_before;
1261 }