PR target/66563
[official-gcc.git] / gcc / tree-ssa-loop-niter.c
blob855d32ceeb01dab8278ca37f55f67dcf92ec1451
1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004-2015 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 3, 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 COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "alias.h"
25 #include "symtab.h"
26 #include "tree.h"
27 #include "stor-layout.h"
28 #include "fold-const.h"
29 #include "calls.h"
30 #include "hard-reg-set.h"
31 #include "function.h"
32 #include "rtl.h"
33 #include "flags.h"
34 #include "insn-config.h"
35 #include "expmed.h"
36 #include "dojump.h"
37 #include "explow.h"
38 #include "emit-rtl.h"
39 #include "varasm.h"
40 #include "stmt.h"
41 #include "expr.h"
42 #include "tm_p.h"
43 #include "predict.h"
44 #include "dominance.h"
45 #include "cfg.h"
46 #include "basic-block.h"
47 #include "gimple-pretty-print.h"
48 #include "intl.h"
49 #include "tree-ssa-alias.h"
50 #include "internal-fn.h"
51 #include "gimple-expr.h"
52 #include "gimple.h"
53 #include "gimplify.h"
54 #include "gimple-iterator.h"
55 #include "gimple-ssa.h"
56 #include "tree-cfg.h"
57 #include "tree-phinodes.h"
58 #include "ssa-iterators.h"
59 #include "tree-ssa-loop-ivopts.h"
60 #include "tree-ssa-loop-niter.h"
61 #include "tree-ssa-loop.h"
62 #include "dumpfile.h"
63 #include "cfgloop.h"
64 #include "tree-chrec.h"
65 #include "tree-scalar-evolution.h"
66 #include "tree-data-ref.h"
67 #include "params.h"
68 #include "diagnostic-core.h"
69 #include "tree-inline.h"
70 #include "tree-pass.h"
71 #include "stringpool.h"
72 #include "tree-ssanames.h"
73 #include "wide-int-print.h"
76 /* The maximum number of dominator BBs we search for conditions
77 of loop header copies we use for simplifying a conditional
78 expression. */
79 #define MAX_DOMINATORS_TO_WALK 8
83 Analysis of number of iterations of an affine exit test.
87 /* Bounds on some value, BELOW <= X <= UP. */
89 typedef struct
91 mpz_t below, up;
92 } bounds;
95 /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
97 static void
98 split_to_var_and_offset (tree expr, tree *var, mpz_t offset)
100 tree type = TREE_TYPE (expr);
101 tree op0, op1;
102 bool negate = false;
104 *var = expr;
105 mpz_set_ui (offset, 0);
107 switch (TREE_CODE (expr))
109 case MINUS_EXPR:
110 negate = true;
111 /* Fallthru. */
113 case PLUS_EXPR:
114 case POINTER_PLUS_EXPR:
115 op0 = TREE_OPERAND (expr, 0);
116 op1 = TREE_OPERAND (expr, 1);
118 if (TREE_CODE (op1) != INTEGER_CST)
119 break;
121 *var = op0;
122 /* Always sign extend the offset. */
123 wi::to_mpz (op1, offset, SIGNED);
124 if (negate)
125 mpz_neg (offset, offset);
126 break;
128 case INTEGER_CST:
129 *var = build_int_cst_type (type, 0);
130 wi::to_mpz (expr, offset, TYPE_SIGN (type));
131 break;
133 default:
134 break;
138 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
139 in TYPE to MIN and MAX. */
141 static void
142 determine_value_range (struct loop *loop, tree type, tree var, mpz_t off,
143 mpz_t min, mpz_t max)
145 wide_int minv, maxv;
146 enum value_range_type rtype = VR_VARYING;
148 /* If the expression is a constant, we know its value exactly. */
149 if (integer_zerop (var))
151 mpz_set (min, off);
152 mpz_set (max, off);
153 return;
156 get_type_static_bounds (type, min, max);
158 /* See if we have some range info from VRP. */
159 if (TREE_CODE (var) == SSA_NAME && INTEGRAL_TYPE_P (type))
161 edge e = loop_preheader_edge (loop);
162 signop sgn = TYPE_SIGN (type);
163 gphi_iterator gsi;
165 /* Either for VAR itself... */
166 rtype = get_range_info (var, &minv, &maxv);
167 /* Or for PHI results in loop->header where VAR is used as
168 PHI argument from the loop preheader edge. */
169 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
171 gphi *phi = gsi.phi ();
172 wide_int minc, maxc;
173 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var
174 && (get_range_info (gimple_phi_result (phi), &minc, &maxc)
175 == VR_RANGE))
177 if (rtype != VR_RANGE)
179 rtype = VR_RANGE;
180 minv = minc;
181 maxv = maxc;
183 else
185 minv = wi::max (minv, minc, sgn);
186 maxv = wi::min (maxv, maxc, sgn);
187 /* If the PHI result range are inconsistent with
188 the VAR range, give up on looking at the PHI
189 results. This can happen if VR_UNDEFINED is
190 involved. */
191 if (wi::gt_p (minv, maxv, sgn))
193 rtype = get_range_info (var, &minv, &maxv);
194 break;
199 if (rtype == VR_RANGE)
201 mpz_t minm, maxm;
202 gcc_assert (wi::le_p (minv, maxv, sgn));
203 mpz_init (minm);
204 mpz_init (maxm);
205 wi::to_mpz (minv, minm, sgn);
206 wi::to_mpz (maxv, maxm, sgn);
207 mpz_add (minm, minm, off);
208 mpz_add (maxm, maxm, off);
209 /* If the computation may not wrap or off is zero, then this
210 is always fine. If off is negative and minv + off isn't
211 smaller than type's minimum, or off is positive and
212 maxv + off isn't bigger than type's maximum, use the more
213 precise range too. */
214 if (nowrap_type_p (type)
215 || mpz_sgn (off) == 0
216 || (mpz_sgn (off) < 0 && mpz_cmp (minm, min) >= 0)
217 || (mpz_sgn (off) > 0 && mpz_cmp (maxm, max) <= 0))
219 mpz_set (min, minm);
220 mpz_set (max, maxm);
221 mpz_clear (minm);
222 mpz_clear (maxm);
223 return;
225 mpz_clear (minm);
226 mpz_clear (maxm);
230 /* If the computation may wrap, we know nothing about the value, except for
231 the range of the type. */
232 if (!nowrap_type_p (type))
233 return;
235 /* Since the addition of OFF does not wrap, if OFF is positive, then we may
236 add it to MIN, otherwise to MAX. */
237 if (mpz_sgn (off) < 0)
238 mpz_add (max, max, off);
239 else
240 mpz_add (min, min, off);
243 /* Stores the bounds on the difference of the values of the expressions
244 (var + X) and (var + Y), computed in TYPE, to BNDS. */
246 static void
247 bound_difference_of_offsetted_base (tree type, mpz_t x, mpz_t y,
248 bounds *bnds)
250 int rel = mpz_cmp (x, y);
251 bool may_wrap = !nowrap_type_p (type);
252 mpz_t m;
254 /* If X == Y, then the expressions are always equal.
255 If X > Y, there are the following possibilities:
256 a) neither of var + X and var + Y overflow or underflow, or both of
257 them do. Then their difference is X - Y.
258 b) var + X overflows, and var + Y does not. Then the values of the
259 expressions are var + X - M and var + Y, where M is the range of
260 the type, and their difference is X - Y - M.
261 c) var + Y underflows and var + X does not. Their difference again
262 is M - X + Y.
263 Therefore, if the arithmetics in type does not overflow, then the
264 bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
265 Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
266 (X - Y, X - Y + M). */
268 if (rel == 0)
270 mpz_set_ui (bnds->below, 0);
271 mpz_set_ui (bnds->up, 0);
272 return;
275 mpz_init (m);
276 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), m, UNSIGNED);
277 mpz_add_ui (m, m, 1);
278 mpz_sub (bnds->up, x, y);
279 mpz_set (bnds->below, bnds->up);
281 if (may_wrap)
283 if (rel > 0)
284 mpz_sub (bnds->below, bnds->below, m);
285 else
286 mpz_add (bnds->up, bnds->up, m);
289 mpz_clear (m);
292 /* From condition C0 CMP C1 derives information regarding the
293 difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
294 and stores it to BNDS. */
296 static void
297 refine_bounds_using_guard (tree type, tree varx, mpz_t offx,
298 tree vary, mpz_t offy,
299 tree c0, enum tree_code cmp, tree c1,
300 bounds *bnds)
302 tree varc0, varc1, ctype;
303 mpz_t offc0, offc1, loffx, loffy, bnd;
304 bool lbound = false;
305 bool no_wrap = nowrap_type_p (type);
306 bool x_ok, y_ok;
308 switch (cmp)
310 case LT_EXPR:
311 case LE_EXPR:
312 case GT_EXPR:
313 case GE_EXPR:
314 STRIP_SIGN_NOPS (c0);
315 STRIP_SIGN_NOPS (c1);
316 ctype = TREE_TYPE (c0);
317 if (!useless_type_conversion_p (ctype, type))
318 return;
320 break;
322 case EQ_EXPR:
323 /* We could derive quite precise information from EQ_EXPR, however, such
324 a guard is unlikely to appear, so we do not bother with handling
325 it. */
326 return;
328 case NE_EXPR:
329 /* NE_EXPR comparisons do not contain much of useful information, except for
330 special case of comparing with the bounds of the type. */
331 if (TREE_CODE (c1) != INTEGER_CST
332 || !INTEGRAL_TYPE_P (type))
333 return;
335 /* Ensure that the condition speaks about an expression in the same type
336 as X and Y. */
337 ctype = TREE_TYPE (c0);
338 if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
339 return;
340 c0 = fold_convert (type, c0);
341 c1 = fold_convert (type, c1);
343 if (TYPE_MIN_VALUE (type)
344 && operand_equal_p (c1, TYPE_MIN_VALUE (type), 0))
346 cmp = GT_EXPR;
347 break;
349 if (TYPE_MAX_VALUE (type)
350 && operand_equal_p (c1, TYPE_MAX_VALUE (type), 0))
352 cmp = LT_EXPR;
353 break;
356 return;
357 default:
358 return;
361 mpz_init (offc0);
362 mpz_init (offc1);
363 split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
364 split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
366 /* We are only interested in comparisons of expressions based on VARX and
367 VARY. TODO -- we might also be able to derive some bounds from
368 expressions containing just one of the variables. */
370 if (operand_equal_p (varx, varc1, 0))
372 std::swap (varc0, varc1);
373 mpz_swap (offc0, offc1);
374 cmp = swap_tree_comparison (cmp);
377 if (!operand_equal_p (varx, varc0, 0)
378 || !operand_equal_p (vary, varc1, 0))
379 goto end;
381 mpz_init_set (loffx, offx);
382 mpz_init_set (loffy, offy);
384 if (cmp == GT_EXPR || cmp == GE_EXPR)
386 std::swap (varx, vary);
387 mpz_swap (offc0, offc1);
388 mpz_swap (loffx, loffy);
389 cmp = swap_tree_comparison (cmp);
390 lbound = true;
393 /* If there is no overflow, the condition implies that
395 (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
397 The overflows and underflows may complicate things a bit; each
398 overflow decreases the appropriate offset by M, and underflow
399 increases it by M. The above inequality would not necessarily be
400 true if
402 -- VARX + OFFX underflows and VARX + OFFC0 does not, or
403 VARX + OFFC0 overflows, but VARX + OFFX does not.
404 This may only happen if OFFX < OFFC0.
405 -- VARY + OFFY overflows and VARY + OFFC1 does not, or
406 VARY + OFFC1 underflows and VARY + OFFY does not.
407 This may only happen if OFFY > OFFC1. */
409 if (no_wrap)
411 x_ok = true;
412 y_ok = true;
414 else
416 x_ok = (integer_zerop (varx)
417 || mpz_cmp (loffx, offc0) >= 0);
418 y_ok = (integer_zerop (vary)
419 || mpz_cmp (loffy, offc1) <= 0);
422 if (x_ok && y_ok)
424 mpz_init (bnd);
425 mpz_sub (bnd, loffx, loffy);
426 mpz_add (bnd, bnd, offc1);
427 mpz_sub (bnd, bnd, offc0);
429 if (cmp == LT_EXPR)
430 mpz_sub_ui (bnd, bnd, 1);
432 if (lbound)
434 mpz_neg (bnd, bnd);
435 if (mpz_cmp (bnds->below, bnd) < 0)
436 mpz_set (bnds->below, bnd);
438 else
440 if (mpz_cmp (bnd, bnds->up) < 0)
441 mpz_set (bnds->up, bnd);
443 mpz_clear (bnd);
446 mpz_clear (loffx);
447 mpz_clear (loffy);
448 end:
449 mpz_clear (offc0);
450 mpz_clear (offc1);
453 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
454 The subtraction is considered to be performed in arbitrary precision,
455 without overflows.
457 We do not attempt to be too clever regarding the value ranges of X and
458 Y; most of the time, they are just integers or ssa names offsetted by
459 integer. However, we try to use the information contained in the
460 comparisons before the loop (usually created by loop header copying). */
462 static void
463 bound_difference (struct loop *loop, tree x, tree y, bounds *bnds)
465 tree type = TREE_TYPE (x);
466 tree varx, vary;
467 mpz_t offx, offy;
468 mpz_t minx, maxx, miny, maxy;
469 int cnt = 0;
470 edge e;
471 basic_block bb;
472 tree c0, c1;
473 gimple cond;
474 enum tree_code cmp;
476 /* Get rid of unnecessary casts, but preserve the value of
477 the expressions. */
478 STRIP_SIGN_NOPS (x);
479 STRIP_SIGN_NOPS (y);
481 mpz_init (bnds->below);
482 mpz_init (bnds->up);
483 mpz_init (offx);
484 mpz_init (offy);
485 split_to_var_and_offset (x, &varx, offx);
486 split_to_var_and_offset (y, &vary, offy);
488 if (!integer_zerop (varx)
489 && operand_equal_p (varx, vary, 0))
491 /* Special case VARX == VARY -- we just need to compare the
492 offsets. The matters are a bit more complicated in the
493 case addition of offsets may wrap. */
494 bound_difference_of_offsetted_base (type, offx, offy, bnds);
496 else
498 /* Otherwise, use the value ranges to determine the initial
499 estimates on below and up. */
500 mpz_init (minx);
501 mpz_init (maxx);
502 mpz_init (miny);
503 mpz_init (maxy);
504 determine_value_range (loop, type, varx, offx, minx, maxx);
505 determine_value_range (loop, type, vary, offy, miny, maxy);
507 mpz_sub (bnds->below, minx, maxy);
508 mpz_sub (bnds->up, maxx, miny);
509 mpz_clear (minx);
510 mpz_clear (maxx);
511 mpz_clear (miny);
512 mpz_clear (maxy);
515 /* If both X and Y are constants, we cannot get any more precise. */
516 if (integer_zerop (varx) && integer_zerop (vary))
517 goto end;
519 /* Now walk the dominators of the loop header and use the entry
520 guards to refine the estimates. */
521 for (bb = loop->header;
522 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
523 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
525 if (!single_pred_p (bb))
526 continue;
527 e = single_pred_edge (bb);
529 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
530 continue;
532 cond = last_stmt (e->src);
533 c0 = gimple_cond_lhs (cond);
534 cmp = gimple_cond_code (cond);
535 c1 = gimple_cond_rhs (cond);
537 if (e->flags & EDGE_FALSE_VALUE)
538 cmp = invert_tree_comparison (cmp, false);
540 refine_bounds_using_guard (type, varx, offx, vary, offy,
541 c0, cmp, c1, bnds);
542 ++cnt;
545 end:
546 mpz_clear (offx);
547 mpz_clear (offy);
550 /* Update the bounds in BNDS that restrict the value of X to the bounds
551 that restrict the value of X + DELTA. X can be obtained as a
552 difference of two values in TYPE. */
554 static void
555 bounds_add (bounds *bnds, const widest_int &delta, tree type)
557 mpz_t mdelta, max;
559 mpz_init (mdelta);
560 wi::to_mpz (delta, mdelta, SIGNED);
562 mpz_init (max);
563 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
565 mpz_add (bnds->up, bnds->up, mdelta);
566 mpz_add (bnds->below, bnds->below, mdelta);
568 if (mpz_cmp (bnds->up, max) > 0)
569 mpz_set (bnds->up, max);
571 mpz_neg (max, max);
572 if (mpz_cmp (bnds->below, max) < 0)
573 mpz_set (bnds->below, max);
575 mpz_clear (mdelta);
576 mpz_clear (max);
579 /* Update the bounds in BNDS that restrict the value of X to the bounds
580 that restrict the value of -X. */
582 static void
583 bounds_negate (bounds *bnds)
585 mpz_t tmp;
587 mpz_init_set (tmp, bnds->up);
588 mpz_neg (bnds->up, bnds->below);
589 mpz_neg (bnds->below, tmp);
590 mpz_clear (tmp);
593 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
595 static tree
596 inverse (tree x, tree mask)
598 tree type = TREE_TYPE (x);
599 tree rslt;
600 unsigned ctr = tree_floor_log2 (mask);
602 if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
604 unsigned HOST_WIDE_INT ix;
605 unsigned HOST_WIDE_INT imask;
606 unsigned HOST_WIDE_INT irslt = 1;
608 gcc_assert (cst_and_fits_in_hwi (x));
609 gcc_assert (cst_and_fits_in_hwi (mask));
611 ix = int_cst_value (x);
612 imask = int_cst_value (mask);
614 for (; ctr; ctr--)
616 irslt *= ix;
617 ix *= ix;
619 irslt &= imask;
621 rslt = build_int_cst_type (type, irslt);
623 else
625 rslt = build_int_cst (type, 1);
626 for (; ctr; ctr--)
628 rslt = int_const_binop (MULT_EXPR, rslt, x);
629 x = int_const_binop (MULT_EXPR, x, x);
631 rslt = int_const_binop (BIT_AND_EXPR, rslt, mask);
634 return rslt;
637 /* Derives the upper bound BND on the number of executions of loop with exit
638 condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
639 the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
640 that the loop ends through this exit, i.e., the induction variable ever
641 reaches the value of C.
643 The value C is equal to final - base, where final and base are the final and
644 initial value of the actual induction variable in the analysed loop. BNDS
645 bounds the value of this difference when computed in signed type with
646 unbounded range, while the computation of C is performed in an unsigned
647 type with the range matching the range of the type of the induction variable.
648 In particular, BNDS.up contains an upper bound on C in the following cases:
649 -- if the iv must reach its final value without overflow, i.e., if
650 NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
651 -- if final >= base, which we know to hold when BNDS.below >= 0. */
653 static void
654 number_of_iterations_ne_max (mpz_t bnd, bool no_overflow, tree c, tree s,
655 bounds *bnds, bool exit_must_be_taken)
657 widest_int max;
658 mpz_t d;
659 tree type = TREE_TYPE (c);
660 bool bnds_u_valid = ((no_overflow && exit_must_be_taken)
661 || mpz_sgn (bnds->below) >= 0);
663 if (integer_onep (s)
664 || (TREE_CODE (c) == INTEGER_CST
665 && TREE_CODE (s) == INTEGER_CST
666 && wi::mod_trunc (c, s, TYPE_SIGN (type)) == 0)
667 || (TYPE_OVERFLOW_UNDEFINED (type)
668 && multiple_of_p (type, c, s)))
670 /* If C is an exact multiple of S, then its value will be reached before
671 the induction variable overflows (unless the loop is exited in some
672 other way before). Note that the actual induction variable in the
673 loop (which ranges from base to final instead of from 0 to C) may
674 overflow, in which case BNDS.up will not be giving a correct upper
675 bound on C; thus, BNDS_U_VALID had to be computed in advance. */
676 no_overflow = true;
677 exit_must_be_taken = true;
680 /* If the induction variable can overflow, the number of iterations is at
681 most the period of the control variable (or infinite, but in that case
682 the whole # of iterations analysis will fail). */
683 if (!no_overflow)
685 max = wi::mask <widest_int> (TYPE_PRECISION (type) - wi::ctz (s), false);
686 wi::to_mpz (max, bnd, UNSIGNED);
687 return;
690 /* Now we know that the induction variable does not overflow, so the loop
691 iterates at most (range of type / S) times. */
692 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), bnd, UNSIGNED);
694 /* If the induction variable is guaranteed to reach the value of C before
695 overflow, ... */
696 if (exit_must_be_taken)
698 /* ... then we can strengthen this to C / S, and possibly we can use
699 the upper bound on C given by BNDS. */
700 if (TREE_CODE (c) == INTEGER_CST)
701 wi::to_mpz (c, bnd, UNSIGNED);
702 else if (bnds_u_valid)
703 mpz_set (bnd, bnds->up);
706 mpz_init (d);
707 wi::to_mpz (s, d, UNSIGNED);
708 mpz_fdiv_q (bnd, bnd, d);
709 mpz_clear (d);
712 /* Determines number of iterations of loop whose ending condition
713 is IV <> FINAL. TYPE is the type of the iv. The number of
714 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
715 we know that the exit must be taken eventually, i.e., that the IV
716 ever reaches the value FINAL (we derived this earlier, and possibly set
717 NITER->assumptions to make sure this is the case). BNDS contains the
718 bounds on the difference FINAL - IV->base. */
720 static bool
721 number_of_iterations_ne (tree type, affine_iv *iv, tree final,
722 struct tree_niter_desc *niter, bool exit_must_be_taken,
723 bounds *bnds)
725 tree niter_type = unsigned_type_for (type);
726 tree s, c, d, bits, assumption, tmp, bound;
727 mpz_t max;
729 niter->control = *iv;
730 niter->bound = final;
731 niter->cmp = NE_EXPR;
733 /* Rearrange the terms so that we get inequality S * i <> C, with S
734 positive. Also cast everything to the unsigned type. If IV does
735 not overflow, BNDS bounds the value of C. Also, this is the
736 case if the computation |FINAL - IV->base| does not overflow, i.e.,
737 if BNDS->below in the result is nonnegative. */
738 if (tree_int_cst_sign_bit (iv->step))
740 s = fold_convert (niter_type,
741 fold_build1 (NEGATE_EXPR, type, iv->step));
742 c = fold_build2 (MINUS_EXPR, niter_type,
743 fold_convert (niter_type, iv->base),
744 fold_convert (niter_type, final));
745 bounds_negate (bnds);
747 else
749 s = fold_convert (niter_type, iv->step);
750 c = fold_build2 (MINUS_EXPR, niter_type,
751 fold_convert (niter_type, final),
752 fold_convert (niter_type, iv->base));
755 mpz_init (max);
756 number_of_iterations_ne_max (max, iv->no_overflow, c, s, bnds,
757 exit_must_be_taken);
758 niter->max = widest_int::from (wi::from_mpz (niter_type, max, false),
759 TYPE_SIGN (niter_type));
760 mpz_clear (max);
762 /* First the trivial cases -- when the step is 1. */
763 if (integer_onep (s))
765 niter->niter = c;
766 return true;
769 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
770 is infinite. Otherwise, the number of iterations is
771 (inverse(s/d) * (c/d)) mod (size of mode/d). */
772 bits = num_ending_zeros (s);
773 bound = build_low_bits_mask (niter_type,
774 (TYPE_PRECISION (niter_type)
775 - tree_to_uhwi (bits)));
777 d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
778 build_int_cst (niter_type, 1), bits);
779 s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
781 if (!exit_must_be_taken)
783 /* If we cannot assume that the exit is taken eventually, record the
784 assumptions for divisibility of c. */
785 assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
786 assumption = fold_build2 (EQ_EXPR, boolean_type_node,
787 assumption, build_int_cst (niter_type, 0));
788 if (!integer_nonzerop (assumption))
789 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
790 niter->assumptions, assumption);
793 c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
794 tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
795 niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
796 return true;
799 /* Checks whether we can determine the final value of the control variable
800 of the loop with ending condition IV0 < IV1 (computed in TYPE).
801 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
802 of the step. The assumptions necessary to ensure that the computation
803 of the final value does not overflow are recorded in NITER. If we
804 find the final value, we adjust DELTA and return TRUE. Otherwise
805 we return false. BNDS bounds the value of IV1->base - IV0->base,
806 and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
807 true if we know that the exit must be taken eventually. */
809 static bool
810 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
811 struct tree_niter_desc *niter,
812 tree *delta, tree step,
813 bool exit_must_be_taken, bounds *bnds)
815 tree niter_type = TREE_TYPE (step);
816 tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
817 tree tmod;
818 mpz_t mmod;
819 tree assumption = boolean_true_node, bound, noloop;
820 bool ret = false, fv_comp_no_overflow;
821 tree type1 = type;
822 if (POINTER_TYPE_P (type))
823 type1 = sizetype;
825 if (TREE_CODE (mod) != INTEGER_CST)
826 return false;
827 if (integer_nonzerop (mod))
828 mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
829 tmod = fold_convert (type1, mod);
831 mpz_init (mmod);
832 wi::to_mpz (mod, mmod, UNSIGNED);
833 mpz_neg (mmod, mmod);
835 /* If the induction variable does not overflow and the exit is taken,
836 then the computation of the final value does not overflow. This is
837 also obviously the case if the new final value is equal to the
838 current one. Finally, we postulate this for pointer type variables,
839 as the code cannot rely on the object to that the pointer points being
840 placed at the end of the address space (and more pragmatically,
841 TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
842 if (integer_zerop (mod) || POINTER_TYPE_P (type))
843 fv_comp_no_overflow = true;
844 else if (!exit_must_be_taken)
845 fv_comp_no_overflow = false;
846 else
847 fv_comp_no_overflow =
848 (iv0->no_overflow && integer_nonzerop (iv0->step))
849 || (iv1->no_overflow && integer_nonzerop (iv1->step));
851 if (integer_nonzerop (iv0->step))
853 /* The final value of the iv is iv1->base + MOD, assuming that this
854 computation does not overflow, and that
855 iv0->base <= iv1->base + MOD. */
856 if (!fv_comp_no_overflow)
858 bound = fold_build2 (MINUS_EXPR, type1,
859 TYPE_MAX_VALUE (type1), tmod);
860 assumption = fold_build2 (LE_EXPR, boolean_type_node,
861 iv1->base, bound);
862 if (integer_zerop (assumption))
863 goto end;
865 if (mpz_cmp (mmod, bnds->below) < 0)
866 noloop = boolean_false_node;
867 else if (POINTER_TYPE_P (type))
868 noloop = fold_build2 (GT_EXPR, boolean_type_node,
869 iv0->base,
870 fold_build_pointer_plus (iv1->base, tmod));
871 else
872 noloop = fold_build2 (GT_EXPR, boolean_type_node,
873 iv0->base,
874 fold_build2 (PLUS_EXPR, type1,
875 iv1->base, tmod));
877 else
879 /* The final value of the iv is iv0->base - MOD, assuming that this
880 computation does not overflow, and that
881 iv0->base - MOD <= iv1->base. */
882 if (!fv_comp_no_overflow)
884 bound = fold_build2 (PLUS_EXPR, type1,
885 TYPE_MIN_VALUE (type1), tmod);
886 assumption = fold_build2 (GE_EXPR, boolean_type_node,
887 iv0->base, bound);
888 if (integer_zerop (assumption))
889 goto end;
891 if (mpz_cmp (mmod, bnds->below) < 0)
892 noloop = boolean_false_node;
893 else if (POINTER_TYPE_P (type))
894 noloop = fold_build2 (GT_EXPR, boolean_type_node,
895 fold_build_pointer_plus (iv0->base,
896 fold_build1 (NEGATE_EXPR,
897 type1, tmod)),
898 iv1->base);
899 else
900 noloop = fold_build2 (GT_EXPR, boolean_type_node,
901 fold_build2 (MINUS_EXPR, type1,
902 iv0->base, tmod),
903 iv1->base);
906 if (!integer_nonzerop (assumption))
907 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
908 niter->assumptions,
909 assumption);
910 if (!integer_zerop (noloop))
911 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
912 niter->may_be_zero,
913 noloop);
914 bounds_add (bnds, wi::to_widest (mod), type);
915 *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
917 ret = true;
918 end:
919 mpz_clear (mmod);
920 return ret;
923 /* Add assertions to NITER that ensure that the control variable of the loop
924 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
925 are TYPE. Returns false if we can prove that there is an overflow, true
926 otherwise. STEP is the absolute value of the step. */
928 static bool
929 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
930 struct tree_niter_desc *niter, tree step)
932 tree bound, d, assumption, diff;
933 tree niter_type = TREE_TYPE (step);
935 if (integer_nonzerop (iv0->step))
937 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
938 if (iv0->no_overflow)
939 return true;
941 /* If iv0->base is a constant, we can determine the last value before
942 overflow precisely; otherwise we conservatively assume
943 MAX - STEP + 1. */
945 if (TREE_CODE (iv0->base) == INTEGER_CST)
947 d = fold_build2 (MINUS_EXPR, niter_type,
948 fold_convert (niter_type, TYPE_MAX_VALUE (type)),
949 fold_convert (niter_type, iv0->base));
950 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
952 else
953 diff = fold_build2 (MINUS_EXPR, niter_type, step,
954 build_int_cst (niter_type, 1));
955 bound = fold_build2 (MINUS_EXPR, type,
956 TYPE_MAX_VALUE (type), fold_convert (type, diff));
957 assumption = fold_build2 (LE_EXPR, boolean_type_node,
958 iv1->base, bound);
960 else
962 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
963 if (iv1->no_overflow)
964 return true;
966 if (TREE_CODE (iv1->base) == INTEGER_CST)
968 d = fold_build2 (MINUS_EXPR, niter_type,
969 fold_convert (niter_type, iv1->base),
970 fold_convert (niter_type, TYPE_MIN_VALUE (type)));
971 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
973 else
974 diff = fold_build2 (MINUS_EXPR, niter_type, step,
975 build_int_cst (niter_type, 1));
976 bound = fold_build2 (PLUS_EXPR, type,
977 TYPE_MIN_VALUE (type), fold_convert (type, diff));
978 assumption = fold_build2 (GE_EXPR, boolean_type_node,
979 iv0->base, bound);
982 if (integer_zerop (assumption))
983 return false;
984 if (!integer_nonzerop (assumption))
985 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
986 niter->assumptions, assumption);
988 iv0->no_overflow = true;
989 iv1->no_overflow = true;
990 return true;
993 /* Add an assumption to NITER that a loop whose ending condition
994 is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
995 bounds the value of IV1->base - IV0->base. */
997 static void
998 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
999 struct tree_niter_desc *niter, bounds *bnds)
1001 tree assumption = boolean_true_node, bound, diff;
1002 tree mbz, mbzl, mbzr, type1;
1003 bool rolls_p, no_overflow_p;
1004 widest_int dstep;
1005 mpz_t mstep, max;
1007 /* We are going to compute the number of iterations as
1008 (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1009 variant of TYPE. This formula only works if
1011 -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1013 (where MAX is the maximum value of the unsigned variant of TYPE, and
1014 the computations in this formula are performed in full precision,
1015 i.e., without overflows).
1017 Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1018 we have a condition of the form iv0->base - step < iv1->base before the loop,
1019 and for loops iv0->base < iv1->base - step * i the condition
1020 iv0->base < iv1->base + step, due to loop header copying, which enable us
1021 to prove the lower bound.
1023 The upper bound is more complicated. Unless the expressions for initial
1024 and final value themselves contain enough information, we usually cannot
1025 derive it from the context. */
1027 /* First check whether the answer does not follow from the bounds we gathered
1028 before. */
1029 if (integer_nonzerop (iv0->step))
1030 dstep = wi::to_widest (iv0->step);
1031 else
1033 dstep = wi::sext (wi::to_widest (iv1->step), TYPE_PRECISION (type));
1034 dstep = -dstep;
1037 mpz_init (mstep);
1038 wi::to_mpz (dstep, mstep, UNSIGNED);
1039 mpz_neg (mstep, mstep);
1040 mpz_add_ui (mstep, mstep, 1);
1042 rolls_p = mpz_cmp (mstep, bnds->below) <= 0;
1044 mpz_init (max);
1045 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
1046 mpz_add (max, max, mstep);
1047 no_overflow_p = (mpz_cmp (bnds->up, max) <= 0
1048 /* For pointers, only values lying inside a single object
1049 can be compared or manipulated by pointer arithmetics.
1050 Gcc in general does not allow or handle objects larger
1051 than half of the address space, hence the upper bound
1052 is satisfied for pointers. */
1053 || POINTER_TYPE_P (type));
1054 mpz_clear (mstep);
1055 mpz_clear (max);
1057 if (rolls_p && no_overflow_p)
1058 return;
1060 type1 = type;
1061 if (POINTER_TYPE_P (type))
1062 type1 = sizetype;
1064 /* Now the hard part; we must formulate the assumption(s) as expressions, and
1065 we must be careful not to introduce overflow. */
1067 if (integer_nonzerop (iv0->step))
1069 diff = fold_build2 (MINUS_EXPR, type1,
1070 iv0->step, build_int_cst (type1, 1));
1072 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1073 0 address never belongs to any object, we can assume this for
1074 pointers. */
1075 if (!POINTER_TYPE_P (type))
1077 bound = fold_build2 (PLUS_EXPR, type1,
1078 TYPE_MIN_VALUE (type), diff);
1079 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1080 iv0->base, bound);
1083 /* And then we can compute iv0->base - diff, and compare it with
1084 iv1->base. */
1085 mbzl = fold_build2 (MINUS_EXPR, type1,
1086 fold_convert (type1, iv0->base), diff);
1087 mbzr = fold_convert (type1, iv1->base);
1089 else
1091 diff = fold_build2 (PLUS_EXPR, type1,
1092 iv1->step, build_int_cst (type1, 1));
1094 if (!POINTER_TYPE_P (type))
1096 bound = fold_build2 (PLUS_EXPR, type1,
1097 TYPE_MAX_VALUE (type), diff);
1098 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1099 iv1->base, bound);
1102 mbzl = fold_convert (type1, iv0->base);
1103 mbzr = fold_build2 (MINUS_EXPR, type1,
1104 fold_convert (type1, iv1->base), diff);
1107 if (!integer_nonzerop (assumption))
1108 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1109 niter->assumptions, assumption);
1110 if (!rolls_p)
1112 mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
1113 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1114 niter->may_be_zero, mbz);
1118 /* Determines number of iterations of loop whose ending condition
1119 is IV0 < IV1. TYPE is the type of the iv. The number of
1120 iterations is stored to NITER. BNDS bounds the difference
1121 IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1122 that the exit must be taken eventually. */
1124 static bool
1125 number_of_iterations_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1126 struct tree_niter_desc *niter,
1127 bool exit_must_be_taken, bounds *bnds)
1129 tree niter_type = unsigned_type_for (type);
1130 tree delta, step, s;
1131 mpz_t mstep, tmp;
1133 if (integer_nonzerop (iv0->step))
1135 niter->control = *iv0;
1136 niter->cmp = LT_EXPR;
1137 niter->bound = iv1->base;
1139 else
1141 niter->control = *iv1;
1142 niter->cmp = GT_EXPR;
1143 niter->bound = iv0->base;
1146 delta = fold_build2 (MINUS_EXPR, niter_type,
1147 fold_convert (niter_type, iv1->base),
1148 fold_convert (niter_type, iv0->base));
1150 /* First handle the special case that the step is +-1. */
1151 if ((integer_onep (iv0->step) && integer_zerop (iv1->step))
1152 || (integer_all_onesp (iv1->step) && integer_zerop (iv0->step)))
1154 /* for (i = iv0->base; i < iv1->base; i++)
1158 for (i = iv1->base; i > iv0->base; i--).
1160 In both cases # of iterations is iv1->base - iv0->base, assuming that
1161 iv1->base >= iv0->base.
1163 First try to derive a lower bound on the value of
1164 iv1->base - iv0->base, computed in full precision. If the difference
1165 is nonnegative, we are done, otherwise we must record the
1166 condition. */
1168 if (mpz_sgn (bnds->below) < 0)
1169 niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
1170 iv1->base, iv0->base);
1171 niter->niter = delta;
1172 niter->max = widest_int::from (wi::from_mpz (niter_type, bnds->up, false),
1173 TYPE_SIGN (niter_type));
1174 niter->control.no_overflow = true;
1175 return true;
1178 if (integer_nonzerop (iv0->step))
1179 step = fold_convert (niter_type, iv0->step);
1180 else
1181 step = fold_convert (niter_type,
1182 fold_build1 (NEGATE_EXPR, type, iv1->step));
1184 /* If we can determine the final value of the control iv exactly, we can
1185 transform the condition to != comparison. In particular, this will be
1186 the case if DELTA is constant. */
1187 if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step,
1188 exit_must_be_taken, bnds))
1190 affine_iv zps;
1192 zps.base = build_int_cst (niter_type, 0);
1193 zps.step = step;
1194 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1195 zps does not overflow. */
1196 zps.no_overflow = true;
1198 return number_of_iterations_ne (type, &zps, delta, niter, true, bnds);
1201 /* Make sure that the control iv does not overflow. */
1202 if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
1203 return false;
1205 /* We determine the number of iterations as (delta + step - 1) / step. For
1206 this to work, we must know that iv1->base >= iv0->base - step + 1,
1207 otherwise the loop does not roll. */
1208 assert_loop_rolls_lt (type, iv0, iv1, niter, bnds);
1210 s = fold_build2 (MINUS_EXPR, niter_type,
1211 step, build_int_cst (niter_type, 1));
1212 delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
1213 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
1215 mpz_init (mstep);
1216 mpz_init (tmp);
1217 wi::to_mpz (step, mstep, UNSIGNED);
1218 mpz_add (tmp, bnds->up, mstep);
1219 mpz_sub_ui (tmp, tmp, 1);
1220 mpz_fdiv_q (tmp, tmp, mstep);
1221 niter->max = widest_int::from (wi::from_mpz (niter_type, tmp, false),
1222 TYPE_SIGN (niter_type));
1223 mpz_clear (mstep);
1224 mpz_clear (tmp);
1226 return true;
1229 /* Determines number of iterations of loop whose ending condition
1230 is IV0 <= IV1. TYPE is the type of the iv. The number of
1231 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1232 we know that this condition must eventually become false (we derived this
1233 earlier, and possibly set NITER->assumptions to make sure this
1234 is the case). BNDS bounds the difference IV1->base - IV0->base. */
1236 static bool
1237 number_of_iterations_le (tree type, affine_iv *iv0, affine_iv *iv1,
1238 struct tree_niter_desc *niter, bool exit_must_be_taken,
1239 bounds *bnds)
1241 tree assumption;
1242 tree type1 = type;
1243 if (POINTER_TYPE_P (type))
1244 type1 = sizetype;
1246 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1247 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1248 value of the type. This we must know anyway, since if it is
1249 equal to this value, the loop rolls forever. We do not check
1250 this condition for pointer type ivs, as the code cannot rely on
1251 the object to that the pointer points being placed at the end of
1252 the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1253 not defined for pointers). */
1255 if (!exit_must_be_taken && !POINTER_TYPE_P (type))
1257 if (integer_nonzerop (iv0->step))
1258 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1259 iv1->base, TYPE_MAX_VALUE (type));
1260 else
1261 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1262 iv0->base, TYPE_MIN_VALUE (type));
1264 if (integer_zerop (assumption))
1265 return false;
1266 if (!integer_nonzerop (assumption))
1267 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1268 niter->assumptions, assumption);
1271 if (integer_nonzerop (iv0->step))
1273 if (POINTER_TYPE_P (type))
1274 iv1->base = fold_build_pointer_plus_hwi (iv1->base, 1);
1275 else
1276 iv1->base = fold_build2 (PLUS_EXPR, type1, iv1->base,
1277 build_int_cst (type1, 1));
1279 else if (POINTER_TYPE_P (type))
1280 iv0->base = fold_build_pointer_plus_hwi (iv0->base, -1);
1281 else
1282 iv0->base = fold_build2 (MINUS_EXPR, type1,
1283 iv0->base, build_int_cst (type1, 1));
1285 bounds_add (bnds, 1, type1);
1287 return number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1288 bnds);
1291 /* Dumps description of affine induction variable IV to FILE. */
1293 static void
1294 dump_affine_iv (FILE *file, affine_iv *iv)
1296 if (!integer_zerop (iv->step))
1297 fprintf (file, "[");
1299 print_generic_expr (dump_file, iv->base, TDF_SLIM);
1301 if (!integer_zerop (iv->step))
1303 fprintf (file, ", + , ");
1304 print_generic_expr (dump_file, iv->step, TDF_SLIM);
1305 fprintf (file, "]%s", iv->no_overflow ? "(no_overflow)" : "");
1309 /* Determine the number of iterations according to condition (for staying
1310 inside loop) which compares two induction variables using comparison
1311 operator CODE. The induction variable on left side of the comparison
1312 is IV0, the right-hand side is IV1. Both induction variables must have
1313 type TYPE, which must be an integer or pointer type. The steps of the
1314 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1316 LOOP is the loop whose number of iterations we are determining.
1318 ONLY_EXIT is true if we are sure this is the only way the loop could be
1319 exited (including possibly non-returning function calls, exceptions, etc.)
1320 -- in this case we can use the information whether the control induction
1321 variables can overflow or not in a more efficient way.
1323 if EVERY_ITERATION is true, we know the test is executed on every iteration.
1325 The results (number of iterations and assumptions as described in
1326 comments at struct tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1327 Returns false if it fails to determine number of iterations, true if it
1328 was determined (possibly with some assumptions). */
1330 static bool
1331 number_of_iterations_cond (struct loop *loop,
1332 tree type, affine_iv *iv0, enum tree_code code,
1333 affine_iv *iv1, struct tree_niter_desc *niter,
1334 bool only_exit, bool every_iteration)
1336 bool exit_must_be_taken = false, ret;
1337 bounds bnds;
1339 /* If the test is not executed every iteration, wrapping may make the test
1340 to pass again.
1341 TODO: the overflow case can be still used as unreliable estimate of upper
1342 bound. But we have no API to pass it down to number of iterations code
1343 and, at present, it will not use it anyway. */
1344 if (!every_iteration
1345 && (!iv0->no_overflow || !iv1->no_overflow
1346 || code == NE_EXPR || code == EQ_EXPR))
1347 return false;
1349 /* The meaning of these assumptions is this:
1350 if !assumptions
1351 then the rest of information does not have to be valid
1352 if may_be_zero then the loop does not roll, even if
1353 niter != 0. */
1354 niter->assumptions = boolean_true_node;
1355 niter->may_be_zero = boolean_false_node;
1356 niter->niter = NULL_TREE;
1357 niter->max = 0;
1358 niter->bound = NULL_TREE;
1359 niter->cmp = ERROR_MARK;
1361 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1362 the control variable is on lhs. */
1363 if (code == GE_EXPR || code == GT_EXPR
1364 || (code == NE_EXPR && integer_zerop (iv0->step)))
1366 std::swap (iv0, iv1);
1367 code = swap_tree_comparison (code);
1370 if (POINTER_TYPE_P (type))
1372 /* Comparison of pointers is undefined unless both iv0 and iv1 point
1373 to the same object. If they do, the control variable cannot wrap
1374 (as wrap around the bounds of memory will never return a pointer
1375 that would be guaranteed to point to the same object, even if we
1376 avoid undefined behavior by casting to size_t and back). */
1377 iv0->no_overflow = true;
1378 iv1->no_overflow = true;
1381 /* If the control induction variable does not overflow and the only exit
1382 from the loop is the one that we analyze, we know it must be taken
1383 eventually. */
1384 if (only_exit)
1386 if (!integer_zerop (iv0->step) && iv0->no_overflow)
1387 exit_must_be_taken = true;
1388 else if (!integer_zerop (iv1->step) && iv1->no_overflow)
1389 exit_must_be_taken = true;
1392 /* We can handle the case when neither of the sides of the comparison is
1393 invariant, provided that the test is NE_EXPR. This rarely occurs in
1394 practice, but it is simple enough to manage. */
1395 if (!integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1397 tree step_type = POINTER_TYPE_P (type) ? sizetype : type;
1398 if (code != NE_EXPR)
1399 return false;
1401 iv0->step = fold_binary_to_constant (MINUS_EXPR, step_type,
1402 iv0->step, iv1->step);
1403 iv0->no_overflow = false;
1404 iv1->step = build_int_cst (step_type, 0);
1405 iv1->no_overflow = true;
1408 /* If the result of the comparison is a constant, the loop is weird. More
1409 precise handling would be possible, but the situation is not common enough
1410 to waste time on it. */
1411 if (integer_zerop (iv0->step) && integer_zerop (iv1->step))
1412 return false;
1414 /* Ignore loops of while (i-- < 10) type. */
1415 if (code != NE_EXPR)
1417 if (iv0->step && tree_int_cst_sign_bit (iv0->step))
1418 return false;
1420 if (!integer_zerop (iv1->step) && !tree_int_cst_sign_bit (iv1->step))
1421 return false;
1424 /* If the loop exits immediately, there is nothing to do. */
1425 tree tem = fold_binary (code, boolean_type_node, iv0->base, iv1->base);
1426 if (tem && integer_zerop (tem))
1428 niter->niter = build_int_cst (unsigned_type_for (type), 0);
1429 niter->max = 0;
1430 return true;
1433 /* OK, now we know we have a senseful loop. Handle several cases, depending
1434 on what comparison operator is used. */
1435 bound_difference (loop, iv1->base, iv0->base, &bnds);
1437 if (dump_file && (dump_flags & TDF_DETAILS))
1439 fprintf (dump_file,
1440 "Analyzing # of iterations of loop %d\n", loop->num);
1442 fprintf (dump_file, " exit condition ");
1443 dump_affine_iv (dump_file, iv0);
1444 fprintf (dump_file, " %s ",
1445 code == NE_EXPR ? "!="
1446 : code == LT_EXPR ? "<"
1447 : "<=");
1448 dump_affine_iv (dump_file, iv1);
1449 fprintf (dump_file, "\n");
1451 fprintf (dump_file, " bounds on difference of bases: ");
1452 mpz_out_str (dump_file, 10, bnds.below);
1453 fprintf (dump_file, " ... ");
1454 mpz_out_str (dump_file, 10, bnds.up);
1455 fprintf (dump_file, "\n");
1458 switch (code)
1460 case NE_EXPR:
1461 gcc_assert (integer_zerop (iv1->step));
1462 ret = number_of_iterations_ne (type, iv0, iv1->base, niter,
1463 exit_must_be_taken, &bnds);
1464 break;
1466 case LT_EXPR:
1467 ret = number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1468 &bnds);
1469 break;
1471 case LE_EXPR:
1472 ret = number_of_iterations_le (type, iv0, iv1, niter, exit_must_be_taken,
1473 &bnds);
1474 break;
1476 default:
1477 gcc_unreachable ();
1480 mpz_clear (bnds.up);
1481 mpz_clear (bnds.below);
1483 if (dump_file && (dump_flags & TDF_DETAILS))
1485 if (ret)
1487 fprintf (dump_file, " result:\n");
1488 if (!integer_nonzerop (niter->assumptions))
1490 fprintf (dump_file, " under assumptions ");
1491 print_generic_expr (dump_file, niter->assumptions, TDF_SLIM);
1492 fprintf (dump_file, "\n");
1495 if (!integer_zerop (niter->may_be_zero))
1497 fprintf (dump_file, " zero if ");
1498 print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1499 fprintf (dump_file, "\n");
1502 fprintf (dump_file, " # of iterations ");
1503 print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1504 fprintf (dump_file, ", bounded by ");
1505 print_decu (niter->max, dump_file);
1506 fprintf (dump_file, "\n");
1508 else
1509 fprintf (dump_file, " failed\n\n");
1511 return ret;
1514 /* Substitute NEW for OLD in EXPR and fold the result. */
1516 static tree
1517 simplify_replace_tree (tree expr, tree old, tree new_tree)
1519 unsigned i, n;
1520 tree ret = NULL_TREE, e, se;
1522 if (!expr)
1523 return NULL_TREE;
1525 /* Do not bother to replace constants. */
1526 if (CONSTANT_CLASS_P (old))
1527 return expr;
1529 if (expr == old
1530 || operand_equal_p (expr, old, 0))
1531 return unshare_expr (new_tree);
1533 if (!EXPR_P (expr))
1534 return expr;
1536 n = TREE_OPERAND_LENGTH (expr);
1537 for (i = 0; i < n; i++)
1539 e = TREE_OPERAND (expr, i);
1540 se = simplify_replace_tree (e, old, new_tree);
1541 if (e == se)
1542 continue;
1544 if (!ret)
1545 ret = copy_node (expr);
1547 TREE_OPERAND (ret, i) = se;
1550 return (ret ? fold (ret) : expr);
1553 /* Expand definitions of ssa names in EXPR as long as they are simple
1554 enough, and return the new expression. If STOP is specified, stop
1555 expanding if EXPR equals to it. */
1557 tree
1558 expand_simple_operations (tree expr, tree stop)
1560 unsigned i, n;
1561 tree ret = NULL_TREE, e, ee, e1;
1562 enum tree_code code;
1563 gimple stmt;
1565 if (expr == NULL_TREE)
1566 return expr;
1568 if (is_gimple_min_invariant (expr))
1569 return expr;
1571 code = TREE_CODE (expr);
1572 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1574 n = TREE_OPERAND_LENGTH (expr);
1575 for (i = 0; i < n; i++)
1577 e = TREE_OPERAND (expr, i);
1578 ee = expand_simple_operations (e, stop);
1579 if (e == ee)
1580 continue;
1582 if (!ret)
1583 ret = copy_node (expr);
1585 TREE_OPERAND (ret, i) = ee;
1588 if (!ret)
1589 return expr;
1591 fold_defer_overflow_warnings ();
1592 ret = fold (ret);
1593 fold_undefer_and_ignore_overflow_warnings ();
1594 return ret;
1597 /* Stop if it's not ssa name or the one we don't want to expand. */
1598 if (TREE_CODE (expr) != SSA_NAME || expr == stop)
1599 return expr;
1601 stmt = SSA_NAME_DEF_STMT (expr);
1602 if (gimple_code (stmt) == GIMPLE_PHI)
1604 basic_block src, dest;
1606 if (gimple_phi_num_args (stmt) != 1)
1607 return expr;
1608 e = PHI_ARG_DEF (stmt, 0);
1610 /* Avoid propagating through loop exit phi nodes, which
1611 could break loop-closed SSA form restrictions. */
1612 dest = gimple_bb (stmt);
1613 src = single_pred (dest);
1614 if (TREE_CODE (e) == SSA_NAME
1615 && src->loop_father != dest->loop_father)
1616 return expr;
1618 return expand_simple_operations (e, stop);
1620 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1621 return expr;
1623 /* Avoid expanding to expressions that contain SSA names that need
1624 to take part in abnormal coalescing. */
1625 ssa_op_iter iter;
1626 FOR_EACH_SSA_TREE_OPERAND (e, stmt, iter, SSA_OP_USE)
1627 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e))
1628 return expr;
1630 e = gimple_assign_rhs1 (stmt);
1631 code = gimple_assign_rhs_code (stmt);
1632 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1634 if (is_gimple_min_invariant (e))
1635 return e;
1637 if (code == SSA_NAME)
1638 return expand_simple_operations (e, stop);
1640 return expr;
1643 switch (code)
1645 CASE_CONVERT:
1646 /* Casts are simple. */
1647 ee = expand_simple_operations (e, stop);
1648 return fold_build1 (code, TREE_TYPE (expr), ee);
1650 case PLUS_EXPR:
1651 case MINUS_EXPR:
1652 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr))
1653 && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr)))
1654 return expr;
1655 /* Fallthru. */
1656 case POINTER_PLUS_EXPR:
1657 /* And increments and decrements by a constant are simple. */
1658 e1 = gimple_assign_rhs2 (stmt);
1659 if (!is_gimple_min_invariant (e1))
1660 return expr;
1662 ee = expand_simple_operations (e, stop);
1663 return fold_build2 (code, TREE_TYPE (expr), ee, e1);
1665 default:
1666 return expr;
1670 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1671 expression (or EXPR unchanged, if no simplification was possible). */
1673 static tree
1674 tree_simplify_using_condition_1 (tree cond, tree expr)
1676 bool changed;
1677 tree e, te, e0, e1, e2, notcond;
1678 enum tree_code code = TREE_CODE (expr);
1680 if (code == INTEGER_CST)
1681 return expr;
1683 if (code == TRUTH_OR_EXPR
1684 || code == TRUTH_AND_EXPR
1685 || code == COND_EXPR)
1687 changed = false;
1689 e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
1690 if (TREE_OPERAND (expr, 0) != e0)
1691 changed = true;
1693 e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
1694 if (TREE_OPERAND (expr, 1) != e1)
1695 changed = true;
1697 if (code == COND_EXPR)
1699 e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
1700 if (TREE_OPERAND (expr, 2) != e2)
1701 changed = true;
1703 else
1704 e2 = NULL_TREE;
1706 if (changed)
1708 if (code == COND_EXPR)
1709 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1710 else
1711 expr = fold_build2 (code, boolean_type_node, e0, e1);
1714 return expr;
1717 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
1718 propagation, and vice versa. Fold does not handle this, since it is
1719 considered too expensive. */
1720 if (TREE_CODE (cond) == EQ_EXPR)
1722 e0 = TREE_OPERAND (cond, 0);
1723 e1 = TREE_OPERAND (cond, 1);
1725 /* We know that e0 == e1. Check whether we cannot simplify expr
1726 using this fact. */
1727 e = simplify_replace_tree (expr, e0, e1);
1728 if (integer_zerop (e) || integer_nonzerop (e))
1729 return e;
1731 e = simplify_replace_tree (expr, e1, e0);
1732 if (integer_zerop (e) || integer_nonzerop (e))
1733 return e;
1735 if (TREE_CODE (expr) == EQ_EXPR)
1737 e0 = TREE_OPERAND (expr, 0);
1738 e1 = TREE_OPERAND (expr, 1);
1740 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
1741 e = simplify_replace_tree (cond, e0, e1);
1742 if (integer_zerop (e))
1743 return e;
1744 e = simplify_replace_tree (cond, e1, e0);
1745 if (integer_zerop (e))
1746 return e;
1748 if (TREE_CODE (expr) == NE_EXPR)
1750 e0 = TREE_OPERAND (expr, 0);
1751 e1 = TREE_OPERAND (expr, 1);
1753 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
1754 e = simplify_replace_tree (cond, e0, e1);
1755 if (integer_zerop (e))
1756 return boolean_true_node;
1757 e = simplify_replace_tree (cond, e1, e0);
1758 if (integer_zerop (e))
1759 return boolean_true_node;
1762 te = expand_simple_operations (expr);
1764 /* Check whether COND ==> EXPR. */
1765 notcond = invert_truthvalue (cond);
1766 e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, te);
1767 if (e && integer_nonzerop (e))
1768 return e;
1770 /* Check whether COND ==> not EXPR. */
1771 e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, te);
1772 if (e && integer_zerop (e))
1773 return e;
1775 return expr;
1778 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1779 expression (or EXPR unchanged, if no simplification was possible).
1780 Wrapper around tree_simplify_using_condition_1 that ensures that chains
1781 of simple operations in definitions of ssa names in COND are expanded,
1782 so that things like casts or incrementing the value of the bound before
1783 the loop do not cause us to fail. */
1785 static tree
1786 tree_simplify_using_condition (tree cond, tree expr)
1788 cond = expand_simple_operations (cond);
1790 return tree_simplify_using_condition_1 (cond, expr);
1793 /* Tries to simplify EXPR using the conditions on entry to LOOP.
1794 Returns the simplified expression (or EXPR unchanged, if no
1795 simplification was possible).*/
1797 static tree
1798 simplify_using_initial_conditions (struct loop *loop, tree expr)
1800 edge e;
1801 basic_block bb;
1802 gimple stmt;
1803 tree cond;
1804 int cnt = 0;
1806 if (TREE_CODE (expr) == INTEGER_CST)
1807 return expr;
1809 /* Limit walking the dominators to avoid quadraticness in
1810 the number of BBs times the number of loops in degenerate
1811 cases. */
1812 for (bb = loop->header;
1813 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
1814 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
1816 if (!single_pred_p (bb))
1817 continue;
1818 e = single_pred_edge (bb);
1820 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
1821 continue;
1823 stmt = last_stmt (e->src);
1824 cond = fold_build2 (gimple_cond_code (stmt),
1825 boolean_type_node,
1826 gimple_cond_lhs (stmt),
1827 gimple_cond_rhs (stmt));
1828 if (e->flags & EDGE_FALSE_VALUE)
1829 cond = invert_truthvalue (cond);
1830 expr = tree_simplify_using_condition (cond, expr);
1831 ++cnt;
1834 return expr;
1837 /* Tries to simplify EXPR using the evolutions of the loop invariants
1838 in the superloops of LOOP. Returns the simplified expression
1839 (or EXPR unchanged, if no simplification was possible). */
1841 static tree
1842 simplify_using_outer_evolutions (struct loop *loop, tree expr)
1844 enum tree_code code = TREE_CODE (expr);
1845 bool changed;
1846 tree e, e0, e1, e2;
1848 if (is_gimple_min_invariant (expr))
1849 return expr;
1851 if (code == TRUTH_OR_EXPR
1852 || code == TRUTH_AND_EXPR
1853 || code == COND_EXPR)
1855 changed = false;
1857 e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
1858 if (TREE_OPERAND (expr, 0) != e0)
1859 changed = true;
1861 e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
1862 if (TREE_OPERAND (expr, 1) != e1)
1863 changed = true;
1865 if (code == COND_EXPR)
1867 e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
1868 if (TREE_OPERAND (expr, 2) != e2)
1869 changed = true;
1871 else
1872 e2 = NULL_TREE;
1874 if (changed)
1876 if (code == COND_EXPR)
1877 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1878 else
1879 expr = fold_build2 (code, boolean_type_node, e0, e1);
1882 return expr;
1885 e = instantiate_parameters (loop, expr);
1886 if (is_gimple_min_invariant (e))
1887 return e;
1889 return expr;
1892 /* Returns true if EXIT is the only possible exit from LOOP. */
1894 bool
1895 loop_only_exit_p (const struct loop *loop, const_edge exit)
1897 basic_block *body;
1898 gimple_stmt_iterator bsi;
1899 unsigned i;
1900 gimple call;
1902 if (exit != single_exit (loop))
1903 return false;
1905 body = get_loop_body (loop);
1906 for (i = 0; i < loop->num_nodes; i++)
1908 for (bsi = gsi_start_bb (body[i]); !gsi_end_p (bsi); gsi_next (&bsi))
1910 call = gsi_stmt (bsi);
1911 if (gimple_code (call) != GIMPLE_CALL)
1912 continue;
1914 if (gimple_has_side_effects (call))
1916 free (body);
1917 return false;
1922 free (body);
1923 return true;
1926 /* Stores description of number of iterations of LOOP derived from
1927 EXIT (an exit edge of the LOOP) in NITER. Returns true if some
1928 useful information could be derived (and fields of NITER has
1929 meaning described in comments at struct tree_niter_desc
1930 declaration), false otherwise. If WARN is true and
1931 -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
1932 potentially unsafe assumptions.
1933 When EVERY_ITERATION is true, only tests that are known to be executed
1934 every iteration are considered (i.e. only test that alone bounds the loop).
1937 bool
1938 number_of_iterations_exit (struct loop *loop, edge exit,
1939 struct tree_niter_desc *niter,
1940 bool warn, bool every_iteration)
1942 gimple last;
1943 gcond *stmt;
1944 tree type;
1945 tree op0, op1;
1946 enum tree_code code;
1947 affine_iv iv0, iv1;
1948 bool safe;
1950 safe = dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src);
1952 if (every_iteration && !safe)
1953 return false;
1955 niter->assumptions = boolean_false_node;
1956 niter->control.base = NULL_TREE;
1957 niter->control.step = NULL_TREE;
1958 niter->control.no_overflow = false;
1959 last = last_stmt (exit->src);
1960 if (!last)
1961 return false;
1962 stmt = dyn_cast <gcond *> (last);
1963 if (!stmt)
1964 return false;
1966 /* We want the condition for staying inside loop. */
1967 code = gimple_cond_code (stmt);
1968 if (exit->flags & EDGE_TRUE_VALUE)
1969 code = invert_tree_comparison (code, false);
1971 switch (code)
1973 case GT_EXPR:
1974 case GE_EXPR:
1975 case LT_EXPR:
1976 case LE_EXPR:
1977 case NE_EXPR:
1978 break;
1980 default:
1981 return false;
1984 op0 = gimple_cond_lhs (stmt);
1985 op1 = gimple_cond_rhs (stmt);
1986 type = TREE_TYPE (op0);
1988 if (TREE_CODE (type) != INTEGER_TYPE
1989 && !POINTER_TYPE_P (type))
1990 return false;
1992 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, false))
1993 return false;
1994 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, false))
1995 return false;
1997 /* We don't want to see undefined signed overflow warnings while
1998 computing the number of iterations. */
1999 fold_defer_overflow_warnings ();
2001 iv0.base = expand_simple_operations (iv0.base);
2002 iv1.base = expand_simple_operations (iv1.base);
2003 if (!number_of_iterations_cond (loop, type, &iv0, code, &iv1, niter,
2004 loop_only_exit_p (loop, exit), safe))
2006 fold_undefer_and_ignore_overflow_warnings ();
2007 return false;
2010 if (optimize >= 3)
2012 niter->assumptions = simplify_using_outer_evolutions (loop,
2013 niter->assumptions);
2014 niter->may_be_zero = simplify_using_outer_evolutions (loop,
2015 niter->may_be_zero);
2016 niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
2019 niter->assumptions
2020 = simplify_using_initial_conditions (loop,
2021 niter->assumptions);
2022 niter->may_be_zero
2023 = simplify_using_initial_conditions (loop,
2024 niter->may_be_zero);
2026 fold_undefer_and_ignore_overflow_warnings ();
2028 /* If NITER has simplified into a constant, update MAX. */
2029 if (TREE_CODE (niter->niter) == INTEGER_CST)
2030 niter->max = wi::to_widest (niter->niter);
2032 if (integer_onep (niter->assumptions))
2033 return true;
2035 /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
2036 But if we can prove that there is overflow or some other source of weird
2037 behavior, ignore the loop even with -funsafe-loop-optimizations. */
2038 if (integer_zerop (niter->assumptions) || !single_exit (loop))
2039 return false;
2041 if (flag_unsafe_loop_optimizations)
2042 niter->assumptions = boolean_true_node;
2044 if (warn)
2046 const char *wording;
2047 location_t loc = gimple_location (stmt);
2049 /* We can provide a more specific warning if one of the operator is
2050 constant and the other advances by +1 or -1. */
2051 if (!integer_zerop (iv1.step)
2052 ? (integer_zerop (iv0.step)
2053 && (integer_onep (iv1.step) || integer_all_onesp (iv1.step)))
2054 : (integer_onep (iv0.step) || integer_all_onesp (iv0.step)))
2055 wording =
2056 flag_unsafe_loop_optimizations
2057 ? N_("assuming that the loop is not infinite")
2058 : N_("cannot optimize possibly infinite loops");
2059 else
2060 wording =
2061 flag_unsafe_loop_optimizations
2062 ? N_("assuming that the loop counter does not overflow")
2063 : N_("cannot optimize loop, the loop counter may overflow");
2065 warning_at ((LOCATION_LINE (loc) > 0) ? loc : input_location,
2066 OPT_Wunsafe_loop_optimizations, "%s", gettext (wording));
2069 return flag_unsafe_loop_optimizations;
2072 /* Try to determine the number of iterations of LOOP. If we succeed,
2073 expression giving number of iterations is returned and *EXIT is
2074 set to the edge from that the information is obtained. Otherwise
2075 chrec_dont_know is returned. */
2077 tree
2078 find_loop_niter (struct loop *loop, edge *exit)
2080 unsigned i;
2081 vec<edge> exits = get_loop_exit_edges (loop);
2082 edge ex;
2083 tree niter = NULL_TREE, aniter;
2084 struct tree_niter_desc desc;
2086 *exit = NULL;
2087 FOR_EACH_VEC_ELT (exits, i, ex)
2089 if (!number_of_iterations_exit (loop, ex, &desc, false))
2090 continue;
2092 if (integer_nonzerop (desc.may_be_zero))
2094 /* We exit in the first iteration through this exit.
2095 We won't find anything better. */
2096 niter = build_int_cst (unsigned_type_node, 0);
2097 *exit = ex;
2098 break;
2101 if (!integer_zerop (desc.may_be_zero))
2102 continue;
2104 aniter = desc.niter;
2106 if (!niter)
2108 /* Nothing recorded yet. */
2109 niter = aniter;
2110 *exit = ex;
2111 continue;
2114 /* Prefer constants, the lower the better. */
2115 if (TREE_CODE (aniter) != INTEGER_CST)
2116 continue;
2118 if (TREE_CODE (niter) != INTEGER_CST)
2120 niter = aniter;
2121 *exit = ex;
2122 continue;
2125 if (tree_int_cst_lt (aniter, niter))
2127 niter = aniter;
2128 *exit = ex;
2129 continue;
2132 exits.release ();
2134 return niter ? niter : chrec_dont_know;
2137 /* Return true if loop is known to have bounded number of iterations. */
2139 bool
2140 finite_loop_p (struct loop *loop)
2142 widest_int nit;
2143 int flags;
2145 if (flag_unsafe_loop_optimizations)
2146 return true;
2147 flags = flags_from_decl_or_type (current_function_decl);
2148 if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
2150 if (dump_file && (dump_flags & TDF_DETAILS))
2151 fprintf (dump_file, "Found loop %i to be finite: it is within pure or const function.\n",
2152 loop->num);
2153 return true;
2156 if (loop->any_upper_bound
2157 || max_loop_iterations (loop, &nit))
2159 if (dump_file && (dump_flags & TDF_DETAILS))
2160 fprintf (dump_file, "Found loop %i to be finite: upper bound found.\n",
2161 loop->num);
2162 return true;
2164 return false;
2169 Analysis of a number of iterations of a loop by a brute-force evaluation.
2173 /* Bound on the number of iterations we try to evaluate. */
2175 #define MAX_ITERATIONS_TO_TRACK \
2176 ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
2178 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
2179 result by a chain of operations such that all but exactly one of their
2180 operands are constants. */
2182 static gphi *
2183 chain_of_csts_start (struct loop *loop, tree x)
2185 gimple stmt = SSA_NAME_DEF_STMT (x);
2186 tree use;
2187 basic_block bb = gimple_bb (stmt);
2188 enum tree_code code;
2190 if (!bb
2191 || !flow_bb_inside_loop_p (loop, bb))
2192 return NULL;
2194 if (gimple_code (stmt) == GIMPLE_PHI)
2196 if (bb == loop->header)
2197 return as_a <gphi *> (stmt);
2199 return NULL;
2202 if (gimple_code (stmt) != GIMPLE_ASSIGN
2203 || gimple_assign_rhs_class (stmt) == GIMPLE_TERNARY_RHS)
2204 return NULL;
2206 code = gimple_assign_rhs_code (stmt);
2207 if (gimple_references_memory_p (stmt)
2208 || TREE_CODE_CLASS (code) == tcc_reference
2209 || (code == ADDR_EXPR
2210 && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
2211 return NULL;
2213 use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
2214 if (use == NULL_TREE)
2215 return NULL;
2217 return chain_of_csts_start (loop, use);
2220 /* Determines whether the expression X is derived from a result of a phi node
2221 in header of LOOP such that
2223 * the derivation of X consists only from operations with constants
2224 * the initial value of the phi node is constant
2225 * the value of the phi node in the next iteration can be derived from the
2226 value in the current iteration by a chain of operations with constants.
2228 If such phi node exists, it is returned, otherwise NULL is returned. */
2230 static gphi *
2231 get_base_for (struct loop *loop, tree x)
2233 gphi *phi;
2234 tree init, next;
2236 if (is_gimple_min_invariant (x))
2237 return NULL;
2239 phi = chain_of_csts_start (loop, x);
2240 if (!phi)
2241 return NULL;
2243 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2244 next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2246 if (TREE_CODE (next) != SSA_NAME)
2247 return NULL;
2249 if (!is_gimple_min_invariant (init))
2250 return NULL;
2252 if (chain_of_csts_start (loop, next) != phi)
2253 return NULL;
2255 return phi;
2258 /* Given an expression X, then
2260 * if X is NULL_TREE, we return the constant BASE.
2261 * otherwise X is a SSA name, whose value in the considered loop is derived
2262 by a chain of operations with constant from a result of a phi node in
2263 the header of the loop. Then we return value of X when the value of the
2264 result of this phi node is given by the constant BASE. */
2266 static tree
2267 get_val_for (tree x, tree base)
2269 gimple stmt;
2271 gcc_checking_assert (is_gimple_min_invariant (base));
2273 if (!x)
2274 return base;
2276 stmt = SSA_NAME_DEF_STMT (x);
2277 if (gimple_code (stmt) == GIMPLE_PHI)
2278 return base;
2280 gcc_checking_assert (is_gimple_assign (stmt));
2282 /* STMT must be either an assignment of a single SSA name or an
2283 expression involving an SSA name and a constant. Try to fold that
2284 expression using the value for the SSA name. */
2285 if (gimple_assign_ssa_name_copy_p (stmt))
2286 return get_val_for (gimple_assign_rhs1 (stmt), base);
2287 else if (gimple_assign_rhs_class (stmt) == GIMPLE_UNARY_RHS
2288 && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
2290 return fold_build1 (gimple_assign_rhs_code (stmt),
2291 gimple_expr_type (stmt),
2292 get_val_for (gimple_assign_rhs1 (stmt), base));
2294 else if (gimple_assign_rhs_class (stmt) == GIMPLE_BINARY_RHS)
2296 tree rhs1 = gimple_assign_rhs1 (stmt);
2297 tree rhs2 = gimple_assign_rhs2 (stmt);
2298 if (TREE_CODE (rhs1) == SSA_NAME)
2299 rhs1 = get_val_for (rhs1, base);
2300 else if (TREE_CODE (rhs2) == SSA_NAME)
2301 rhs2 = get_val_for (rhs2, base);
2302 else
2303 gcc_unreachable ();
2304 return fold_build2 (gimple_assign_rhs_code (stmt),
2305 gimple_expr_type (stmt), rhs1, rhs2);
2307 else
2308 gcc_unreachable ();
2312 /* Tries to count the number of iterations of LOOP till it exits by EXIT
2313 by brute force -- i.e. by determining the value of the operands of the
2314 condition at EXIT in first few iterations of the loop (assuming that
2315 these values are constant) and determining the first one in that the
2316 condition is not satisfied. Returns the constant giving the number
2317 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
2319 tree
2320 loop_niter_by_eval (struct loop *loop, edge exit)
2322 tree acnd;
2323 tree op[2], val[2], next[2], aval[2];
2324 gphi *phi;
2325 gimple cond;
2326 unsigned i, j;
2327 enum tree_code cmp;
2329 cond = last_stmt (exit->src);
2330 if (!cond || gimple_code (cond) != GIMPLE_COND)
2331 return chrec_dont_know;
2333 cmp = gimple_cond_code (cond);
2334 if (exit->flags & EDGE_TRUE_VALUE)
2335 cmp = invert_tree_comparison (cmp, false);
2337 switch (cmp)
2339 case EQ_EXPR:
2340 case NE_EXPR:
2341 case GT_EXPR:
2342 case GE_EXPR:
2343 case LT_EXPR:
2344 case LE_EXPR:
2345 op[0] = gimple_cond_lhs (cond);
2346 op[1] = gimple_cond_rhs (cond);
2347 break;
2349 default:
2350 return chrec_dont_know;
2353 for (j = 0; j < 2; j++)
2355 if (is_gimple_min_invariant (op[j]))
2357 val[j] = op[j];
2358 next[j] = NULL_TREE;
2359 op[j] = NULL_TREE;
2361 else
2363 phi = get_base_for (loop, op[j]);
2364 if (!phi)
2365 return chrec_dont_know;
2366 val[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2367 next[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2371 /* Don't issue signed overflow warnings. */
2372 fold_defer_overflow_warnings ();
2374 for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
2376 for (j = 0; j < 2; j++)
2377 aval[j] = get_val_for (op[j], val[j]);
2379 acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
2380 if (acnd && integer_zerop (acnd))
2382 fold_undefer_and_ignore_overflow_warnings ();
2383 if (dump_file && (dump_flags & TDF_DETAILS))
2384 fprintf (dump_file,
2385 "Proved that loop %d iterates %d times using brute force.\n",
2386 loop->num, i);
2387 return build_int_cst (unsigned_type_node, i);
2390 for (j = 0; j < 2; j++)
2392 val[j] = get_val_for (next[j], val[j]);
2393 if (!is_gimple_min_invariant (val[j]))
2395 fold_undefer_and_ignore_overflow_warnings ();
2396 return chrec_dont_know;
2401 fold_undefer_and_ignore_overflow_warnings ();
2403 return chrec_dont_know;
2406 /* Finds the exit of the LOOP by that the loop exits after a constant
2407 number of iterations and stores the exit edge to *EXIT. The constant
2408 giving the number of iterations of LOOP is returned. The number of
2409 iterations is determined using loop_niter_by_eval (i.e. by brute force
2410 evaluation). If we are unable to find the exit for that loop_niter_by_eval
2411 determines the number of iterations, chrec_dont_know is returned. */
2413 tree
2414 find_loop_niter_by_eval (struct loop *loop, edge *exit)
2416 unsigned i;
2417 vec<edge> exits = get_loop_exit_edges (loop);
2418 edge ex;
2419 tree niter = NULL_TREE, aniter;
2421 *exit = NULL;
2423 /* Loops with multiple exits are expensive to handle and less important. */
2424 if (!flag_expensive_optimizations
2425 && exits.length () > 1)
2427 exits.release ();
2428 return chrec_dont_know;
2431 FOR_EACH_VEC_ELT (exits, i, ex)
2433 if (!just_once_each_iteration_p (loop, ex->src))
2434 continue;
2436 aniter = loop_niter_by_eval (loop, ex);
2437 if (chrec_contains_undetermined (aniter))
2438 continue;
2440 if (niter
2441 && !tree_int_cst_lt (aniter, niter))
2442 continue;
2444 niter = aniter;
2445 *exit = ex;
2447 exits.release ();
2449 return niter ? niter : chrec_dont_know;
2454 Analysis of upper bounds on number of iterations of a loop.
2458 static widest_int derive_constant_upper_bound_ops (tree, tree,
2459 enum tree_code, tree);
2461 /* Returns a constant upper bound on the value of the right-hand side of
2462 an assignment statement STMT. */
2464 static widest_int
2465 derive_constant_upper_bound_assign (gimple stmt)
2467 enum tree_code code = gimple_assign_rhs_code (stmt);
2468 tree op0 = gimple_assign_rhs1 (stmt);
2469 tree op1 = gimple_assign_rhs2 (stmt);
2471 return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt)),
2472 op0, code, op1);
2475 /* Returns a constant upper bound on the value of expression VAL. VAL
2476 is considered to be unsigned. If its type is signed, its value must
2477 be nonnegative. */
2479 static widest_int
2480 derive_constant_upper_bound (tree val)
2482 enum tree_code code;
2483 tree op0, op1;
2485 extract_ops_from_tree (val, &code, &op0, &op1);
2486 return derive_constant_upper_bound_ops (TREE_TYPE (val), op0, code, op1);
2489 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
2490 whose type is TYPE. The expression is considered to be unsigned. If
2491 its type is signed, its value must be nonnegative. */
2493 static widest_int
2494 derive_constant_upper_bound_ops (tree type, tree op0,
2495 enum tree_code code, tree op1)
2497 tree subtype, maxt;
2498 widest_int bnd, max, mmax, cst;
2499 gimple stmt;
2501 if (INTEGRAL_TYPE_P (type))
2502 maxt = TYPE_MAX_VALUE (type);
2503 else
2504 maxt = upper_bound_in_type (type, type);
2506 max = wi::to_widest (maxt);
2508 switch (code)
2510 case INTEGER_CST:
2511 return wi::to_widest (op0);
2513 CASE_CONVERT:
2514 subtype = TREE_TYPE (op0);
2515 if (!TYPE_UNSIGNED (subtype)
2516 /* If TYPE is also signed, the fact that VAL is nonnegative implies
2517 that OP0 is nonnegative. */
2518 && TYPE_UNSIGNED (type)
2519 && !tree_expr_nonnegative_p (op0))
2521 /* If we cannot prove that the casted expression is nonnegative,
2522 we cannot establish more useful upper bound than the precision
2523 of the type gives us. */
2524 return max;
2527 /* We now know that op0 is an nonnegative value. Try deriving an upper
2528 bound for it. */
2529 bnd = derive_constant_upper_bound (op0);
2531 /* If the bound does not fit in TYPE, max. value of TYPE could be
2532 attained. */
2533 if (wi::ltu_p (max, bnd))
2534 return max;
2536 return bnd;
2538 case PLUS_EXPR:
2539 case POINTER_PLUS_EXPR:
2540 case MINUS_EXPR:
2541 if (TREE_CODE (op1) != INTEGER_CST
2542 || !tree_expr_nonnegative_p (op0))
2543 return max;
2545 /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
2546 choose the most logical way how to treat this constant regardless
2547 of the signedness of the type. */
2548 cst = wi::sext (wi::to_widest (op1), TYPE_PRECISION (type));
2549 if (code != MINUS_EXPR)
2550 cst = -cst;
2552 bnd = derive_constant_upper_bound (op0);
2554 if (wi::neg_p (cst))
2556 cst = -cst;
2557 /* Avoid CST == 0x80000... */
2558 if (wi::neg_p (cst))
2559 return max;
2561 /* OP0 + CST. We need to check that
2562 BND <= MAX (type) - CST. */
2564 mmax -= cst;
2565 if (wi::ltu_p (bnd, max))
2566 return max;
2568 return bnd + cst;
2570 else
2572 /* OP0 - CST, where CST >= 0.
2574 If TYPE is signed, we have already verified that OP0 >= 0, and we
2575 know that the result is nonnegative. This implies that
2576 VAL <= BND - CST.
2578 If TYPE is unsigned, we must additionally know that OP0 >= CST,
2579 otherwise the operation underflows.
2582 /* This should only happen if the type is unsigned; however, for
2583 buggy programs that use overflowing signed arithmetics even with
2584 -fno-wrapv, this condition may also be true for signed values. */
2585 if (wi::ltu_p (bnd, cst))
2586 return max;
2588 if (TYPE_UNSIGNED (type))
2590 tree tem = fold_binary (GE_EXPR, boolean_type_node, op0,
2591 wide_int_to_tree (type, cst));
2592 if (!tem || integer_nonzerop (tem))
2593 return max;
2596 bnd -= cst;
2599 return bnd;
2601 case FLOOR_DIV_EXPR:
2602 case EXACT_DIV_EXPR:
2603 if (TREE_CODE (op1) != INTEGER_CST
2604 || tree_int_cst_sign_bit (op1))
2605 return max;
2607 bnd = derive_constant_upper_bound (op0);
2608 return wi::udiv_floor (bnd, wi::to_widest (op1));
2610 case BIT_AND_EXPR:
2611 if (TREE_CODE (op1) != INTEGER_CST
2612 || tree_int_cst_sign_bit (op1))
2613 return max;
2614 return wi::to_widest (op1);
2616 case SSA_NAME:
2617 stmt = SSA_NAME_DEF_STMT (op0);
2618 if (gimple_code (stmt) != GIMPLE_ASSIGN
2619 || gimple_assign_lhs (stmt) != op0)
2620 return max;
2621 return derive_constant_upper_bound_assign (stmt);
2623 default:
2624 return max;
2628 /* Emit a -Waggressive-loop-optimizations warning if needed. */
2630 static void
2631 do_warn_aggressive_loop_optimizations (struct loop *loop,
2632 widest_int i_bound, gimple stmt)
2634 /* Don't warn if the loop doesn't have known constant bound. */
2635 if (!loop->nb_iterations
2636 || TREE_CODE (loop->nb_iterations) != INTEGER_CST
2637 || !warn_aggressive_loop_optimizations
2638 /* To avoid warning multiple times for the same loop,
2639 only start warning when we preserve loops. */
2640 || (cfun->curr_properties & PROP_loops) == 0
2641 /* Only warn once per loop. */
2642 || loop->warned_aggressive_loop_optimizations
2643 /* Only warn if undefined behavior gives us lower estimate than the
2644 known constant bound. */
2645 || wi::cmpu (i_bound, wi::to_widest (loop->nb_iterations)) >= 0
2646 /* And undefined behavior happens unconditionally. */
2647 || !dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (stmt)))
2648 return;
2650 edge e = single_exit (loop);
2651 if (e == NULL)
2652 return;
2654 gimple estmt = last_stmt (e->src);
2655 if (warning_at (gimple_location (stmt), OPT_Waggressive_loop_optimizations,
2656 "iteration %E invokes undefined behavior",
2657 wide_int_to_tree (TREE_TYPE (loop->nb_iterations),
2658 i_bound)))
2659 inform (gimple_location (estmt), "containing loop");
2660 loop->warned_aggressive_loop_optimizations = true;
2663 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
2664 is true if the loop is exited immediately after STMT, and this exit
2665 is taken at last when the STMT is executed BOUND + 1 times.
2666 REALISTIC is true if BOUND is expected to be close to the real number
2667 of iterations. UPPER is true if we are sure the loop iterates at most
2668 BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
2670 static void
2671 record_estimate (struct loop *loop, tree bound, const widest_int &i_bound,
2672 gimple at_stmt, bool is_exit, bool realistic, bool upper)
2674 widest_int delta;
2676 if (dump_file && (dump_flags & TDF_DETAILS))
2678 fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
2679 print_gimple_stmt (dump_file, at_stmt, 0, TDF_SLIM);
2680 fprintf (dump_file, " is %sexecuted at most ",
2681 upper ? "" : "probably ");
2682 print_generic_expr (dump_file, bound, TDF_SLIM);
2683 fprintf (dump_file, " (bounded by ");
2684 print_decu (i_bound, dump_file);
2685 fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
2688 /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
2689 real number of iterations. */
2690 if (TREE_CODE (bound) != INTEGER_CST)
2691 realistic = false;
2692 else
2693 gcc_checking_assert (i_bound == wi::to_widest (bound));
2694 if (!upper && !realistic)
2695 return;
2697 /* If we have a guaranteed upper bound, record it in the appropriate
2698 list, unless this is an !is_exit bound (i.e. undefined behavior in
2699 at_stmt) in a loop with known constant number of iterations. */
2700 if (upper
2701 && (is_exit
2702 || loop->nb_iterations == NULL_TREE
2703 || TREE_CODE (loop->nb_iterations) != INTEGER_CST))
2705 struct nb_iter_bound *elt = ggc_alloc<nb_iter_bound> ();
2707 elt->bound = i_bound;
2708 elt->stmt = at_stmt;
2709 elt->is_exit = is_exit;
2710 elt->next = loop->bounds;
2711 loop->bounds = elt;
2714 /* If statement is executed on every path to the loop latch, we can directly
2715 infer the upper bound on the # of iterations of the loop. */
2716 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (at_stmt)))
2717 return;
2719 /* Update the number of iteration estimates according to the bound.
2720 If at_stmt is an exit then the loop latch is executed at most BOUND times,
2721 otherwise it can be executed BOUND + 1 times. We will lower the estimate
2722 later if such statement must be executed on last iteration */
2723 if (is_exit)
2724 delta = 0;
2725 else
2726 delta = 1;
2727 widest_int new_i_bound = i_bound + delta;
2729 /* If an overflow occurred, ignore the result. */
2730 if (wi::ltu_p (new_i_bound, delta))
2731 return;
2733 if (upper && !is_exit)
2734 do_warn_aggressive_loop_optimizations (loop, new_i_bound, at_stmt);
2735 record_niter_bound (loop, new_i_bound, realistic, upper);
2738 /* Records the control iv analyzed in NITER for LOOP if the iv is valid
2739 and doesn't overflow. */
2741 static void
2742 record_control_iv (struct loop *loop, struct tree_niter_desc *niter)
2744 struct control_iv *iv;
2746 if (!niter->control.base || !niter->control.step)
2747 return;
2749 if (!integer_onep (niter->assumptions) || !niter->control.no_overflow)
2750 return;
2752 iv = ggc_alloc<control_iv> ();
2753 iv->base = niter->control.base;
2754 iv->step = niter->control.step;
2755 iv->next = loop->control_ivs;
2756 loop->control_ivs = iv;
2758 return;
2761 /* Record the estimate on number of iterations of LOOP based on the fact that
2762 the induction variable BASE + STEP * i evaluated in STMT does not wrap and
2763 its values belong to the range <LOW, HIGH>. REALISTIC is true if the
2764 estimated number of iterations is expected to be close to the real one.
2765 UPPER is true if we are sure the induction variable does not wrap. */
2767 static void
2768 record_nonwrapping_iv (struct loop *loop, tree base, tree step, gimple stmt,
2769 tree low, tree high, bool realistic, bool upper)
2771 tree niter_bound, extreme, delta;
2772 tree type = TREE_TYPE (base), unsigned_type;
2773 tree orig_base = base;
2775 if (TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
2776 return;
2778 if (dump_file && (dump_flags & TDF_DETAILS))
2780 fprintf (dump_file, "Induction variable (");
2781 print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
2782 fprintf (dump_file, ") ");
2783 print_generic_expr (dump_file, base, TDF_SLIM);
2784 fprintf (dump_file, " + ");
2785 print_generic_expr (dump_file, step, TDF_SLIM);
2786 fprintf (dump_file, " * iteration does not wrap in statement ");
2787 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2788 fprintf (dump_file, " in loop %d.\n", loop->num);
2791 unsigned_type = unsigned_type_for (type);
2792 base = fold_convert (unsigned_type, base);
2793 step = fold_convert (unsigned_type, step);
2795 if (tree_int_cst_sign_bit (step))
2797 wide_int min, max;
2798 extreme = fold_convert (unsigned_type, low);
2799 if (TREE_CODE (orig_base) == SSA_NAME
2800 && TREE_CODE (high) == INTEGER_CST
2801 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
2802 && get_range_info (orig_base, &min, &max) == VR_RANGE
2803 && wi::gts_p (high, max))
2804 base = wide_int_to_tree (unsigned_type, max);
2805 else if (TREE_CODE (base) != INTEGER_CST)
2806 base = fold_convert (unsigned_type, high);
2807 delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
2808 step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
2810 else
2812 wide_int min, max;
2813 extreme = fold_convert (unsigned_type, high);
2814 if (TREE_CODE (orig_base) == SSA_NAME
2815 && TREE_CODE (low) == INTEGER_CST
2816 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
2817 && get_range_info (orig_base, &min, &max) == VR_RANGE
2818 && wi::gts_p (min, low))
2819 base = wide_int_to_tree (unsigned_type, min);
2820 else if (TREE_CODE (base) != INTEGER_CST)
2821 base = fold_convert (unsigned_type, low);
2822 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
2825 /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
2826 would get out of the range. */
2827 niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
2828 widest_int max = derive_constant_upper_bound (niter_bound);
2829 record_estimate (loop, niter_bound, max, stmt, false, realistic, upper);
2832 /* Determine information about number of iterations a LOOP from the index
2833 IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
2834 guaranteed to be executed in every iteration of LOOP. Callback for
2835 for_each_index. */
2837 struct ilb_data
2839 struct loop *loop;
2840 gimple stmt;
2843 static bool
2844 idx_infer_loop_bounds (tree base, tree *idx, void *dta)
2846 struct ilb_data *data = (struct ilb_data *) dta;
2847 tree ev, init, step;
2848 tree low, high, type, next;
2849 bool sign, upper = true, at_end = false;
2850 struct loop *loop = data->loop;
2851 bool reliable = true;
2853 if (TREE_CODE (base) != ARRAY_REF)
2854 return true;
2856 /* For arrays at the end of the structure, we are not guaranteed that they
2857 do not really extend over their declared size. However, for arrays of
2858 size greater than one, this is unlikely to be intended. */
2859 if (array_at_struct_end_p (base))
2861 at_end = true;
2862 upper = false;
2865 struct loop *dloop = loop_containing_stmt (data->stmt);
2866 if (!dloop)
2867 return true;
2869 ev = analyze_scalar_evolution (dloop, *idx);
2870 ev = instantiate_parameters (loop, ev);
2871 init = initial_condition (ev);
2872 step = evolution_part_in_loop_num (ev, loop->num);
2874 if (!init
2875 || !step
2876 || TREE_CODE (step) != INTEGER_CST
2877 || integer_zerop (step)
2878 || tree_contains_chrecs (init, NULL)
2879 || chrec_contains_symbols_defined_in_loop (init, loop->num))
2880 return true;
2882 low = array_ref_low_bound (base);
2883 high = array_ref_up_bound (base);
2885 /* The case of nonconstant bounds could be handled, but it would be
2886 complicated. */
2887 if (TREE_CODE (low) != INTEGER_CST
2888 || !high
2889 || TREE_CODE (high) != INTEGER_CST)
2890 return true;
2891 sign = tree_int_cst_sign_bit (step);
2892 type = TREE_TYPE (step);
2894 /* The array of length 1 at the end of a structure most likely extends
2895 beyond its bounds. */
2896 if (at_end
2897 && operand_equal_p (low, high, 0))
2898 return true;
2900 /* In case the relevant bound of the array does not fit in type, or
2901 it does, but bound + step (in type) still belongs into the range of the
2902 array, the index may wrap and still stay within the range of the array
2903 (consider e.g. if the array is indexed by the full range of
2904 unsigned char).
2906 To make things simpler, we require both bounds to fit into type, although
2907 there are cases where this would not be strictly necessary. */
2908 if (!int_fits_type_p (high, type)
2909 || !int_fits_type_p (low, type))
2910 return true;
2911 low = fold_convert (type, low);
2912 high = fold_convert (type, high);
2914 if (sign)
2915 next = fold_binary (PLUS_EXPR, type, low, step);
2916 else
2917 next = fold_binary (PLUS_EXPR, type, high, step);
2919 if (tree_int_cst_compare (low, next) <= 0
2920 && tree_int_cst_compare (next, high) <= 0)
2921 return true;
2923 /* If access is not executed on every iteration, we must ensure that overlow may
2924 not make the access valid later. */
2925 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (data->stmt))
2926 && scev_probably_wraps_p (initial_condition_in_loop_num (ev, loop->num),
2927 step, data->stmt, loop, true))
2928 reliable = false;
2930 record_nonwrapping_iv (loop, init, step, data->stmt, low, high, reliable, upper);
2931 return true;
2934 /* Determine information about number of iterations a LOOP from the bounds
2935 of arrays in the data reference REF accessed in STMT. RELIABLE is true if
2936 STMT is guaranteed to be executed in every iteration of LOOP.*/
2938 static void
2939 infer_loop_bounds_from_ref (struct loop *loop, gimple stmt, tree ref)
2941 struct ilb_data data;
2943 data.loop = loop;
2944 data.stmt = stmt;
2945 for_each_index (&ref, idx_infer_loop_bounds, &data);
2948 /* Determine information about number of iterations of a LOOP from the way
2949 arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
2950 executed in every iteration of LOOP. */
2952 static void
2953 infer_loop_bounds_from_array (struct loop *loop, gimple stmt)
2955 if (is_gimple_assign (stmt))
2957 tree op0 = gimple_assign_lhs (stmt);
2958 tree op1 = gimple_assign_rhs1 (stmt);
2960 /* For each memory access, analyze its access function
2961 and record a bound on the loop iteration domain. */
2962 if (REFERENCE_CLASS_P (op0))
2963 infer_loop_bounds_from_ref (loop, stmt, op0);
2965 if (REFERENCE_CLASS_P (op1))
2966 infer_loop_bounds_from_ref (loop, stmt, op1);
2968 else if (is_gimple_call (stmt))
2970 tree arg, lhs;
2971 unsigned i, n = gimple_call_num_args (stmt);
2973 lhs = gimple_call_lhs (stmt);
2974 if (lhs && REFERENCE_CLASS_P (lhs))
2975 infer_loop_bounds_from_ref (loop, stmt, lhs);
2977 for (i = 0; i < n; i++)
2979 arg = gimple_call_arg (stmt, i);
2980 if (REFERENCE_CLASS_P (arg))
2981 infer_loop_bounds_from_ref (loop, stmt, arg);
2986 /* Determine information about number of iterations of a LOOP from the fact
2987 that pointer arithmetics in STMT does not overflow. */
2989 static void
2990 infer_loop_bounds_from_pointer_arith (struct loop *loop, gimple stmt)
2992 tree def, base, step, scev, type, low, high;
2993 tree var, ptr;
2995 if (!is_gimple_assign (stmt)
2996 || gimple_assign_rhs_code (stmt) != POINTER_PLUS_EXPR)
2997 return;
2999 def = gimple_assign_lhs (stmt);
3000 if (TREE_CODE (def) != SSA_NAME)
3001 return;
3003 type = TREE_TYPE (def);
3004 if (!nowrap_type_p (type))
3005 return;
3007 ptr = gimple_assign_rhs1 (stmt);
3008 if (!expr_invariant_in_loop_p (loop, ptr))
3009 return;
3011 var = gimple_assign_rhs2 (stmt);
3012 if (TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (var)))
3013 return;
3015 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
3016 if (chrec_contains_undetermined (scev))
3017 return;
3019 base = initial_condition_in_loop_num (scev, loop->num);
3020 step = evolution_part_in_loop_num (scev, loop->num);
3022 if (!base || !step
3023 || TREE_CODE (step) != INTEGER_CST
3024 || tree_contains_chrecs (base, NULL)
3025 || chrec_contains_symbols_defined_in_loop (base, loop->num))
3026 return;
3028 low = lower_bound_in_type (type, type);
3029 high = upper_bound_in_type (type, type);
3031 /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
3032 produce a NULL pointer. The contrary would mean NULL points to an object,
3033 while NULL is supposed to compare unequal with the address of all objects.
3034 Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
3035 NULL pointer since that would mean wrapping, which we assume here not to
3036 happen. So, we can exclude NULL from the valid range of pointer
3037 arithmetic. */
3038 if (flag_delete_null_pointer_checks && int_cst_value (low) == 0)
3039 low = build_int_cstu (TREE_TYPE (low), TYPE_ALIGN_UNIT (TREE_TYPE (type)));
3041 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
3044 /* Determine information about number of iterations of a LOOP from the fact
3045 that signed arithmetics in STMT does not overflow. */
3047 static void
3048 infer_loop_bounds_from_signedness (struct loop *loop, gimple stmt)
3050 tree def, base, step, scev, type, low, high;
3052 if (gimple_code (stmt) != GIMPLE_ASSIGN)
3053 return;
3055 def = gimple_assign_lhs (stmt);
3057 if (TREE_CODE (def) != SSA_NAME)
3058 return;
3060 type = TREE_TYPE (def);
3061 if (!INTEGRAL_TYPE_P (type)
3062 || !TYPE_OVERFLOW_UNDEFINED (type))
3063 return;
3065 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
3066 if (chrec_contains_undetermined (scev))
3067 return;
3069 base = initial_condition_in_loop_num (scev, loop->num);
3070 step = evolution_part_in_loop_num (scev, loop->num);
3072 if (!base || !step
3073 || TREE_CODE (step) != INTEGER_CST
3074 || tree_contains_chrecs (base, NULL)
3075 || chrec_contains_symbols_defined_in_loop (base, loop->num))
3076 return;
3078 low = lower_bound_in_type (type, type);
3079 high = upper_bound_in_type (type, type);
3081 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
3084 /* The following analyzers are extracting informations on the bounds
3085 of LOOP from the following undefined behaviors:
3087 - data references should not access elements over the statically
3088 allocated size,
3090 - signed variables should not overflow when flag_wrapv is not set.
3093 static void
3094 infer_loop_bounds_from_undefined (struct loop *loop)
3096 unsigned i;
3097 basic_block *bbs;
3098 gimple_stmt_iterator bsi;
3099 basic_block bb;
3100 bool reliable;
3102 bbs = get_loop_body (loop);
3104 for (i = 0; i < loop->num_nodes; i++)
3106 bb = bbs[i];
3108 /* If BB is not executed in each iteration of the loop, we cannot
3109 use the operations in it to infer reliable upper bound on the
3110 # of iterations of the loop. However, we can use it as a guess.
3111 Reliable guesses come only from array bounds. */
3112 reliable = dominated_by_p (CDI_DOMINATORS, loop->latch, bb);
3114 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
3116 gimple stmt = gsi_stmt (bsi);
3118 infer_loop_bounds_from_array (loop, stmt);
3120 if (reliable)
3122 infer_loop_bounds_from_signedness (loop, stmt);
3123 infer_loop_bounds_from_pointer_arith (loop, stmt);
3129 free (bbs);
3132 /* Compare wide ints, callback for qsort. */
3134 static int
3135 wide_int_cmp (const void *p1, const void *p2)
3137 const widest_int *d1 = (const widest_int *) p1;
3138 const widest_int *d2 = (const widest_int *) p2;
3139 return wi::cmpu (*d1, *d2);
3142 /* Return index of BOUND in BOUNDS array sorted in increasing order.
3143 Lookup by binary search. */
3145 static int
3146 bound_index (vec<widest_int> bounds, const widest_int &bound)
3148 unsigned int end = bounds.length ();
3149 unsigned int begin = 0;
3151 /* Find a matching index by means of a binary search. */
3152 while (begin != end)
3154 unsigned int middle = (begin + end) / 2;
3155 widest_int index = bounds[middle];
3157 if (index == bound)
3158 return middle;
3159 else if (wi::ltu_p (index, bound))
3160 begin = middle + 1;
3161 else
3162 end = middle;
3164 gcc_unreachable ();
3167 /* We recorded loop bounds only for statements dominating loop latch (and thus
3168 executed each loop iteration). If there are any bounds on statements not
3169 dominating the loop latch we can improve the estimate by walking the loop
3170 body and seeing if every path from loop header to loop latch contains
3171 some bounded statement. */
3173 static void
3174 discover_iteration_bound_by_body_walk (struct loop *loop)
3176 struct nb_iter_bound *elt;
3177 vec<widest_int> bounds = vNULL;
3178 vec<vec<basic_block> > queues = vNULL;
3179 vec<basic_block> queue = vNULL;
3180 ptrdiff_t queue_index;
3181 ptrdiff_t latch_index = 0;
3183 /* Discover what bounds may interest us. */
3184 for (elt = loop->bounds; elt; elt = elt->next)
3186 widest_int bound = elt->bound;
3188 /* Exit terminates loop at given iteration, while non-exits produce undefined
3189 effect on the next iteration. */
3190 if (!elt->is_exit)
3192 bound += 1;
3193 /* If an overflow occurred, ignore the result. */
3194 if (bound == 0)
3195 continue;
3198 if (!loop->any_upper_bound
3199 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3200 bounds.safe_push (bound);
3203 /* Exit early if there is nothing to do. */
3204 if (!bounds.exists ())
3205 return;
3207 if (dump_file && (dump_flags & TDF_DETAILS))
3208 fprintf (dump_file, " Trying to walk loop body to reduce the bound.\n");
3210 /* Sort the bounds in decreasing order. */
3211 bounds.qsort (wide_int_cmp);
3213 /* For every basic block record the lowest bound that is guaranteed to
3214 terminate the loop. */
3216 hash_map<basic_block, ptrdiff_t> bb_bounds;
3217 for (elt = loop->bounds; elt; elt = elt->next)
3219 widest_int bound = elt->bound;
3220 if (!elt->is_exit)
3222 bound += 1;
3223 /* If an overflow occurred, ignore the result. */
3224 if (bound == 0)
3225 continue;
3228 if (!loop->any_upper_bound
3229 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3231 ptrdiff_t index = bound_index (bounds, bound);
3232 ptrdiff_t *entry = bb_bounds.get (gimple_bb (elt->stmt));
3233 if (!entry)
3234 bb_bounds.put (gimple_bb (elt->stmt), index);
3235 else if ((ptrdiff_t)*entry > index)
3236 *entry = index;
3240 hash_map<basic_block, ptrdiff_t> block_priority;
3242 /* Perform shortest path discovery loop->header ... loop->latch.
3244 The "distance" is given by the smallest loop bound of basic block
3245 present in the path and we look for path with largest smallest bound
3246 on it.
3248 To avoid the need for fibonacci heap on double ints we simply compress
3249 double ints into indexes to BOUNDS array and then represent the queue
3250 as arrays of queues for every index.
3251 Index of BOUNDS.length() means that the execution of given BB has
3252 no bounds determined.
3254 VISITED is a pointer map translating basic block into smallest index
3255 it was inserted into the priority queue with. */
3256 latch_index = -1;
3258 /* Start walk in loop header with index set to infinite bound. */
3259 queue_index = bounds.length ();
3260 queues.safe_grow_cleared (queue_index + 1);
3261 queue.safe_push (loop->header);
3262 queues[queue_index] = queue;
3263 block_priority.put (loop->header, queue_index);
3265 for (; queue_index >= 0; queue_index--)
3267 if (latch_index < queue_index)
3269 while (queues[queue_index].length ())
3271 basic_block bb;
3272 ptrdiff_t bound_index = queue_index;
3273 edge e;
3274 edge_iterator ei;
3276 queue = queues[queue_index];
3277 bb = queue.pop ();
3279 /* OK, we later inserted the BB with lower priority, skip it. */
3280 if (*block_priority.get (bb) > queue_index)
3281 continue;
3283 /* See if we can improve the bound. */
3284 ptrdiff_t *entry = bb_bounds.get (bb);
3285 if (entry && *entry < bound_index)
3286 bound_index = *entry;
3288 /* Insert succesors into the queue, watch for latch edge
3289 and record greatest index we saw. */
3290 FOR_EACH_EDGE (e, ei, bb->succs)
3292 bool insert = false;
3294 if (loop_exit_edge_p (loop, e))
3295 continue;
3297 if (e == loop_latch_edge (loop)
3298 && latch_index < bound_index)
3299 latch_index = bound_index;
3300 else if (!(entry = block_priority.get (e->dest)))
3302 insert = true;
3303 block_priority.put (e->dest, bound_index);
3305 else if (*entry < bound_index)
3307 insert = true;
3308 *entry = bound_index;
3311 if (insert)
3312 queues[bound_index].safe_push (e->dest);
3316 queues[queue_index].release ();
3319 gcc_assert (latch_index >= 0);
3320 if ((unsigned)latch_index < bounds.length ())
3322 if (dump_file && (dump_flags & TDF_DETAILS))
3324 fprintf (dump_file, "Found better loop bound ");
3325 print_decu (bounds[latch_index], dump_file);
3326 fprintf (dump_file, "\n");
3328 record_niter_bound (loop, bounds[latch_index], false, true);
3331 queues.release ();
3332 bounds.release ();
3335 /* See if every path cross the loop goes through a statement that is known
3336 to not execute at the last iteration. In that case we can decrese iteration
3337 count by 1. */
3339 static void
3340 maybe_lower_iteration_bound (struct loop *loop)
3342 hash_set<gimple> *not_executed_last_iteration = NULL;
3343 struct nb_iter_bound *elt;
3344 bool found_exit = false;
3345 vec<basic_block> queue = vNULL;
3346 bitmap visited;
3348 /* Collect all statements with interesting (i.e. lower than
3349 nb_iterations_upper_bound) bound on them.
3351 TODO: Due to the way record_estimate choose estimates to store, the bounds
3352 will be always nb_iterations_upper_bound-1. We can change this to record
3353 also statements not dominating the loop latch and update the walk bellow
3354 to the shortest path algorthm. */
3355 for (elt = loop->bounds; elt; elt = elt->next)
3357 if (!elt->is_exit
3358 && wi::ltu_p (elt->bound, loop->nb_iterations_upper_bound))
3360 if (!not_executed_last_iteration)
3361 not_executed_last_iteration = new hash_set<gimple>;
3362 not_executed_last_iteration->add (elt->stmt);
3365 if (!not_executed_last_iteration)
3366 return;
3368 /* Start DFS walk in the loop header and see if we can reach the
3369 loop latch or any of the exits (including statements with side
3370 effects that may terminate the loop otherwise) without visiting
3371 any of the statements known to have undefined effect on the last
3372 iteration. */
3373 queue.safe_push (loop->header);
3374 visited = BITMAP_ALLOC (NULL);
3375 bitmap_set_bit (visited, loop->header->index);
3376 found_exit = false;
3380 basic_block bb = queue.pop ();
3381 gimple_stmt_iterator gsi;
3382 bool stmt_found = false;
3384 /* Loop for possible exits and statements bounding the execution. */
3385 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3387 gimple stmt = gsi_stmt (gsi);
3388 if (not_executed_last_iteration->contains (stmt))
3390 stmt_found = true;
3391 break;
3393 if (gimple_has_side_effects (stmt))
3395 found_exit = true;
3396 break;
3399 if (found_exit)
3400 break;
3402 /* If no bounding statement is found, continue the walk. */
3403 if (!stmt_found)
3405 edge e;
3406 edge_iterator ei;
3408 FOR_EACH_EDGE (e, ei, bb->succs)
3410 if (loop_exit_edge_p (loop, e)
3411 || e == loop_latch_edge (loop))
3413 found_exit = true;
3414 break;
3416 if (bitmap_set_bit (visited, e->dest->index))
3417 queue.safe_push (e->dest);
3421 while (queue.length () && !found_exit);
3423 /* If every path through the loop reach bounding statement before exit,
3424 then we know the last iteration of the loop will have undefined effect
3425 and we can decrease number of iterations. */
3427 if (!found_exit)
3429 if (dump_file && (dump_flags & TDF_DETAILS))
3430 fprintf (dump_file, "Reducing loop iteration estimate by 1; "
3431 "undefined statement must be executed at the last iteration.\n");
3432 record_niter_bound (loop, loop->nb_iterations_upper_bound - 1,
3433 false, true);
3436 BITMAP_FREE (visited);
3437 queue.release ();
3438 delete not_executed_last_iteration;
3441 /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
3442 is true also use estimates derived from undefined behavior. */
3444 static void
3445 estimate_numbers_of_iterations_loop (struct loop *loop)
3447 vec<edge> exits;
3448 tree niter, type;
3449 unsigned i;
3450 struct tree_niter_desc niter_desc;
3451 edge ex;
3452 widest_int bound;
3453 edge likely_exit;
3455 /* Give up if we already have tried to compute an estimation. */
3456 if (loop->estimate_state != EST_NOT_COMPUTED)
3457 return;
3459 loop->estimate_state = EST_AVAILABLE;
3460 /* Force estimate compuation but leave any existing upper bound in place. */
3461 loop->any_estimate = false;
3463 /* Ensure that loop->nb_iterations is computed if possible. If it turns out
3464 to be constant, we avoid undefined behavior implied bounds and instead
3465 diagnose those loops with -Waggressive-loop-optimizations. */
3466 number_of_latch_executions (loop);
3468 exits = get_loop_exit_edges (loop);
3469 likely_exit = single_likely_exit (loop);
3470 FOR_EACH_VEC_ELT (exits, i, ex)
3472 if (!number_of_iterations_exit (loop, ex, &niter_desc, false, false))
3473 continue;
3475 niter = niter_desc.niter;
3476 type = TREE_TYPE (niter);
3477 if (TREE_CODE (niter_desc.may_be_zero) != INTEGER_CST)
3478 niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
3479 build_int_cst (type, 0),
3480 niter);
3481 record_estimate (loop, niter, niter_desc.max,
3482 last_stmt (ex->src),
3483 true, ex == likely_exit, true);
3484 record_control_iv (loop, &niter_desc);
3486 exits.release ();
3488 if (flag_aggressive_loop_optimizations)
3489 infer_loop_bounds_from_undefined (loop);
3491 discover_iteration_bound_by_body_walk (loop);
3493 maybe_lower_iteration_bound (loop);
3495 /* If we have a measured profile, use it to estimate the number of
3496 iterations. */
3497 if (loop->header->count != 0)
3499 gcov_type nit = expected_loop_iterations_unbounded (loop) + 1;
3500 bound = gcov_type_to_wide_int (nit);
3501 record_niter_bound (loop, bound, true, false);
3504 /* If we know the exact number of iterations of this loop, try to
3505 not break code with undefined behavior by not recording smaller
3506 maximum number of iterations. */
3507 if (loop->nb_iterations
3508 && TREE_CODE (loop->nb_iterations) == INTEGER_CST)
3510 loop->any_upper_bound = true;
3511 loop->nb_iterations_upper_bound = wi::to_widest (loop->nb_iterations);
3515 /* Sets NIT to the estimated number of executions of the latch of the
3516 LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
3517 large as the number of iterations. If we have no reliable estimate,
3518 the function returns false, otherwise returns true. */
3520 bool
3521 estimated_loop_iterations (struct loop *loop, widest_int *nit)
3523 /* When SCEV information is available, try to update loop iterations
3524 estimate. Otherwise just return whatever we recorded earlier. */
3525 if (scev_initialized_p ())
3526 estimate_numbers_of_iterations_loop (loop);
3528 return (get_estimated_loop_iterations (loop, nit));
3531 /* Similar to estimated_loop_iterations, but returns the estimate only
3532 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3533 on the number of iterations of LOOP could not be derived, returns -1. */
3535 HOST_WIDE_INT
3536 estimated_loop_iterations_int (struct loop *loop)
3538 widest_int nit;
3539 HOST_WIDE_INT hwi_nit;
3541 if (!estimated_loop_iterations (loop, &nit))
3542 return -1;
3544 if (!wi::fits_shwi_p (nit))
3545 return -1;
3546 hwi_nit = nit.to_shwi ();
3548 return hwi_nit < 0 ? -1 : hwi_nit;
3552 /* Sets NIT to an upper bound for the maximum number of executions of the
3553 latch of the LOOP. If we have no reliable estimate, the function returns
3554 false, otherwise returns true. */
3556 bool
3557 max_loop_iterations (struct loop *loop, widest_int *nit)
3559 /* When SCEV information is available, try to update loop iterations
3560 estimate. Otherwise just return whatever we recorded earlier. */
3561 if (scev_initialized_p ())
3562 estimate_numbers_of_iterations_loop (loop);
3564 return get_max_loop_iterations (loop, nit);
3567 /* Similar to max_loop_iterations, but returns the estimate only
3568 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3569 on the number of iterations of LOOP could not be derived, returns -1. */
3571 HOST_WIDE_INT
3572 max_loop_iterations_int (struct loop *loop)
3574 widest_int nit;
3575 HOST_WIDE_INT hwi_nit;
3577 if (!max_loop_iterations (loop, &nit))
3578 return -1;
3580 if (!wi::fits_shwi_p (nit))
3581 return -1;
3582 hwi_nit = nit.to_shwi ();
3584 return hwi_nit < 0 ? -1 : hwi_nit;
3587 /* Returns an estimate for the number of executions of statements
3588 in the LOOP. For statements before the loop exit, this exceeds
3589 the number of execution of the latch by one. */
3591 HOST_WIDE_INT
3592 estimated_stmt_executions_int (struct loop *loop)
3594 HOST_WIDE_INT nit = estimated_loop_iterations_int (loop);
3595 HOST_WIDE_INT snit;
3597 if (nit == -1)
3598 return -1;
3600 snit = (HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) nit + 1);
3602 /* If the computation overflows, return -1. */
3603 return snit < 0 ? -1 : snit;
3606 /* Sets NIT to the estimated maximum number of executions of the latch of the
3607 LOOP, plus one. If we have no reliable estimate, the function returns
3608 false, otherwise returns true. */
3610 bool
3611 max_stmt_executions (struct loop *loop, widest_int *nit)
3613 widest_int nit_minus_one;
3615 if (!max_loop_iterations (loop, nit))
3616 return false;
3618 nit_minus_one = *nit;
3620 *nit += 1;
3622 return wi::gtu_p (*nit, nit_minus_one);
3625 /* Sets NIT to the estimated number of executions of the latch of the
3626 LOOP, plus one. If we have no reliable estimate, the function returns
3627 false, otherwise returns true. */
3629 bool
3630 estimated_stmt_executions (struct loop *loop, widest_int *nit)
3632 widest_int nit_minus_one;
3634 if (!estimated_loop_iterations (loop, nit))
3635 return false;
3637 nit_minus_one = *nit;
3639 *nit += 1;
3641 return wi::gtu_p (*nit, nit_minus_one);
3644 /* Records estimates on numbers of iterations of loops. */
3646 void
3647 estimate_numbers_of_iterations (void)
3649 struct loop *loop;
3651 /* We don't want to issue signed overflow warnings while getting
3652 loop iteration estimates. */
3653 fold_defer_overflow_warnings ();
3655 FOR_EACH_LOOP (loop, 0)
3657 estimate_numbers_of_iterations_loop (loop);
3660 fold_undefer_and_ignore_overflow_warnings ();
3663 /* Returns true if statement S1 dominates statement S2. */
3665 bool
3666 stmt_dominates_stmt_p (gimple s1, gimple s2)
3668 basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
3670 if (!bb1
3671 || s1 == s2)
3672 return true;
3674 if (bb1 == bb2)
3676 gimple_stmt_iterator bsi;
3678 if (gimple_code (s2) == GIMPLE_PHI)
3679 return false;
3681 if (gimple_code (s1) == GIMPLE_PHI)
3682 return true;
3684 for (bsi = gsi_start_bb (bb1); gsi_stmt (bsi) != s2; gsi_next (&bsi))
3685 if (gsi_stmt (bsi) == s1)
3686 return true;
3688 return false;
3691 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
3694 /* Returns true when we can prove that the number of executions of
3695 STMT in the loop is at most NITER, according to the bound on
3696 the number of executions of the statement NITER_BOUND->stmt recorded in
3697 NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
3699 ??? This code can become quite a CPU hog - we can have many bounds,
3700 and large basic block forcing stmt_dominates_stmt_p to be queried
3701 many times on a large basic blocks, so the whole thing is O(n^2)
3702 for scev_probably_wraps_p invocation (that can be done n times).
3704 It would make more sense (and give better answers) to remember BB
3705 bounds computed by discover_iteration_bound_by_body_walk. */
3707 static bool
3708 n_of_executions_at_most (gimple stmt,
3709 struct nb_iter_bound *niter_bound,
3710 tree niter)
3712 widest_int bound = niter_bound->bound;
3713 tree nit_type = TREE_TYPE (niter), e;
3714 enum tree_code cmp;
3716 gcc_assert (TYPE_UNSIGNED (nit_type));
3718 /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
3719 the number of iterations is small. */
3720 if (!wi::fits_to_tree_p (bound, nit_type))
3721 return false;
3723 /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
3724 times. This means that:
3726 -- if NITER_BOUND->is_exit is true, then everything after
3727 it at most NITER_BOUND->bound times.
3729 -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
3730 is executed, then NITER_BOUND->stmt is executed as well in the same
3731 iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
3733 If we can determine that NITER_BOUND->stmt is always executed
3734 after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
3735 We conclude that if both statements belong to the same
3736 basic block and STMT is before NITER_BOUND->stmt and there are no
3737 statements with side effects in between. */
3739 if (niter_bound->is_exit)
3741 if (stmt == niter_bound->stmt
3742 || !stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3743 return false;
3744 cmp = GE_EXPR;
3746 else
3748 if (!stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3750 gimple_stmt_iterator bsi;
3751 if (gimple_bb (stmt) != gimple_bb (niter_bound->stmt)
3752 || gimple_code (stmt) == GIMPLE_PHI
3753 || gimple_code (niter_bound->stmt) == GIMPLE_PHI)
3754 return false;
3756 /* By stmt_dominates_stmt_p we already know that STMT appears
3757 before NITER_BOUND->STMT. Still need to test that the loop
3758 can not be terinated by a side effect in between. */
3759 for (bsi = gsi_for_stmt (stmt); gsi_stmt (bsi) != niter_bound->stmt;
3760 gsi_next (&bsi))
3761 if (gimple_has_side_effects (gsi_stmt (bsi)))
3762 return false;
3763 bound += 1;
3764 if (bound == 0
3765 || !wi::fits_to_tree_p (bound, nit_type))
3766 return false;
3768 cmp = GT_EXPR;
3771 e = fold_binary (cmp, boolean_type_node,
3772 niter, wide_int_to_tree (nit_type, bound));
3773 return e && integer_nonzerop (e);
3776 /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
3778 bool
3779 nowrap_type_p (tree type)
3781 if (INTEGRAL_TYPE_P (type)
3782 && TYPE_OVERFLOW_UNDEFINED (type))
3783 return true;
3785 if (POINTER_TYPE_P (type))
3786 return true;
3788 return false;
3791 /* Return true if we can prove LOOP is exited before evolution of induction
3792 variabled {BASE, STEP} overflows with respect to its type bound. */
3794 static bool
3795 loop_exits_before_overflow (tree base, tree step,
3796 gimple at_stmt, struct loop *loop)
3798 widest_int niter;
3799 struct control_iv *civ;
3800 struct nb_iter_bound *bound;
3801 tree e, delta, step_abs, unsigned_base;
3802 tree type = TREE_TYPE (step);
3803 tree unsigned_type, valid_niter;
3805 /* Don't issue signed overflow warnings. */
3806 fold_defer_overflow_warnings ();
3808 /* Compute the number of iterations before we reach the bound of the
3809 type, and verify that the loop is exited before this occurs. */
3810 unsigned_type = unsigned_type_for (type);
3811 unsigned_base = fold_convert (unsigned_type, base);
3813 if (tree_int_cst_sign_bit (step))
3815 tree extreme = fold_convert (unsigned_type,
3816 lower_bound_in_type (type, type));
3817 delta = fold_build2 (MINUS_EXPR, unsigned_type, unsigned_base, extreme);
3818 step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
3819 fold_convert (unsigned_type, step));
3821 else
3823 tree extreme = fold_convert (unsigned_type,
3824 upper_bound_in_type (type, type));
3825 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, unsigned_base);
3826 step_abs = fold_convert (unsigned_type, step);
3829 valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
3831 estimate_numbers_of_iterations_loop (loop);
3833 if (max_loop_iterations (loop, &niter)
3834 && wi::fits_to_tree_p (niter, TREE_TYPE (valid_niter))
3835 && (e = fold_binary (GT_EXPR, boolean_type_node, valid_niter,
3836 wide_int_to_tree (TREE_TYPE (valid_niter),
3837 niter))) != NULL
3838 && integer_nonzerop (e))
3840 fold_undefer_and_ignore_overflow_warnings ();
3841 return true;
3843 if (at_stmt)
3844 for (bound = loop->bounds; bound; bound = bound->next)
3846 if (n_of_executions_at_most (at_stmt, bound, valid_niter))
3848 fold_undefer_and_ignore_overflow_warnings ();
3849 return true;
3852 fold_undefer_and_ignore_overflow_warnings ();
3854 /* Try to prove loop is exited before {base, step} overflows with the
3855 help of analyzed loop control IV. This is done only for IVs with
3856 constant step because otherwise we don't have the information. */
3857 if (TREE_CODE (step) == INTEGER_CST)
3858 for (civ = loop->control_ivs; civ; civ = civ->next)
3860 enum tree_code code;
3861 tree stepped, extreme, civ_type = TREE_TYPE (civ->step);
3863 /* Have to consider type difference because operand_equal_p ignores
3864 that for constants. */
3865 if (TYPE_UNSIGNED (type) != TYPE_UNSIGNED (civ_type)
3866 || element_precision (type) != element_precision (civ_type))
3867 continue;
3869 /* Only consider control IV with same step. */
3870 if (!operand_equal_p (step, civ->step, 0))
3871 continue;
3873 /* Done proving if this is a no-overflow control IV. */
3874 if (operand_equal_p (base, civ->base, 0))
3875 return true;
3877 /* If this is a before stepping control IV, in other words, we have
3879 {civ_base, step} = {base + step, step}
3881 Because civ {base + step, step} doesn't overflow during loop
3882 iterations, {base, step} will not overflow if we can prove the
3883 operation "base + step" does not overflow. Specifically, we try
3884 to prove below conditions are satisfied:
3886 base <= UPPER_BOUND (type) - step ;;step > 0
3887 base >= LOWER_BOUND (type) - step ;;step < 0
3889 by proving the reverse conditions are false using loop's initial
3890 condition. */
3891 if (POINTER_TYPE_P (TREE_TYPE (base)))
3892 code = POINTER_PLUS_EXPR;
3893 else
3894 code = PLUS_EXPR;
3896 stepped = fold_build2 (code, TREE_TYPE (base), base, step);
3897 if (operand_equal_p (stepped, civ->base, 0))
3899 if (tree_int_cst_sign_bit (step))
3901 code = LT_EXPR;
3902 extreme = lower_bound_in_type (type, type);
3904 else
3906 code = GT_EXPR;
3907 extreme = upper_bound_in_type (type, type);
3909 extreme = fold_build2 (MINUS_EXPR, type, extreme, step);
3910 e = fold_build2 (code, boolean_type_node, base, extreme);
3911 e = simplify_using_initial_conditions (loop, e);
3912 if (integer_zerop (e))
3913 return true;
3915 continue;
3918 /* Similar to above, only in this case we have:
3920 {civ_base, step} = {(signed T)((unsigned T)base + step), step}
3921 && TREE_TYPE (civ_base) = signed T.
3923 We prove that below condition is satisfied:
3925 (signed T)((unsigned T)base + step)
3926 == (signed T)(unsigned T)base + step
3927 == base + step
3929 because of exact the same reason as above. This also proves
3930 there is no overflow in the operation "base + step", thus the
3931 induction variable {base, step} during loop iterations.
3933 This is necessary to handle cases as below:
3935 int foo (int *a, signed char s, signed char l)
3937 signed char i;
3938 for (i = s; i < l; i++)
3939 a[i] = 0;
3940 return 0;
3943 The variable I is firstly converted to type unsigned char,
3944 incremented, then converted back to type signed char. */
3945 if (!CONVERT_EXPR_P (civ->base) || TREE_TYPE (civ->base) != type)
3946 continue;
3947 e = TREE_OPERAND (civ->base, 0);
3948 if (TREE_CODE (e) != PLUS_EXPR
3949 || TREE_CODE (TREE_OPERAND (e, 1)) != INTEGER_CST
3950 || !operand_equal_p (step,
3951 fold_convert (type,
3952 TREE_OPERAND (e, 1)), 0))
3953 continue;
3954 e = TREE_OPERAND (e, 0);
3955 if (!CONVERT_EXPR_P (e) || !operand_equal_p (e, unsigned_base, 0))
3956 continue;
3957 e = TREE_OPERAND (e, 0);
3958 gcc_assert (operand_equal_p (e, base, 0));
3959 if (tree_int_cst_sign_bit (step))
3961 code = LT_EXPR;
3962 extreme = lower_bound_in_type (type, type);
3964 else
3966 code = GT_EXPR;
3967 extreme = upper_bound_in_type (type, type);
3969 extreme = fold_build2 (MINUS_EXPR, type, extreme, step);
3970 e = fold_build2 (code, boolean_type_node, base, extreme);
3971 e = simplify_using_initial_conditions (loop, e);
3972 if (integer_zerop (e))
3973 return true;
3976 return false;
3979 /* Return false only when the induction variable BASE + STEP * I is
3980 known to not overflow: i.e. when the number of iterations is small
3981 enough with respect to the step and initial condition in order to
3982 keep the evolution confined in TYPEs bounds. Return true when the
3983 iv is known to overflow or when the property is not computable.
3985 USE_OVERFLOW_SEMANTICS is true if this function should assume that
3986 the rules for overflow of the given language apply (e.g., that signed
3987 arithmetics in C does not overflow). */
3989 bool
3990 scev_probably_wraps_p (tree base, tree step,
3991 gimple at_stmt, struct loop *loop,
3992 bool use_overflow_semantics)
3994 /* FIXME: We really need something like
3995 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
3997 We used to test for the following situation that frequently appears
3998 during address arithmetics:
4000 D.1621_13 = (long unsigned intD.4) D.1620_12;
4001 D.1622_14 = D.1621_13 * 8;
4002 D.1623_15 = (doubleD.29 *) D.1622_14;
4004 And derived that the sequence corresponding to D_14
4005 can be proved to not wrap because it is used for computing a
4006 memory access; however, this is not really the case -- for example,
4007 if D_12 = (unsigned char) [254,+,1], then D_14 has values
4008 2032, 2040, 0, 8, ..., but the code is still legal. */
4010 if (chrec_contains_undetermined (base)
4011 || chrec_contains_undetermined (step))
4012 return true;
4014 if (integer_zerop (step))
4015 return false;
4017 /* If we can use the fact that signed and pointer arithmetics does not
4018 wrap, we are done. */
4019 if (use_overflow_semantics && nowrap_type_p (TREE_TYPE (base)))
4020 return false;
4022 /* To be able to use estimates on number of iterations of the loop,
4023 we must have an upper bound on the absolute value of the step. */
4024 if (TREE_CODE (step) != INTEGER_CST)
4025 return true;
4027 if (loop_exits_before_overflow (base, step, at_stmt, loop))
4028 return false;
4030 /* At this point we still don't have a proof that the iv does not
4031 overflow: give up. */
4032 return true;
4035 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
4037 void
4038 free_numbers_of_iterations_estimates_loop (struct loop *loop)
4040 struct control_iv *civ;
4041 struct nb_iter_bound *bound;
4043 loop->nb_iterations = NULL;
4044 loop->estimate_state = EST_NOT_COMPUTED;
4045 for (bound = loop->bounds; bound;)
4047 struct nb_iter_bound *next = bound->next;
4048 ggc_free (bound);
4049 bound = next;
4051 loop->bounds = NULL;
4053 for (civ = loop->control_ivs; civ;)
4055 struct control_iv *next = civ->next;
4056 ggc_free (civ);
4057 civ = next;
4059 loop->control_ivs = NULL;
4062 /* Frees the information on upper bounds on numbers of iterations of loops. */
4064 void
4065 free_numbers_of_iterations_estimates (void)
4067 struct loop *loop;
4069 FOR_EACH_LOOP (loop, 0)
4071 free_numbers_of_iterations_estimates_loop (loop);
4075 /* Substitute value VAL for ssa name NAME inside expressions held
4076 at LOOP. */
4078 void
4079 substitute_in_loop_info (struct loop *loop, tree name, tree val)
4081 loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);