2006-02-09 Kaz Kojima <kkojima@gcc.gnu.org>
[official-gcc.git] / gcc / tree-ssa-loop-niter.c
blob7566e7cad49b5be9379951bcc49adcf34c5c7a93
1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004, 2005 Free Software Foundation, Inc.
4 This file is part of GCC.
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 2, or (at your option) any
9 later version.
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.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING. If not, write to the Free
18 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301, USA. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "hard-reg-set.h"
29 #include "basic-block.h"
30 #include "output.h"
31 #include "diagnostic.h"
32 #include "intl.h"
33 #include "tree-flow.h"
34 #include "tree-dump.h"
35 #include "cfgloop.h"
36 #include "tree-pass.h"
37 #include "ggc.h"
38 #include "tree-chrec.h"
39 #include "tree-scalar-evolution.h"
40 #include "tree-data-ref.h"
41 #include "params.h"
42 #include "flags.h"
43 #include "toplev.h"
44 #include "tree-inline.h"
46 #define SWAP(X, Y) do { void *tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
51 Analysis of number of iterations of an affine exit test.
55 /* Returns true if ARG is either NULL_TREE or constant zero. Unlike
56 integer_zerop, it does not care about overflow flags. */
58 bool
59 zero_p (tree arg)
61 if (!arg)
62 return true;
64 if (TREE_CODE (arg) != INTEGER_CST)
65 return false;
67 return (TREE_INT_CST_LOW (arg) == 0 && TREE_INT_CST_HIGH (arg) == 0);
70 /* Returns true if ARG a nonzero constant. Unlike integer_nonzerop, it does
71 not care about overflow flags. */
73 static bool
74 nonzero_p (tree arg)
76 if (!arg)
77 return false;
79 if (TREE_CODE (arg) != INTEGER_CST)
80 return false;
82 return (TREE_INT_CST_LOW (arg) != 0 || TREE_INT_CST_HIGH (arg) != 0);
85 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
87 static tree
88 inverse (tree x, tree mask)
90 tree type = TREE_TYPE (x);
91 tree rslt;
92 unsigned ctr = tree_floor_log2 (mask);
94 if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
96 unsigned HOST_WIDE_INT ix;
97 unsigned HOST_WIDE_INT imask;
98 unsigned HOST_WIDE_INT irslt = 1;
100 gcc_assert (cst_and_fits_in_hwi (x));
101 gcc_assert (cst_and_fits_in_hwi (mask));
103 ix = int_cst_value (x);
104 imask = int_cst_value (mask);
106 for (; ctr; ctr--)
108 irslt *= ix;
109 ix *= ix;
111 irslt &= imask;
113 rslt = build_int_cst_type (type, irslt);
115 else
117 rslt = build_int_cst_type (type, 1);
118 for (; ctr; ctr--)
120 rslt = int_const_binop (MULT_EXPR, rslt, x, 0);
121 x = int_const_binop (MULT_EXPR, x, x, 0);
123 rslt = int_const_binop (BIT_AND_EXPR, rslt, mask, 0);
126 return rslt;
129 /* Determines number of iterations of loop whose ending condition
130 is IV <> FINAL. TYPE is the type of the iv. The number of
131 iterations is stored to NITER. NEVER_INFINITE is true if
132 we know that the loop cannot be infinite (we derived this
133 earlier, and possibly set NITER->assumptions to make sure this
134 is the case. */
136 static bool
137 number_of_iterations_ne (tree type, affine_iv *iv, tree final,
138 struct tree_niter_desc *niter, bool never_infinite)
140 tree niter_type = unsigned_type_for (type);
141 tree s, c, d, bits, assumption, tmp, bound;
143 /* Rearrange the terms so that we get inequality s * i <> c, with s
144 positive. Also cast everything to the unsigned type. */
145 if (tree_int_cst_sign_bit (iv->step))
147 s = fold_convert (niter_type,
148 fold_build1 (NEGATE_EXPR, type, iv->step));
149 c = fold_build2 (MINUS_EXPR, niter_type,
150 fold_convert (niter_type, iv->base),
151 fold_convert (niter_type, final));
153 else
155 s = fold_convert (niter_type, iv->step);
156 c = fold_build2 (MINUS_EXPR, niter_type,
157 fold_convert (niter_type, final),
158 fold_convert (niter_type, iv->base));
161 /* First the trivial cases -- when the step is 1. */
162 if (integer_onep (s))
164 niter->niter = c;
165 return true;
168 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
169 is infinite. Otherwise, the number of iterations is
170 (inverse(s/d) * (c/d)) mod (size of mode/d). */
171 bits = num_ending_zeros (s);
172 bound = build_low_bits_mask (niter_type,
173 (TYPE_PRECISION (niter_type)
174 - tree_low_cst (bits, 1)));
176 d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
177 build_int_cst_type (niter_type, 1), bits);
178 s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
180 if (!never_infinite)
182 /* If we cannot assume that the loop is not infinite, record the
183 assumptions for divisibility of c. */
184 assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
185 assumption = fold_build2 (EQ_EXPR, boolean_type_node,
186 assumption, build_int_cst (niter_type, 0));
187 if (!nonzero_p (assumption))
188 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
189 niter->assumptions, assumption);
192 c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
193 tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
194 niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
195 return true;
198 /* Checks whether we can determine the final value of the control variable
199 of the loop with ending condition IV0 < IV1 (computed in TYPE).
200 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
201 of the step. The assumptions necessary to ensure that the computation
202 of the final value does not overflow are recorded in NITER. If we
203 find the final value, we adjust DELTA and return TRUE. Otherwise
204 we return false. */
206 static bool
207 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
208 struct tree_niter_desc *niter,
209 tree *delta, tree step)
211 tree niter_type = TREE_TYPE (step);
212 tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
213 tree tmod;
214 tree assumption = boolean_true_node, bound, noloop;
216 if (TREE_CODE (mod) != INTEGER_CST)
217 return false;
218 if (nonzero_p (mod))
219 mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
220 tmod = fold_convert (type, mod);
222 if (nonzero_p (iv0->step))
224 /* The final value of the iv is iv1->base + MOD, assuming that this
225 computation does not overflow, and that
226 iv0->base <= iv1->base + MOD. */
227 if (!iv1->no_overflow && !zero_p (mod))
229 bound = fold_build2 (MINUS_EXPR, type,
230 TYPE_MAX_VALUE (type), tmod);
231 assumption = fold_build2 (LE_EXPR, boolean_type_node,
232 iv1->base, bound);
233 if (zero_p (assumption))
234 return false;
236 noloop = fold_build2 (GT_EXPR, boolean_type_node,
237 iv0->base,
238 fold_build2 (PLUS_EXPR, type,
239 iv1->base, tmod));
241 else
243 /* The final value of the iv is iv0->base - MOD, assuming that this
244 computation does not overflow, and that
245 iv0->base - MOD <= iv1->base. */
246 if (!iv0->no_overflow && !zero_p (mod))
248 bound = fold_build2 (PLUS_EXPR, type,
249 TYPE_MIN_VALUE (type), tmod);
250 assumption = fold_build2 (GE_EXPR, boolean_type_node,
251 iv0->base, bound);
252 if (zero_p (assumption))
253 return false;
255 noloop = fold_build2 (GT_EXPR, boolean_type_node,
256 fold_build2 (MINUS_EXPR, type,
257 iv0->base, tmod),
258 iv1->base);
261 if (!nonzero_p (assumption))
262 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
263 niter->assumptions,
264 assumption);
265 if (!zero_p (noloop))
266 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
267 niter->may_be_zero,
268 noloop);
269 *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
270 return true;
273 /* Add assertions to NITER that ensure that the control variable of the loop
274 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
275 are TYPE. Returns false if we can prove that there is an overflow, true
276 otherwise. STEP is the absolute value of the step. */
278 static bool
279 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
280 struct tree_niter_desc *niter, tree step)
282 tree bound, d, assumption, diff;
283 tree niter_type = TREE_TYPE (step);
285 if (nonzero_p (iv0->step))
287 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
288 if (iv0->no_overflow)
289 return true;
291 /* If iv0->base is a constant, we can determine the last value before
292 overflow precisely; otherwise we conservatively assume
293 MAX - STEP + 1. */
295 if (TREE_CODE (iv0->base) == INTEGER_CST)
297 d = fold_build2 (MINUS_EXPR, niter_type,
298 fold_convert (niter_type, TYPE_MAX_VALUE (type)),
299 fold_convert (niter_type, iv0->base));
300 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
302 else
303 diff = fold_build2 (MINUS_EXPR, niter_type, step,
304 build_int_cst_type (niter_type, 1));
305 bound = fold_build2 (MINUS_EXPR, type,
306 TYPE_MAX_VALUE (type), fold_convert (type, diff));
307 assumption = fold_build2 (LE_EXPR, boolean_type_node,
308 iv1->base, bound);
310 else
312 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
313 if (iv1->no_overflow)
314 return true;
316 if (TREE_CODE (iv1->base) == INTEGER_CST)
318 d = fold_build2 (MINUS_EXPR, niter_type,
319 fold_convert (niter_type, iv1->base),
320 fold_convert (niter_type, TYPE_MIN_VALUE (type)));
321 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
323 else
324 diff = fold_build2 (MINUS_EXPR, niter_type, step,
325 build_int_cst_type (niter_type, 1));
326 bound = fold_build2 (PLUS_EXPR, type,
327 TYPE_MIN_VALUE (type), fold_convert (type, diff));
328 assumption = fold_build2 (GE_EXPR, boolean_type_node,
329 iv0->base, bound);
332 if (zero_p (assumption))
333 return false;
334 if (!nonzero_p (assumption))
335 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
336 niter->assumptions, assumption);
338 iv0->no_overflow = true;
339 iv1->no_overflow = true;
340 return true;
343 /* Add an assumption to NITER that a loop whose ending condition
344 is IV0 < IV1 rolls. TYPE is the type of the control iv. */
346 static void
347 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
348 struct tree_niter_desc *niter)
350 tree assumption = boolean_true_node, bound, diff;
351 tree mbz, mbzl, mbzr;
353 if (nonzero_p (iv0->step))
355 diff = fold_build2 (MINUS_EXPR, type,
356 iv0->step, build_int_cst_type (type, 1));
358 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
359 0 address never belongs to any object, we can assume this for
360 pointers. */
361 if (!POINTER_TYPE_P (type))
363 bound = fold_build2 (PLUS_EXPR, type,
364 TYPE_MIN_VALUE (type), diff);
365 assumption = fold_build2 (GE_EXPR, boolean_type_node,
366 iv0->base, bound);
369 /* And then we can compute iv0->base - diff, and compare it with
370 iv1->base. */
371 mbzl = fold_build2 (MINUS_EXPR, type, iv0->base, diff);
372 mbzr = iv1->base;
374 else
376 diff = fold_build2 (PLUS_EXPR, type,
377 iv1->step, build_int_cst_type (type, 1));
379 if (!POINTER_TYPE_P (type))
381 bound = fold_build2 (PLUS_EXPR, type,
382 TYPE_MAX_VALUE (type), diff);
383 assumption = fold_build2 (LE_EXPR, boolean_type_node,
384 iv1->base, bound);
387 mbzl = iv0->base;
388 mbzr = fold_build2 (MINUS_EXPR, type, iv1->base, diff);
391 mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
393 if (!nonzero_p (assumption))
394 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
395 niter->assumptions, assumption);
396 if (!zero_p (mbz))
397 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
398 niter->may_be_zero, mbz);
401 /* Determines number of iterations of loop whose ending condition
402 is IV0 < IV1. TYPE is the type of the iv. The number of
403 iterations is stored to NITER. */
405 static bool
406 number_of_iterations_lt (tree type, affine_iv *iv0, affine_iv *iv1,
407 struct tree_niter_desc *niter,
408 bool never_infinite ATTRIBUTE_UNUSED)
410 tree niter_type = unsigned_type_for (type);
411 tree delta, step, s;
413 delta = fold_build2 (MINUS_EXPR, niter_type,
414 fold_convert (niter_type, iv1->base),
415 fold_convert (niter_type, iv0->base));
417 /* First handle the special case that the step is +-1. */
418 if ((iv0->step && integer_onep (iv0->step)
419 && zero_p (iv1->step))
420 || (iv1->step && integer_all_onesp (iv1->step)
421 && zero_p (iv0->step)))
423 /* for (i = iv0->base; i < iv1->base; i++)
427 for (i = iv1->base; i > iv0->base; i--).
429 In both cases # of iterations is iv1->base - iv0->base, assuming that
430 iv1->base >= iv0->base. */
431 niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
432 iv1->base, iv0->base);
433 niter->niter = delta;
434 return true;
437 if (nonzero_p (iv0->step))
438 step = fold_convert (niter_type, iv0->step);
439 else
440 step = fold_convert (niter_type,
441 fold_build1 (NEGATE_EXPR, type, iv1->step));
443 /* If we can determine the final value of the control iv exactly, we can
444 transform the condition to != comparison. In particular, this will be
445 the case if DELTA is constant. */
446 if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step))
448 affine_iv zps;
450 zps.base = build_int_cst_type (niter_type, 0);
451 zps.step = step;
452 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
453 zps does not overflow. */
454 zps.no_overflow = true;
456 return number_of_iterations_ne (type, &zps, delta, niter, true);
459 /* Make sure that the control iv does not overflow. */
460 if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
461 return false;
463 /* We determine the number of iterations as (delta + step - 1) / step. For
464 this to work, we must know that iv1->base >= iv0->base - step + 1,
465 otherwise the loop does not roll. */
466 assert_loop_rolls_lt (type, iv0, iv1, niter);
468 s = fold_build2 (MINUS_EXPR, niter_type,
469 step, build_int_cst_type (niter_type, 1));
470 delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
471 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
472 return true;
475 /* Determines number of iterations of loop whose ending condition
476 is IV0 <= IV1. TYPE is the type of the iv. The number of
477 iterations is stored to NITER. NEVER_INFINITE is true if
478 we know that the loop cannot be infinite (we derived this
479 earlier, and possibly set NITER->assumptions to make sure this
480 is the case. */
482 static bool
483 number_of_iterations_le (tree type, affine_iv *iv0, affine_iv *iv1,
484 struct tree_niter_desc *niter, bool never_infinite)
486 tree assumption;
488 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
489 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
490 value of the type. This we must know anyway, since if it is
491 equal to this value, the loop rolls forever. */
493 if (!never_infinite)
495 if (nonzero_p (iv0->step))
496 assumption = fold_build2 (NE_EXPR, boolean_type_node,
497 iv1->base, TYPE_MAX_VALUE (type));
498 else
499 assumption = fold_build2 (NE_EXPR, boolean_type_node,
500 iv0->base, TYPE_MIN_VALUE (type));
502 if (zero_p (assumption))
503 return false;
504 if (!nonzero_p (assumption))
505 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
506 niter->assumptions, assumption);
509 if (nonzero_p (iv0->step))
510 iv1->base = fold_build2 (PLUS_EXPR, type,
511 iv1->base, build_int_cst_type (type, 1));
512 else
513 iv0->base = fold_build2 (MINUS_EXPR, type,
514 iv0->base, build_int_cst_type (type, 1));
515 return number_of_iterations_lt (type, iv0, iv1, niter, never_infinite);
518 /* Determine the number of iterations according to condition (for staying
519 inside loop) which compares two induction variables using comparison
520 operator CODE. The induction variable on left side of the comparison
521 is IV0, the right-hand side is IV1. Both induction variables must have
522 type TYPE, which must be an integer or pointer type. The steps of the
523 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
525 The results (number of iterations and assumptions as described in
526 comments at struct tree_niter_desc in tree-flow.h) are stored to NITER.
527 Returns false if it fails to determine number of iterations, true if it
528 was determined (possibly with some assumptions). */
530 static bool
531 number_of_iterations_cond (tree type, affine_iv *iv0, enum tree_code code,
532 affine_iv *iv1, struct tree_niter_desc *niter)
534 bool never_infinite;
536 /* The meaning of these assumptions is this:
537 if !assumptions
538 then the rest of information does not have to be valid
539 if may_be_zero then the loop does not roll, even if
540 niter != 0. */
541 niter->assumptions = boolean_true_node;
542 niter->may_be_zero = boolean_false_node;
543 niter->niter = NULL_TREE;
544 niter->additional_info = boolean_true_node;
546 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
547 the control variable is on lhs. */
548 if (code == GE_EXPR || code == GT_EXPR
549 || (code == NE_EXPR && zero_p (iv0->step)))
551 SWAP (iv0, iv1);
552 code = swap_tree_comparison (code);
555 if (POINTER_TYPE_P (type))
557 /* Comparison of pointers is undefined unless both iv0 and iv1 point
558 to the same object. If they do, the control variable cannot wrap
559 (as wrap around the bounds of memory will never return a pointer
560 that would be guaranteed to point to the same object, even if we
561 avoid undefined behavior by casting to size_t and back). */
562 iv0->no_overflow = true;
563 iv1->no_overflow = true;
566 /* If the control induction variable does not overflow, the loop obviously
567 cannot be infinite. */
568 if (!zero_p (iv0->step) && iv0->no_overflow)
569 never_infinite = true;
570 else if (!zero_p (iv1->step) && iv1->no_overflow)
571 never_infinite = true;
572 else
573 never_infinite = false;
575 /* We can handle the case when neither of the sides of the comparison is
576 invariant, provided that the test is NE_EXPR. This rarely occurs in
577 practice, but it is simple enough to manage. */
578 if (!zero_p (iv0->step) && !zero_p (iv1->step))
580 if (code != NE_EXPR)
581 return false;
583 iv0->step = fold_binary_to_constant (MINUS_EXPR, type,
584 iv0->step, iv1->step);
585 iv0->no_overflow = false;
586 iv1->step = NULL_TREE;
587 iv1->no_overflow = true;
590 /* If the result of the comparison is a constant, the loop is weird. More
591 precise handling would be possible, but the situation is not common enough
592 to waste time on it. */
593 if (zero_p (iv0->step) && zero_p (iv1->step))
594 return false;
596 /* Ignore loops of while (i-- < 10) type. */
597 if (code != NE_EXPR)
599 if (iv0->step && tree_int_cst_sign_bit (iv0->step))
600 return false;
602 if (!zero_p (iv1->step) && !tree_int_cst_sign_bit (iv1->step))
603 return false;
606 /* If the loop exits immediatelly, there is nothing to do. */
607 if (zero_p (fold_build2 (code, boolean_type_node, iv0->base, iv1->base)))
609 niter->niter = build_int_cst_type (unsigned_type_for (type), 0);
610 return true;
613 /* OK, now we know we have a senseful loop. Handle several cases, depending
614 on what comparison operator is used. */
615 switch (code)
617 case NE_EXPR:
618 gcc_assert (zero_p (iv1->step));
619 return number_of_iterations_ne (type, iv0, iv1->base, niter, never_infinite);
620 case LT_EXPR:
621 return number_of_iterations_lt (type, iv0, iv1, niter, never_infinite);
622 case LE_EXPR:
623 return number_of_iterations_le (type, iv0, iv1, niter, never_infinite);
624 default:
625 gcc_unreachable ();
629 /* Substitute NEW for OLD in EXPR and fold the result. */
631 static tree
632 simplify_replace_tree (tree expr, tree old, tree new)
634 unsigned i, n;
635 tree ret = NULL_TREE, e, se;
637 if (!expr)
638 return NULL_TREE;
640 if (expr == old
641 || operand_equal_p (expr, old, 0))
642 return unshare_expr (new);
644 if (!EXPR_P (expr))
645 return expr;
647 n = TREE_CODE_LENGTH (TREE_CODE (expr));
648 for (i = 0; i < n; i++)
650 e = TREE_OPERAND (expr, i);
651 se = simplify_replace_tree (e, old, new);
652 if (e == se)
653 continue;
655 if (!ret)
656 ret = copy_node (expr);
658 TREE_OPERAND (ret, i) = se;
661 return (ret ? fold (ret) : expr);
664 /* Expand definitions of ssa names in EXPR as long as they are simple
665 enough, and return the new expression. */
667 tree
668 expand_simple_operations (tree expr)
670 unsigned i, n;
671 tree ret = NULL_TREE, e, ee, stmt;
672 enum tree_code code;
674 if (expr == NULL_TREE)
675 return expr;
677 if (is_gimple_min_invariant (expr))
678 return expr;
680 code = TREE_CODE (expr);
681 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
683 n = TREE_CODE_LENGTH (code);
684 for (i = 0; i < n; i++)
686 e = TREE_OPERAND (expr, i);
687 ee = expand_simple_operations (e);
688 if (e == ee)
689 continue;
691 if (!ret)
692 ret = copy_node (expr);
694 TREE_OPERAND (ret, i) = ee;
697 return (ret ? fold (ret) : expr);
700 if (TREE_CODE (expr) != SSA_NAME)
701 return expr;
703 stmt = SSA_NAME_DEF_STMT (expr);
704 if (TREE_CODE (stmt) != MODIFY_EXPR)
705 return expr;
707 e = TREE_OPERAND (stmt, 1);
708 if (/* Casts are simple. */
709 TREE_CODE (e) != NOP_EXPR
710 && TREE_CODE (e) != CONVERT_EXPR
711 /* Copies are simple. */
712 && TREE_CODE (e) != SSA_NAME
713 /* Assignments of invariants are simple. */
714 && !is_gimple_min_invariant (e)
715 /* And increments and decrements by a constant are simple. */
716 && !((TREE_CODE (e) == PLUS_EXPR
717 || TREE_CODE (e) == MINUS_EXPR)
718 && is_gimple_min_invariant (TREE_OPERAND (e, 1))))
719 return expr;
721 return expand_simple_operations (e);
724 /* Tries to simplify EXPR using the condition COND. Returns the simplified
725 expression (or EXPR unchanged, if no simplification was possible). */
727 static tree
728 tree_simplify_using_condition_1 (tree cond, tree expr)
730 bool changed;
731 tree e, te, e0, e1, e2, notcond;
732 enum tree_code code = TREE_CODE (expr);
734 if (code == INTEGER_CST)
735 return expr;
737 if (code == TRUTH_OR_EXPR
738 || code == TRUTH_AND_EXPR
739 || code == COND_EXPR)
741 changed = false;
743 e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
744 if (TREE_OPERAND (expr, 0) != e0)
745 changed = true;
747 e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
748 if (TREE_OPERAND (expr, 1) != e1)
749 changed = true;
751 if (code == COND_EXPR)
753 e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
754 if (TREE_OPERAND (expr, 2) != e2)
755 changed = true;
757 else
758 e2 = NULL_TREE;
760 if (changed)
762 if (code == COND_EXPR)
763 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
764 else
765 expr = fold_build2 (code, boolean_type_node, e0, e1);
768 return expr;
771 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
772 propagation, and vice versa. Fold does not handle this, since it is
773 considered too expensive. */
774 if (TREE_CODE (cond) == EQ_EXPR)
776 e0 = TREE_OPERAND (cond, 0);
777 e1 = TREE_OPERAND (cond, 1);
779 /* We know that e0 == e1. Check whether we cannot simplify expr
780 using this fact. */
781 e = simplify_replace_tree (expr, e0, e1);
782 if (zero_p (e) || nonzero_p (e))
783 return e;
785 e = simplify_replace_tree (expr, e1, e0);
786 if (zero_p (e) || nonzero_p (e))
787 return e;
789 if (TREE_CODE (expr) == EQ_EXPR)
791 e0 = TREE_OPERAND (expr, 0);
792 e1 = TREE_OPERAND (expr, 1);
794 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
795 e = simplify_replace_tree (cond, e0, e1);
796 if (zero_p (e))
797 return e;
798 e = simplify_replace_tree (cond, e1, e0);
799 if (zero_p (e))
800 return e;
802 if (TREE_CODE (expr) == NE_EXPR)
804 e0 = TREE_OPERAND (expr, 0);
805 e1 = TREE_OPERAND (expr, 1);
807 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
808 e = simplify_replace_tree (cond, e0, e1);
809 if (zero_p (e))
810 return boolean_true_node;
811 e = simplify_replace_tree (cond, e1, e0);
812 if (zero_p (e))
813 return boolean_true_node;
816 te = expand_simple_operations (expr);
818 /* Check whether COND ==> EXPR. */
819 notcond = invert_truthvalue (cond);
820 e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, te);
821 if (nonzero_p (e))
822 return e;
824 /* Check whether COND ==> not EXPR. */
825 e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, te);
826 if (e && zero_p (e))
827 return e;
829 return expr;
832 /* Tries to simplify EXPR using the condition COND. Returns the simplified
833 expression (or EXPR unchanged, if no simplification was possible).
834 Wrapper around tree_simplify_using_condition_1 that ensures that chains
835 of simple operations in definitions of ssa names in COND are expanded,
836 so that things like casts or incrementing the value of the bound before
837 the loop do not cause us to fail. */
839 static tree
840 tree_simplify_using_condition (tree cond, tree expr)
842 cond = expand_simple_operations (cond);
844 return tree_simplify_using_condition_1 (cond, expr);
847 /* Tries to simplify EXPR using the conditions on entry to LOOP.
848 Record the conditions used for simplification to CONDS_USED.
849 Returns the simplified expression (or EXPR unchanged, if no
850 simplification was possible).*/
852 static tree
853 simplify_using_initial_conditions (struct loop *loop, tree expr,
854 tree *conds_used)
856 edge e;
857 basic_block bb;
858 tree exp, cond;
860 if (TREE_CODE (expr) == INTEGER_CST)
861 return expr;
863 for (bb = loop->header;
864 bb != ENTRY_BLOCK_PTR;
865 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
867 if (!single_pred_p (bb))
868 continue;
869 e = single_pred_edge (bb);
871 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
872 continue;
874 cond = COND_EXPR_COND (last_stmt (e->src));
875 if (e->flags & EDGE_FALSE_VALUE)
876 cond = invert_truthvalue (cond);
877 exp = tree_simplify_using_condition (cond, expr);
879 if (exp != expr)
880 *conds_used = fold_build2 (TRUTH_AND_EXPR,
881 boolean_type_node,
882 *conds_used,
883 cond);
885 expr = exp;
888 return expr;
891 /* Tries to simplify EXPR using the evolutions of the loop invariants
892 in the superloops of LOOP. Returns the simplified expression
893 (or EXPR unchanged, if no simplification was possible). */
895 static tree
896 simplify_using_outer_evolutions (struct loop *loop, tree expr)
898 enum tree_code code = TREE_CODE (expr);
899 bool changed;
900 tree e, e0, e1, e2;
902 if (is_gimple_min_invariant (expr))
903 return expr;
905 if (code == TRUTH_OR_EXPR
906 || code == TRUTH_AND_EXPR
907 || code == COND_EXPR)
909 changed = false;
911 e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
912 if (TREE_OPERAND (expr, 0) != e0)
913 changed = true;
915 e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
916 if (TREE_OPERAND (expr, 1) != e1)
917 changed = true;
919 if (code == COND_EXPR)
921 e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
922 if (TREE_OPERAND (expr, 2) != e2)
923 changed = true;
925 else
926 e2 = NULL_TREE;
928 if (changed)
930 if (code == COND_EXPR)
931 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
932 else
933 expr = fold_build2 (code, boolean_type_node, e0, e1);
936 return expr;
939 e = instantiate_parameters (loop, expr);
940 if (is_gimple_min_invariant (e))
941 return e;
943 return expr;
946 /* Stores description of number of iterations of LOOP derived from
947 EXIT (an exit edge of the LOOP) in NITER. Returns true if some
948 useful information could be derived (and fields of NITER has
949 meaning described in comments at struct tree_niter_desc
950 declaration), false otherwise. If WARN is true and
951 -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
952 potentially unsafe assumptions. */
954 bool
955 number_of_iterations_exit (struct loop *loop, edge exit,
956 struct tree_niter_desc *niter,
957 bool warn)
959 tree stmt, cond, type;
960 tree op0, op1;
961 enum tree_code code;
962 affine_iv iv0, iv1;
964 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src))
965 return false;
967 niter->assumptions = boolean_false_node;
968 stmt = last_stmt (exit->src);
969 if (!stmt || TREE_CODE (stmt) != COND_EXPR)
970 return false;
972 /* We want the condition for staying inside loop. */
973 cond = COND_EXPR_COND (stmt);
974 if (exit->flags & EDGE_TRUE_VALUE)
975 cond = invert_truthvalue (cond);
977 code = TREE_CODE (cond);
978 switch (code)
980 case GT_EXPR:
981 case GE_EXPR:
982 case NE_EXPR:
983 case LT_EXPR:
984 case LE_EXPR:
985 break;
987 default:
988 return false;
991 op0 = TREE_OPERAND (cond, 0);
992 op1 = TREE_OPERAND (cond, 1);
993 type = TREE_TYPE (op0);
995 if (TREE_CODE (type) != INTEGER_TYPE
996 && !POINTER_TYPE_P (type))
997 return false;
999 if (!simple_iv (loop, stmt, op0, &iv0, false))
1000 return false;
1001 if (!simple_iv (loop, stmt, op1, &iv1, false))
1002 return false;
1004 iv0.base = expand_simple_operations (iv0.base);
1005 iv1.base = expand_simple_operations (iv1.base);
1006 if (!number_of_iterations_cond (type, &iv0, code, &iv1, niter))
1007 return false;
1009 if (optimize >= 3)
1011 niter->assumptions = simplify_using_outer_evolutions (loop,
1012 niter->assumptions);
1013 niter->may_be_zero = simplify_using_outer_evolutions (loop,
1014 niter->may_be_zero);
1015 niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
1018 niter->additional_info = boolean_true_node;
1019 niter->assumptions
1020 = simplify_using_initial_conditions (loop,
1021 niter->assumptions,
1022 &niter->additional_info);
1023 niter->may_be_zero
1024 = simplify_using_initial_conditions (loop,
1025 niter->may_be_zero,
1026 &niter->additional_info);
1028 if (integer_onep (niter->assumptions))
1029 return true;
1031 /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
1032 But if we can prove that there is overflow or some other source of weird
1033 behavior, ignore the loop even with -funsafe-loop-optimizations. */
1034 if (integer_zerop (niter->assumptions))
1035 return false;
1037 if (flag_unsafe_loop_optimizations)
1038 niter->assumptions = boolean_true_node;
1040 if (warn)
1042 const char *wording;
1043 location_t loc = EXPR_LOCATION (stmt);
1045 /* We can provide a more specific warning if one of the operator is
1046 constant and the other advances by +1 or -1. */
1047 if (!zero_p (iv1.step)
1048 ? (zero_p (iv0.step)
1049 && (integer_onep (iv1.step) || integer_all_onesp (iv1.step)))
1050 : (iv0.step
1051 && (integer_onep (iv0.step) || integer_all_onesp (iv0.step))))
1052 wording =
1053 flag_unsafe_loop_optimizations
1054 ? N_("assuming that the loop is not infinite")
1055 : N_("cannot optimize possibly infinite loops");
1056 else
1057 wording =
1058 flag_unsafe_loop_optimizations
1059 ? N_("assuming that the loop counter does not overflow")
1060 : N_("cannot optimize loop, the loop counter may overflow");
1062 if (LOCATION_LINE (loc) > 0)
1063 warning (OPT_Wunsafe_loop_optimizations, "%H%s", &loc, gettext (wording));
1064 else
1065 warning (OPT_Wunsafe_loop_optimizations, "%s", gettext (wording));
1068 return flag_unsafe_loop_optimizations;
1071 /* Try to determine the number of iterations of LOOP. If we succeed,
1072 expression giving number of iterations is returned and *EXIT is
1073 set to the edge from that the information is obtained. Otherwise
1074 chrec_dont_know is returned. */
1076 tree
1077 find_loop_niter (struct loop *loop, edge *exit)
1079 unsigned n_exits, i;
1080 edge *exits = get_loop_exit_edges (loop, &n_exits);
1081 edge ex;
1082 tree niter = NULL_TREE, aniter;
1083 struct tree_niter_desc desc;
1085 *exit = NULL;
1086 for (i = 0; i < n_exits; i++)
1088 ex = exits[i];
1089 if (!just_once_each_iteration_p (loop, ex->src))
1090 continue;
1092 if (!number_of_iterations_exit (loop, ex, &desc, false))
1093 continue;
1095 if (nonzero_p (desc.may_be_zero))
1097 /* We exit in the first iteration through this exit.
1098 We won't find anything better. */
1099 niter = build_int_cst_type (unsigned_type_node, 0);
1100 *exit = ex;
1101 break;
1104 if (!zero_p (desc.may_be_zero))
1105 continue;
1107 aniter = desc.niter;
1109 if (!niter)
1111 /* Nothing recorded yet. */
1112 niter = aniter;
1113 *exit = ex;
1114 continue;
1117 /* Prefer constants, the lower the better. */
1118 if (TREE_CODE (aniter) != INTEGER_CST)
1119 continue;
1121 if (TREE_CODE (niter) != INTEGER_CST)
1123 niter = aniter;
1124 *exit = ex;
1125 continue;
1128 if (tree_int_cst_lt (aniter, niter))
1130 niter = aniter;
1131 *exit = ex;
1132 continue;
1135 free (exits);
1137 return niter ? niter : chrec_dont_know;
1142 Analysis of a number of iterations of a loop by a brute-force evaluation.
1146 /* Bound on the number of iterations we try to evaluate. */
1148 #define MAX_ITERATIONS_TO_TRACK \
1149 ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
1151 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
1152 result by a chain of operations such that all but exactly one of their
1153 operands are constants. */
1155 static tree
1156 chain_of_csts_start (struct loop *loop, tree x)
1158 tree stmt = SSA_NAME_DEF_STMT (x);
1159 tree use;
1160 basic_block bb = bb_for_stmt (stmt);
1162 if (!bb
1163 || !flow_bb_inside_loop_p (loop, bb))
1164 return NULL_TREE;
1166 if (TREE_CODE (stmt) == PHI_NODE)
1168 if (bb == loop->header)
1169 return stmt;
1171 return NULL_TREE;
1174 if (TREE_CODE (stmt) != MODIFY_EXPR)
1175 return NULL_TREE;
1177 if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
1178 return NULL_TREE;
1179 if (SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF) == NULL_DEF_OPERAND_P)
1180 return NULL_TREE;
1182 use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1183 if (use == NULL_USE_OPERAND_P)
1184 return NULL_TREE;
1186 return chain_of_csts_start (loop, use);
1189 /* Determines whether the expression X is derived from a result of a phi node
1190 in header of LOOP such that
1192 * the derivation of X consists only from operations with constants
1193 * the initial value of the phi node is constant
1194 * the value of the phi node in the next iteration can be derived from the
1195 value in the current iteration by a chain of operations with constants.
1197 If such phi node exists, it is returned. If X is a constant, X is returned
1198 unchanged. Otherwise NULL_TREE is returned. */
1200 static tree
1201 get_base_for (struct loop *loop, tree x)
1203 tree phi, init, next;
1205 if (is_gimple_min_invariant (x))
1206 return x;
1208 phi = chain_of_csts_start (loop, x);
1209 if (!phi)
1210 return NULL_TREE;
1212 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1213 next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1215 if (TREE_CODE (next) != SSA_NAME)
1216 return NULL_TREE;
1218 if (!is_gimple_min_invariant (init))
1219 return NULL_TREE;
1221 if (chain_of_csts_start (loop, next) != phi)
1222 return NULL_TREE;
1224 return phi;
1227 /* Given an expression X, then
1229 * if BASE is NULL_TREE, X must be a constant and we return X.
1230 * otherwise X is a SSA name, whose value in the considered loop is derived
1231 by a chain of operations with constant from a result of a phi node in
1232 the header of the loop. Then we return value of X when the value of the
1233 result of this phi node is given by the constant BASE. */
1235 static tree
1236 get_val_for (tree x, tree base)
1238 tree stmt, nx, val;
1239 use_operand_p op;
1240 ssa_op_iter iter;
1242 if (!x)
1243 return base;
1245 stmt = SSA_NAME_DEF_STMT (x);
1246 if (TREE_CODE (stmt) == PHI_NODE)
1247 return base;
1249 FOR_EACH_SSA_USE_OPERAND (op, stmt, iter, SSA_OP_USE)
1251 nx = USE_FROM_PTR (op);
1252 val = get_val_for (nx, base);
1253 SET_USE (op, val);
1254 val = fold (TREE_OPERAND (stmt, 1));
1255 SET_USE (op, nx);
1256 /* only iterate loop once. */
1257 return val;
1260 /* Should never reach here. */
1261 gcc_unreachable();
1264 /* Tries to count the number of iterations of LOOP till it exits by EXIT
1265 by brute force -- i.e. by determining the value of the operands of the
1266 condition at EXIT in first few iterations of the loop (assuming that
1267 these values are constant) and determining the first one in that the
1268 condition is not satisfied. Returns the constant giving the number
1269 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
1271 tree
1272 loop_niter_by_eval (struct loop *loop, edge exit)
1274 tree cond, cnd, acnd;
1275 tree op[2], val[2], next[2], aval[2], phi[2];
1276 unsigned i, j;
1277 enum tree_code cmp;
1279 cond = last_stmt (exit->src);
1280 if (!cond || TREE_CODE (cond) != COND_EXPR)
1281 return chrec_dont_know;
1283 cnd = COND_EXPR_COND (cond);
1284 if (exit->flags & EDGE_TRUE_VALUE)
1285 cnd = invert_truthvalue (cnd);
1287 cmp = TREE_CODE (cnd);
1288 switch (cmp)
1290 case EQ_EXPR:
1291 case NE_EXPR:
1292 case GT_EXPR:
1293 case GE_EXPR:
1294 case LT_EXPR:
1295 case LE_EXPR:
1296 for (j = 0; j < 2; j++)
1297 op[j] = TREE_OPERAND (cnd, j);
1298 break;
1300 default:
1301 return chrec_dont_know;
1304 for (j = 0; j < 2; j++)
1306 phi[j] = get_base_for (loop, op[j]);
1307 if (!phi[j])
1308 return chrec_dont_know;
1311 for (j = 0; j < 2; j++)
1313 if (TREE_CODE (phi[j]) == PHI_NODE)
1315 val[j] = PHI_ARG_DEF_FROM_EDGE (phi[j], loop_preheader_edge (loop));
1316 next[j] = PHI_ARG_DEF_FROM_EDGE (phi[j], loop_latch_edge (loop));
1318 else
1320 val[j] = phi[j];
1321 next[j] = NULL_TREE;
1322 op[j] = NULL_TREE;
1326 for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
1328 for (j = 0; j < 2; j++)
1329 aval[j] = get_val_for (op[j], val[j]);
1331 acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
1332 if (acnd && zero_p (acnd))
1334 if (dump_file && (dump_flags & TDF_DETAILS))
1335 fprintf (dump_file,
1336 "Proved that loop %d iterates %d times using brute force.\n",
1337 loop->num, i);
1338 return build_int_cst (unsigned_type_node, i);
1341 for (j = 0; j < 2; j++)
1342 val[j] = get_val_for (next[j], val[j]);
1345 return chrec_dont_know;
1348 /* Finds the exit of the LOOP by that the loop exits after a constant
1349 number of iterations and stores the exit edge to *EXIT. The constant
1350 giving the number of iterations of LOOP is returned. The number of
1351 iterations is determined using loop_niter_by_eval (i.e. by brute force
1352 evaluation). If we are unable to find the exit for that loop_niter_by_eval
1353 determines the number of iterations, chrec_dont_know is returned. */
1355 tree
1356 find_loop_niter_by_eval (struct loop *loop, edge *exit)
1358 unsigned n_exits, i;
1359 edge *exits = get_loop_exit_edges (loop, &n_exits);
1360 edge ex;
1361 tree niter = NULL_TREE, aniter;
1363 *exit = NULL;
1364 for (i = 0; i < n_exits; i++)
1366 ex = exits[i];
1367 if (!just_once_each_iteration_p (loop, ex->src))
1368 continue;
1370 aniter = loop_niter_by_eval (loop, ex);
1371 if (chrec_contains_undetermined (aniter))
1372 continue;
1374 if (niter
1375 && !tree_int_cst_lt (aniter, niter))
1376 continue;
1378 niter = aniter;
1379 *exit = ex;
1381 free (exits);
1383 return niter ? niter : chrec_dont_know;
1388 Analysis of upper bounds on number of iterations of a loop.
1392 /* Records that AT_STMT is executed at most BOUND times in LOOP. The
1393 additional condition ADDITIONAL is recorded with the bound. */
1395 void
1396 record_estimate (struct loop *loop, tree bound, tree additional, tree at_stmt)
1398 struct nb_iter_bound *elt = xmalloc (sizeof (struct nb_iter_bound));
1400 if (dump_file && (dump_flags & TDF_DETAILS))
1402 fprintf (dump_file, "Statements after ");
1403 print_generic_expr (dump_file, at_stmt, TDF_SLIM);
1404 fprintf (dump_file, " are executed at most ");
1405 print_generic_expr (dump_file, bound, TDF_SLIM);
1406 fprintf (dump_file, " times in loop %d.\n", loop->num);
1409 elt->bound = bound;
1410 elt->at_stmt = at_stmt;
1411 elt->additional = additional;
1412 elt->next = loop->bounds;
1413 loop->bounds = elt;
1416 /* Initialize LOOP->ESTIMATED_NB_ITERATIONS with the lowest safe
1417 approximation of the number of iterations for LOOP. */
1419 static void
1420 compute_estimated_nb_iterations (struct loop *loop)
1422 struct nb_iter_bound *bound;
1424 for (bound = loop->bounds; bound; bound = bound->next)
1425 if (TREE_CODE (bound->bound) == INTEGER_CST
1426 /* Update only when there is no previous estimation. */
1427 && (chrec_contains_undetermined (loop->estimated_nb_iterations)
1428 /* Or when the current estimation is smaller. */
1429 || tree_int_cst_lt (bound->bound, loop->estimated_nb_iterations)))
1430 loop->estimated_nb_iterations = bound->bound;
1433 /* The following analyzers are extracting informations on the bounds
1434 of LOOP from the following undefined behaviors:
1436 - data references should not access elements over the statically
1437 allocated size,
1439 - signed variables should not overflow when flag_wrapv is not set.
1442 static void
1443 infer_loop_bounds_from_undefined (struct loop *loop)
1445 unsigned i;
1446 basic_block bb, *bbs;
1447 block_stmt_iterator bsi;
1449 bbs = get_loop_body (loop);
1451 for (i = 0; i < loop->num_nodes; i++)
1453 bb = bbs[i];
1455 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1457 tree stmt = bsi_stmt (bsi);
1459 switch (TREE_CODE (stmt))
1461 case MODIFY_EXPR:
1463 tree op0 = TREE_OPERAND (stmt, 0);
1464 tree op1 = TREE_OPERAND (stmt, 1);
1466 /* For each array access, analyze its access function
1467 and record a bound on the loop iteration domain. */
1468 if (TREE_CODE (op1) == ARRAY_REF
1469 && !array_ref_contains_indirect_ref (op1))
1470 estimate_iters_using_array (stmt, op1);
1472 if (TREE_CODE (op0) == ARRAY_REF
1473 && !array_ref_contains_indirect_ref (op0))
1474 estimate_iters_using_array (stmt, op0);
1476 /* For each signed type variable in LOOP, analyze its
1477 scalar evolution and record a bound of the loop
1478 based on the type's ranges. */
1479 else if (!flag_wrapv && TREE_CODE (op0) == SSA_NAME)
1481 tree init, step, diff, estimation;
1482 tree scev = instantiate_parameters
1483 (loop, analyze_scalar_evolution (loop, op0));
1484 tree type = chrec_type (scev);
1485 tree utype;
1487 if (chrec_contains_undetermined (scev)
1488 || TYPE_UNSIGNED (type))
1489 break;
1491 init = initial_condition_in_loop_num (scev, loop->num);
1492 step = evolution_part_in_loop_num (scev, loop->num);
1494 if (init == NULL_TREE
1495 || step == NULL_TREE
1496 || TREE_CODE (init) != INTEGER_CST
1497 || TREE_CODE (step) != INTEGER_CST
1498 || TYPE_MIN_VALUE (type) == NULL_TREE
1499 || TYPE_MAX_VALUE (type) == NULL_TREE)
1500 break;
1502 utype = unsigned_type_for (type);
1503 if (tree_int_cst_lt (step, integer_zero_node))
1504 diff = fold_build2 (MINUS_EXPR, utype, init,
1505 TYPE_MIN_VALUE (type));
1506 else
1507 diff = fold_build2 (MINUS_EXPR, utype,
1508 TYPE_MAX_VALUE (type), init);
1510 estimation = fold_build2 (CEIL_DIV_EXPR, utype, diff,
1511 step);
1512 record_estimate (loop, estimation, boolean_true_node, stmt);
1515 break;
1518 case CALL_EXPR:
1520 tree args;
1522 for (args = TREE_OPERAND (stmt, 1); args;
1523 args = TREE_CHAIN (args))
1524 if (TREE_CODE (TREE_VALUE (args)) == ARRAY_REF
1525 && !array_ref_contains_indirect_ref (TREE_VALUE (args)))
1526 estimate_iters_using_array (stmt, TREE_VALUE (args));
1528 break;
1531 default:
1532 break;
1536 if (chrec_contains_undetermined (loop->estimated_nb_iterations))
1537 compute_estimated_nb_iterations (loop);
1540 free (bbs);
1543 /* Records estimates on numbers of iterations of LOOP. */
1545 static void
1546 estimate_numbers_of_iterations_loop (struct loop *loop)
1548 edge *exits;
1549 tree niter, type;
1550 unsigned i, n_exits;
1551 struct tree_niter_desc niter_desc;
1553 /* Give up if we already have tried to compute an estimation. */
1554 if (loop->estimated_nb_iterations == chrec_dont_know
1555 /* Or when we already have an estimation. */
1556 || (loop->estimated_nb_iterations != NULL_TREE
1557 && TREE_CODE (loop->estimated_nb_iterations) == INTEGER_CST))
1558 return;
1559 else
1560 loop->estimated_nb_iterations = chrec_dont_know;
1562 exits = get_loop_exit_edges (loop, &n_exits);
1563 for (i = 0; i < n_exits; i++)
1565 if (!number_of_iterations_exit (loop, exits[i], &niter_desc, false))
1566 continue;
1568 niter = niter_desc.niter;
1569 type = TREE_TYPE (niter);
1570 if (!zero_p (niter_desc.may_be_zero)
1571 && !nonzero_p (niter_desc.may_be_zero))
1572 niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
1573 build_int_cst_type (type, 0),
1574 niter);
1575 record_estimate (loop, niter,
1576 niter_desc.additional_info,
1577 last_stmt (exits[i]->src));
1579 free (exits);
1581 if (chrec_contains_undetermined (loop->estimated_nb_iterations))
1582 infer_loop_bounds_from_undefined (loop);
1585 /* Records estimates on numbers of iterations of LOOPS. */
1587 void
1588 estimate_numbers_of_iterations (struct loops *loops)
1590 unsigned i;
1591 struct loop *loop;
1593 for (i = 1; i < loops->num; i++)
1595 loop = loops->parray[i];
1596 if (loop)
1597 estimate_numbers_of_iterations_loop (loop);
1601 /* If A > B, returns -1. If A == B, returns 0. If A < B, returns 1.
1602 If neither of these relations can be proved, returns 2. */
1604 static int
1605 compare_trees (tree a, tree b)
1607 tree typea = TREE_TYPE (a), typeb = TREE_TYPE (b);
1608 tree type;
1610 if (TYPE_PRECISION (typea) > TYPE_PRECISION (typeb))
1611 type = typea;
1612 else
1613 type = typeb;
1615 a = fold_convert (type, a);
1616 b = fold_convert (type, b);
1618 if (nonzero_p (fold_binary (EQ_EXPR, boolean_type_node, a, b)))
1619 return 0;
1620 if (nonzero_p (fold_binary (LT_EXPR, boolean_type_node, a, b)))
1621 return 1;
1622 if (nonzero_p (fold_binary (GT_EXPR, boolean_type_node, a, b)))
1623 return -1;
1625 return 2;
1628 /* Returns true if statement S1 dominates statement S2. */
1630 static bool
1631 stmt_dominates_stmt_p (tree s1, tree s2)
1633 basic_block bb1 = bb_for_stmt (s1), bb2 = bb_for_stmt (s2);
1635 if (!bb1
1636 || s1 == s2)
1637 return true;
1639 if (bb1 == bb2)
1641 block_stmt_iterator bsi;
1643 for (bsi = bsi_start (bb1); bsi_stmt (bsi) != s2; bsi_next (&bsi))
1644 if (bsi_stmt (bsi) == s1)
1645 return true;
1647 return false;
1650 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
1653 /* Return true when it is possible to prove that the induction
1654 variable does not wrap: vary outside the type specified bounds.
1655 Checks whether BOUND < VALID_NITER that means in the context of iv
1656 conversion that all the iterations in the loop are safe: not
1657 producing wraps.
1659 The statement NITER_BOUND->AT_STMT is executed at most
1660 NITER_BOUND->BOUND times in the loop.
1662 NITER_BOUND->ADDITIONAL is the additional condition recorded for
1663 operands of the bound. This is useful in the following case,
1664 created by loop header copying:
1666 i = 0;
1667 if (n > 0)
1670 something;
1671 } while (++i < n)
1673 If the n > 0 condition is taken into account, the number of iterations of the
1674 loop can be expressed as n - 1. If the type of n is signed, the ADDITIONAL
1675 assumption "n > 0" says us that the value of the number of iterations is at
1676 most MAX_TYPE - 1 (without this assumption, it might overflow). */
1678 static bool
1679 proved_non_wrapping_p (tree at_stmt,
1680 struct nb_iter_bound *niter_bound,
1681 tree new_type,
1682 tree valid_niter)
1684 tree cond;
1685 tree bound = niter_bound->bound;
1686 enum tree_code cmp;
1688 if (TYPE_PRECISION (new_type) > TYPE_PRECISION (TREE_TYPE (bound)))
1689 bound = fold_convert (unsigned_type_for (new_type), bound);
1690 else
1691 valid_niter = fold_convert (TREE_TYPE (bound), valid_niter);
1693 /* Give up if BOUND was not folded to an INTEGER_CST, as in PR23434. */
1694 if (TREE_CODE (bound) != INTEGER_CST)
1695 return false;
1697 /* After the statement niter_bound->at_stmt we know that anything is
1698 executed at most BOUND times. */
1699 if (at_stmt && stmt_dominates_stmt_p (niter_bound->at_stmt, at_stmt))
1700 cmp = GE_EXPR;
1701 /* Before the statement niter_bound->at_stmt we know that anything
1702 is executed at most BOUND + 1 times. */
1703 else
1704 cmp = GT_EXPR;
1706 cond = fold_binary (cmp, boolean_type_node, valid_niter, bound);
1707 if (nonzero_p (cond))
1708 return true;
1710 cond = build2 (cmp, boolean_type_node, valid_niter, bound);
1711 /* Try taking additional conditions into account. */
1712 cond = fold_binary (TRUTH_OR_EXPR, boolean_type_node,
1713 invert_truthvalue (niter_bound->additional),
1714 cond);
1716 if (nonzero_p (cond))
1717 return true;
1719 return false;
1722 /* Checks whether it is correct to count the induction variable BASE +
1723 STEP * I at AT_STMT in a wider type NEW_TYPE, using the bounds on
1724 numbers of iterations of a LOOP. If it is possible, return the
1725 value of step of the induction variable in the NEW_TYPE, otherwise
1726 return NULL_TREE. */
1728 static tree
1729 convert_step_widening (struct loop *loop, tree new_type, tree base, tree step,
1730 tree at_stmt)
1732 struct nb_iter_bound *bound;
1733 tree base_in_new_type, base_plus_step_in_new_type, step_in_new_type;
1734 tree delta, step_abs;
1735 tree unsigned_type, valid_niter;
1737 /* Compute the new step. For example, {(uchar) 100, +, (uchar) 240}
1738 is converted to {(uint) 100, +, (uint) 0xfffffff0} in order to
1739 keep the values of the induction variable unchanged: 100, 84, 68,
1742 Another example is: (uint) {(uchar)100, +, (uchar)3} is converted
1743 to {(uint)100, +, (uint)3}.
1745 Before returning the new step, verify that the number of
1746 iterations is less than DELTA / STEP_ABS (i.e. in the previous
1747 example (256 - 100) / 3) such that the iv does not wrap (in which
1748 case the operations are too difficult to be represented and
1749 handled: the values of the iv should be taken modulo 256 in the
1750 wider type; this is not implemented). */
1751 base_in_new_type = fold_convert (new_type, base);
1752 base_plus_step_in_new_type =
1753 fold_convert (new_type,
1754 fold_build2 (PLUS_EXPR, TREE_TYPE (base), base, step));
1755 step_in_new_type = fold_build2 (MINUS_EXPR, new_type,
1756 base_plus_step_in_new_type,
1757 base_in_new_type);
1759 if (TREE_CODE (step_in_new_type) != INTEGER_CST)
1760 return NULL_TREE;
1762 switch (compare_trees (base_plus_step_in_new_type, base_in_new_type))
1764 case -1:
1766 tree extreme = upper_bound_in_type (new_type, TREE_TYPE (base));
1767 delta = fold_build2 (MINUS_EXPR, new_type, extreme,
1768 base_in_new_type);
1769 step_abs = step_in_new_type;
1770 break;
1773 case 1:
1775 tree extreme = lower_bound_in_type (new_type, TREE_TYPE (base));
1776 delta = fold_build2 (MINUS_EXPR, new_type, base_in_new_type,
1777 extreme);
1778 step_abs = fold_build1 (NEGATE_EXPR, new_type, step_in_new_type);
1779 break;
1782 case 0:
1783 return step_in_new_type;
1785 default:
1786 return NULL_TREE;
1789 unsigned_type = unsigned_type_for (new_type);
1790 delta = fold_convert (unsigned_type, delta);
1791 step_abs = fold_convert (unsigned_type, step_abs);
1792 valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type,
1793 delta, step_abs);
1795 estimate_numbers_of_iterations_loop (loop);
1796 for (bound = loop->bounds; bound; bound = bound->next)
1797 if (proved_non_wrapping_p (at_stmt, bound, new_type, valid_niter))
1798 return step_in_new_type;
1800 /* Fail when the loop has no bound estimations, or when no bound can
1801 be used for verifying the conversion. */
1802 return NULL_TREE;
1805 /* Returns true when VAR is used in pointer arithmetics. DEPTH is
1806 used for limiting the search. */
1808 static bool
1809 used_in_pointer_arithmetic_p (tree var, int depth)
1811 use_operand_p use_p;
1812 imm_use_iterator iter;
1814 if (depth == 0
1815 || TREE_CODE (var) != SSA_NAME
1816 || !has_single_use (var))
1817 return false;
1819 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
1821 tree stmt = USE_STMT (use_p);
1823 if (stmt && TREE_CODE (stmt) == MODIFY_EXPR)
1825 tree rhs = TREE_OPERAND (stmt, 1);
1827 if (TREE_CODE (rhs) == NOP_EXPR
1828 || TREE_CODE (rhs) == CONVERT_EXPR)
1830 if (POINTER_TYPE_P (TREE_TYPE (rhs)))
1831 return true;
1832 return false;
1834 else
1835 return used_in_pointer_arithmetic_p (TREE_OPERAND (stmt, 0),
1836 depth - 1);
1839 return false;
1842 /* Return false only when the induction variable BASE + STEP * I is
1843 known to not overflow: i.e. when the number of iterations is small
1844 enough with respect to the step and initial condition in order to
1845 keep the evolution confined in TYPEs bounds. Return true when the
1846 iv is known to overflow or when the property is not computable.
1848 Initialize INIT_IS_MAX to true when the evolution goes from
1849 INIT_IS_MAX to LOWER_BOUND_IN_TYPE, false in the contrary case.
1850 When this property cannot be determined, UNKNOWN_MAX is set to
1851 true. */
1853 bool
1854 scev_probably_wraps_p (tree type, tree base, tree step,
1855 tree at_stmt, struct loop *loop,
1856 bool *init_is_max, bool *unknown_max)
1858 struct nb_iter_bound *bound;
1859 tree delta, step_abs;
1860 tree unsigned_type, valid_niter;
1861 tree base_plus_step, bpsps;
1862 int cps, cpsps;
1864 /* FIXME: The following code will not be used anymore once
1865 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html is
1866 committed.
1868 If AT_STMT is a cast to unsigned that is later used for
1869 referencing a memory location, it is followed by a pointer
1870 conversion just after. Because pointers do not wrap, the
1871 sequences that reference the memory do not wrap either. In the
1872 following example, sequences corresponding to D_13 and to D_14
1873 can be proved to not wrap because they are used for computing a
1874 memory access:
1876 D.1621_13 = (long unsigned intD.4) D.1620_12;
1877 D.1622_14 = D.1621_13 * 8;
1878 D.1623_15 = (doubleD.29 *) D.1622_14;
1880 if (at_stmt && TREE_CODE (at_stmt) == MODIFY_EXPR)
1882 tree op0 = TREE_OPERAND (at_stmt, 0);
1883 tree op1 = TREE_OPERAND (at_stmt, 1);
1884 tree type_op1 = TREE_TYPE (op1);
1886 if ((TYPE_UNSIGNED (type_op1)
1887 && used_in_pointer_arithmetic_p (op0, 2))
1888 || POINTER_TYPE_P (type_op1))
1890 *unknown_max = true;
1891 return false;
1895 if (chrec_contains_undetermined (base)
1896 || chrec_contains_undetermined (step)
1897 || TREE_CODE (base) == REAL_CST
1898 || TREE_CODE (step) == REAL_CST)
1900 *unknown_max = true;
1901 return true;
1904 *unknown_max = false;
1905 base_plus_step = fold_build2 (PLUS_EXPR, type, base, step);
1906 bpsps = fold_build2 (PLUS_EXPR, type, base_plus_step, step);
1907 cps = compare_trees (base_plus_step, base);
1908 cpsps = compare_trees (bpsps, base_plus_step);
1910 /* Check that the sequence is not wrapping in the first step: it
1911 should have the same monotonicity for the first two steps. See
1912 PR23410. */
1913 if (cps != cpsps)
1914 return true;
1916 switch (cps)
1918 case -1:
1920 tree extreme = upper_bound_in_type (type, TREE_TYPE (base));
1921 delta = fold_build2 (MINUS_EXPR, type, extreme, base);
1922 step_abs = step;
1923 *init_is_max = false;
1924 break;
1927 case 1:
1929 tree extreme = lower_bound_in_type (type, TREE_TYPE (base));
1930 delta = fold_build2 (MINUS_EXPR, type, base, extreme);
1931 step_abs = fold_build1 (NEGATE_EXPR, type, step);
1932 *init_is_max = true;
1933 break;
1936 case 0:
1937 /* This means step is equal to 0. This should not happen. It
1938 could happen in convert step, but not here. Safely answer
1939 don't know as in the default case. */
1941 default:
1942 *unknown_max = true;
1943 return true;
1946 /* If AT_STMT represents a cast operation, we may not be able to
1947 take advantage of the undefinedness of signed type evolutions.
1949 implement-c.texi states: "For conversion to a type of width
1950 N, the value is reduced modulo 2^N to be within range of the
1951 type;"
1953 See PR 21959 for a test case. Essentially, given a cast
1954 operation
1955 unsigned char uc;
1956 signed char sc;
1958 sc = (signed char) uc;
1959 if (sc < 0)
1962 where uc and sc have the scev {0, +, 1}, we would consider uc to
1963 wrap around, but not sc, because it is of a signed type. This
1964 causes VRP to erroneously fold the predicate above because it
1965 thinks that sc cannot be negative. */
1966 if (at_stmt && TREE_CODE (at_stmt) == MODIFY_EXPR)
1968 tree rhs = TREE_OPERAND (at_stmt, 1);
1969 tree outer_t = TREE_TYPE (rhs);
1971 if (!TYPE_UNSIGNED (outer_t)
1972 && (TREE_CODE (rhs) == NOP_EXPR || TREE_CODE (rhs) == CONVERT_EXPR))
1974 tree inner_t = TREE_TYPE (TREE_OPERAND (rhs, 0));
1976 /* If the inner type is unsigned and its size and/or
1977 precision are smaller to that of the outer type, then the
1978 expression may wrap around. */
1979 if (TYPE_UNSIGNED (inner_t)
1980 && (TYPE_SIZE (inner_t) <= TYPE_SIZE (outer_t)
1981 || TYPE_PRECISION (inner_t) <= TYPE_PRECISION (outer_t)))
1983 *unknown_max = true;
1984 return true;
1989 /* After having set INIT_IS_MAX, we can return false: when not using
1990 wrapping arithmetic, signed types don't wrap. */
1991 if (!flag_wrapv && !TYPE_UNSIGNED (type))
1992 return false;
1994 unsigned_type = unsigned_type_for (type);
1995 delta = fold_convert (unsigned_type, delta);
1996 step_abs = fold_convert (unsigned_type, step_abs);
1997 valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
1999 estimate_numbers_of_iterations_loop (loop);
2000 for (bound = loop->bounds; bound; bound = bound->next)
2001 if (proved_non_wrapping_p (at_stmt, bound, type, valid_niter))
2002 return false;
2004 /* At this point we still don't have a proof that the iv does not
2005 overflow: give up. */
2006 *unknown_max = true;
2007 return true;
2010 /* Return the conversion to NEW_TYPE of the STEP of an induction
2011 variable BASE + STEP * I at AT_STMT. When it fails, return
2012 NULL_TREE. */
2014 tree
2015 convert_step (struct loop *loop, tree new_type, tree base, tree step,
2016 tree at_stmt)
2018 tree base_type;
2020 if (chrec_contains_undetermined (base)
2021 || chrec_contains_undetermined (step))
2022 return NULL_TREE;
2024 base_type = TREE_TYPE (base);
2026 /* When not using wrapping arithmetic, signed types don't wrap. */
2027 if (!flag_wrapv && !TYPE_UNSIGNED (base_type))
2028 return fold_convert (new_type, step);
2030 if (TYPE_PRECISION (new_type) > TYPE_PRECISION (base_type))
2031 return convert_step_widening (loop, new_type, base, step, at_stmt);
2033 return fold_convert (new_type, step);
2036 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
2038 void
2039 free_numbers_of_iterations_estimates_loop (struct loop *loop)
2041 struct nb_iter_bound *bound, *next;
2043 loop->nb_iterations = NULL;
2044 loop->estimated_nb_iterations = NULL;
2045 for (bound = loop->bounds; bound; bound = next)
2047 next = bound->next;
2048 free (bound);
2051 loop->bounds = NULL;
2054 /* Frees the information on upper bounds on numbers of iterations of LOOPS. */
2056 void
2057 free_numbers_of_iterations_estimates (struct loops *loops)
2059 unsigned i;
2060 struct loop *loop;
2062 for (i = 1; i < loops->num; i++)
2064 loop = loops->parray[i];
2065 if (loop)
2066 free_numbers_of_iterations_estimates_loop (loop);
2070 /* Substitute value VAL for ssa name NAME inside expressions held
2071 at LOOP. */
2073 void
2074 substitute_in_loop_info (struct loop *loop, tree name, tree val)
2076 struct nb_iter_bound *bound;
2078 loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);
2079 loop->estimated_nb_iterations
2080 = simplify_replace_tree (loop->estimated_nb_iterations, name, val);
2081 for (bound = loop->bounds; bound; bound = bound->next)
2083 bound->bound = simplify_replace_tree (bound->bound, name, val);
2084 bound->additional = simplify_replace_tree (bound->additional, name, val);