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