libcpp, c, middle-end: Optimize initializers using #embed in C
[official-gcc.git] / gcc / tree-ssa-loop-niter.cc
blobf87731ef8929acc61e3714dd6c338c3b3b082a66
1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004-2024 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 "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "tree-pass.h"
28 #include "ssa.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "stor-layout.h"
32 #include "fold-const.h"
33 #include "calls.h"
34 #include "intl.h"
35 #include "gimplify.h"
36 #include "gimple-iterator.h"
37 #include "tree-cfg.h"
38 #include "tree-ssa-loop-ivopts.h"
39 #include "tree-ssa-loop-niter.h"
40 #include "tree-ssa-loop.h"
41 #include "cfgloop.h"
42 #include "tree-chrec.h"
43 #include "tree-scalar-evolution.h"
44 #include "tree-dfa.h"
45 #include "internal-fn.h"
46 #include "gimple-range.h"
47 #include "sreal.h"
50 /* The maximum number of dominator BBs we search for conditions
51 of loop header copies we use for simplifying a conditional
52 expression. */
53 #define MAX_DOMINATORS_TO_WALK 8
57 Analysis of number of iterations of an affine exit test.
61 /* Bounds on some value, BELOW <= X <= UP. */
63 struct bounds
65 mpz_t below, up;
68 /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
70 static void
71 split_to_var_and_offset (tree expr, tree *var, mpz_t offset)
73 tree type = TREE_TYPE (expr);
74 tree op0, op1;
75 bool negate = false;
77 *var = expr;
78 mpz_set_ui (offset, 0);
80 switch (TREE_CODE (expr))
82 case MINUS_EXPR:
83 negate = true;
84 /* Fallthru. */
86 case PLUS_EXPR:
87 case POINTER_PLUS_EXPR:
88 op0 = TREE_OPERAND (expr, 0);
89 op1 = TREE_OPERAND (expr, 1);
91 if (TREE_CODE (op1) != INTEGER_CST)
92 break;
94 *var = op0;
95 /* Always sign extend the offset. */
96 wi::to_mpz (wi::to_wide (op1), offset, SIGNED);
97 if (negate)
98 mpz_neg (offset, offset);
99 break;
101 case INTEGER_CST:
102 *var = build_int_cst_type (type, 0);
103 wi::to_mpz (wi::to_wide (expr), offset, TYPE_SIGN (type));
104 break;
106 default:
107 break;
111 /* From condition C0 CMP C1 derives information regarding the value range
112 of VAR, which is of TYPE. Results are stored in to BELOW and UP. */
114 static void
115 refine_value_range_using_guard (tree type, tree var,
116 tree c0, enum tree_code cmp, tree c1,
117 mpz_t below, mpz_t up)
119 tree varc0, varc1, ctype;
120 mpz_t offc0, offc1;
121 mpz_t mint, maxt, minc1, maxc1;
122 bool no_wrap = nowrap_type_p (type);
123 bool c0_ok, c1_ok;
124 signop sgn = TYPE_SIGN (type);
126 switch (cmp)
128 case LT_EXPR:
129 case LE_EXPR:
130 case GT_EXPR:
131 case GE_EXPR:
132 STRIP_SIGN_NOPS (c0);
133 STRIP_SIGN_NOPS (c1);
134 ctype = TREE_TYPE (c0);
135 if (!useless_type_conversion_p (ctype, type))
136 return;
138 break;
140 case EQ_EXPR:
141 /* We could derive quite precise information from EQ_EXPR, however,
142 such a guard is unlikely to appear, so we do not bother with
143 handling it. */
144 return;
146 case NE_EXPR:
147 /* NE_EXPR comparisons do not contain much of useful information,
148 except for cases of comparing with bounds. */
149 if (TREE_CODE (c1) != INTEGER_CST
150 || !INTEGRAL_TYPE_P (type))
151 return;
153 /* Ensure that the condition speaks about an expression in the same
154 type as X and Y. */
155 ctype = TREE_TYPE (c0);
156 if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
157 return;
158 c0 = fold_convert (type, c0);
159 c1 = fold_convert (type, c1);
161 if (operand_equal_p (var, c0, 0))
163 /* Case of comparing VAR with its below/up bounds. */
164 auto_mpz valc1;
165 wi::to_mpz (wi::to_wide (c1), valc1, TYPE_SIGN (type));
166 if (mpz_cmp (valc1, below) == 0)
167 cmp = GT_EXPR;
168 if (mpz_cmp (valc1, up) == 0)
169 cmp = LT_EXPR;
171 else
173 /* Case of comparing with the bounds of the type. */
174 wide_int min = wi::min_value (type);
175 wide_int max = wi::max_value (type);
177 if (wi::to_wide (c1) == min)
178 cmp = GT_EXPR;
179 if (wi::to_wide (c1) == max)
180 cmp = LT_EXPR;
183 /* Quick return if no useful information. */
184 if (cmp == NE_EXPR)
185 return;
187 break;
189 default:
190 return;
193 mpz_init (offc0);
194 mpz_init (offc1);
195 split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
196 split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
198 /* We are only interested in comparisons of expressions based on VAR. */
199 if (operand_equal_p (var, varc1, 0))
201 std::swap (varc0, varc1);
202 mpz_swap (offc0, offc1);
203 cmp = swap_tree_comparison (cmp);
205 else if (!operand_equal_p (var, varc0, 0))
207 mpz_clear (offc0);
208 mpz_clear (offc1);
209 return;
212 mpz_init (mint);
213 mpz_init (maxt);
214 get_type_static_bounds (type, mint, maxt);
215 mpz_init (minc1);
216 mpz_init (maxc1);
217 int_range_max r (TREE_TYPE (varc1));
218 /* Setup range information for varc1. */
219 if (integer_zerop (varc1))
221 wi::to_mpz (0, minc1, TYPE_SIGN (type));
222 wi::to_mpz (0, maxc1, TYPE_SIGN (type));
224 else if (TREE_CODE (varc1) == SSA_NAME
225 && INTEGRAL_TYPE_P (type)
226 && get_range_query (cfun)->range_of_expr (r, varc1)
227 && !r.undefined_p ()
228 && !r.varying_p ())
230 gcc_assert (wi::le_p (r.lower_bound (), r.upper_bound (), sgn));
231 wi::to_mpz (r.lower_bound (), minc1, sgn);
232 wi::to_mpz (r.upper_bound (), maxc1, sgn);
234 else
236 mpz_set (minc1, mint);
237 mpz_set (maxc1, maxt);
240 /* Compute valid range information for varc1 + offc1. Note nothing
241 useful can be derived if it overflows or underflows. Overflow or
242 underflow could happen when:
244 offc1 > 0 && varc1 + offc1 > MAX_VAL (type)
245 offc1 < 0 && varc1 + offc1 < MIN_VAL (type). */
246 mpz_add (minc1, minc1, offc1);
247 mpz_add (maxc1, maxc1, offc1);
248 c1_ok = (no_wrap
249 || mpz_sgn (offc1) == 0
250 || (mpz_sgn (offc1) < 0 && mpz_cmp (minc1, mint) >= 0)
251 || (mpz_sgn (offc1) > 0 && mpz_cmp (maxc1, maxt) <= 0));
252 if (!c1_ok)
253 goto end;
255 if (mpz_cmp (minc1, mint) < 0)
256 mpz_set (minc1, mint);
257 if (mpz_cmp (maxc1, maxt) > 0)
258 mpz_set (maxc1, maxt);
260 if (cmp == LT_EXPR)
262 cmp = LE_EXPR;
263 mpz_sub_ui (maxc1, maxc1, 1);
265 if (cmp == GT_EXPR)
267 cmp = GE_EXPR;
268 mpz_add_ui (minc1, minc1, 1);
271 /* Compute range information for varc0. If there is no overflow,
272 the condition implied that
274 (varc0) cmp (varc1 + offc1 - offc0)
276 We can possibly improve the upper bound of varc0 if cmp is LE_EXPR,
277 or the below bound if cmp is GE_EXPR.
279 To prove there is no overflow/underflow, we need to check below
280 four cases:
281 1) cmp == LE_EXPR && offc0 > 0
283 (varc0 + offc0) doesn't overflow
284 && (varc1 + offc1 - offc0) doesn't underflow
286 2) cmp == LE_EXPR && offc0 < 0
288 (varc0 + offc0) doesn't underflow
289 && (varc1 + offc1 - offc0) doesn't overfloe
291 In this case, (varc0 + offc0) will never underflow if we can
292 prove (varc1 + offc1 - offc0) doesn't overflow.
294 3) cmp == GE_EXPR && offc0 < 0
296 (varc0 + offc0) doesn't underflow
297 && (varc1 + offc1 - offc0) doesn't overflow
299 4) cmp == GE_EXPR && offc0 > 0
301 (varc0 + offc0) doesn't overflow
302 && (varc1 + offc1 - offc0) doesn't underflow
304 In this case, (varc0 + offc0) will never overflow if we can
305 prove (varc1 + offc1 - offc0) doesn't underflow.
307 Note we only handle case 2 and 4 in below code. */
309 mpz_sub (minc1, minc1, offc0);
310 mpz_sub (maxc1, maxc1, offc0);
311 c0_ok = (no_wrap
312 || mpz_sgn (offc0) == 0
313 || (cmp == LE_EXPR
314 && mpz_sgn (offc0) < 0 && mpz_cmp (maxc1, maxt) <= 0)
315 || (cmp == GE_EXPR
316 && mpz_sgn (offc0) > 0 && mpz_cmp (minc1, mint) >= 0));
317 if (!c0_ok)
318 goto end;
320 if (cmp == LE_EXPR)
322 if (mpz_cmp (up, maxc1) > 0)
323 mpz_set (up, maxc1);
325 else
327 if (mpz_cmp (below, minc1) < 0)
328 mpz_set (below, minc1);
331 end:
332 mpz_clear (mint);
333 mpz_clear (maxt);
334 mpz_clear (minc1);
335 mpz_clear (maxc1);
336 mpz_clear (offc0);
337 mpz_clear (offc1);
340 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
341 in TYPE to MIN and MAX. */
343 static void
344 determine_value_range (class loop *loop, tree type, tree var, mpz_t off,
345 mpz_t min, mpz_t max)
347 int cnt = 0;
348 mpz_t minm, maxm;
349 basic_block bb;
350 wide_int minv, maxv;
351 enum value_range_kind rtype = VR_VARYING;
353 /* If the expression is a constant, we know its value exactly. */
354 if (integer_zerop (var))
356 mpz_set (min, off);
357 mpz_set (max, off);
358 return;
361 get_type_static_bounds (type, min, max);
363 /* See if we have some range info from VRP. */
364 if (TREE_CODE (var) == SSA_NAME && INTEGRAL_TYPE_P (type))
366 edge e = loop_preheader_edge (loop);
367 signop sgn = TYPE_SIGN (type);
368 gphi_iterator gsi;
370 /* Either for VAR itself... */
371 int_range_max var_range (TREE_TYPE (var));
372 get_range_query (cfun)->range_of_expr (var_range, var);
373 if (var_range.varying_p () || var_range.undefined_p ())
374 rtype = VR_VARYING;
375 else
376 rtype = VR_RANGE;
377 if (!var_range.undefined_p ())
379 minv = var_range.lower_bound ();
380 maxv = var_range.upper_bound ();
383 /* Or for PHI results in loop->header where VAR is used as
384 PHI argument from the loop preheader edge. */
385 int_range_max phi_range (TREE_TYPE (var));
386 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
388 gphi *phi = gsi.phi ();
389 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var
390 && get_range_query (cfun)->range_of_expr (phi_range,
391 gimple_phi_result (phi))
392 && !phi_range.varying_p ()
393 && !phi_range.undefined_p ())
395 if (rtype != VR_RANGE)
397 rtype = VR_RANGE;
398 minv = phi_range.lower_bound ();
399 maxv = phi_range.upper_bound ();
401 else
403 minv = wi::max (minv, phi_range.lower_bound (), sgn);
404 maxv = wi::min (maxv, phi_range.upper_bound (), sgn);
405 /* If the PHI result range are inconsistent with
406 the VAR range, give up on looking at the PHI
407 results. This can happen if VR_UNDEFINED is
408 involved. */
409 if (wi::gt_p (minv, maxv, sgn))
411 int_range_max vr (TREE_TYPE (var));
412 get_range_query (cfun)->range_of_expr (vr, var);
413 if (vr.varying_p () || vr.undefined_p ())
414 rtype = VR_VARYING;
415 else
416 rtype = VR_RANGE;
417 if (!vr.undefined_p ())
419 minv = vr.lower_bound ();
420 maxv = vr.upper_bound ();
422 break;
427 mpz_init (minm);
428 mpz_init (maxm);
429 if (rtype != VR_RANGE)
431 mpz_set (minm, min);
432 mpz_set (maxm, max);
434 else
436 gcc_assert (wi::le_p (minv, maxv, sgn));
437 wi::to_mpz (minv, minm, sgn);
438 wi::to_mpz (maxv, maxm, sgn);
440 /* Now walk the dominators of the loop header and use the entry
441 guards to refine the estimates. */
442 for (bb = loop->header;
443 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
444 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
446 edge e;
447 tree c0, c1;
448 enum tree_code cmp;
450 if (!single_pred_p (bb))
451 continue;
452 e = single_pred_edge (bb);
454 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
455 continue;
457 gcond *cond = as_a <gcond *> (*gsi_last_bb (e->src));
458 c0 = gimple_cond_lhs (cond);
459 cmp = gimple_cond_code (cond);
460 c1 = gimple_cond_rhs (cond);
462 if (e->flags & EDGE_FALSE_VALUE)
463 cmp = invert_tree_comparison (cmp, false);
465 refine_value_range_using_guard (type, var, c0, cmp, c1, minm, maxm);
466 ++cnt;
469 mpz_add (minm, minm, off);
470 mpz_add (maxm, maxm, off);
471 /* If the computation may not wrap or off is zero, then this
472 is always fine. If off is negative and minv + off isn't
473 smaller than type's minimum, or off is positive and
474 maxv + off isn't bigger than type's maximum, use the more
475 precise range too. */
476 if (nowrap_type_p (type)
477 || mpz_sgn (off) == 0
478 || (mpz_sgn (off) < 0 && mpz_cmp (minm, min) >= 0)
479 || (mpz_sgn (off) > 0 && mpz_cmp (maxm, max) <= 0))
481 mpz_set (min, minm);
482 mpz_set (max, maxm);
483 mpz_clear (minm);
484 mpz_clear (maxm);
485 return;
487 mpz_clear (minm);
488 mpz_clear (maxm);
491 /* If the computation may wrap, we know nothing about the value, except for
492 the range of the type. */
493 if (!nowrap_type_p (type))
494 return;
496 /* Since the addition of OFF does not wrap, if OFF is positive, then we may
497 add it to MIN, otherwise to MAX. */
498 if (mpz_sgn (off) < 0)
499 mpz_add (max, max, off);
500 else
501 mpz_add (min, min, off);
504 /* Stores the bounds on the difference of the values of the expressions
505 (var + X) and (var + Y), computed in TYPE, to BNDS. */
507 static void
508 bound_difference_of_offsetted_base (tree type, mpz_t x, mpz_t y,
509 bounds *bnds)
511 int rel = mpz_cmp (x, y);
512 bool may_wrap = !nowrap_type_p (type);
514 /* If X == Y, then the expressions are always equal.
515 If X > Y, there are the following possibilities:
516 a) neither of var + X and var + Y overflow or underflow, or both of
517 them do. Then their difference is X - Y.
518 b) var + X overflows, and var + Y does not. Then the values of the
519 expressions are var + X - M and var + Y, where M is the range of
520 the type, and their difference is X - Y - M.
521 c) var + Y underflows and var + X does not. Their difference again
522 is M - X + Y.
523 Therefore, if the arithmetics in type does not overflow, then the
524 bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
525 Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
526 (X - Y, X - Y + M). */
528 if (rel == 0)
530 mpz_set_ui (bnds->below, 0);
531 mpz_set_ui (bnds->up, 0);
532 return;
535 auto_mpz m;
536 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), m, UNSIGNED);
537 mpz_add_ui (m, m, 1);
538 mpz_sub (bnds->up, x, y);
539 mpz_set (bnds->below, bnds->up);
541 if (may_wrap)
543 if (rel > 0)
544 mpz_sub (bnds->below, bnds->below, m);
545 else
546 mpz_add (bnds->up, bnds->up, m);
550 /* From condition C0 CMP C1 derives information regarding the
551 difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
552 and stores it to BNDS. */
554 static void
555 refine_bounds_using_guard (tree type, tree varx, mpz_t offx,
556 tree vary, mpz_t offy,
557 tree c0, enum tree_code cmp, tree c1,
558 bounds *bnds)
560 tree varc0, varc1, ctype;
561 mpz_t offc0, offc1, loffx, loffy, bnd;
562 bool lbound = false;
563 bool no_wrap = nowrap_type_p (type);
564 bool x_ok, y_ok;
566 switch (cmp)
568 case LT_EXPR:
569 case LE_EXPR:
570 case GT_EXPR:
571 case GE_EXPR:
572 STRIP_SIGN_NOPS (c0);
573 STRIP_SIGN_NOPS (c1);
574 ctype = TREE_TYPE (c0);
575 if (!useless_type_conversion_p (ctype, type))
576 return;
578 break;
580 case EQ_EXPR:
581 /* We could derive quite precise information from EQ_EXPR, however, such
582 a guard is unlikely to appear, so we do not bother with handling
583 it. */
584 return;
586 case NE_EXPR:
587 /* NE_EXPR comparisons do not contain much of useful information, except for
588 special case of comparing with the bounds of the type. */
589 if (TREE_CODE (c1) != INTEGER_CST
590 || !INTEGRAL_TYPE_P (type))
591 return;
593 /* Ensure that the condition speaks about an expression in the same type
594 as X and Y. */
595 ctype = TREE_TYPE (c0);
596 if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
597 return;
598 c0 = fold_convert (type, c0);
599 c1 = fold_convert (type, c1);
601 if (TYPE_MIN_VALUE (type)
602 && operand_equal_p (c1, TYPE_MIN_VALUE (type), 0))
604 cmp = GT_EXPR;
605 break;
607 if (TYPE_MAX_VALUE (type)
608 && operand_equal_p (c1, TYPE_MAX_VALUE (type), 0))
610 cmp = LT_EXPR;
611 break;
614 return;
615 default:
616 return;
619 mpz_init (offc0);
620 mpz_init (offc1);
621 split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
622 split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
624 /* We are only interested in comparisons of expressions based on VARX and
625 VARY. TODO -- we might also be able to derive some bounds from
626 expressions containing just one of the variables. */
628 if (operand_equal_p (varx, varc1, 0))
630 std::swap (varc0, varc1);
631 mpz_swap (offc0, offc1);
632 cmp = swap_tree_comparison (cmp);
635 if (!operand_equal_p (varx, varc0, 0)
636 || !operand_equal_p (vary, varc1, 0))
637 goto end;
639 mpz_init_set (loffx, offx);
640 mpz_init_set (loffy, offy);
642 if (cmp == GT_EXPR || cmp == GE_EXPR)
644 std::swap (varx, vary);
645 mpz_swap (offc0, offc1);
646 mpz_swap (loffx, loffy);
647 cmp = swap_tree_comparison (cmp);
648 lbound = true;
651 /* If there is no overflow, the condition implies that
653 (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
655 The overflows and underflows may complicate things a bit; each
656 overflow decreases the appropriate offset by M, and underflow
657 increases it by M. The above inequality would not necessarily be
658 true if
660 -- VARX + OFFX underflows and VARX + OFFC0 does not, or
661 VARX + OFFC0 overflows, but VARX + OFFX does not.
662 This may only happen if OFFX < OFFC0.
663 -- VARY + OFFY overflows and VARY + OFFC1 does not, or
664 VARY + OFFC1 underflows and VARY + OFFY does not.
665 This may only happen if OFFY > OFFC1. */
667 if (no_wrap)
669 x_ok = true;
670 y_ok = true;
672 else
674 x_ok = (integer_zerop (varx)
675 || mpz_cmp (loffx, offc0) >= 0);
676 y_ok = (integer_zerop (vary)
677 || mpz_cmp (loffy, offc1) <= 0);
680 if (x_ok && y_ok)
682 mpz_init (bnd);
683 mpz_sub (bnd, loffx, loffy);
684 mpz_add (bnd, bnd, offc1);
685 mpz_sub (bnd, bnd, offc0);
687 if (cmp == LT_EXPR)
688 mpz_sub_ui (bnd, bnd, 1);
690 if (lbound)
692 mpz_neg (bnd, bnd);
693 if (mpz_cmp (bnds->below, bnd) < 0)
694 mpz_set (bnds->below, bnd);
696 else
698 if (mpz_cmp (bnd, bnds->up) < 0)
699 mpz_set (bnds->up, bnd);
701 mpz_clear (bnd);
704 mpz_clear (loffx);
705 mpz_clear (loffy);
706 end:
707 mpz_clear (offc0);
708 mpz_clear (offc1);
711 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
712 The subtraction is considered to be performed in arbitrary precision,
713 without overflows.
715 We do not attempt to be too clever regarding the value ranges of X and
716 Y; most of the time, they are just integers or ssa names offsetted by
717 integer. However, we try to use the information contained in the
718 comparisons before the loop (usually created by loop header copying). */
720 static void
721 bound_difference (class loop *loop, tree x, tree y, bounds *bnds)
723 tree type = TREE_TYPE (x);
724 tree varx, vary;
725 mpz_t offx, offy;
726 int cnt = 0;
727 edge e;
728 basic_block bb;
729 tree c0, c1;
730 enum tree_code cmp;
732 /* Get rid of unnecessary casts, but preserve the value of
733 the expressions. */
734 STRIP_SIGN_NOPS (x);
735 STRIP_SIGN_NOPS (y);
737 mpz_init (bnds->below);
738 mpz_init (bnds->up);
739 mpz_init (offx);
740 mpz_init (offy);
741 split_to_var_and_offset (x, &varx, offx);
742 split_to_var_and_offset (y, &vary, offy);
744 if (!integer_zerop (varx)
745 && operand_equal_p (varx, vary, 0))
747 /* Special case VARX == VARY -- we just need to compare the
748 offsets. The matters are a bit more complicated in the
749 case addition of offsets may wrap. */
750 bound_difference_of_offsetted_base (type, offx, offy, bnds);
752 else
754 /* Otherwise, use the value ranges to determine the initial
755 estimates on below and up. */
756 auto_mpz minx, maxx, miny, maxy;
757 determine_value_range (loop, type, varx, offx, minx, maxx);
758 determine_value_range (loop, type, vary, offy, miny, maxy);
760 mpz_sub (bnds->below, minx, maxy);
761 mpz_sub (bnds->up, maxx, miny);
764 /* If both X and Y are constants, we cannot get any more precise. */
765 if (integer_zerop (varx) && integer_zerop (vary))
766 goto end;
768 /* Now walk the dominators of the loop header and use the entry
769 guards to refine the estimates. */
770 for (bb = loop->header;
771 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
772 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
774 if (!single_pred_p (bb))
775 continue;
776 e = single_pred_edge (bb);
778 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
779 continue;
781 gcond *cond = as_a <gcond *> (*gsi_last_bb (e->src));
782 c0 = gimple_cond_lhs (cond);
783 cmp = gimple_cond_code (cond);
784 c1 = gimple_cond_rhs (cond);
786 if (e->flags & EDGE_FALSE_VALUE)
787 cmp = invert_tree_comparison (cmp, false);
789 refine_bounds_using_guard (type, varx, offx, vary, offy,
790 c0, cmp, c1, bnds);
791 ++cnt;
794 end:
795 mpz_clear (offx);
796 mpz_clear (offy);
799 /* Update the bounds in BNDS that restrict the value of X to the bounds
800 that restrict the value of X + DELTA. X can be obtained as a
801 difference of two values in TYPE. */
803 static void
804 bounds_add (bounds *bnds, const widest_int &delta, tree type)
806 mpz_t mdelta, max;
808 mpz_init (mdelta);
809 wi::to_mpz (delta, mdelta, SIGNED);
811 mpz_init (max);
812 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
814 mpz_add (bnds->up, bnds->up, mdelta);
815 mpz_add (bnds->below, bnds->below, mdelta);
817 if (mpz_cmp (bnds->up, max) > 0)
818 mpz_set (bnds->up, max);
820 mpz_neg (max, max);
821 if (mpz_cmp (bnds->below, max) < 0)
822 mpz_set (bnds->below, max);
824 mpz_clear (mdelta);
825 mpz_clear (max);
828 /* Update the bounds in BNDS that restrict the value of X to the bounds
829 that restrict the value of -X. */
831 static void
832 bounds_negate (bounds *bnds)
834 mpz_t tmp;
836 mpz_init_set (tmp, bnds->up);
837 mpz_neg (bnds->up, bnds->below);
838 mpz_neg (bnds->below, tmp);
839 mpz_clear (tmp);
842 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
844 static tree
845 inverse (tree x, tree mask)
847 tree type = TREE_TYPE (x);
848 tree rslt;
849 unsigned ctr = tree_floor_log2 (mask);
851 if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
853 unsigned HOST_WIDE_INT ix;
854 unsigned HOST_WIDE_INT imask;
855 unsigned HOST_WIDE_INT irslt = 1;
857 gcc_assert (cst_and_fits_in_hwi (x));
858 gcc_assert (cst_and_fits_in_hwi (mask));
860 ix = int_cst_value (x);
861 imask = int_cst_value (mask);
863 for (; ctr; ctr--)
865 irslt *= ix;
866 ix *= ix;
868 irslt &= imask;
870 rslt = build_int_cst_type (type, irslt);
872 else
874 rslt = build_int_cst (type, 1);
875 for (; ctr; ctr--)
877 rslt = int_const_binop (MULT_EXPR, rslt, x);
878 x = int_const_binop (MULT_EXPR, x, x);
880 rslt = int_const_binop (BIT_AND_EXPR, rslt, mask);
883 return rslt;
886 /* Derives the upper bound BND on the number of executions of loop with exit
887 condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
888 the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
889 that the loop ends through this exit, i.e., the induction variable ever
890 reaches the value of C.
892 The value C is equal to final - base, where final and base are the final and
893 initial value of the actual induction variable in the analysed loop. BNDS
894 bounds the value of this difference when computed in signed type with
895 unbounded range, while the computation of C is performed in an unsigned
896 type with the range matching the range of the type of the induction variable.
897 In particular, BNDS.up contains an upper bound on C in the following cases:
898 -- if the iv must reach its final value without overflow, i.e., if
899 NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
900 -- if final >= base, which we know to hold when BNDS.below >= 0. */
902 static void
903 number_of_iterations_ne_max (mpz_t bnd, bool no_overflow, tree c, tree s,
904 bounds *bnds, bool exit_must_be_taken)
906 widest_int max;
907 mpz_t d;
908 tree type = TREE_TYPE (c);
909 bool bnds_u_valid = ((no_overflow && exit_must_be_taken)
910 || mpz_sgn (bnds->below) >= 0);
912 if (integer_onep (s)
913 || (TREE_CODE (c) == INTEGER_CST
914 && TREE_CODE (s) == INTEGER_CST
915 && wi::mod_trunc (wi::to_wide (c), wi::to_wide (s),
916 TYPE_SIGN (type)) == 0)
917 || (TYPE_OVERFLOW_UNDEFINED (type)
918 && multiple_of_p (type, c, s)))
920 /* If C is an exact multiple of S, then its value will be reached before
921 the induction variable overflows (unless the loop is exited in some
922 other way before). Note that the actual induction variable in the
923 loop (which ranges from base to final instead of from 0 to C) may
924 overflow, in which case BNDS.up will not be giving a correct upper
925 bound on C; thus, BNDS_U_VALID had to be computed in advance. */
926 no_overflow = true;
927 exit_must_be_taken = true;
930 /* If the induction variable can overflow, the number of iterations is at
931 most the period of the control variable (or infinite, but in that case
932 the whole # of iterations analysis will fail). */
933 if (!no_overflow)
935 max = wi::mask <widest_int> (TYPE_PRECISION (type)
936 - wi::ctz (wi::to_wide (s)), false);
937 wi::to_mpz (max, bnd, UNSIGNED);
938 return;
941 /* Now we know that the induction variable does not overflow, so the loop
942 iterates at most (range of type / S) times. */
943 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), bnd, UNSIGNED);
945 /* If the induction variable is guaranteed to reach the value of C before
946 overflow, ... */
947 if (exit_must_be_taken)
949 /* ... then we can strengthen this to C / S, and possibly we can use
950 the upper bound on C given by BNDS. */
951 if (TREE_CODE (c) == INTEGER_CST)
952 wi::to_mpz (wi::to_wide (c), bnd, UNSIGNED);
953 else if (bnds_u_valid)
954 mpz_set (bnd, bnds->up);
957 mpz_init (d);
958 wi::to_mpz (wi::to_wide (s), d, UNSIGNED);
959 mpz_fdiv_q (bnd, bnd, d);
960 mpz_clear (d);
963 /* Determines number of iterations of loop whose ending condition
964 is IV <> FINAL. TYPE is the type of the iv. The number of
965 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
966 we know that the exit must be taken eventually, i.e., that the IV
967 ever reaches the value FINAL (we derived this earlier, and possibly set
968 NITER->assumptions to make sure this is the case). BNDS contains the
969 bounds on the difference FINAL - IV->base. */
971 static bool
972 number_of_iterations_ne (class loop *loop, tree type, affine_iv *iv,
973 tree final, class tree_niter_desc *niter,
974 bool exit_must_be_taken, bounds *bnds)
976 tree niter_type = unsigned_type_for (type);
977 tree s, c, d, bits, assumption, tmp, bound;
979 niter->control = *iv;
980 niter->bound = final;
981 niter->cmp = NE_EXPR;
983 /* Rearrange the terms so that we get inequality S * i <> C, with S
984 positive. Also cast everything to the unsigned type. If IV does
985 not overflow, BNDS bounds the value of C. Also, this is the
986 case if the computation |FINAL - IV->base| does not overflow, i.e.,
987 if BNDS->below in the result is nonnegative. */
988 if (tree_int_cst_sign_bit (iv->step))
990 s = fold_convert (niter_type,
991 fold_build1 (NEGATE_EXPR, type, iv->step));
992 c = fold_build2 (MINUS_EXPR, niter_type,
993 fold_convert (niter_type, iv->base),
994 fold_convert (niter_type, final));
995 bounds_negate (bnds);
997 else
999 s = fold_convert (niter_type, iv->step);
1000 c = fold_build2 (MINUS_EXPR, niter_type,
1001 fold_convert (niter_type, final),
1002 fold_convert (niter_type, iv->base));
1005 auto_mpz max;
1006 number_of_iterations_ne_max (max, iv->no_overflow, c, s, bnds,
1007 exit_must_be_taken);
1008 niter->max = widest_int::from (wi::from_mpz (niter_type, max, false),
1009 TYPE_SIGN (niter_type));
1011 /* Compute no-overflow information for the control iv. This can be
1012 proven when below two conditions are satisfied:
1014 1) IV evaluates toward FINAL at beginning, i.e:
1015 base <= FINAL ; step > 0
1016 base >= FINAL ; step < 0
1018 2) |FINAL - base| is an exact multiple of step.
1020 Unfortunately, it's hard to prove above conditions after pass loop-ch
1021 because loop with exit condition (IV != FINAL) usually will be guarded
1022 by initial-condition (IV.base - IV.step != FINAL). In this case, we
1023 can alternatively try to prove below conditions:
1025 1') IV evaluates toward FINAL at beginning, i.e:
1026 new_base = base - step < FINAL ; step > 0
1027 && base - step doesn't underflow
1028 new_base = base - step > FINAL ; step < 0
1029 && base - step doesn't overflow
1031 Please refer to PR34114 as an example of loop-ch's impact.
1033 Note, for NE_EXPR, base equals to FINAL is a special case, in
1034 which the loop exits immediately, and the iv does not overflow.
1036 Also note, we prove condition 2) by checking base and final seperately
1037 along with condition 1) or 1'). Since we ensure the difference
1038 computation of c does not wrap with cond below and the adjusted s
1039 will fit a signed type as well as an unsigned we can safely do
1040 this using the type of the IV if it is not pointer typed. */
1041 tree mtype = type;
1042 if (POINTER_TYPE_P (type))
1043 mtype = niter_type;
1044 if (!niter->control.no_overflow
1045 && (integer_onep (s)
1046 || (multiple_of_p (mtype, fold_convert (mtype, iv->base),
1047 fold_convert (mtype, s), false)
1048 && multiple_of_p (mtype, fold_convert (mtype, final),
1049 fold_convert (mtype, s), false))))
1051 tree t, cond, relaxed_cond = boolean_false_node;
1053 if (tree_int_cst_sign_bit (iv->step))
1055 cond = fold_build2 (GE_EXPR, boolean_type_node, iv->base, final);
1056 if (TREE_CODE (type) == INTEGER_TYPE)
1058 /* Only when base - step doesn't overflow. */
1059 t = TYPE_MAX_VALUE (type);
1060 t = fold_build2 (PLUS_EXPR, type, t, iv->step);
1061 t = fold_build2 (GE_EXPR, boolean_type_node, t, iv->base);
1062 if (integer_nonzerop (t))
1064 t = fold_build2 (MINUS_EXPR, type, iv->base, iv->step);
1065 relaxed_cond = fold_build2 (GT_EXPR, boolean_type_node, t,
1066 final);
1070 else
1072 cond = fold_build2 (LE_EXPR, boolean_type_node, iv->base, final);
1073 if (TREE_CODE (type) == INTEGER_TYPE)
1075 /* Only when base - step doesn't underflow. */
1076 t = TYPE_MIN_VALUE (type);
1077 t = fold_build2 (PLUS_EXPR, type, t, iv->step);
1078 t = fold_build2 (LE_EXPR, boolean_type_node, t, iv->base);
1079 if (integer_nonzerop (t))
1081 t = fold_build2 (MINUS_EXPR, type, iv->base, iv->step);
1082 relaxed_cond = fold_build2 (LT_EXPR, boolean_type_node, t,
1083 final);
1088 t = simplify_using_initial_conditions (loop, cond);
1089 if (!t || !integer_onep (t))
1090 t = simplify_using_initial_conditions (loop, relaxed_cond);
1092 if (t && integer_onep (t))
1094 niter->control.no_overflow = true;
1095 niter->niter = fold_build2 (EXACT_DIV_EXPR, niter_type, c, s);
1096 return true;
1100 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
1101 is infinite. Otherwise, the number of iterations is
1102 (inverse(s/d) * (c/d)) mod (size of mode/d). */
1103 bits = num_ending_zeros (s);
1104 bound = build_low_bits_mask (niter_type,
1105 (TYPE_PRECISION (niter_type)
1106 - tree_to_uhwi (bits)));
1108 d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
1109 build_int_cst (niter_type, 1), bits);
1110 s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
1112 if (!exit_must_be_taken)
1114 /* If we cannot assume that the exit is taken eventually, record the
1115 assumptions for divisibility of c. */
1116 assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
1117 assumption = fold_build2 (EQ_EXPR, boolean_type_node,
1118 assumption, build_int_cst (niter_type, 0));
1119 if (!integer_nonzerop (assumption))
1120 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1121 niter->assumptions, assumption);
1124 c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
1125 if (integer_onep (s))
1127 niter->niter = c;
1129 else
1131 tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
1132 niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
1134 return true;
1137 /* Checks whether we can determine the final value of the control variable
1138 of the loop with ending condition IV0 < IV1 (computed in TYPE).
1139 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
1140 of the step. The assumptions necessary to ensure that the computation
1141 of the final value does not overflow are recorded in NITER. If we
1142 find the final value, we adjust DELTA and return TRUE. Otherwise
1143 we return false. BNDS bounds the value of IV1->base - IV0->base,
1144 and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
1145 true if we know that the exit must be taken eventually. */
1147 static bool
1148 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
1149 class tree_niter_desc *niter,
1150 tree *delta, tree step,
1151 bool exit_must_be_taken, bounds *bnds)
1153 tree niter_type = TREE_TYPE (step);
1154 tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
1155 tree tmod;
1156 tree assumption = boolean_true_node, bound, noloop;
1157 bool fv_comp_no_overflow;
1158 tree type1 = type;
1159 if (POINTER_TYPE_P (type))
1160 type1 = sizetype;
1162 if (TREE_CODE (mod) != INTEGER_CST)
1163 return false;
1164 if (integer_nonzerop (mod))
1165 mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
1166 tmod = fold_convert (type1, mod);
1168 auto_mpz mmod;
1169 wi::to_mpz (wi::to_wide (mod), mmod, UNSIGNED);
1170 mpz_neg (mmod, mmod);
1172 /* If the induction variable does not overflow and the exit is taken,
1173 then the computation of the final value does not overflow. This is
1174 also obviously the case if the new final value is equal to the
1175 current one. Finally, we postulate this for pointer type variables,
1176 as the code cannot rely on the object to that the pointer points being
1177 placed at the end of the address space (and more pragmatically,
1178 TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
1179 if (integer_zerop (mod) || POINTER_TYPE_P (type))
1180 fv_comp_no_overflow = true;
1181 else if (!exit_must_be_taken)
1182 fv_comp_no_overflow = false;
1183 else
1184 fv_comp_no_overflow =
1185 (iv0->no_overflow && integer_nonzerop (iv0->step))
1186 || (iv1->no_overflow && integer_nonzerop (iv1->step));
1188 if (integer_nonzerop (iv0->step))
1190 /* The final value of the iv is iv1->base + MOD, assuming that this
1191 computation does not overflow, and that
1192 iv0->base <= iv1->base + MOD. */
1193 if (!fv_comp_no_overflow)
1195 bound = fold_build2 (MINUS_EXPR, type1,
1196 TYPE_MAX_VALUE (type1), tmod);
1197 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1198 iv1->base, bound);
1199 if (integer_zerop (assumption))
1200 return false;
1202 if (mpz_cmp (mmod, bnds->below) < 0)
1203 noloop = boolean_false_node;
1204 else if (POINTER_TYPE_P (type))
1205 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1206 iv0->base,
1207 fold_build_pointer_plus (iv1->base, tmod));
1208 else
1209 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1210 iv0->base,
1211 fold_build2 (PLUS_EXPR, type1,
1212 iv1->base, tmod));
1214 else
1216 /* The final value of the iv is iv0->base - MOD, assuming that this
1217 computation does not overflow, and that
1218 iv0->base - MOD <= iv1->base. */
1219 if (!fv_comp_no_overflow)
1221 bound = fold_build2 (PLUS_EXPR, type1,
1222 TYPE_MIN_VALUE (type1), tmod);
1223 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1224 iv0->base, bound);
1225 if (integer_zerop (assumption))
1226 return false;
1228 if (mpz_cmp (mmod, bnds->below) < 0)
1229 noloop = boolean_false_node;
1230 else if (POINTER_TYPE_P (type))
1231 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1232 fold_build_pointer_plus (iv0->base,
1233 fold_build1 (NEGATE_EXPR,
1234 type1, tmod)),
1235 iv1->base);
1236 else
1237 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1238 fold_build2 (MINUS_EXPR, type1,
1239 iv0->base, tmod),
1240 iv1->base);
1243 if (!integer_nonzerop (assumption))
1244 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1245 niter->assumptions,
1246 assumption);
1247 if (!integer_zerop (noloop))
1248 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1249 niter->may_be_zero,
1250 noloop);
1251 bounds_add (bnds, wi::to_widest (mod), type);
1252 *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
1254 return true;
1257 /* Add assertions to NITER that ensure that the control variable of the loop
1258 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
1259 are TYPE. Returns false if we can prove that there is an overflow, true
1260 otherwise. STEP is the absolute value of the step. */
1262 static bool
1263 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1264 class tree_niter_desc *niter, tree step)
1266 tree bound, d, assumption, diff;
1267 tree niter_type = TREE_TYPE (step);
1269 if (integer_nonzerop (iv0->step))
1271 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
1272 if (iv0->no_overflow)
1273 return true;
1275 /* If iv0->base is a constant, we can determine the last value before
1276 overflow precisely; otherwise we conservatively assume
1277 MAX - STEP + 1. */
1279 if (TREE_CODE (iv0->base) == INTEGER_CST)
1281 d = fold_build2 (MINUS_EXPR, niter_type,
1282 fold_convert (niter_type, TYPE_MAX_VALUE (type)),
1283 fold_convert (niter_type, iv0->base));
1284 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
1286 else
1287 diff = fold_build2 (MINUS_EXPR, niter_type, step,
1288 build_int_cst (niter_type, 1));
1289 bound = fold_build2 (MINUS_EXPR, type,
1290 TYPE_MAX_VALUE (type), fold_convert (type, diff));
1291 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1292 iv1->base, bound);
1294 else
1296 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
1297 if (iv1->no_overflow)
1298 return true;
1300 if (TREE_CODE (iv1->base) == INTEGER_CST)
1302 d = fold_build2 (MINUS_EXPR, niter_type,
1303 fold_convert (niter_type, iv1->base),
1304 fold_convert (niter_type, TYPE_MIN_VALUE (type)));
1305 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
1307 else
1308 diff = fold_build2 (MINUS_EXPR, niter_type, step,
1309 build_int_cst (niter_type, 1));
1310 bound = fold_build2 (PLUS_EXPR, type,
1311 TYPE_MIN_VALUE (type), fold_convert (type, diff));
1312 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1313 iv0->base, bound);
1316 if (integer_zerop (assumption))
1317 return false;
1318 if (!integer_nonzerop (assumption))
1319 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1320 niter->assumptions, assumption);
1322 iv0->no_overflow = true;
1323 iv1->no_overflow = true;
1324 return true;
1327 /* Add an assumption to NITER that a loop whose ending condition
1328 is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
1329 bounds the value of IV1->base - IV0->base. */
1331 static void
1332 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1333 class tree_niter_desc *niter, bounds *bnds)
1335 tree assumption = boolean_true_node, bound, diff;
1336 tree mbz, mbzl, mbzr, type1;
1337 bool rolls_p, no_overflow_p;
1338 widest_int dstep;
1339 mpz_t mstep, max;
1341 /* We are going to compute the number of iterations as
1342 (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1343 variant of TYPE. This formula only works if
1345 -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1347 (where MAX is the maximum value of the unsigned variant of TYPE, and
1348 the computations in this formula are performed in full precision,
1349 i.e., without overflows).
1351 Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1352 we have a condition of the form iv0->base - step < iv1->base before the loop,
1353 and for loops iv0->base < iv1->base - step * i the condition
1354 iv0->base < iv1->base + step, due to loop header copying, which enable us
1355 to prove the lower bound.
1357 The upper bound is more complicated. Unless the expressions for initial
1358 and final value themselves contain enough information, we usually cannot
1359 derive it from the context. */
1361 /* First check whether the answer does not follow from the bounds we gathered
1362 before. */
1363 if (integer_nonzerop (iv0->step))
1364 dstep = wi::to_widest (iv0->step);
1365 else
1367 dstep = wi::sext (wi::to_widest (iv1->step), TYPE_PRECISION (type));
1368 dstep = -dstep;
1371 mpz_init (mstep);
1372 wi::to_mpz (dstep, mstep, UNSIGNED);
1373 mpz_neg (mstep, mstep);
1374 mpz_add_ui (mstep, mstep, 1);
1376 rolls_p = mpz_cmp (mstep, bnds->below) <= 0;
1378 mpz_init (max);
1379 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
1380 mpz_add (max, max, mstep);
1381 no_overflow_p = (mpz_cmp (bnds->up, max) <= 0
1382 /* For pointers, only values lying inside a single object
1383 can be compared or manipulated by pointer arithmetics.
1384 Gcc in general does not allow or handle objects larger
1385 than half of the address space, hence the upper bound
1386 is satisfied for pointers. */
1387 || POINTER_TYPE_P (type));
1388 mpz_clear (mstep);
1389 mpz_clear (max);
1391 if (rolls_p && no_overflow_p)
1392 return;
1394 type1 = type;
1395 if (POINTER_TYPE_P (type))
1396 type1 = sizetype;
1398 /* Now the hard part; we must formulate the assumption(s) as expressions, and
1399 we must be careful not to introduce overflow. */
1401 if (integer_nonzerop (iv0->step))
1403 diff = fold_build2 (MINUS_EXPR, type1,
1404 iv0->step, build_int_cst (type1, 1));
1406 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1407 0 address never belongs to any object, we can assume this for
1408 pointers. */
1409 if (!POINTER_TYPE_P (type))
1411 bound = fold_build2 (PLUS_EXPR, type1,
1412 TYPE_MIN_VALUE (type), diff);
1413 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1414 iv0->base, bound);
1417 /* And then we can compute iv0->base - diff, and compare it with
1418 iv1->base. */
1419 mbzl = fold_build2 (MINUS_EXPR, type1,
1420 fold_convert (type1, iv0->base), diff);
1421 mbzr = fold_convert (type1, iv1->base);
1423 else
1425 diff = fold_build2 (PLUS_EXPR, type1,
1426 iv1->step, build_int_cst (type1, 1));
1428 if (!POINTER_TYPE_P (type))
1430 bound = fold_build2 (PLUS_EXPR, type1,
1431 TYPE_MAX_VALUE (type), diff);
1432 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1433 iv1->base, bound);
1436 mbzl = fold_convert (type1, iv0->base);
1437 mbzr = fold_build2 (MINUS_EXPR, type1,
1438 fold_convert (type1, iv1->base), diff);
1441 if (!integer_nonzerop (assumption))
1442 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1443 niter->assumptions, assumption);
1444 if (!rolls_p)
1446 mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
1447 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1448 niter->may_be_zero, mbz);
1452 /* Determines number of iterations of loop whose ending condition
1453 is IV0 < IV1 which likes: {base, -C} < n, or n < {base, C}.
1454 The number of iterations is stored to NITER. */
1456 static bool
1457 number_of_iterations_until_wrap (class loop *loop, tree type, affine_iv *iv0,
1458 affine_iv *iv1, class tree_niter_desc *niter)
1460 tree niter_type = unsigned_type_for (type);
1461 tree step, num, assumptions, may_be_zero, span;
1462 wide_int high, low, max, min;
1464 may_be_zero = fold_build2 (LE_EXPR, boolean_type_node, iv1->base, iv0->base);
1465 if (integer_onep (may_be_zero))
1466 return false;
1468 int prec = TYPE_PRECISION (type);
1469 signop sgn = TYPE_SIGN (type);
1470 min = wi::min_value (prec, sgn);
1471 max = wi::max_value (prec, sgn);
1473 /* n < {base, C}. */
1474 if (integer_zerop (iv0->step) && !tree_int_cst_sign_bit (iv1->step))
1476 step = iv1->step;
1477 /* MIN + C - 1 <= n. */
1478 tree last = wide_int_to_tree (type, min + wi::to_wide (step) - 1);
1479 assumptions = fold_build2 (LE_EXPR, boolean_type_node, last, iv0->base);
1480 if (integer_zerop (assumptions))
1481 return false;
1483 num = fold_build2 (MINUS_EXPR, niter_type,
1484 wide_int_to_tree (niter_type, max),
1485 fold_convert (niter_type, iv1->base));
1487 /* When base has the form iv + 1, if we know iv >= n, then iv + 1 < n
1488 only when iv + 1 overflows, i.e. when iv == TYPE_VALUE_MAX. */
1489 if (sgn == UNSIGNED
1490 && integer_onep (step)
1491 && TREE_CODE (iv1->base) == PLUS_EXPR
1492 && integer_onep (TREE_OPERAND (iv1->base, 1)))
1494 tree cond = fold_build2 (GE_EXPR, boolean_type_node,
1495 TREE_OPERAND (iv1->base, 0), iv0->base);
1496 cond = simplify_using_initial_conditions (loop, cond);
1497 if (integer_onep (cond))
1498 may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node,
1499 TREE_OPERAND (iv1->base, 0),
1500 TYPE_MAX_VALUE (type));
1503 high = max;
1504 if (TREE_CODE (iv1->base) == INTEGER_CST)
1505 low = wi::to_wide (iv1->base) - 1;
1506 else if (TREE_CODE (iv0->base) == INTEGER_CST)
1507 low = wi::to_wide (iv0->base);
1508 else
1509 low = min;
1511 /* {base, -C} < n. */
1512 else if (tree_int_cst_sign_bit (iv0->step) && integer_zerop (iv1->step))
1514 step = fold_build1 (NEGATE_EXPR, TREE_TYPE (iv0->step), iv0->step);
1515 /* MAX - C + 1 >= n. */
1516 tree last = wide_int_to_tree (type, max - wi::to_wide (step) + 1);
1517 assumptions = fold_build2 (GE_EXPR, boolean_type_node, last, iv1->base);
1518 if (integer_zerop (assumptions))
1519 return false;
1521 num = fold_build2 (MINUS_EXPR, niter_type,
1522 fold_convert (niter_type, iv0->base),
1523 wide_int_to_tree (niter_type, min));
1524 low = min;
1525 if (TREE_CODE (iv0->base) == INTEGER_CST)
1526 high = wi::to_wide (iv0->base) + 1;
1527 else if (TREE_CODE (iv1->base) == INTEGER_CST)
1528 high = wi::to_wide (iv1->base);
1529 else
1530 high = max;
1532 else
1533 return false;
1535 /* (delta + step - 1) / step */
1536 step = fold_convert (niter_type, step);
1537 num = fold_build2 (PLUS_EXPR, niter_type, num, step);
1538 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, num, step);
1540 widest_int delta, s;
1541 delta = widest_int::from (high, sgn) - widest_int::from (low, sgn);
1542 s = wi::to_widest (step);
1543 delta = delta + s - 1;
1544 niter->max = wi::udiv_floor (delta, s);
1546 niter->may_be_zero = may_be_zero;
1548 if (!integer_nonzerop (assumptions))
1549 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1550 niter->assumptions, assumptions);
1552 niter->control.no_overflow = false;
1554 /* Update bound and exit condition as:
1555 bound = niter * STEP + (IVbase - STEP).
1556 { IVbase - STEP, +, STEP } != bound
1557 Here, biasing IVbase by 1 step makes 'bound' be the value before wrap.
1559 tree base_type = TREE_TYPE (niter->control.base);
1560 if (POINTER_TYPE_P (base_type))
1562 tree utype = unsigned_type_for (base_type);
1563 niter->control.base
1564 = fold_build2 (MINUS_EXPR, utype,
1565 fold_convert (utype, niter->control.base),
1566 fold_convert (utype, niter->control.step));
1567 niter->control.base = fold_convert (base_type, niter->control.base);
1569 else
1570 niter->control.base
1571 = fold_build2 (MINUS_EXPR, base_type, niter->control.base,
1572 niter->control.step);
1574 span = fold_build2 (MULT_EXPR, niter_type, niter->niter,
1575 fold_convert (niter_type, niter->control.step));
1576 niter->bound = fold_build2 (PLUS_EXPR, niter_type, span,
1577 fold_convert (niter_type, niter->control.base));
1578 niter->bound = fold_convert (type, niter->bound);
1579 niter->cmp = NE_EXPR;
1581 return true;
1584 /* Determines number of iterations of loop whose ending condition
1585 is IV0 < IV1. TYPE is the type of the iv. The number of
1586 iterations is stored to NITER. BNDS bounds the difference
1587 IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1588 that the exit must be taken eventually. */
1590 static bool
1591 number_of_iterations_lt (class loop *loop, tree type, affine_iv *iv0,
1592 affine_iv *iv1, class tree_niter_desc *niter,
1593 bool exit_must_be_taken, bounds *bnds)
1595 tree niter_type = unsigned_type_for (type);
1596 tree delta, step, s;
1597 mpz_t mstep, tmp;
1599 if (integer_nonzerop (iv0->step))
1601 niter->control = *iv0;
1602 niter->cmp = LT_EXPR;
1603 niter->bound = iv1->base;
1605 else
1607 niter->control = *iv1;
1608 niter->cmp = GT_EXPR;
1609 niter->bound = iv0->base;
1612 /* {base, -C} < n, or n < {base, C} */
1613 if (tree_int_cst_sign_bit (iv0->step)
1614 || (!integer_zerop (iv1->step) && !tree_int_cst_sign_bit (iv1->step)))
1615 return number_of_iterations_until_wrap (loop, type, iv0, iv1, niter);
1617 delta = fold_build2 (MINUS_EXPR, niter_type,
1618 fold_convert (niter_type, iv1->base),
1619 fold_convert (niter_type, iv0->base));
1621 /* First handle the special case that the step is +-1. */
1622 if ((integer_onep (iv0->step) && integer_zerop (iv1->step))
1623 || (integer_all_onesp (iv1->step) && integer_zerop (iv0->step)))
1625 /* for (i = iv0->base; i < iv1->base; i++)
1629 for (i = iv1->base; i > iv0->base; i--).
1631 In both cases # of iterations is iv1->base - iv0->base, assuming that
1632 iv1->base >= iv0->base.
1634 First try to derive a lower bound on the value of
1635 iv1->base - iv0->base, computed in full precision. If the difference
1636 is nonnegative, we are done, otherwise we must record the
1637 condition. */
1639 if (mpz_sgn (bnds->below) < 0)
1640 niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
1641 iv1->base, iv0->base);
1642 niter->niter = delta;
1643 niter->max = widest_int::from (wi::from_mpz (niter_type, bnds->up, false),
1644 TYPE_SIGN (niter_type));
1645 niter->control.no_overflow = true;
1646 return true;
1649 if (integer_nonzerop (iv0->step))
1650 step = fold_convert (niter_type, iv0->step);
1651 else
1652 step = fold_convert (niter_type,
1653 fold_build1 (NEGATE_EXPR, type, iv1->step));
1655 /* If we can determine the final value of the control iv exactly, we can
1656 transform the condition to != comparison. In particular, this will be
1657 the case if DELTA is constant. */
1658 if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step,
1659 exit_must_be_taken, bnds))
1661 affine_iv zps;
1663 zps.base = build_int_cst (niter_type, 0);
1664 zps.step = step;
1665 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1666 zps does not overflow. */
1667 zps.no_overflow = true;
1669 return number_of_iterations_ne (loop, type, &zps,
1670 delta, niter, true, bnds);
1673 /* Make sure that the control iv does not overflow. */
1674 if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
1675 return false;
1677 /* We determine the number of iterations as (delta + step - 1) / step. For
1678 this to work, we must know that iv1->base >= iv0->base - step + 1,
1679 otherwise the loop does not roll. */
1680 assert_loop_rolls_lt (type, iv0, iv1, niter, bnds);
1682 s = fold_build2 (MINUS_EXPR, niter_type,
1683 step, build_int_cst (niter_type, 1));
1684 delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
1685 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
1687 mpz_init (mstep);
1688 mpz_init (tmp);
1689 wi::to_mpz (wi::to_wide (step), mstep, UNSIGNED);
1690 mpz_add (tmp, bnds->up, mstep);
1691 mpz_sub_ui (tmp, tmp, 1);
1692 mpz_fdiv_q (tmp, tmp, mstep);
1693 niter->max = widest_int::from (wi::from_mpz (niter_type, tmp, false),
1694 TYPE_SIGN (niter_type));
1695 mpz_clear (mstep);
1696 mpz_clear (tmp);
1698 return true;
1701 /* Determines number of iterations of loop whose ending condition
1702 is IV0 <= IV1. TYPE is the type of the iv. The number of
1703 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1704 we know that this condition must eventually become false (we derived this
1705 earlier, and possibly set NITER->assumptions to make sure this
1706 is the case). BNDS bounds the difference IV1->base - IV0->base. */
1708 static bool
1709 number_of_iterations_le (class loop *loop, tree type, affine_iv *iv0,
1710 affine_iv *iv1, class tree_niter_desc *niter,
1711 bool exit_must_be_taken, bounds *bnds)
1713 tree assumption;
1714 tree type1 = type;
1715 if (POINTER_TYPE_P (type))
1716 type1 = sizetype;
1718 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1719 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1720 value of the type. This we must know anyway, since if it is
1721 equal to this value, the loop rolls forever. We do not check
1722 this condition for pointer type ivs, as the code cannot rely on
1723 the object to that the pointer points being placed at the end of
1724 the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1725 not defined for pointers). */
1727 if (!exit_must_be_taken && !POINTER_TYPE_P (type))
1729 if (integer_nonzerop (iv0->step))
1730 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1731 iv1->base, TYPE_MAX_VALUE (type));
1732 else
1733 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1734 iv0->base, TYPE_MIN_VALUE (type));
1736 if (integer_zerop (assumption))
1737 return false;
1738 if (!integer_nonzerop (assumption))
1739 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1740 niter->assumptions, assumption);
1743 if (integer_nonzerop (iv0->step))
1745 if (POINTER_TYPE_P (type))
1746 iv1->base = fold_build_pointer_plus_hwi (iv1->base, 1);
1747 else
1748 iv1->base = fold_build2 (PLUS_EXPR, type1, iv1->base,
1749 build_int_cst (type1, 1));
1751 else if (POINTER_TYPE_P (type))
1752 iv0->base = fold_build_pointer_plus_hwi (iv0->base, -1);
1753 else
1754 iv0->base = fold_build2 (MINUS_EXPR, type1,
1755 iv0->base, build_int_cst (type1, 1));
1757 bounds_add (bnds, 1, type1);
1759 return number_of_iterations_lt (loop, type, iv0, iv1, niter, exit_must_be_taken,
1760 bnds);
1763 /* Dumps description of affine induction variable IV to FILE. */
1765 static void
1766 dump_affine_iv (FILE *file, affine_iv *iv)
1768 if (!integer_zerop (iv->step))
1769 fprintf (file, "[");
1771 print_generic_expr (dump_file, iv->base, TDF_SLIM);
1773 if (!integer_zerop (iv->step))
1775 fprintf (file, ", + , ");
1776 print_generic_expr (dump_file, iv->step, TDF_SLIM);
1777 fprintf (file, "]%s", iv->no_overflow ? "(no_overflow)" : "");
1781 /* Determine the number of iterations according to condition (for staying
1782 inside loop) which compares two induction variables using comparison
1783 operator CODE. The induction variable on left side of the comparison
1784 is IV0, the right-hand side is IV1. Both induction variables must have
1785 type TYPE, which must be an integer or pointer type. The steps of the
1786 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1788 LOOP is the loop whose number of iterations we are determining.
1790 ONLY_EXIT is true if we are sure this is the only way the loop could be
1791 exited (including possibly non-returning function calls, exceptions, etc.)
1792 -- in this case we can use the information whether the control induction
1793 variables can overflow or not in a more efficient way.
1795 if EVERY_ITERATION is true, we know the test is executed on every iteration.
1797 The results (number of iterations and assumptions as described in
1798 comments at class tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1799 Returns false if it fails to determine number of iterations, true if it
1800 was determined (possibly with some assumptions). */
1802 static bool
1803 number_of_iterations_cond (class loop *loop,
1804 tree type, affine_iv *iv0, enum tree_code code,
1805 affine_iv *iv1, class tree_niter_desc *niter,
1806 bool only_exit, bool every_iteration)
1808 bool exit_must_be_taken = false, ret;
1809 bounds bnds;
1811 /* If the test is not executed every iteration, wrapping may make the test
1812 to pass again.
1813 TODO: the overflow case can be still used as unreliable estimate of upper
1814 bound. But we have no API to pass it down to number of iterations code
1815 and, at present, it will not use it anyway. */
1816 if (!every_iteration
1817 && (!iv0->no_overflow || !iv1->no_overflow
1818 || code == NE_EXPR || code == EQ_EXPR))
1819 return false;
1821 /* The meaning of these assumptions is this:
1822 if !assumptions
1823 then the rest of information does not have to be valid
1824 if may_be_zero then the loop does not roll, even if
1825 niter != 0. */
1826 niter->assumptions = boolean_true_node;
1827 niter->may_be_zero = boolean_false_node;
1828 niter->niter = NULL_TREE;
1829 niter->max = 0;
1830 niter->bound = NULL_TREE;
1831 niter->cmp = ERROR_MARK;
1833 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1834 the control variable is on lhs. */
1835 if (code == GE_EXPR || code == GT_EXPR
1836 || (code == NE_EXPR && integer_zerop (iv0->step)))
1838 std::swap (iv0, iv1);
1839 code = swap_tree_comparison (code);
1842 if (POINTER_TYPE_P (type))
1844 /* Comparison of pointers is undefined unless both iv0 and iv1 point
1845 to the same object. If they do, the control variable cannot wrap
1846 (as wrap around the bounds of memory will never return a pointer
1847 that would be guaranteed to point to the same object, even if we
1848 avoid undefined behavior by casting to size_t and back). */
1849 iv0->no_overflow = true;
1850 iv1->no_overflow = true;
1853 /* If the control induction variable does not overflow and the only exit
1854 from the loop is the one that we analyze, we know it must be taken
1855 eventually. */
1856 if (only_exit)
1858 if (!integer_zerop (iv0->step) && iv0->no_overflow)
1859 exit_must_be_taken = true;
1860 else if (!integer_zerop (iv1->step) && iv1->no_overflow)
1861 exit_must_be_taken = true;
1864 /* We can handle cases which neither of the sides of the comparison is
1865 invariant:
1867 {iv0.base, iv0.step} cmp_code {iv1.base, iv1.step}
1868 as if:
1869 {iv0.base, iv0.step - iv1.step} cmp_code {iv1.base, 0}
1871 provided that either below condition is satisfied:
1873 a) the test is NE_EXPR;
1874 b) iv0 and iv1 do not overflow and iv0.step - iv1.step is of
1875 the same sign and of less or equal magnitude than iv0.step
1877 This rarely occurs in practice, but it is simple enough to manage. */
1878 if (!integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1880 tree step_type = POINTER_TYPE_P (type) ? sizetype : type;
1881 tree step = fold_binary_to_constant (MINUS_EXPR, step_type,
1882 iv0->step, iv1->step);
1884 /* For code other than NE_EXPR we have to ensure moving the evolution
1885 of IV1 to that of IV0 does not introduce overflow. */
1886 if (TREE_CODE (step) != INTEGER_CST
1887 || !iv0->no_overflow || !iv1->no_overflow)
1889 if (code != NE_EXPR)
1890 return false;
1891 iv0->no_overflow = false;
1893 /* If the new step of IV0 has changed sign or is of greater
1894 magnitude then we do not know whether IV0 does overflow
1895 and thus the transform is not valid for code other than NE_EXPR. */
1896 else if (tree_int_cst_sign_bit (step) != tree_int_cst_sign_bit (iv0->step)
1897 || wi::gtu_p (wi::abs (wi::to_widest (step)),
1898 wi::abs (wi::to_widest (iv0->step))))
1900 if (POINTER_TYPE_P (type) && code != NE_EXPR)
1901 /* For relational pointer compares we have further guarantees
1902 that the pointers always point to the same object (or one
1903 after it) and that objects do not cross the zero page. So
1904 not only is the transform always valid for relational
1905 pointer compares, we also know the resulting IV does not
1906 overflow. */
1908 else if (code != NE_EXPR)
1909 return false;
1910 else
1911 iv0->no_overflow = false;
1914 iv0->step = step;
1915 iv1->step = build_int_cst (step_type, 0);
1916 iv1->no_overflow = true;
1919 /* If the result of the comparison is a constant, the loop is weird. More
1920 precise handling would be possible, but the situation is not common enough
1921 to waste time on it. */
1922 if (integer_zerop (iv0->step) && integer_zerop (iv1->step))
1923 return false;
1925 /* If the loop exits immediately, there is nothing to do. */
1926 tree tem = fold_binary (code, boolean_type_node, iv0->base, iv1->base);
1927 if (tem && integer_zerop (tem))
1929 if (!every_iteration)
1930 return false;
1931 niter->niter = build_int_cst (unsigned_type_for (type), 0);
1932 niter->max = 0;
1933 return true;
1936 /* OK, now we know we have a senseful loop. Handle several cases, depending
1937 on what comparison operator is used. */
1938 bound_difference (loop, iv1->base, iv0->base, &bnds);
1940 if (dump_file && (dump_flags & TDF_DETAILS))
1942 fprintf (dump_file,
1943 "Analyzing # of iterations of loop %d\n", loop->num);
1945 fprintf (dump_file, " exit condition ");
1946 dump_affine_iv (dump_file, iv0);
1947 fprintf (dump_file, " %s ",
1948 code == NE_EXPR ? "!="
1949 : code == LT_EXPR ? "<"
1950 : "<=");
1951 dump_affine_iv (dump_file, iv1);
1952 fprintf (dump_file, "\n");
1954 fprintf (dump_file, " bounds on difference of bases: ");
1955 mpz_out_str (dump_file, 10, bnds.below);
1956 fprintf (dump_file, " ... ");
1957 mpz_out_str (dump_file, 10, bnds.up);
1958 fprintf (dump_file, "\n");
1961 switch (code)
1963 case NE_EXPR:
1964 gcc_assert (integer_zerop (iv1->step));
1965 ret = number_of_iterations_ne (loop, type, iv0, iv1->base, niter,
1966 exit_must_be_taken, &bnds);
1967 break;
1969 case LT_EXPR:
1970 ret = number_of_iterations_lt (loop, type, iv0, iv1, niter,
1971 exit_must_be_taken, &bnds);
1972 break;
1974 case LE_EXPR:
1975 ret = number_of_iterations_le (loop, type, iv0, iv1, niter,
1976 exit_must_be_taken, &bnds);
1977 break;
1979 default:
1980 gcc_unreachable ();
1983 mpz_clear (bnds.up);
1984 mpz_clear (bnds.below);
1986 if (dump_file && (dump_flags & TDF_DETAILS))
1988 if (ret)
1990 fprintf (dump_file, " result:\n");
1991 if (!integer_nonzerop (niter->assumptions))
1993 fprintf (dump_file, " under assumptions ");
1994 print_generic_expr (dump_file, niter->assumptions, TDF_SLIM);
1995 fprintf (dump_file, "\n");
1998 if (!integer_zerop (niter->may_be_zero))
2000 fprintf (dump_file, " zero if ");
2001 print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
2002 fprintf (dump_file, "\n");
2005 fprintf (dump_file, " # of iterations ");
2006 print_generic_expr (dump_file, niter->niter, TDF_SLIM);
2007 fprintf (dump_file, ", bounded by ");
2008 print_decu (niter->max, dump_file);
2009 fprintf (dump_file, "\n");
2011 else
2012 fprintf (dump_file, " failed\n\n");
2014 return ret;
2017 /* Return an expression that computes the popcount of src. */
2019 static tree
2020 build_popcount_expr (tree src)
2022 tree fn;
2023 bool use_ifn = false;
2024 int prec = TYPE_PRECISION (TREE_TYPE (src));
2025 int i_prec = TYPE_PRECISION (integer_type_node);
2026 int li_prec = TYPE_PRECISION (long_integer_type_node);
2027 int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
2029 tree utype = unsigned_type_for (TREE_TYPE (src));
2030 src = fold_convert (utype, src);
2032 if (direct_internal_fn_supported_p (IFN_POPCOUNT, utype, OPTIMIZE_FOR_BOTH))
2033 use_ifn = true;
2034 else if (prec <= i_prec)
2035 fn = builtin_decl_implicit (BUILT_IN_POPCOUNT);
2036 else if (prec == li_prec)
2037 fn = builtin_decl_implicit (BUILT_IN_POPCOUNTL);
2038 else if (prec == lli_prec || prec == 2 * lli_prec)
2039 fn = builtin_decl_implicit (BUILT_IN_POPCOUNTLL);
2040 else
2041 return NULL_TREE;
2043 tree call;
2044 if (use_ifn)
2045 call = build_call_expr_internal_loc (UNKNOWN_LOCATION, IFN_POPCOUNT,
2046 integer_type_node, 1, src);
2047 else if (prec == 2 * lli_prec)
2049 tree src1 = fold_convert (long_long_unsigned_type_node,
2050 fold_build2 (RSHIFT_EXPR, TREE_TYPE (src),
2051 unshare_expr (src),
2052 build_int_cst (integer_type_node,
2053 lli_prec)));
2054 tree src2 = fold_convert (long_long_unsigned_type_node, src);
2055 tree call1 = build_call_expr (fn, 1, src1);
2056 tree call2 = build_call_expr (fn, 1, src2);
2057 call = fold_build2 (PLUS_EXPR, integer_type_node, call1, call2);
2059 else
2061 if (prec < i_prec)
2062 src = fold_convert (unsigned_type_node, src);
2064 call = build_call_expr (fn, 1, src);
2067 return call;
2070 /* Utility function to check if OP is defined by a stmt
2071 that is a val - 1. */
2073 static bool
2074 ssa_defined_by_minus_one_stmt_p (tree op, tree val)
2076 gimple *stmt;
2077 return (TREE_CODE (op) == SSA_NAME
2078 && (stmt = SSA_NAME_DEF_STMT (op))
2079 && is_gimple_assign (stmt)
2080 && (gimple_assign_rhs_code (stmt) == PLUS_EXPR)
2081 && val == gimple_assign_rhs1 (stmt)
2082 && integer_minus_onep (gimple_assign_rhs2 (stmt)));
2085 /* See comment below for number_of_iterations_bitcount.
2086 For popcount, we have:
2088 modify:
2089 _1 = iv_1 + -1
2090 iv_2 = iv_1 & _1
2092 test:
2093 if (iv != 0)
2095 modification count:
2096 popcount (src)
2100 static bool
2101 number_of_iterations_popcount (loop_p loop, edge exit,
2102 enum tree_code code,
2103 class tree_niter_desc *niter)
2105 bool modify_before_test = true;
2106 HOST_WIDE_INT max;
2108 /* Check that condition for staying inside the loop is like
2109 if (iv != 0). */
2110 gcond *cond_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
2111 if (!cond_stmt
2112 || code != NE_EXPR
2113 || !integer_zerop (gimple_cond_rhs (cond_stmt))
2114 || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2115 return false;
2117 tree iv_2 = gimple_cond_lhs (cond_stmt);
2118 gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2120 /* If the test comes before the iv modification, then these will actually be
2121 iv_1 and a phi node. */
2122 if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2123 && gimple_bb (iv_2_stmt) == loop->header
2124 && gimple_phi_num_args (iv_2_stmt) == 2
2125 && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2126 loop_latch_edge (loop)->dest_idx))
2127 == SSA_NAME))
2129 /* iv_2 is actually one of the inputs to the phi. */
2130 iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2131 iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2132 modify_before_test = false;
2135 /* Make sure iv_2_stmt is an and stmt (iv_2 = _1 & iv_1). */
2136 if (!is_gimple_assign (iv_2_stmt)
2137 || gimple_assign_rhs_code (iv_2_stmt) != BIT_AND_EXPR)
2138 return false;
2140 tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2141 tree _1 = gimple_assign_rhs2 (iv_2_stmt);
2143 /* Check that _1 is defined by (_1 = iv_1 + -1).
2144 Also make sure that _1 is the same in and_stmt and _1 defining stmt.
2145 Also canonicalize if _1 and _b11 are revrsed. */
2146 if (ssa_defined_by_minus_one_stmt_p (iv_1, _1))
2147 std::swap (iv_1, _1);
2148 else if (ssa_defined_by_minus_one_stmt_p (_1, iv_1))
2150 else
2151 return false;
2153 /* Check the recurrence. */
2154 gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2155 if (gimple_code (phi) != GIMPLE_PHI
2156 || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2157 || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx)))
2158 return false;
2160 /* We found a match. */
2161 tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2162 int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2164 /* Get the corresponding popcount builtin. */
2165 tree expr = build_popcount_expr (src);
2167 if (!expr)
2168 return false;
2170 max = src_precision;
2172 tree may_be_zero = boolean_false_node;
2174 if (modify_before_test)
2176 expr = fold_build2 (MINUS_EXPR, integer_type_node, expr,
2177 integer_one_node);
2178 max = max - 1;
2179 may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node, src,
2180 build_zero_cst (TREE_TYPE (src)));
2183 expr = fold_convert (unsigned_type_node, expr);
2185 niter->assumptions = boolean_true_node;
2186 niter->may_be_zero = simplify_using_initial_conditions (loop, may_be_zero);
2187 niter->niter = simplify_using_initial_conditions(loop, expr);
2189 if (TREE_CODE (niter->niter) == INTEGER_CST)
2190 niter->max = tree_to_uhwi (niter->niter);
2191 else
2192 niter->max = max;
2194 niter->bound = NULL_TREE;
2195 niter->cmp = ERROR_MARK;
2196 return true;
2199 /* Return an expression that counts the leading/trailing zeroes of src.
2201 If define_at_zero is true, then the built expression will be defined to
2202 return the precision of src when src == 0 (using either a conditional
2203 expression or a suitable internal function).
2204 Otherwise, we can elide the conditional expression and let src = 0 invoke
2205 undefined behaviour. */
2207 static tree
2208 build_cltz_expr (tree src, bool leading, bool define_at_zero)
2210 tree fn;
2211 internal_fn ifn = leading ? IFN_CLZ : IFN_CTZ;
2212 bool use_ifn = false;
2213 int prec = TYPE_PRECISION (TREE_TYPE (src));
2214 int i_prec = TYPE_PRECISION (integer_type_node);
2215 int li_prec = TYPE_PRECISION (long_integer_type_node);
2216 int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
2218 tree utype = unsigned_type_for (TREE_TYPE (src));
2219 src = fold_convert (utype, src);
2221 if (direct_internal_fn_supported_p (ifn, utype, OPTIMIZE_FOR_BOTH))
2222 use_ifn = true;
2223 else if (prec <= i_prec)
2224 fn = leading ? builtin_decl_implicit (BUILT_IN_CLZ)
2225 : builtin_decl_implicit (BUILT_IN_CTZ);
2226 else if (prec == li_prec)
2227 fn = leading ? builtin_decl_implicit (BUILT_IN_CLZL)
2228 : builtin_decl_implicit (BUILT_IN_CTZL);
2229 else if (prec == lli_prec || prec == 2 * lli_prec)
2230 fn = leading ? builtin_decl_implicit (BUILT_IN_CLZLL)
2231 : builtin_decl_implicit (BUILT_IN_CTZLL);
2232 else
2233 return NULL_TREE;
2235 tree call;
2236 if (use_ifn)
2238 int val;
2239 int optab_defined_at_zero
2240 = (leading
2241 ? CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (utype), val)
2242 : CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (utype), val));
2243 tree arg2 = NULL_TREE;
2244 if (define_at_zero && optab_defined_at_zero == 2 && val == prec)
2245 arg2 = build_int_cst (integer_type_node, val);
2246 call = build_call_expr_internal_loc (UNKNOWN_LOCATION, ifn,
2247 integer_type_node, arg2 ? 2 : 1,
2248 src, arg2);
2249 if (define_at_zero && arg2 == NULL_TREE)
2251 tree is_zero = fold_build2 (NE_EXPR, boolean_type_node, src,
2252 build_zero_cst (TREE_TYPE (src)));
2253 call = fold_build3 (COND_EXPR, integer_type_node, is_zero, call,
2254 build_int_cst (integer_type_node, prec));
2257 else if (prec == 2 * lli_prec)
2259 tree src1 = fold_convert (long_long_unsigned_type_node,
2260 fold_build2 (RSHIFT_EXPR, TREE_TYPE (src),
2261 unshare_expr (src),
2262 build_int_cst (integer_type_node,
2263 lli_prec)));
2264 tree src2 = fold_convert (long_long_unsigned_type_node, src);
2265 /* We count the zeroes in src1, and add the number in src2 when src1
2266 is 0. */
2267 if (!leading)
2268 std::swap (src1, src2);
2269 tree call1 = build_call_expr (fn, 1, src1);
2270 tree call2 = build_call_expr (fn, 1, src2);
2271 if (define_at_zero)
2273 tree is_zero2 = fold_build2 (NE_EXPR, boolean_type_node, src2,
2274 build_zero_cst (TREE_TYPE (src2)));
2275 call2 = fold_build3 (COND_EXPR, integer_type_node, is_zero2, call2,
2276 build_int_cst (integer_type_node, lli_prec));
2278 tree is_zero1 = fold_build2 (NE_EXPR, boolean_type_node, src1,
2279 build_zero_cst (TREE_TYPE (src1)));
2280 call = fold_build3 (COND_EXPR, integer_type_node, is_zero1, call1,
2281 fold_build2 (PLUS_EXPR, integer_type_node, call2,
2282 build_int_cst (integer_type_node,
2283 lli_prec)));
2285 else
2287 if (prec < i_prec)
2288 src = fold_convert (unsigned_type_node, src);
2290 call = build_call_expr (fn, 1, src);
2291 if (leading && prec < i_prec)
2292 call = fold_build2 (MINUS_EXPR, integer_type_node, call,
2293 build_int_cst (integer_type_node, i_prec - prec));
2294 if (define_at_zero)
2296 tree is_zero = fold_build2 (NE_EXPR, boolean_type_node, src,
2297 build_zero_cst (TREE_TYPE (src)));
2298 call = fold_build3 (COND_EXPR, integer_type_node, is_zero, call,
2299 build_int_cst (integer_type_node, prec));
2303 return call;
2306 /* Returns true if STMT is equivalent to x << 1. */
2308 static bool
2309 is_lshift_by_1 (gassign *stmt)
2311 if (gimple_assign_rhs_code (stmt) == LSHIFT_EXPR
2312 && integer_onep (gimple_assign_rhs2 (stmt)))
2313 return true;
2314 if (gimple_assign_rhs_code (stmt) == MULT_EXPR
2315 && tree_fits_shwi_p (gimple_assign_rhs2 (stmt))
2316 && tree_to_shwi (gimple_assign_rhs2 (stmt)) == 2)
2317 return true;
2318 return false;
2321 /* Returns true if STMT is equivalent to x >> 1. */
2323 static bool
2324 is_rshift_by_1 (gassign *stmt)
2326 if (!TYPE_UNSIGNED (TREE_TYPE (gimple_assign_lhs (stmt))))
2327 return false;
2328 if (gimple_assign_rhs_code (stmt) == RSHIFT_EXPR
2329 && integer_onep (gimple_assign_rhs2 (stmt)))
2330 return true;
2331 if (gimple_assign_rhs_code (stmt) == TRUNC_DIV_EXPR
2332 && tree_fits_shwi_p (gimple_assign_rhs2 (stmt))
2333 && tree_to_shwi (gimple_assign_rhs2 (stmt)) == 2)
2334 return true;
2335 return false;
2338 /* See comment below for number_of_iterations_bitcount.
2339 For c[lt]z, we have:
2341 modify:
2342 iv_2 = iv_1 << 1 OR iv_1 >> 1
2344 test:
2345 if (iv & 1 << (prec-1)) OR (iv & 1)
2347 modification count:
2348 src precision - c[lt]z (src)
2352 static bool
2353 number_of_iterations_cltz (loop_p loop, edge exit,
2354 enum tree_code code,
2355 class tree_niter_desc *niter)
2357 bool modify_before_test = true;
2358 HOST_WIDE_INT max;
2359 int checked_bit;
2360 tree iv_2;
2362 /* Check that condition for staying inside the loop is like
2363 if (iv == 0). */
2364 gcond *cond_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
2365 if (!cond_stmt
2366 || (code != EQ_EXPR && code != GE_EXPR)
2367 || !integer_zerop (gimple_cond_rhs (cond_stmt))
2368 || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2369 return false;
2371 if (code == EQ_EXPR)
2373 /* Make sure we check a bitwise and with a suitable constant */
2374 gimple *and_stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (cond_stmt));
2375 if (!is_gimple_assign (and_stmt)
2376 || gimple_assign_rhs_code (and_stmt) != BIT_AND_EXPR
2377 || !integer_pow2p (gimple_assign_rhs2 (and_stmt))
2378 || TREE_CODE (gimple_assign_rhs1 (and_stmt)) != SSA_NAME)
2379 return false;
2381 checked_bit = tree_log2 (gimple_assign_rhs2 (and_stmt));
2383 iv_2 = gimple_assign_rhs1 (and_stmt);
2385 else
2387 /* We have a GE_EXPR - a signed comparison with zero is equivalent to
2388 testing the leading bit, so check for this pattern too. */
2390 iv_2 = gimple_cond_lhs (cond_stmt);
2391 tree test_value_type = TREE_TYPE (iv_2);
2393 if (TYPE_UNSIGNED (test_value_type))
2394 return false;
2396 gimple *test_value_stmt = SSA_NAME_DEF_STMT (iv_2);
2398 if (is_gimple_assign (test_value_stmt)
2399 && gimple_assign_rhs_code (test_value_stmt) == NOP_EXPR)
2401 /* If the test value comes from a NOP_EXPR, then we need to unwrap
2402 this. We conservatively require that both types have the same
2403 precision. */
2404 iv_2 = gimple_assign_rhs1 (test_value_stmt);
2405 tree rhs_type = TREE_TYPE (iv_2);
2406 if (TREE_CODE (iv_2) != SSA_NAME
2407 || TREE_CODE (rhs_type) != INTEGER_TYPE
2408 || (TYPE_PRECISION (rhs_type)
2409 != TYPE_PRECISION (test_value_type)))
2410 return false;
2413 checked_bit = TYPE_PRECISION (test_value_type) - 1;
2416 gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2418 /* If the test comes before the iv modification, then these will actually be
2419 iv_1 and a phi node. */
2420 if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2421 && gimple_bb (iv_2_stmt) == loop->header
2422 && gimple_phi_num_args (iv_2_stmt) == 2
2423 && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2424 loop_latch_edge (loop)->dest_idx))
2425 == SSA_NAME))
2427 /* iv_2 is actually one of the inputs to the phi. */
2428 iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2429 iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2430 modify_before_test = false;
2433 /* Make sure iv_2_stmt is a logical shift by one stmt:
2434 iv_2 = iv_1 {<<|>>} 1 */
2435 if (!is_gimple_assign (iv_2_stmt))
2436 return false;
2437 bool left_shift = false;
2438 if (!((left_shift = is_lshift_by_1 (as_a <gassign *> (iv_2_stmt)))
2439 || is_rshift_by_1 (as_a <gassign *> (iv_2_stmt))))
2440 return false;
2442 tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2444 /* Check the recurrence. */
2445 gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2446 if (gimple_code (phi) != GIMPLE_PHI
2447 || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2448 || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx)))
2449 return false;
2451 /* We found a match. */
2452 tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2453 int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2455 /* Apply any needed preprocessing to src. */
2456 int num_ignored_bits;
2457 if (left_shift)
2458 num_ignored_bits = src_precision - checked_bit - 1;
2459 else
2460 num_ignored_bits = checked_bit;
2462 if (modify_before_test)
2463 num_ignored_bits++;
2465 if (num_ignored_bits != 0)
2466 src = fold_build2 (left_shift ? LSHIFT_EXPR : RSHIFT_EXPR,
2467 TREE_TYPE (src), src,
2468 build_int_cst (integer_type_node, num_ignored_bits));
2470 /* Get the corresponding c[lt]z builtin. */
2471 tree expr = build_cltz_expr (src, left_shift, false);
2473 if (!expr)
2474 return false;
2476 max = src_precision - num_ignored_bits - 1;
2478 expr = fold_convert (unsigned_type_node, expr);
2480 tree assumptions = fold_build2 (NE_EXPR, boolean_type_node, src,
2481 build_zero_cst (TREE_TYPE (src)));
2483 niter->assumptions = simplify_using_initial_conditions (loop, assumptions);
2484 niter->may_be_zero = boolean_false_node;
2485 niter->niter = simplify_using_initial_conditions (loop, expr);
2487 if (TREE_CODE (niter->niter) == INTEGER_CST)
2488 niter->max = tree_to_uhwi (niter->niter);
2489 else
2490 niter->max = max;
2492 niter->bound = NULL_TREE;
2493 niter->cmp = ERROR_MARK;
2495 return true;
2498 /* See comment below for number_of_iterations_bitcount.
2499 For c[lt]z complement, we have:
2501 modify:
2502 iv_2 = iv_1 >> 1 OR iv_1 << 1
2504 test:
2505 if (iv != 0)
2507 modification count:
2508 src precision - c[lt]z (src)
2512 static bool
2513 number_of_iterations_cltz_complement (loop_p loop, edge exit,
2514 enum tree_code code,
2515 class tree_niter_desc *niter)
2517 bool modify_before_test = true;
2518 HOST_WIDE_INT max;
2520 /* Check that condition for staying inside the loop is like
2521 if (iv != 0). */
2522 gcond *cond_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
2523 if (!cond_stmt
2524 || code != NE_EXPR
2525 || !integer_zerop (gimple_cond_rhs (cond_stmt))
2526 || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2527 return false;
2529 tree iv_2 = gimple_cond_lhs (cond_stmt);
2530 gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2532 /* If the test comes before the iv modification, then these will actually be
2533 iv_1 and a phi node. */
2534 if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2535 && gimple_bb (iv_2_stmt) == loop->header
2536 && gimple_phi_num_args (iv_2_stmt) == 2
2537 && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2538 loop_latch_edge (loop)->dest_idx))
2539 == SSA_NAME))
2541 /* iv_2 is actually one of the inputs to the phi. */
2542 iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2543 iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2544 modify_before_test = false;
2547 /* Make sure iv_2_stmt is a logical shift by one stmt:
2548 iv_2 = iv_1 {>>|<<} 1 */
2549 if (!is_gimple_assign (iv_2_stmt))
2550 return false;
2551 bool left_shift = false;
2552 if (!((left_shift = is_lshift_by_1 (as_a <gassign *> (iv_2_stmt)))
2553 || is_rshift_by_1 (as_a <gassign *> (iv_2_stmt))))
2554 return false;
2556 tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2558 /* Check the recurrence. */
2559 gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2560 if (gimple_code (phi) != GIMPLE_PHI
2561 || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2562 || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx)))
2563 return false;
2565 /* We found a match. */
2566 tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2567 int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2569 /* Get the corresponding c[lt]z builtin. */
2570 tree expr = build_cltz_expr (src, !left_shift, true);
2572 if (!expr)
2573 return false;
2575 expr = fold_build2 (MINUS_EXPR, integer_type_node,
2576 build_int_cst (integer_type_node, src_precision),
2577 expr);
2579 max = src_precision;
2581 tree may_be_zero = boolean_false_node;
2583 if (modify_before_test)
2585 expr = fold_build2 (MINUS_EXPR, integer_type_node, expr,
2586 integer_one_node);
2587 max = max - 1;
2588 may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node, src,
2589 build_zero_cst (TREE_TYPE (src)));
2592 expr = fold_convert (unsigned_type_node, expr);
2594 niter->assumptions = boolean_true_node;
2595 niter->may_be_zero = simplify_using_initial_conditions (loop, may_be_zero);
2596 niter->niter = simplify_using_initial_conditions (loop, expr);
2598 if (TREE_CODE (niter->niter) == INTEGER_CST)
2599 niter->max = tree_to_uhwi (niter->niter);
2600 else
2601 niter->max = max;
2603 niter->bound = NULL_TREE;
2604 niter->cmp = ERROR_MARK;
2605 return true;
2608 /* See if LOOP contains a bit counting idiom. The idiom consists of two parts:
2609 1. A modification to the induction variabler;.
2610 2. A test to determine whether or not to exit the loop.
2612 These can come in either order - i.e.:
2614 <bb 3>
2615 iv_1 = PHI <src(2), iv_2(4)>
2616 if (test (iv_1))
2617 goto <bb 4>
2618 else
2619 goto <bb 5>
2621 <bb 4>
2622 iv_2 = modify (iv_1)
2623 goto <bb 3>
2627 <bb 3>
2628 iv_1 = PHI <src(2), iv_2(4)>
2629 iv_2 = modify (iv_1)
2631 <bb 4>
2632 if (test (iv_2))
2633 goto <bb 3>
2634 else
2635 goto <bb 5>
2637 The second form can be generated by copying the loop header out of the loop.
2639 In the first case, the number of latch executions will be equal to the
2640 number of induction variable modifications required before the test fails.
2642 In the second case (modify_before_test), if we assume that the number of
2643 modifications required before the test fails is nonzero, then the number of
2644 latch executions will be one less than this number.
2646 If we recognise the pattern, then we update niter accordingly, and return
2647 true. */
2649 static bool
2650 number_of_iterations_bitcount (loop_p loop, edge exit,
2651 enum tree_code code,
2652 class tree_niter_desc *niter)
2654 return (number_of_iterations_popcount (loop, exit, code, niter)
2655 || number_of_iterations_cltz (loop, exit, code, niter)
2656 || number_of_iterations_cltz_complement (loop, exit, code, niter));
2659 /* Substitute NEW_TREE for OLD in EXPR and fold the result.
2660 If VALUEIZE is non-NULL then OLD and NEW_TREE are ignored and instead
2661 all SSA names are replaced with the result of calling the VALUEIZE
2662 function with the SSA name as argument. */
2664 tree
2665 simplify_replace_tree (tree expr, tree old, tree new_tree,
2666 tree (*valueize) (tree, void*), void *context,
2667 bool do_fold)
2669 unsigned i, n;
2670 tree ret = NULL_TREE, e, se;
2672 if (!expr)
2673 return NULL_TREE;
2675 /* Do not bother to replace constants. */
2676 if (CONSTANT_CLASS_P (expr))
2677 return expr;
2679 if (valueize)
2681 if (TREE_CODE (expr) == SSA_NAME)
2683 new_tree = valueize (expr, context);
2684 if (new_tree != expr)
2685 return new_tree;
2688 else if (expr == old
2689 || operand_equal_p (expr, old, 0))
2690 return unshare_expr (new_tree);
2692 if (!EXPR_P (expr))
2693 return expr;
2695 n = TREE_OPERAND_LENGTH (expr);
2696 for (i = 0; i < n; i++)
2698 e = TREE_OPERAND (expr, i);
2699 se = simplify_replace_tree (e, old, new_tree, valueize, context, do_fold);
2700 if (e == se)
2701 continue;
2703 if (!ret)
2704 ret = copy_node (expr);
2706 TREE_OPERAND (ret, i) = se;
2709 return (ret ? (do_fold ? fold (ret) : ret) : expr);
2712 /* Expand definitions of ssa names in EXPR as long as they are simple
2713 enough, and return the new expression. If STOP is specified, stop
2714 expanding if EXPR equals to it. */
2716 static tree
2717 expand_simple_operations (tree expr, tree stop, hash_map<tree, tree> &cache)
2719 unsigned i, n;
2720 tree ret = NULL_TREE, e, ee, e1;
2721 enum tree_code code;
2722 gimple *stmt;
2724 if (expr == NULL_TREE)
2725 return expr;
2727 if (is_gimple_min_invariant (expr))
2728 return expr;
2730 code = TREE_CODE (expr);
2731 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
2733 n = TREE_OPERAND_LENGTH (expr);
2734 for (i = 0; i < n; i++)
2736 e = TREE_OPERAND (expr, i);
2737 if (!e)
2738 continue;
2739 /* SCEV analysis feeds us with a proper expression
2740 graph matching the SSA graph. Avoid turning it
2741 into a tree here, thus handle tree sharing
2742 properly.
2743 ??? The SSA walk below still turns the SSA graph
2744 into a tree but until we find a testcase do not
2745 introduce additional tree sharing here. */
2746 bool existed_p;
2747 tree &cee = cache.get_or_insert (e, &existed_p);
2748 if (existed_p)
2749 ee = cee;
2750 else
2752 cee = e;
2753 ee = expand_simple_operations (e, stop, cache);
2754 if (ee != e)
2755 *cache.get (e) = ee;
2757 if (e == ee)
2758 continue;
2760 if (!ret)
2761 ret = copy_node (expr);
2763 TREE_OPERAND (ret, i) = ee;
2766 if (!ret)
2767 return expr;
2769 fold_defer_overflow_warnings ();
2770 ret = fold (ret);
2771 fold_undefer_and_ignore_overflow_warnings ();
2772 return ret;
2775 /* Stop if it's not ssa name or the one we don't want to expand. */
2776 if (TREE_CODE (expr) != SSA_NAME || expr == stop)
2777 return expr;
2779 stmt = SSA_NAME_DEF_STMT (expr);
2780 if (gimple_code (stmt) == GIMPLE_PHI)
2782 basic_block src, dest;
2784 if (gimple_phi_num_args (stmt) != 1)
2785 return expr;
2786 e = PHI_ARG_DEF (stmt, 0);
2788 /* Avoid propagating through loop exit phi nodes, which
2789 could break loop-closed SSA form restrictions. */
2790 dest = gimple_bb (stmt);
2791 src = single_pred (dest);
2792 if (TREE_CODE (e) == SSA_NAME
2793 && src->loop_father != dest->loop_father)
2794 return expr;
2796 return expand_simple_operations (e, stop, cache);
2798 if (gimple_code (stmt) != GIMPLE_ASSIGN)
2799 return expr;
2801 /* Avoid expanding to expressions that contain SSA names that need
2802 to take part in abnormal coalescing. */
2803 ssa_op_iter iter;
2804 FOR_EACH_SSA_TREE_OPERAND (e, stmt, iter, SSA_OP_USE)
2805 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e))
2806 return expr;
2808 e = gimple_assign_rhs1 (stmt);
2809 code = gimple_assign_rhs_code (stmt);
2810 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
2812 if (is_gimple_min_invariant (e))
2813 return e;
2815 if (code == SSA_NAME)
2816 return expand_simple_operations (e, stop, cache);
2817 else if (code == ADDR_EXPR)
2819 poly_int64 offset;
2820 tree base = get_addr_base_and_unit_offset (TREE_OPERAND (e, 0),
2821 &offset);
2822 if (base
2823 && TREE_CODE (base) == MEM_REF)
2825 ee = expand_simple_operations (TREE_OPERAND (base, 0), stop,
2826 cache);
2827 return fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (expr), ee,
2828 wide_int_to_tree (sizetype,
2829 mem_ref_offset (base)
2830 + offset));
2834 return expr;
2837 switch (code)
2839 CASE_CONVERT:
2840 /* Casts are simple. */
2841 ee = expand_simple_operations (e, stop, cache);
2842 return fold_build1 (code, TREE_TYPE (expr), ee);
2844 case PLUS_EXPR:
2845 case MINUS_EXPR:
2846 case MULT_EXPR:
2847 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr))
2848 && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr)))
2849 return expr;
2850 /* Fallthru. */
2851 case POINTER_PLUS_EXPR:
2852 /* And increments and decrements by a constant are simple. */
2853 e1 = gimple_assign_rhs2 (stmt);
2854 if (!is_gimple_min_invariant (e1))
2855 return expr;
2857 ee = expand_simple_operations (e, stop, cache);
2858 return fold_build2 (code, TREE_TYPE (expr), ee, e1);
2860 default:
2861 return expr;
2865 tree
2866 expand_simple_operations (tree expr, tree stop)
2868 hash_map<tree, tree> cache;
2869 return expand_simple_operations (expr, stop, cache);
2872 /* Tries to simplify EXPR using the condition COND. Returns the simplified
2873 expression (or EXPR unchanged, if no simplification was possible). */
2875 static tree
2876 tree_simplify_using_condition_1 (tree cond, tree expr)
2878 bool changed;
2879 tree e, e0, e1, e2, notcond;
2880 enum tree_code code = TREE_CODE (expr);
2882 if (code == INTEGER_CST)
2883 return expr;
2885 if (code == TRUTH_OR_EXPR
2886 || code == TRUTH_AND_EXPR
2887 || code == COND_EXPR)
2889 changed = false;
2891 e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
2892 if (TREE_OPERAND (expr, 0) != e0)
2893 changed = true;
2895 e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
2896 if (TREE_OPERAND (expr, 1) != e1)
2897 changed = true;
2899 if (code == COND_EXPR)
2901 e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
2902 if (TREE_OPERAND (expr, 2) != e2)
2903 changed = true;
2905 else
2906 e2 = NULL_TREE;
2908 if (changed)
2910 if (code == COND_EXPR)
2911 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
2912 else
2913 expr = fold_build2 (code, boolean_type_node, e0, e1);
2916 return expr;
2919 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
2920 propagation, and vice versa. Fold does not handle this, since it is
2921 considered too expensive. */
2922 if (TREE_CODE (cond) == EQ_EXPR)
2924 e0 = TREE_OPERAND (cond, 0);
2925 e1 = TREE_OPERAND (cond, 1);
2927 /* We know that e0 == e1. Check whether we cannot simplify expr
2928 using this fact. */
2929 e = simplify_replace_tree (expr, e0, e1);
2930 if (integer_zerop (e) || integer_nonzerop (e))
2931 return e;
2933 e = simplify_replace_tree (expr, e1, e0);
2934 if (integer_zerop (e) || integer_nonzerop (e))
2935 return e;
2937 if (TREE_CODE (expr) == EQ_EXPR)
2939 e0 = TREE_OPERAND (expr, 0);
2940 e1 = TREE_OPERAND (expr, 1);
2942 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
2943 e = simplify_replace_tree (cond, e0, e1);
2944 if (integer_zerop (e))
2945 return e;
2946 e = simplify_replace_tree (cond, e1, e0);
2947 if (integer_zerop (e))
2948 return e;
2950 if (TREE_CODE (expr) == NE_EXPR)
2952 e0 = TREE_OPERAND (expr, 0);
2953 e1 = TREE_OPERAND (expr, 1);
2955 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
2956 e = simplify_replace_tree (cond, e0, e1);
2957 if (integer_zerop (e))
2958 return boolean_true_node;
2959 e = simplify_replace_tree (cond, e1, e0);
2960 if (integer_zerop (e))
2961 return boolean_true_node;
2964 /* Check whether COND ==> EXPR. */
2965 notcond = invert_truthvalue (cond);
2966 e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, expr);
2967 if (e && integer_nonzerop (e))
2968 return e;
2970 /* Check whether COND ==> not EXPR. */
2971 e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, expr);
2972 if (e && integer_zerop (e))
2973 return e;
2975 return expr;
2978 /* Tries to simplify EXPR using the condition COND. Returns the simplified
2979 expression (or EXPR unchanged, if no simplification was possible).
2980 Wrapper around tree_simplify_using_condition_1 that ensures that chains
2981 of simple operations in definitions of ssa names in COND are expanded,
2982 so that things like casts or incrementing the value of the bound before
2983 the loop do not cause us to fail. */
2985 static tree
2986 tree_simplify_using_condition (tree cond, tree expr)
2988 cond = expand_simple_operations (cond);
2990 return tree_simplify_using_condition_1 (cond, expr);
2993 /* Tries to simplify EXPR using the conditions on entry to LOOP.
2994 Returns the simplified expression (or EXPR unchanged, if no
2995 simplification was possible). */
2997 tree
2998 simplify_using_initial_conditions (class loop *loop, tree expr)
3000 edge e;
3001 basic_block bb;
3002 tree cond, expanded, backup;
3003 int cnt = 0;
3005 if (TREE_CODE (expr) == INTEGER_CST)
3006 return expr;
3008 backup = expanded = expand_simple_operations (expr);
3010 /* Limit walking the dominators to avoid quadraticness in
3011 the number of BBs times the number of loops in degenerate
3012 cases. */
3013 for (bb = loop->header;
3014 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
3015 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
3017 if (!single_pred_p (bb))
3018 continue;
3019 e = single_pred_edge (bb);
3021 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
3022 continue;
3024 gcond *stmt = as_a <gcond *> (*gsi_last_bb (e->src));
3025 cond = fold_build2 (gimple_cond_code (stmt),
3026 boolean_type_node,
3027 gimple_cond_lhs (stmt),
3028 gimple_cond_rhs (stmt));
3029 if (e->flags & EDGE_FALSE_VALUE)
3030 cond = invert_truthvalue (cond);
3031 expanded = tree_simplify_using_condition (cond, expanded);
3032 /* Break if EXPR is simplified to const values. */
3033 if (expanded
3034 && (integer_zerop (expanded) || integer_nonzerop (expanded)))
3035 return expanded;
3037 ++cnt;
3040 /* Return the original expression if no simplification is done. */
3041 return operand_equal_p (backup, expanded, 0) ? expr : expanded;
3044 /* Tries to simplify EXPR using the evolutions of the loop invariants
3045 in the superloops of LOOP. Returns the simplified expression
3046 (or EXPR unchanged, if no simplification was possible). */
3048 static tree
3049 simplify_using_outer_evolutions (class loop *loop, tree expr)
3051 enum tree_code code = TREE_CODE (expr);
3052 bool changed;
3053 tree e, e0, e1, e2;
3055 if (is_gimple_min_invariant (expr))
3056 return expr;
3058 if (code == TRUTH_OR_EXPR
3059 || code == TRUTH_AND_EXPR
3060 || code == COND_EXPR)
3062 changed = false;
3064 e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
3065 if (TREE_OPERAND (expr, 0) != e0)
3066 changed = true;
3068 e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
3069 if (TREE_OPERAND (expr, 1) != e1)
3070 changed = true;
3072 if (code == COND_EXPR)
3074 e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
3075 if (TREE_OPERAND (expr, 2) != e2)
3076 changed = true;
3078 else
3079 e2 = NULL_TREE;
3081 if (changed)
3083 if (code == COND_EXPR)
3084 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
3085 else
3086 expr = fold_build2 (code, boolean_type_node, e0, e1);
3089 return expr;
3092 e = instantiate_parameters (loop, expr);
3093 if (is_gimple_min_invariant (e))
3094 return e;
3096 return expr;
3099 /* Returns true if EXIT is the only possible exit from LOOP. */
3101 bool
3102 loop_only_exit_p (const class loop *loop, basic_block *body, const_edge exit)
3104 gimple_stmt_iterator bsi;
3105 unsigned i;
3107 if (exit != single_exit (loop))
3108 return false;
3110 for (i = 0; i < loop->num_nodes; i++)
3111 for (bsi = gsi_start_bb (body[i]); !gsi_end_p (bsi); gsi_next (&bsi))
3112 if (stmt_can_terminate_bb_p (gsi_stmt (bsi)))
3113 return false;
3115 return true;
3118 /* Stores description of number of iterations of LOOP derived from
3119 EXIT (an exit edge of the LOOP) in NITER. Returns true if some useful
3120 information could be derived (and fields of NITER have meaning described
3121 in comments at class tree_niter_desc declaration), false otherwise.
3122 When EVERY_ITERATION is true, only tests that are known to be executed
3123 every iteration are considered (i.e. only test that alone bounds the loop).
3124 If AT_STMT is not NULL, this function stores LOOP's condition statement in
3125 it when returning true. */
3127 bool
3128 number_of_iterations_exit_assumptions (class loop *loop, edge exit,
3129 class tree_niter_desc *niter,
3130 gcond **at_stmt, bool every_iteration,
3131 basic_block *body)
3133 tree type;
3134 tree op0, op1;
3135 enum tree_code code;
3136 affine_iv iv0, iv1;
3137 bool safe;
3139 /* The condition at a fake exit (if it exists) does not control its
3140 execution. */
3141 if (exit->flags & EDGE_FAKE)
3142 return false;
3144 /* Nothing to analyze if the loop is known to be infinite. */
3145 if (loop_constraint_set_p (loop, LOOP_C_INFINITE))
3146 return false;
3148 safe = dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src);
3150 if (every_iteration && !safe)
3151 return false;
3153 niter->assumptions = boolean_false_node;
3154 niter->control.base = NULL_TREE;
3155 niter->control.step = NULL_TREE;
3156 niter->control.no_overflow = false;
3157 gcond *stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
3158 if (!stmt)
3159 return false;
3161 if (at_stmt)
3162 *at_stmt = stmt;
3164 /* We want the condition for staying inside loop. */
3165 code = gimple_cond_code (stmt);
3166 if (exit->flags & EDGE_TRUE_VALUE)
3167 code = invert_tree_comparison (code, false);
3169 switch (code)
3171 case GT_EXPR:
3172 case GE_EXPR:
3173 case LT_EXPR:
3174 case LE_EXPR:
3175 case NE_EXPR:
3176 break;
3178 case EQ_EXPR:
3179 return number_of_iterations_cltz (loop, exit, code, niter);
3181 default:
3182 return false;
3185 op0 = gimple_cond_lhs (stmt);
3186 op1 = gimple_cond_rhs (stmt);
3187 type = TREE_TYPE (op0);
3189 if (TREE_CODE (type) != INTEGER_TYPE
3190 && !POINTER_TYPE_P (type))
3191 return false;
3193 tree iv0_niters = NULL_TREE;
3194 if (!simple_iv_with_niters (loop, loop_containing_stmt (stmt),
3195 op0, &iv0, safe ? &iv0_niters : NULL, false))
3196 return number_of_iterations_bitcount (loop, exit, code, niter);
3197 tree iv1_niters = NULL_TREE;
3198 if (!simple_iv_with_niters (loop, loop_containing_stmt (stmt),
3199 op1, &iv1, safe ? &iv1_niters : NULL, false))
3200 return false;
3201 /* Give up on complicated case. */
3202 if (iv0_niters && iv1_niters)
3203 return false;
3205 /* We don't want to see undefined signed overflow warnings while
3206 computing the number of iterations. */
3207 fold_defer_overflow_warnings ();
3209 iv0.base = expand_simple_operations (iv0.base);
3210 iv1.base = expand_simple_operations (iv1.base);
3211 bool body_from_caller = true;
3212 if (!body)
3214 body = get_loop_body (loop);
3215 body_from_caller = false;
3217 bool only_exit_p = loop_only_exit_p (loop, body, exit);
3218 if (!body_from_caller)
3219 free (body);
3220 if (!number_of_iterations_cond (loop, type, &iv0, code, &iv1, niter,
3221 only_exit_p, safe))
3223 fold_undefer_and_ignore_overflow_warnings ();
3224 return false;
3227 /* Incorporate additional assumption implied by control iv. */
3228 tree iv_niters = iv0_niters ? iv0_niters : iv1_niters;
3229 if (iv_niters)
3231 tree assumption = fold_build2 (LE_EXPR, boolean_type_node, niter->niter,
3232 fold_convert (TREE_TYPE (niter->niter),
3233 iv_niters));
3235 if (!integer_nonzerop (assumption))
3236 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3237 niter->assumptions, assumption);
3239 /* Refine upper bound if possible. */
3240 if (TREE_CODE (iv_niters) == INTEGER_CST
3241 && niter->max > wi::to_widest (iv_niters))
3242 niter->max = wi::to_widest (iv_niters);
3245 /* There is no assumptions if the loop is known to be finite. */
3246 if (!integer_zerop (niter->assumptions)
3247 && loop_constraint_set_p (loop, LOOP_C_FINITE))
3248 niter->assumptions = boolean_true_node;
3250 if (optimize >= 3)
3252 niter->assumptions = simplify_using_outer_evolutions (loop,
3253 niter->assumptions);
3254 niter->may_be_zero = simplify_using_outer_evolutions (loop,
3255 niter->may_be_zero);
3256 niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
3259 niter->assumptions
3260 = simplify_using_initial_conditions (loop,
3261 niter->assumptions);
3262 niter->may_be_zero
3263 = simplify_using_initial_conditions (loop,
3264 niter->may_be_zero);
3266 fold_undefer_and_ignore_overflow_warnings ();
3268 /* If NITER has simplified into a constant, update MAX. */
3269 if (TREE_CODE (niter->niter) == INTEGER_CST)
3270 niter->max = wi::to_widest (niter->niter);
3272 return (!integer_zerop (niter->assumptions));
3275 /* Like number_of_iterations_exit_assumptions, but return TRUE only if
3276 the niter information holds unconditionally. */
3278 bool
3279 number_of_iterations_exit (class loop *loop, edge exit,
3280 class tree_niter_desc *niter,
3281 bool warn, bool every_iteration,
3282 basic_block *body)
3284 gcond *stmt;
3285 if (!number_of_iterations_exit_assumptions (loop, exit, niter,
3286 &stmt, every_iteration, body))
3287 return false;
3289 if (integer_nonzerop (niter->assumptions))
3290 return true;
3292 if (warn && dump_enabled_p ())
3293 dump_printf_loc (MSG_MISSED_OPTIMIZATION, stmt,
3294 "missed loop optimization: niters analysis ends up "
3295 "with assumptions.\n");
3297 return false;
3300 /* Try to determine the number of iterations of LOOP. If we succeed,
3301 expression giving number of iterations is returned and *EXIT is
3302 set to the edge from that the information is obtained. Otherwise
3303 chrec_dont_know is returned. */
3305 tree
3306 find_loop_niter (class loop *loop, edge *exit)
3308 unsigned i;
3309 auto_vec<edge> exits = get_loop_exit_edges (loop);
3310 edge ex;
3311 tree niter = NULL_TREE, aniter;
3312 class tree_niter_desc desc;
3314 *exit = NULL;
3315 FOR_EACH_VEC_ELT (exits, i, ex)
3317 if (!number_of_iterations_exit (loop, ex, &desc, false))
3318 continue;
3320 if (integer_nonzerop (desc.may_be_zero))
3322 /* We exit in the first iteration through this exit.
3323 We won't find anything better. */
3324 niter = build_int_cst (unsigned_type_node, 0);
3325 *exit = ex;
3326 break;
3329 if (!integer_zerop (desc.may_be_zero))
3330 continue;
3332 aniter = desc.niter;
3334 if (!niter)
3336 /* Nothing recorded yet. */
3337 niter = aniter;
3338 *exit = ex;
3339 continue;
3342 /* Prefer constants, the lower the better. */
3343 if (TREE_CODE (aniter) != INTEGER_CST)
3344 continue;
3346 if (TREE_CODE (niter) != INTEGER_CST)
3348 niter = aniter;
3349 *exit = ex;
3350 continue;
3353 if (tree_int_cst_lt (aniter, niter))
3355 niter = aniter;
3356 *exit = ex;
3357 continue;
3361 return niter ? niter : chrec_dont_know;
3364 /* Return true if loop is known to have bounded number of iterations. */
3366 bool
3367 finite_loop_p (class loop *loop)
3369 widest_int nit;
3370 int flags;
3372 if (loop->finite_p)
3374 unsigned i;
3375 auto_vec<edge> exits = get_loop_exit_edges (loop);
3376 edge ex;
3378 /* If the loop has a normal exit, we can assume it will terminate. */
3379 FOR_EACH_VEC_ELT (exits, i, ex)
3380 if (!(ex->flags & (EDGE_EH | EDGE_ABNORMAL | EDGE_FAKE)))
3382 if (dump_file)
3383 fprintf (dump_file, "Assume loop %i to be finite: it has an exit "
3384 "and -ffinite-loops is on or loop was "
3385 "previously finite.\n",
3386 loop->num);
3387 return true;
3391 flags = flags_from_decl_or_type (current_function_decl);
3392 if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
3394 if (dump_file && (dump_flags & TDF_DETAILS))
3395 fprintf (dump_file,
3396 "Found loop %i to be finite: it is within "
3397 "pure or const function.\n",
3398 loop->num);
3399 loop->finite_p = true;
3400 return true;
3403 if (loop->any_upper_bound
3404 /* Loop with no normal exit will not pass max_loop_iterations. */
3405 || (!loop->finite_p && max_loop_iterations (loop, &nit)))
3407 if (dump_file && (dump_flags & TDF_DETAILS))
3408 fprintf (dump_file, "Found loop %i to be finite: upper bound found.\n",
3409 loop->num);
3410 loop->finite_p = true;
3411 return true;
3414 return false;
3419 Analysis of a number of iterations of a loop by a brute-force evaluation.
3423 /* Bound on the number of iterations we try to evaluate. */
3425 #define MAX_ITERATIONS_TO_TRACK \
3426 ((unsigned) param_max_iterations_to_track)
3428 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
3429 result by a chain of operations such that all but exactly one of their
3430 operands are constants. */
3432 static gphi *
3433 chain_of_csts_start (class loop *loop, tree x)
3435 gimple *stmt = SSA_NAME_DEF_STMT (x);
3436 tree use;
3437 basic_block bb = gimple_bb (stmt);
3438 enum tree_code code;
3440 if (!bb
3441 || !flow_bb_inside_loop_p (loop, bb))
3442 return NULL;
3444 if (gimple_code (stmt) == GIMPLE_PHI)
3446 if (bb == loop->header)
3447 return as_a <gphi *> (stmt);
3449 return NULL;
3452 if (gimple_code (stmt) != GIMPLE_ASSIGN
3453 || gimple_assign_rhs_class (stmt) == GIMPLE_TERNARY_RHS)
3454 return NULL;
3456 code = gimple_assign_rhs_code (stmt);
3457 if (gimple_references_memory_p (stmt)
3458 || TREE_CODE_CLASS (code) == tcc_reference
3459 || (code == ADDR_EXPR
3460 && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
3461 return NULL;
3463 use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
3464 if (use == NULL_TREE)
3465 return NULL;
3467 return chain_of_csts_start (loop, use);
3470 /* Determines whether the expression X is derived from a result of a phi node
3471 in header of LOOP such that
3473 * the derivation of X consists only from operations with constants
3474 * the initial value of the phi node is constant
3475 * the value of the phi node in the next iteration can be derived from the
3476 value in the current iteration by a chain of operations with constants,
3477 or is also a constant
3479 If such phi node exists, it is returned, otherwise NULL is returned. */
3481 static gphi *
3482 get_base_for (class loop *loop, tree x)
3484 gphi *phi;
3485 tree init, next;
3487 if (is_gimple_min_invariant (x))
3488 return NULL;
3490 phi = chain_of_csts_start (loop, x);
3491 if (!phi)
3492 return NULL;
3494 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
3495 next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
3497 if (!is_gimple_min_invariant (init))
3498 return NULL;
3500 if (TREE_CODE (next) == SSA_NAME
3501 && chain_of_csts_start (loop, next) != phi)
3502 return NULL;
3504 return phi;
3507 /* Given an expression X, then
3509 * if X is NULL_TREE, we return the constant BASE.
3510 * if X is a constant, we return the constant X.
3511 * otherwise X is a SSA name, whose value in the considered loop is derived
3512 by a chain of operations with constant from a result of a phi node in
3513 the header of the loop. Then we return value of X when the value of the
3514 result of this phi node is given by the constant BASE. */
3516 static tree
3517 get_val_for (tree x, tree base)
3519 gimple *stmt;
3521 gcc_checking_assert (is_gimple_min_invariant (base));
3523 if (!x)
3524 return base;
3525 else if (is_gimple_min_invariant (x))
3526 return x;
3528 stmt = SSA_NAME_DEF_STMT (x);
3529 if (gimple_code (stmt) == GIMPLE_PHI)
3530 return base;
3532 gcc_checking_assert (is_gimple_assign (stmt));
3534 /* STMT must be either an assignment of a single SSA name or an
3535 expression involving an SSA name and a constant. Try to fold that
3536 expression using the value for the SSA name. */
3537 if (gimple_assign_ssa_name_copy_p (stmt))
3538 return get_val_for (gimple_assign_rhs1 (stmt), base);
3539 else if (gimple_assign_rhs_class (stmt) == GIMPLE_UNARY_RHS
3540 && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
3541 return fold_build1 (gimple_assign_rhs_code (stmt),
3542 TREE_TYPE (gimple_assign_lhs (stmt)),
3543 get_val_for (gimple_assign_rhs1 (stmt), base));
3544 else if (gimple_assign_rhs_class (stmt) == GIMPLE_BINARY_RHS)
3546 tree rhs1 = gimple_assign_rhs1 (stmt);
3547 tree rhs2 = gimple_assign_rhs2 (stmt);
3548 if (TREE_CODE (rhs1) == SSA_NAME)
3549 rhs1 = get_val_for (rhs1, base);
3550 else if (TREE_CODE (rhs2) == SSA_NAME)
3551 rhs2 = get_val_for (rhs2, base);
3552 else
3553 gcc_unreachable ();
3554 return fold_build2 (gimple_assign_rhs_code (stmt),
3555 TREE_TYPE (gimple_assign_lhs (stmt)), rhs1, rhs2);
3557 else
3558 gcc_unreachable ();
3562 /* Tries to count the number of iterations of LOOP till it exits by EXIT
3563 by brute force -- i.e. by determining the value of the operands of the
3564 condition at EXIT in first few iterations of the loop (assuming that
3565 these values are constant) and determining the first one in that the
3566 condition is not satisfied. Returns the constant giving the number
3567 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
3569 tree
3570 loop_niter_by_eval (class loop *loop, edge exit)
3572 tree acnd;
3573 tree op[2], val[2], next[2], aval[2];
3574 gphi *phi;
3575 unsigned i, j;
3576 enum tree_code cmp;
3578 gcond *cond = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
3579 if (!cond)
3580 return chrec_dont_know;
3582 cmp = gimple_cond_code (cond);
3583 if (exit->flags & EDGE_TRUE_VALUE)
3584 cmp = invert_tree_comparison (cmp, false);
3586 switch (cmp)
3588 case EQ_EXPR:
3589 case NE_EXPR:
3590 case GT_EXPR:
3591 case GE_EXPR:
3592 case LT_EXPR:
3593 case LE_EXPR:
3594 op[0] = gimple_cond_lhs (cond);
3595 op[1] = gimple_cond_rhs (cond);
3596 break;
3598 default:
3599 return chrec_dont_know;
3602 for (j = 0; j < 2; j++)
3604 if (is_gimple_min_invariant (op[j]))
3606 val[j] = op[j];
3607 next[j] = NULL_TREE;
3608 op[j] = NULL_TREE;
3610 else
3612 phi = get_base_for (loop, op[j]);
3613 if (!phi)
3614 return chrec_dont_know;
3615 val[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
3616 next[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
3620 /* Don't issue signed overflow warnings. */
3621 fold_defer_overflow_warnings ();
3623 for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
3625 for (j = 0; j < 2; j++)
3626 aval[j] = get_val_for (op[j], val[j]);
3628 acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
3629 if (acnd && integer_zerop (acnd))
3631 fold_undefer_and_ignore_overflow_warnings ();
3632 if (dump_file && (dump_flags & TDF_DETAILS))
3633 fprintf (dump_file,
3634 "Proved that loop %d iterates %d times using brute force.\n",
3635 loop->num, i);
3636 return build_int_cst (unsigned_type_node, i);
3639 for (j = 0; j < 2; j++)
3641 aval[j] = val[j];
3642 val[j] = get_val_for (next[j], val[j]);
3643 if (!is_gimple_min_invariant (val[j]))
3645 fold_undefer_and_ignore_overflow_warnings ();
3646 return chrec_dont_know;
3650 /* If the next iteration would use the same base values
3651 as the current one, there is no point looping further,
3652 all following iterations will be the same as this one. */
3653 if (val[0] == aval[0] && val[1] == aval[1])
3654 break;
3657 fold_undefer_and_ignore_overflow_warnings ();
3659 return chrec_dont_know;
3662 /* Finds the exit of the LOOP by that the loop exits after a constant
3663 number of iterations and stores the exit edge to *EXIT. The constant
3664 giving the number of iterations of LOOP is returned. The number of
3665 iterations is determined using loop_niter_by_eval (i.e. by brute force
3666 evaluation). If we are unable to find the exit for that loop_niter_by_eval
3667 determines the number of iterations, chrec_dont_know is returned. */
3669 tree
3670 find_loop_niter_by_eval (class loop *loop, edge *exit)
3672 unsigned i;
3673 auto_vec<edge> exits = get_loop_exit_edges (loop);
3674 edge ex;
3675 tree niter = NULL_TREE, aniter;
3677 *exit = NULL;
3679 /* Loops with multiple exits are expensive to handle and less important. */
3680 if (!flag_expensive_optimizations
3681 && exits.length () > 1)
3682 return chrec_dont_know;
3684 FOR_EACH_VEC_ELT (exits, i, ex)
3686 if (!just_once_each_iteration_p (loop, ex->src))
3687 continue;
3689 aniter = loop_niter_by_eval (loop, ex);
3690 if (chrec_contains_undetermined (aniter))
3691 continue;
3693 if (niter
3694 && !tree_int_cst_lt (aniter, niter))
3695 continue;
3697 niter = aniter;
3698 *exit = ex;
3701 return niter ? niter : chrec_dont_know;
3706 Analysis of upper bounds on number of iterations of a loop.
3710 static widest_int derive_constant_upper_bound_ops (tree, tree,
3711 enum tree_code, tree);
3713 /* Returns a constant upper bound on the value of the right-hand side of
3714 an assignment statement STMT. */
3716 static widest_int
3717 derive_constant_upper_bound_assign (gimple *stmt)
3719 enum tree_code code = gimple_assign_rhs_code (stmt);
3720 tree op0 = gimple_assign_rhs1 (stmt);
3721 tree op1 = gimple_assign_rhs2 (stmt);
3723 return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt)),
3724 op0, code, op1);
3727 /* Returns a constant upper bound on the value of expression VAL. VAL
3728 is considered to be unsigned. If its type is signed, its value must
3729 be nonnegative. */
3731 static widest_int
3732 derive_constant_upper_bound (tree val)
3734 enum tree_code code;
3735 tree op0, op1, op2;
3737 extract_ops_from_tree (val, &code, &op0, &op1, &op2);
3738 return derive_constant_upper_bound_ops (TREE_TYPE (val), op0, code, op1);
3741 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
3742 whose type is TYPE. The expression is considered to be unsigned. If
3743 its type is signed, its value must be nonnegative. */
3745 static widest_int
3746 derive_constant_upper_bound_ops (tree type, tree op0,
3747 enum tree_code code, tree op1)
3749 tree subtype, maxt;
3750 widest_int bnd, max, cst;
3751 gimple *stmt;
3753 if (INTEGRAL_TYPE_P (type))
3754 maxt = TYPE_MAX_VALUE (type);
3755 else
3756 maxt = upper_bound_in_type (type, type);
3758 max = wi::to_widest (maxt);
3760 switch (code)
3762 case INTEGER_CST:
3763 return wi::to_widest (op0);
3765 CASE_CONVERT:
3766 subtype = TREE_TYPE (op0);
3767 if (!TYPE_UNSIGNED (subtype)
3768 /* If TYPE is also signed, the fact that VAL is nonnegative implies
3769 that OP0 is nonnegative. */
3770 && TYPE_UNSIGNED (type)
3771 && !tree_expr_nonnegative_p (op0))
3773 /* If we cannot prove that the casted expression is nonnegative,
3774 we cannot establish more useful upper bound than the precision
3775 of the type gives us. */
3776 return max;
3779 /* We now know that op0 is an nonnegative value. Try deriving an upper
3780 bound for it. */
3781 bnd = derive_constant_upper_bound (op0);
3783 /* If the bound does not fit in TYPE, max. value of TYPE could be
3784 attained. */
3785 if (wi::ltu_p (max, bnd))
3786 return max;
3788 return bnd;
3790 case PLUS_EXPR:
3791 case POINTER_PLUS_EXPR:
3792 case MINUS_EXPR:
3793 if (TREE_CODE (op1) != INTEGER_CST
3794 || !tree_expr_nonnegative_p (op0))
3795 return max;
3797 /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
3798 choose the most logical way how to treat this constant regardless
3799 of the signedness of the type. */
3800 cst = wi::sext (wi::to_widest (op1), TYPE_PRECISION (type));
3801 if (code != MINUS_EXPR)
3802 cst = -cst;
3804 bnd = derive_constant_upper_bound (op0);
3806 if (wi::neg_p (cst))
3808 cst = -cst;
3809 /* Avoid CST == 0x80000... */
3810 if (wi::neg_p (cst))
3811 return max;
3813 /* OP0 + CST. We need to check that
3814 BND <= MAX (type) - CST. */
3816 widest_int mmax = max - cst;
3817 if (wi::leu_p (bnd, mmax))
3818 return max;
3820 return bnd + cst;
3822 else
3824 /* OP0 - CST, where CST >= 0.
3826 If TYPE is signed, we have already verified that OP0 >= 0, and we
3827 know that the result is nonnegative. This implies that
3828 VAL <= BND - CST.
3830 If TYPE is unsigned, we must additionally know that OP0 >= CST,
3831 otherwise the operation underflows.
3834 /* This should only happen if the type is unsigned; however, for
3835 buggy programs that use overflowing signed arithmetics even with
3836 -fno-wrapv, this condition may also be true for signed values. */
3837 if (wi::ltu_p (bnd, cst))
3838 return max;
3840 if (TYPE_UNSIGNED (type))
3842 tree tem = fold_binary (GE_EXPR, boolean_type_node, op0,
3843 wide_int_to_tree (type, cst));
3844 if (!tem || integer_nonzerop (tem))
3845 return max;
3848 bnd -= cst;
3851 return bnd;
3853 case FLOOR_DIV_EXPR:
3854 case EXACT_DIV_EXPR:
3855 if (TREE_CODE (op1) != INTEGER_CST
3856 || tree_int_cst_sign_bit (op1))
3857 return max;
3859 bnd = derive_constant_upper_bound (op0);
3860 return wi::udiv_floor (bnd, wi::to_widest (op1));
3862 case BIT_AND_EXPR:
3863 if (TREE_CODE (op1) != INTEGER_CST
3864 || tree_int_cst_sign_bit (op1))
3865 return max;
3866 return wi::to_widest (op1);
3868 case SSA_NAME:
3869 stmt = SSA_NAME_DEF_STMT (op0);
3870 if (gimple_code (stmt) != GIMPLE_ASSIGN
3871 || gimple_assign_lhs (stmt) != op0)
3872 return max;
3873 return derive_constant_upper_bound_assign (stmt);
3875 default:
3876 return max;
3880 /* Emit a -Waggressive-loop-optimizations warning if needed. */
3882 static void
3883 do_warn_aggressive_loop_optimizations (class loop *loop,
3884 widest_int i_bound, gimple *stmt)
3886 /* Don't warn if the loop doesn't have known constant bound. */
3887 if (!loop->nb_iterations
3888 || TREE_CODE (loop->nb_iterations) != INTEGER_CST
3889 || !warn_aggressive_loop_optimizations
3890 /* To avoid warning multiple times for the same loop,
3891 only start warning when we preserve loops. */
3892 || (cfun->curr_properties & PROP_loops) == 0
3893 /* Only warn once per loop. */
3894 || loop->warned_aggressive_loop_optimizations
3895 /* Only warn if undefined behavior gives us lower estimate than the
3896 known constant bound. */
3897 || wi::cmpu (i_bound, wi::to_widest (loop->nb_iterations)) >= 0
3898 /* And undefined behavior happens unconditionally. */
3899 || !dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (stmt)))
3900 return;
3902 edge e = single_exit (loop);
3903 if (e == NULL)
3904 return;
3906 gimple *estmt = last_nondebug_stmt (e->src);
3907 char buf[WIDE_INT_PRINT_BUFFER_SIZE], *p;
3908 unsigned len;
3909 if (print_dec_buf_size (i_bound, TYPE_SIGN (TREE_TYPE (loop->nb_iterations)),
3910 &len))
3911 p = XALLOCAVEC (char, len);
3912 else
3913 p = buf;
3914 print_dec (i_bound, p, TYPE_SIGN (TREE_TYPE (loop->nb_iterations)));
3915 auto_diagnostic_group d;
3916 if (warning_at (gimple_location (stmt), OPT_Waggressive_loop_optimizations,
3917 "iteration %s invokes undefined behavior", p))
3918 inform (gimple_location (estmt), "within this loop");
3919 loop->warned_aggressive_loop_optimizations = true;
3922 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
3923 is true if the loop is exited immediately after STMT, and this exit
3924 is taken at last when the STMT is executed BOUND + 1 times.
3925 REALISTIC is true if BOUND is expected to be close to the real number
3926 of iterations. UPPER is true if we are sure the loop iterates at most
3927 BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
3929 static void
3930 record_estimate (class loop *loop, tree bound, const widest_int &i_bound,
3931 gimple *at_stmt, bool is_exit, bool realistic, bool upper)
3933 widest_int delta;
3935 if (dump_file && (dump_flags & TDF_DETAILS))
3937 fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
3938 print_gimple_stmt (dump_file, at_stmt, 0, TDF_SLIM);
3939 fprintf (dump_file, " is %sexecuted at most ",
3940 upper ? "" : "probably ");
3941 print_generic_expr (dump_file, bound, TDF_SLIM);
3942 fprintf (dump_file, " (bounded by ");
3943 print_decu (i_bound, dump_file);
3944 fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
3947 /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
3948 real number of iterations. */
3949 if (TREE_CODE (bound) != INTEGER_CST)
3950 realistic = false;
3951 else
3952 gcc_checking_assert (i_bound == wi::to_widest (bound));
3954 if (wi::min_precision (i_bound, SIGNED) > bound_wide_int ().get_precision ())
3955 return;
3957 /* If we have a guaranteed upper bound, record it in the appropriate
3958 list, unless this is an !is_exit bound (i.e. undefined behavior in
3959 at_stmt) in a loop with known constant number of iterations. */
3960 if (upper
3961 && (is_exit
3962 || loop->nb_iterations == NULL_TREE
3963 || TREE_CODE (loop->nb_iterations) != INTEGER_CST))
3965 class nb_iter_bound *elt = ggc_alloc<nb_iter_bound> ();
3967 elt->bound = bound_wide_int::from (i_bound, SIGNED);
3968 elt->stmt = at_stmt;
3969 elt->is_exit = is_exit;
3970 elt->next = loop->bounds;
3971 loop->bounds = elt;
3974 /* If statement is executed on every path to the loop latch, we can directly
3975 infer the upper bound on the # of iterations of the loop. */
3976 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (at_stmt)))
3977 upper = false;
3979 /* Update the number of iteration estimates according to the bound.
3980 If at_stmt is an exit then the loop latch is executed at most BOUND times,
3981 otherwise it can be executed BOUND + 1 times. We will lower the estimate
3982 later if such statement must be executed on last iteration */
3983 if (is_exit)
3984 delta = 0;
3985 else
3986 delta = 1;
3987 widest_int new_i_bound = i_bound + delta;
3989 /* If an overflow occurred, ignore the result. */
3990 if (wi::ltu_p (new_i_bound, delta))
3991 return;
3993 if (upper && !is_exit)
3994 do_warn_aggressive_loop_optimizations (loop, new_i_bound, at_stmt);
3995 record_niter_bound (loop, new_i_bound, realistic, upper);
3998 /* Records the control iv analyzed in NITER for LOOP if the iv is valid
3999 and doesn't overflow. */
4001 static void
4002 record_control_iv (class loop *loop, class tree_niter_desc *niter)
4004 struct control_iv *iv;
4006 if (!niter->control.base || !niter->control.step)
4007 return;
4009 if (!integer_onep (niter->assumptions) || !niter->control.no_overflow)
4010 return;
4012 iv = ggc_alloc<control_iv> ();
4013 iv->base = niter->control.base;
4014 iv->step = niter->control.step;
4015 iv->next = loop->control_ivs;
4016 loop->control_ivs = iv;
4018 return;
4021 /* This function returns TRUE if below conditions are satisfied:
4022 1) VAR is SSA variable.
4023 2) VAR is an IV:{base, step} in its defining loop.
4024 3) IV doesn't overflow.
4025 4) Both base and step are integer constants.
4026 5) Base is the MIN/MAX value depends on IS_MIN.
4027 Store value of base to INIT correspondingly. */
4029 static bool
4030 get_cst_init_from_scev (tree var, wide_int *init, bool is_min)
4032 if (TREE_CODE (var) != SSA_NAME)
4033 return false;
4035 gimple *def_stmt = SSA_NAME_DEF_STMT (var);
4036 class loop *loop = loop_containing_stmt (def_stmt);
4038 if (loop == NULL)
4039 return false;
4041 affine_iv iv;
4042 if (!simple_iv (loop, loop, var, &iv, false))
4043 return false;
4045 if (!iv.no_overflow)
4046 return false;
4048 if (TREE_CODE (iv.base) != INTEGER_CST || TREE_CODE (iv.step) != INTEGER_CST)
4049 return false;
4051 if (is_min == tree_int_cst_sign_bit (iv.step))
4052 return false;
4054 *init = wi::to_wide (iv.base);
4055 return true;
4058 /* Record the estimate on number of iterations of LOOP based on the fact that
4059 the induction variable BASE + STEP * i evaluated in STMT does not wrap and
4060 its values belong to the range <LOW, HIGH>. REALISTIC is true if the
4061 estimated number of iterations is expected to be close to the real one.
4062 UPPER is true if we are sure the induction variable does not wrap. */
4064 static void
4065 record_nonwrapping_iv (class loop *loop, tree base, tree step, gimple *stmt,
4066 tree low, tree high, bool realistic, bool upper)
4068 tree niter_bound, extreme, delta;
4069 tree type = TREE_TYPE (base), unsigned_type;
4070 tree orig_base = base;
4072 if (TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
4073 return;
4075 if (dump_file && (dump_flags & TDF_DETAILS))
4077 fprintf (dump_file, "Induction variable (");
4078 print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
4079 fprintf (dump_file, ") ");
4080 print_generic_expr (dump_file, base, TDF_SLIM);
4081 fprintf (dump_file, " + ");
4082 print_generic_expr (dump_file, step, TDF_SLIM);
4083 fprintf (dump_file, " * iteration does not wrap in statement ");
4084 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
4085 fprintf (dump_file, " in loop %d.\n", loop->num);
4088 unsigned_type = unsigned_type_for (type);
4089 base = fold_convert (unsigned_type, base);
4090 step = fold_convert (unsigned_type, step);
4092 if (tree_int_cst_sign_bit (step))
4094 wide_int max;
4095 value_range base_range (TREE_TYPE (orig_base));
4096 if (get_range_query (cfun)->range_of_expr (base_range, orig_base)
4097 && !base_range.undefined_p ())
4098 max = wi::to_wide (base_range.ubound ());
4099 extreme = fold_convert (unsigned_type, low);
4100 if (TREE_CODE (orig_base) == SSA_NAME
4101 && TREE_CODE (high) == INTEGER_CST
4102 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
4103 && ((!base_range.varying_p ()
4104 && !base_range.undefined_p ())
4105 || get_cst_init_from_scev (orig_base, &max, false))
4106 && wi::gts_p (wi::to_wide (high), max))
4107 base = wide_int_to_tree (unsigned_type, max);
4108 else if (TREE_CODE (base) != INTEGER_CST
4109 && dominated_by_p (CDI_DOMINATORS,
4110 loop->latch, gimple_bb (stmt)))
4111 base = fold_convert (unsigned_type, high);
4112 delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
4113 step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
4115 else
4117 wide_int min;
4118 value_range base_range (TREE_TYPE (orig_base));
4119 if (get_range_query (cfun)->range_of_expr (base_range, orig_base)
4120 && !base_range.undefined_p ())
4121 min = wi::to_wide (base_range.lbound ());
4122 extreme = fold_convert (unsigned_type, high);
4123 if (TREE_CODE (orig_base) == SSA_NAME
4124 && TREE_CODE (low) == INTEGER_CST
4125 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
4126 && ((!base_range.varying_p ()
4127 && !base_range.undefined_p ())
4128 || get_cst_init_from_scev (orig_base, &min, true))
4129 && wi::gts_p (min, wi::to_wide (low)))
4130 base = wide_int_to_tree (unsigned_type, min);
4131 else if (TREE_CODE (base) != INTEGER_CST
4132 && dominated_by_p (CDI_DOMINATORS,
4133 loop->latch, gimple_bb (stmt)))
4134 base = fold_convert (unsigned_type, low);
4135 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
4138 /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
4139 would get out of the range. */
4140 niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
4141 widest_int max = derive_constant_upper_bound (niter_bound);
4142 record_estimate (loop, niter_bound, max, stmt, false, realistic, upper);
4145 /* Determine information about number of iterations a LOOP from the index
4146 IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
4147 guaranteed to be executed in every iteration of LOOP. Callback for
4148 for_each_index. */
4150 struct ilb_data
4152 class loop *loop;
4153 gimple *stmt;
4156 static bool
4157 idx_infer_loop_bounds (tree base, tree *idx, void *dta)
4159 struct ilb_data *data = (struct ilb_data *) dta;
4160 tree ev, init, step;
4161 tree low, high, type, next;
4162 bool sign, upper = true, has_flexible_size = false;
4163 class loop *loop = data->loop;
4165 if (TREE_CODE (base) != ARRAY_REF)
4166 return true;
4168 /* For arrays that might have flexible sizes, it is not guaranteed that they
4169 do not really extend over their declared size. */
4170 if (array_ref_flexible_size_p (base))
4172 has_flexible_size = true;
4173 upper = false;
4176 class loop *dloop = loop_containing_stmt (data->stmt);
4177 if (!dloop)
4178 return true;
4180 ev = analyze_scalar_evolution (dloop, *idx);
4181 ev = instantiate_parameters (loop, ev);
4182 init = initial_condition (ev);
4183 step = evolution_part_in_loop_num (ev, loop->num);
4185 if (!init
4186 || !step
4187 || TREE_CODE (step) != INTEGER_CST
4188 || integer_zerop (step)
4189 || tree_contains_chrecs (init, NULL)
4190 || chrec_contains_symbols_defined_in_loop (init, loop->num))
4191 return true;
4193 low = array_ref_low_bound (base);
4194 high = array_ref_up_bound (base);
4196 /* The case of nonconstant bounds could be handled, but it would be
4197 complicated. */
4198 if (TREE_CODE (low) != INTEGER_CST
4199 || !high
4200 || TREE_CODE (high) != INTEGER_CST)
4201 return true;
4202 sign = tree_int_cst_sign_bit (step);
4203 type = TREE_TYPE (step);
4205 /* The array that might have flexible size most likely extends
4206 beyond its bounds. */
4207 if (has_flexible_size
4208 && operand_equal_p (low, high, 0))
4209 return true;
4211 /* In case the relevant bound of the array does not fit in type, or
4212 it does, but bound + step (in type) still belongs into the range of the
4213 array, the index may wrap and still stay within the range of the array
4214 (consider e.g. if the array is indexed by the full range of
4215 unsigned char).
4217 To make things simpler, we require both bounds to fit into type, although
4218 there are cases where this would not be strictly necessary. */
4219 if (!int_fits_type_p (high, type)
4220 || !int_fits_type_p (low, type))
4221 return true;
4222 low = fold_convert (type, low);
4223 high = fold_convert (type, high);
4225 if (sign)
4226 next = fold_binary (PLUS_EXPR, type, low, step);
4227 else
4228 next = fold_binary (PLUS_EXPR, type, high, step);
4230 if (tree_int_cst_compare (low, next) <= 0
4231 && tree_int_cst_compare (next, high) <= 0)
4232 return true;
4234 /* If access is not executed on every iteration, we must ensure that overlow
4235 may not make the access valid later. */
4236 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (data->stmt)))
4238 if (scev_probably_wraps_p (NULL_TREE,
4239 initial_condition_in_loop_num (ev, loop->num),
4240 step, data->stmt, loop, true))
4241 upper = false;
4243 else
4244 record_nonwrapping_chrec (ev);
4246 record_nonwrapping_iv (loop, init, step, data->stmt, low, high, false, upper);
4247 return true;
4250 /* Determine information about number of iterations a LOOP from the bounds
4251 of arrays in the data reference REF accessed in STMT. RELIABLE is true if
4252 STMT is guaranteed to be executed in every iteration of LOOP.*/
4254 static void
4255 infer_loop_bounds_from_ref (class loop *loop, gimple *stmt, tree ref)
4257 struct ilb_data data;
4259 data.loop = loop;
4260 data.stmt = stmt;
4261 for_each_index (&ref, idx_infer_loop_bounds, &data);
4264 /* Determine information about number of iterations of a LOOP from the way
4265 arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
4266 executed in every iteration of LOOP. */
4268 static void
4269 infer_loop_bounds_from_array (class loop *loop, gimple *stmt)
4271 if (is_gimple_assign (stmt))
4273 tree op0 = gimple_assign_lhs (stmt);
4274 tree op1 = gimple_assign_rhs1 (stmt);
4276 /* For each memory access, analyze its access function
4277 and record a bound on the loop iteration domain. */
4278 if (REFERENCE_CLASS_P (op0))
4279 infer_loop_bounds_from_ref (loop, stmt, op0);
4281 if (REFERENCE_CLASS_P (op1))
4282 infer_loop_bounds_from_ref (loop, stmt, op1);
4284 else if (is_gimple_call (stmt))
4286 tree arg, lhs;
4287 unsigned i, n = gimple_call_num_args (stmt);
4289 lhs = gimple_call_lhs (stmt);
4290 if (lhs && REFERENCE_CLASS_P (lhs))
4291 infer_loop_bounds_from_ref (loop, stmt, lhs);
4293 for (i = 0; i < n; i++)
4295 arg = gimple_call_arg (stmt, i);
4296 if (REFERENCE_CLASS_P (arg))
4297 infer_loop_bounds_from_ref (loop, stmt, arg);
4302 /* Determine information about number of iterations of a LOOP from the fact
4303 that pointer arithmetics in STMT does not overflow. */
4305 static void
4306 infer_loop_bounds_from_pointer_arith (class loop *loop, gimple *stmt)
4308 tree def, base, step, scev, type, low, high;
4309 tree var, ptr;
4311 if (!is_gimple_assign (stmt)
4312 || gimple_assign_rhs_code (stmt) != POINTER_PLUS_EXPR)
4313 return;
4315 def = gimple_assign_lhs (stmt);
4316 if (TREE_CODE (def) != SSA_NAME)
4317 return;
4319 type = TREE_TYPE (def);
4320 if (!nowrap_type_p (type))
4321 return;
4323 ptr = gimple_assign_rhs1 (stmt);
4324 if (!expr_invariant_in_loop_p (loop, ptr))
4325 return;
4327 var = gimple_assign_rhs2 (stmt);
4328 if (TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (var)))
4329 return;
4331 class loop *uloop = loop_containing_stmt (stmt);
4332 scev = instantiate_parameters (loop, analyze_scalar_evolution (uloop, def));
4333 if (chrec_contains_undetermined (scev))
4334 return;
4336 base = initial_condition_in_loop_num (scev, loop->num);
4337 step = evolution_part_in_loop_num (scev, loop->num);
4339 if (!base || !step
4340 || TREE_CODE (step) != INTEGER_CST
4341 || tree_contains_chrecs (base, NULL)
4342 || chrec_contains_symbols_defined_in_loop (base, loop->num))
4343 return;
4345 low = lower_bound_in_type (type, type);
4346 high = upper_bound_in_type (type, type);
4348 /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
4349 produce a NULL pointer. The contrary would mean NULL points to an object,
4350 while NULL is supposed to compare unequal with the address of all objects.
4351 Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
4352 NULL pointer since that would mean wrapping, which we assume here not to
4353 happen. So, we can exclude NULL from the valid range of pointer
4354 arithmetic. */
4355 if (flag_delete_null_pointer_checks && int_cst_value (low) == 0)
4356 low = build_int_cstu (TREE_TYPE (low), TYPE_ALIGN_UNIT (TREE_TYPE (type)));
4358 record_nonwrapping_chrec (scev);
4359 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
4362 /* Determine information about number of iterations of a LOOP from the fact
4363 that signed arithmetics in STMT does not overflow. */
4365 static void
4366 infer_loop_bounds_from_signedness (class loop *loop, gimple *stmt)
4368 tree def, base, step, scev, type, low, high;
4370 if (gimple_code (stmt) != GIMPLE_ASSIGN)
4371 return;
4373 def = gimple_assign_lhs (stmt);
4375 if (TREE_CODE (def) != SSA_NAME)
4376 return;
4378 type = TREE_TYPE (def);
4379 if (!INTEGRAL_TYPE_P (type)
4380 || !TYPE_OVERFLOW_UNDEFINED (type))
4381 return;
4383 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
4384 if (chrec_contains_undetermined (scev))
4385 return;
4387 base = initial_condition_in_loop_num (scev, loop->num);
4388 step = evolution_part_in_loop_num (scev, loop->num);
4390 if (!base || !step
4391 || TREE_CODE (step) != INTEGER_CST
4392 || tree_contains_chrecs (base, NULL)
4393 || chrec_contains_symbols_defined_in_loop (base, loop->num))
4394 return;
4396 low = lower_bound_in_type (type, type);
4397 high = upper_bound_in_type (type, type);
4398 int_range_max r (TREE_TYPE (def));
4399 get_range_query (cfun)->range_of_expr (r, def);
4400 if (!r.varying_p () && !r.undefined_p ())
4402 low = wide_int_to_tree (type, r.lower_bound ());
4403 high = wide_int_to_tree (type, r.upper_bound ());
4406 record_nonwrapping_chrec (scev);
4407 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
4410 /* The following analyzers are extracting informations on the bounds
4411 of LOOP from the following undefined behaviors:
4413 - data references should not access elements over the statically
4414 allocated size,
4416 - signed variables should not overflow when flag_wrapv is not set.
4419 static void
4420 infer_loop_bounds_from_undefined (class loop *loop, basic_block *bbs)
4422 unsigned i;
4423 gimple_stmt_iterator bsi;
4424 basic_block bb;
4425 bool reliable;
4427 for (i = 0; i < loop->num_nodes; i++)
4429 bb = bbs[i];
4431 /* If BB is not executed in each iteration of the loop, we cannot
4432 use the operations in it to infer reliable upper bound on the
4433 # of iterations of the loop. However, we can use it as a guess.
4434 Reliable guesses come only from array bounds. */
4435 reliable = dominated_by_p (CDI_DOMINATORS, loop->latch, bb);
4437 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
4439 gimple *stmt = gsi_stmt (bsi);
4441 infer_loop_bounds_from_array (loop, stmt);
4443 if (reliable)
4445 infer_loop_bounds_from_signedness (loop, stmt);
4446 infer_loop_bounds_from_pointer_arith (loop, stmt);
4453 /* Compare wide ints, callback for qsort. */
4455 static int
4456 wide_int_cmp (const void *p1, const void *p2)
4458 const bound_wide_int *d1 = (const bound_wide_int *) p1;
4459 const bound_wide_int *d2 = (const bound_wide_int *) p2;
4460 return wi::cmpu (*d1, *d2);
4463 /* Return index of BOUND in BOUNDS array sorted in increasing order.
4464 Lookup by binary search. */
4466 static int
4467 bound_index (const vec<bound_wide_int> &bounds, const bound_wide_int &bound)
4469 unsigned int end = bounds.length ();
4470 unsigned int begin = 0;
4472 /* Find a matching index by means of a binary search. */
4473 while (begin != end)
4475 unsigned int middle = (begin + end) / 2;
4476 bound_wide_int index = bounds[middle];
4478 if (index == bound)
4479 return middle;
4480 else if (wi::ltu_p (index, bound))
4481 begin = middle + 1;
4482 else
4483 end = middle;
4485 gcc_unreachable ();
4488 /* We recorded loop bounds only for statements dominating loop latch (and thus
4489 executed each loop iteration). If there are any bounds on statements not
4490 dominating the loop latch we can improve the estimate by walking the loop
4491 body and seeing if every path from loop header to loop latch contains
4492 some bounded statement. */
4494 static void
4495 discover_iteration_bound_by_body_walk (class loop *loop)
4497 class nb_iter_bound *elt;
4498 auto_vec<bound_wide_int> bounds;
4499 vec<vec<basic_block> > queues = vNULL;
4500 vec<basic_block> queue = vNULL;
4501 ptrdiff_t queue_index;
4502 ptrdiff_t latch_index = 0;
4504 /* Discover what bounds may interest us. */
4505 for (elt = loop->bounds; elt; elt = elt->next)
4507 bound_wide_int bound = elt->bound;
4509 /* Exit terminates loop at given iteration, while non-exits produce undefined
4510 effect on the next iteration. */
4511 if (!elt->is_exit)
4513 bound += 1;
4514 /* If an overflow occurred, ignore the result. */
4515 if (bound == 0)
4516 continue;
4519 if (!loop->any_upper_bound
4520 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
4521 bounds.safe_push (bound);
4524 /* Exit early if there is nothing to do. */
4525 if (!bounds.exists ())
4526 return;
4528 if (dump_file && (dump_flags & TDF_DETAILS))
4529 fprintf (dump_file, " Trying to walk loop body to reduce the bound.\n");
4531 /* Sort the bounds in decreasing order. */
4532 bounds.qsort (wide_int_cmp);
4534 /* For every basic block record the lowest bound that is guaranteed to
4535 terminate the loop. */
4537 hash_map<basic_block, ptrdiff_t> bb_bounds;
4538 for (elt = loop->bounds; elt; elt = elt->next)
4540 bound_wide_int bound = elt->bound;
4541 if (!elt->is_exit)
4543 bound += 1;
4544 /* If an overflow occurred, ignore the result. */
4545 if (bound == 0)
4546 continue;
4549 if (!loop->any_upper_bound
4550 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
4552 ptrdiff_t index = bound_index (bounds, bound);
4553 ptrdiff_t *entry = bb_bounds.get (gimple_bb (elt->stmt));
4554 if (!entry)
4555 bb_bounds.put (gimple_bb (elt->stmt), index);
4556 else if ((ptrdiff_t)*entry > index)
4557 *entry = index;
4561 hash_map<basic_block, ptrdiff_t> block_priority;
4563 /* Perform shortest path discovery loop->header ... loop->latch.
4565 The "distance" is given by the smallest loop bound of basic block
4566 present in the path and we look for path with largest smallest bound
4567 on it.
4569 To avoid the need for fibonacci heap on double ints we simply compress
4570 double ints into indexes to BOUNDS array and then represent the queue
4571 as arrays of queues for every index.
4572 Index of BOUNDS.length() means that the execution of given BB has
4573 no bounds determined.
4575 VISITED is a pointer map translating basic block into smallest index
4576 it was inserted into the priority queue with. */
4577 latch_index = -1;
4579 /* Start walk in loop header with index set to infinite bound. */
4580 queue_index = bounds.length ();
4581 queues.safe_grow_cleared (queue_index + 1, true);
4582 queue.safe_push (loop->header);
4583 queues[queue_index] = queue;
4584 block_priority.put (loop->header, queue_index);
4586 for (; queue_index >= 0; queue_index--)
4588 if (latch_index < queue_index)
4590 while (queues[queue_index].length ())
4592 basic_block bb;
4593 ptrdiff_t bound_index = queue_index;
4594 edge e;
4595 edge_iterator ei;
4597 queue = queues[queue_index];
4598 bb = queue.pop ();
4600 /* OK, we later inserted the BB with lower priority, skip it. */
4601 if (*block_priority.get (bb) > queue_index)
4602 continue;
4604 /* See if we can improve the bound. */
4605 ptrdiff_t *entry = bb_bounds.get (bb);
4606 if (entry && *entry < bound_index)
4607 bound_index = *entry;
4609 /* Insert succesors into the queue, watch for latch edge
4610 and record greatest index we saw. */
4611 FOR_EACH_EDGE (e, ei, bb->succs)
4613 bool insert = false;
4615 if (loop_exit_edge_p (loop, e))
4616 continue;
4618 if (e == loop_latch_edge (loop)
4619 && latch_index < bound_index)
4620 latch_index = bound_index;
4621 else if (!(entry = block_priority.get (e->dest)))
4623 insert = true;
4624 block_priority.put (e->dest, bound_index);
4626 else if (*entry < bound_index)
4628 insert = true;
4629 *entry = bound_index;
4632 if (insert)
4633 queues[bound_index].safe_push (e->dest);
4637 queues[queue_index].release ();
4640 gcc_assert (latch_index >= 0);
4641 if ((unsigned)latch_index < bounds.length ())
4643 if (dump_file && (dump_flags & TDF_DETAILS))
4645 fprintf (dump_file, "Found better loop bound ");
4646 print_decu (bounds[latch_index], dump_file);
4647 fprintf (dump_file, "\n");
4649 record_niter_bound (loop, widest_int::from (bounds[latch_index],
4650 SIGNED), false, true);
4653 queues.release ();
4656 /* See if every path cross the loop goes through a statement that is known
4657 to not execute at the last iteration. In that case we can decrese iteration
4658 count by 1. */
4660 static void
4661 maybe_lower_iteration_bound (class loop *loop)
4663 hash_set<gimple *> *not_executed_last_iteration = NULL;
4664 class nb_iter_bound *elt;
4665 bool found_exit = false;
4666 auto_vec<basic_block> queue;
4667 bitmap visited;
4669 /* Collect all statements with interesting (i.e. lower than
4670 nb_iterations_upper_bound) bound on them.
4672 TODO: Due to the way record_estimate choose estimates to store, the bounds
4673 will be always nb_iterations_upper_bound-1. We can change this to record
4674 also statements not dominating the loop latch and update the walk bellow
4675 to the shortest path algorithm. */
4676 for (elt = loop->bounds; elt; elt = elt->next)
4678 if (!elt->is_exit
4679 && wi::ltu_p (elt->bound, loop->nb_iterations_upper_bound))
4681 if (!not_executed_last_iteration)
4682 not_executed_last_iteration = new hash_set<gimple *>;
4683 not_executed_last_iteration->add (elt->stmt);
4686 if (!not_executed_last_iteration)
4687 return;
4689 /* Start DFS walk in the loop header and see if we can reach the
4690 loop latch or any of the exits (including statements with side
4691 effects that may terminate the loop otherwise) without visiting
4692 any of the statements known to have undefined effect on the last
4693 iteration. */
4694 queue.safe_push (loop->header);
4695 visited = BITMAP_ALLOC (NULL);
4696 bitmap_set_bit (visited, loop->header->index);
4697 found_exit = false;
4701 basic_block bb = queue.pop ();
4702 gimple_stmt_iterator gsi;
4703 bool stmt_found = false;
4705 /* Loop for possible exits and statements bounding the execution. */
4706 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4708 gimple *stmt = gsi_stmt (gsi);
4709 if (not_executed_last_iteration->contains (stmt))
4711 stmt_found = true;
4712 break;
4714 if (gimple_has_side_effects (stmt))
4716 found_exit = true;
4717 break;
4720 if (found_exit)
4721 break;
4723 /* If no bounding statement is found, continue the walk. */
4724 if (!stmt_found)
4726 edge e;
4727 edge_iterator ei;
4729 FOR_EACH_EDGE (e, ei, bb->succs)
4731 if (loop_exit_edge_p (loop, e)
4732 || e == loop_latch_edge (loop))
4734 found_exit = true;
4735 break;
4737 if (bitmap_set_bit (visited, e->dest->index))
4738 queue.safe_push (e->dest);
4742 while (queue.length () && !found_exit);
4744 /* If every path through the loop reach bounding statement before exit,
4745 then we know the last iteration of the loop will have undefined effect
4746 and we can decrease number of iterations. */
4748 if (!found_exit)
4750 if (dump_file && (dump_flags & TDF_DETAILS))
4751 fprintf (dump_file, "Reducing loop iteration estimate by 1; "
4752 "undefined statement must be executed at the last iteration.\n");
4753 record_niter_bound (loop, widest_int::from (loop->nb_iterations_upper_bound,
4754 SIGNED) - 1,
4755 false, true);
4758 BITMAP_FREE (visited);
4759 delete not_executed_last_iteration;
4762 /* Get expected upper bound for number of loop iterations for
4763 BUILT_IN_EXPECT_WITH_PROBABILITY for a condition COND. */
4765 static tree
4766 get_upper_bound_based_on_builtin_expr_with_prob (gcond *cond)
4768 if (cond == NULL)
4769 return NULL_TREE;
4771 tree lhs = gimple_cond_lhs (cond);
4772 if (TREE_CODE (lhs) != SSA_NAME)
4773 return NULL_TREE;
4775 gimple *stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (cond));
4776 gcall *def = dyn_cast<gcall *> (stmt);
4777 if (def == NULL)
4778 return NULL_TREE;
4780 tree decl = gimple_call_fndecl (def);
4781 if (!decl
4782 || !fndecl_built_in_p (decl, BUILT_IN_EXPECT_WITH_PROBABILITY)
4783 || gimple_call_num_args (stmt) != 3)
4784 return NULL_TREE;
4786 tree c = gimple_call_arg (def, 1);
4787 tree condt = TREE_TYPE (lhs);
4788 tree res = fold_build2 (gimple_cond_code (cond),
4789 condt, c,
4790 gimple_cond_rhs (cond));
4791 if (TREE_CODE (res) != INTEGER_CST)
4792 return NULL_TREE;
4795 tree prob = gimple_call_arg (def, 2);
4796 tree t = TREE_TYPE (prob);
4797 tree one
4798 = build_real_from_int_cst (t,
4799 integer_one_node);
4800 if (integer_zerop (res))
4801 prob = fold_build2 (MINUS_EXPR, t, one, prob);
4802 tree r = fold_build2 (RDIV_EXPR, t, one, prob);
4803 if (TREE_CODE (r) != REAL_CST)
4804 return NULL_TREE;
4806 HOST_WIDE_INT probi
4807 = real_to_integer (TREE_REAL_CST_PTR (r));
4808 return build_int_cst (condt, probi);
4811 /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
4812 is true also use estimates derived from undefined behavior. */
4814 void
4815 estimate_numbers_of_iterations (class loop *loop)
4817 tree niter, type;
4818 unsigned i;
4819 class tree_niter_desc niter_desc;
4820 edge ex;
4821 widest_int bound;
4822 edge likely_exit;
4824 /* Give up if we already have tried to compute an estimation. */
4825 if (loop->estimate_state != EST_NOT_COMPUTED)
4826 return;
4828 if (dump_file && (dump_flags & TDF_DETAILS))
4829 fprintf (dump_file, "Estimating # of iterations of loop %d\n", loop->num);
4831 loop->estimate_state = EST_AVAILABLE;
4833 sreal nit;
4834 bool reliable;
4836 /* If we have a measured profile, use it to estimate the number of
4837 iterations. Normally this is recorded by branch_prob right after
4838 reading the profile. In case we however found a new loop, record the
4839 information here.
4841 Explicitly check for profile status so we do not report
4842 wrong prediction hitrates for guessed loop iterations heuristics.
4843 Do not recompute already recorded bounds - we ought to be better on
4844 updating iteration bounds than updating profile in general and thus
4845 recomputing iteration bounds later in the compilation process will just
4846 introduce random roundoff errors. */
4847 if (!loop->any_estimate
4848 && expected_loop_iterations_by_profile (loop, &nit, &reliable)
4849 && reliable)
4851 bound = nit.to_nearest_int ();
4852 record_niter_bound (loop, bound, true, false);
4855 /* Ensure that loop->nb_iterations is computed if possible. If it turns out
4856 to be constant, we avoid undefined behavior implied bounds and instead
4857 diagnose those loops with -Waggressive-loop-optimizations. */
4858 number_of_latch_executions (loop);
4860 basic_block *body = get_loop_body (loop);
4861 auto_vec<edge> exits = get_loop_exit_edges (loop, body);
4862 likely_exit = single_likely_exit (loop, exits);
4863 FOR_EACH_VEC_ELT (exits, i, ex)
4865 if (ex == likely_exit)
4867 gimple *stmt = *gsi_last_bb (ex->src);
4868 if (stmt != NULL)
4870 gcond *cond = dyn_cast<gcond *> (stmt);
4871 tree niter_bound
4872 = get_upper_bound_based_on_builtin_expr_with_prob (cond);
4873 if (niter_bound != NULL_TREE)
4875 widest_int max = derive_constant_upper_bound (niter_bound);
4876 record_estimate (loop, niter_bound, max, cond,
4877 true, true, false);
4882 if (!number_of_iterations_exit (loop, ex, &niter_desc,
4883 false, false, body))
4884 continue;
4886 niter = niter_desc.niter;
4887 type = TREE_TYPE (niter);
4888 if (TREE_CODE (niter_desc.may_be_zero) != INTEGER_CST)
4889 niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
4890 build_int_cst (type, 0),
4891 niter);
4892 record_estimate (loop, niter, niter_desc.max,
4893 last_nondebug_stmt (ex->src),
4894 true, ex == likely_exit, true);
4895 record_control_iv (loop, &niter_desc);
4898 if (flag_aggressive_loop_optimizations)
4899 infer_loop_bounds_from_undefined (loop, body);
4900 free (body);
4902 discover_iteration_bound_by_body_walk (loop);
4904 maybe_lower_iteration_bound (loop);
4906 /* If we know the exact number of iterations of this loop, try to
4907 not break code with undefined behavior by not recording smaller
4908 maximum number of iterations. */
4909 if (loop->nb_iterations
4910 && TREE_CODE (loop->nb_iterations) == INTEGER_CST
4911 && (wi::min_precision (wi::to_widest (loop->nb_iterations), SIGNED)
4912 <= bound_wide_int ().get_precision ()))
4914 loop->any_upper_bound = true;
4915 loop->nb_iterations_upper_bound
4916 = bound_wide_int::from (wi::to_widest (loop->nb_iterations), SIGNED);
4920 /* Sets NIT to the estimated number of executions of the latch of the
4921 LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
4922 large as the number of iterations. If we have no reliable estimate,
4923 the function returns false, otherwise returns true. */
4925 bool
4926 estimated_loop_iterations (class loop *loop, widest_int *nit)
4928 /* When SCEV information is available, try to update loop iterations
4929 estimate. Otherwise just return whatever we recorded earlier. */
4930 if (scev_initialized_p ())
4931 estimate_numbers_of_iterations (loop);
4933 return (get_estimated_loop_iterations (loop, nit));
4936 /* Similar to estimated_loop_iterations, but returns the estimate only
4937 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4938 on the number of iterations of LOOP could not be derived, returns -1. */
4940 HOST_WIDE_INT
4941 estimated_loop_iterations_int (class loop *loop)
4943 widest_int nit;
4944 HOST_WIDE_INT hwi_nit;
4946 if (!estimated_loop_iterations (loop, &nit))
4947 return -1;
4949 if (!wi::fits_shwi_p (nit))
4950 return -1;
4951 hwi_nit = nit.to_shwi ();
4953 return hwi_nit < 0 ? -1 : hwi_nit;
4957 /* Sets NIT to an upper bound for the maximum number of executions of the
4958 latch of the LOOP. If we have no reliable estimate, the function returns
4959 false, otherwise returns true. */
4961 bool
4962 max_loop_iterations (class loop *loop, widest_int *nit)
4964 /* When SCEV information is available, try to update loop iterations
4965 estimate. Otherwise just return whatever we recorded earlier. */
4966 if (scev_initialized_p ())
4967 estimate_numbers_of_iterations (loop);
4969 return get_max_loop_iterations (loop, nit);
4972 /* Similar to max_loop_iterations, but returns the estimate only
4973 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4974 on the number of iterations of LOOP could not be derived, returns -1. */
4976 HOST_WIDE_INT
4977 max_loop_iterations_int (class loop *loop)
4979 widest_int nit;
4980 HOST_WIDE_INT hwi_nit;
4982 if (!max_loop_iterations (loop, &nit))
4983 return -1;
4985 if (!wi::fits_shwi_p (nit))
4986 return -1;
4987 hwi_nit = nit.to_shwi ();
4989 return hwi_nit < 0 ? -1 : hwi_nit;
4992 /* Sets NIT to an likely upper bound for the maximum number of executions of the
4993 latch of the LOOP. If we have no reliable estimate, the function returns
4994 false, otherwise returns true. */
4996 bool
4997 likely_max_loop_iterations (class loop *loop, widest_int *nit)
4999 /* When SCEV information is available, try to update loop iterations
5000 estimate. Otherwise just return whatever we recorded earlier. */
5001 if (scev_initialized_p ())
5002 estimate_numbers_of_iterations (loop);
5004 return get_likely_max_loop_iterations (loop, nit);
5007 /* Similar to max_loop_iterations, but returns the estimate only
5008 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
5009 on the number of iterations of LOOP could not be derived, returns -1. */
5011 HOST_WIDE_INT
5012 likely_max_loop_iterations_int (class loop *loop)
5014 widest_int nit;
5015 HOST_WIDE_INT hwi_nit;
5017 if (!likely_max_loop_iterations (loop, &nit))
5018 return -1;
5020 if (!wi::fits_shwi_p (nit))
5021 return -1;
5022 hwi_nit = nit.to_shwi ();
5024 return hwi_nit < 0 ? -1 : hwi_nit;
5027 /* Returns an estimate for the number of executions of statements
5028 in the LOOP. For statements before the loop exit, this exceeds
5029 the number of execution of the latch by one. */
5031 HOST_WIDE_INT
5032 estimated_stmt_executions_int (class loop *loop)
5034 HOST_WIDE_INT nit = estimated_loop_iterations_int (loop);
5035 HOST_WIDE_INT snit;
5037 if (nit == -1)
5038 return -1;
5040 snit = (HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) nit + 1);
5042 /* If the computation overflows, return -1. */
5043 return snit < 0 ? -1 : snit;
5046 /* Sets NIT to the maximum number of executions of the latch of the
5047 LOOP, plus one. If we have no reliable estimate, the function returns
5048 false, otherwise returns true. */
5050 bool
5051 max_stmt_executions (class loop *loop, widest_int *nit)
5053 widest_int nit_minus_one;
5055 if (!max_loop_iterations (loop, nit))
5056 return false;
5058 nit_minus_one = *nit;
5060 *nit += 1;
5062 return wi::gtu_p (*nit, nit_minus_one);
5065 /* Sets NIT to the estimated maximum number of executions of the latch of the
5066 LOOP, plus one. If we have no likely estimate, the function returns
5067 false, otherwise returns true. */
5069 bool
5070 likely_max_stmt_executions (class loop *loop, widest_int *nit)
5072 widest_int nit_minus_one;
5074 if (!likely_max_loop_iterations (loop, nit))
5075 return false;
5077 nit_minus_one = *nit;
5079 *nit += 1;
5081 return wi::gtu_p (*nit, nit_minus_one);
5084 /* Sets NIT to the estimated number of executions of the latch of the
5085 LOOP, plus one. If we have no reliable estimate, the function returns
5086 false, otherwise returns true. */
5088 bool
5089 estimated_stmt_executions (class loop *loop, widest_int *nit)
5091 widest_int nit_minus_one;
5093 if (!estimated_loop_iterations (loop, nit))
5094 return false;
5096 nit_minus_one = *nit;
5098 *nit += 1;
5100 return wi::gtu_p (*nit, nit_minus_one);
5103 /* Records estimates on numbers of iterations of loops. */
5105 void
5106 estimate_numbers_of_iterations (function *fn)
5108 /* We don't want to issue signed overflow warnings while getting
5109 loop iteration estimates. */
5110 fold_defer_overflow_warnings ();
5112 for (auto loop : loops_list (fn, 0))
5113 estimate_numbers_of_iterations (loop);
5115 fold_undefer_and_ignore_overflow_warnings ();
5118 /* Returns true if statement S1 dominates statement S2. */
5120 bool
5121 stmt_dominates_stmt_p (gimple *s1, gimple *s2)
5123 basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
5125 if (!bb1
5126 || s1 == s2)
5127 return true;
5129 if (bb1 == bb2)
5131 gimple_stmt_iterator bsi;
5133 if (gimple_code (s2) == GIMPLE_PHI)
5134 return false;
5136 if (gimple_code (s1) == GIMPLE_PHI)
5137 return true;
5139 for (bsi = gsi_start_bb (bb1); gsi_stmt (bsi) != s2; gsi_next (&bsi))
5140 if (gsi_stmt (bsi) == s1)
5141 return true;
5143 return false;
5146 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
5149 /* Returns true when we can prove that the number of executions of
5150 STMT in the loop is at most NITER, according to the bound on
5151 the number of executions of the statement NITER_BOUND->stmt recorded in
5152 NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
5154 ??? This code can become quite a CPU hog - we can have many bounds,
5155 and large basic block forcing stmt_dominates_stmt_p to be queried
5156 many times on a large basic blocks, so the whole thing is O(n^2)
5157 for scev_probably_wraps_p invocation (that can be done n times).
5159 It would make more sense (and give better answers) to remember BB
5160 bounds computed by discover_iteration_bound_by_body_walk. */
5162 static bool
5163 n_of_executions_at_most (gimple *stmt,
5164 class nb_iter_bound *niter_bound,
5165 tree niter)
5167 widest_int bound = widest_int::from (niter_bound->bound, SIGNED);
5168 tree nit_type = TREE_TYPE (niter), e;
5169 enum tree_code cmp;
5171 gcc_assert (TYPE_UNSIGNED (nit_type));
5173 /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
5174 the number of iterations is small. */
5175 if (!wi::fits_to_tree_p (bound, nit_type))
5176 return false;
5178 /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
5179 times. This means that:
5181 -- if NITER_BOUND->is_exit is true, then everything after
5182 it at most NITER_BOUND->bound times.
5184 -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
5185 is executed, then NITER_BOUND->stmt is executed as well in the same
5186 iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
5188 If we can determine that NITER_BOUND->stmt is always executed
5189 after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
5190 We conclude that if both statements belong to the same
5191 basic block and STMT is before NITER_BOUND->stmt and there are no
5192 statements with side effects in between. */
5194 if (niter_bound->is_exit)
5196 if (stmt == niter_bound->stmt
5197 || !stmt_dominates_stmt_p (niter_bound->stmt, stmt))
5198 return false;
5199 cmp = GE_EXPR;
5201 else
5203 if (!stmt_dominates_stmt_p (niter_bound->stmt, stmt))
5205 gimple_stmt_iterator bsi;
5206 if (gimple_bb (stmt) != gimple_bb (niter_bound->stmt)
5207 || gimple_code (stmt) == GIMPLE_PHI
5208 || gimple_code (niter_bound->stmt) == GIMPLE_PHI)
5209 return false;
5211 /* By stmt_dominates_stmt_p we already know that STMT appears
5212 before NITER_BOUND->STMT. Still need to test that the loop
5213 cannot be terinated by a side effect in between. */
5214 for (bsi = gsi_for_stmt (stmt); gsi_stmt (bsi) != niter_bound->stmt;
5215 gsi_next (&bsi))
5216 if (gimple_has_side_effects (gsi_stmt (bsi)))
5217 return false;
5218 bound += 1;
5219 if (bound == 0
5220 || !wi::fits_to_tree_p (bound, nit_type))
5221 return false;
5223 cmp = GT_EXPR;
5226 e = fold_binary (cmp, boolean_type_node,
5227 niter, wide_int_to_tree (nit_type, bound));
5228 return e && integer_nonzerop (e);
5231 /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
5233 bool
5234 nowrap_type_p (tree type)
5236 if (ANY_INTEGRAL_TYPE_P (type)
5237 && TYPE_OVERFLOW_UNDEFINED (type))
5238 return true;
5240 if (POINTER_TYPE_P (type))
5241 return true;
5243 return false;
5246 /* Return true if we can prove LOOP is exited before evolution of induction
5247 variable {BASE, STEP} overflows with respect to its type bound. */
5249 static bool
5250 loop_exits_before_overflow (tree base, tree step,
5251 gimple *at_stmt, class loop *loop)
5253 widest_int niter;
5254 struct control_iv *civ;
5255 class nb_iter_bound *bound;
5256 tree e, delta, step_abs, unsigned_base;
5257 tree type = TREE_TYPE (step);
5258 tree unsigned_type, valid_niter;
5260 /* Don't issue signed overflow warnings. */
5261 fold_defer_overflow_warnings ();
5263 /* Compute the number of iterations before we reach the bound of the
5264 type, and verify that the loop is exited before this occurs. */
5265 unsigned_type = unsigned_type_for (type);
5266 unsigned_base = fold_convert (unsigned_type, base);
5268 if (tree_int_cst_sign_bit (step))
5270 tree extreme = fold_convert (unsigned_type,
5271 lower_bound_in_type (type, type));
5272 delta = fold_build2 (MINUS_EXPR, unsigned_type, unsigned_base, extreme);
5273 step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
5274 fold_convert (unsigned_type, step));
5276 else
5278 tree extreme = fold_convert (unsigned_type,
5279 upper_bound_in_type (type, type));
5280 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, unsigned_base);
5281 step_abs = fold_convert (unsigned_type, step);
5284 valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
5286 estimate_numbers_of_iterations (loop);
5288 if (max_loop_iterations (loop, &niter)
5289 && wi::fits_to_tree_p (niter, TREE_TYPE (valid_niter))
5290 && (e = fold_binary (GT_EXPR, boolean_type_node, valid_niter,
5291 wide_int_to_tree (TREE_TYPE (valid_niter),
5292 niter))) != NULL
5293 && integer_nonzerop (e))
5295 fold_undefer_and_ignore_overflow_warnings ();
5296 return true;
5298 if (at_stmt)
5299 for (bound = loop->bounds; bound; bound = bound->next)
5301 if (n_of_executions_at_most (at_stmt, bound, valid_niter))
5303 fold_undefer_and_ignore_overflow_warnings ();
5304 return true;
5307 fold_undefer_and_ignore_overflow_warnings ();
5309 /* Try to prove loop is exited before {base, step} overflows with the
5310 help of analyzed loop control IV. This is done only for IVs with
5311 constant step because otherwise we don't have the information. */
5312 if (TREE_CODE (step) == INTEGER_CST)
5314 for (civ = loop->control_ivs; civ; civ = civ->next)
5316 enum tree_code code;
5317 tree civ_type = TREE_TYPE (civ->step);
5319 /* Have to consider type difference because operand_equal_p ignores
5320 that for constants. */
5321 if (TYPE_UNSIGNED (type) != TYPE_UNSIGNED (civ_type)
5322 || element_precision (type) != element_precision (civ_type))
5323 continue;
5325 /* Only consider control IV with same step. */
5326 if (!operand_equal_p (step, civ->step, 0))
5327 continue;
5329 /* Done proving if this is a no-overflow control IV. */
5330 if (operand_equal_p (base, civ->base, 0))
5331 return true;
5333 /* Control IV is recorded after expanding simple operations,
5334 Here we expand base and compare it too. */
5335 tree expanded_base = expand_simple_operations (base);
5336 if (operand_equal_p (expanded_base, civ->base, 0))
5337 return true;
5339 /* If this is a before stepping control IV, in other words, we have
5341 {civ_base, step} = {base + step, step}
5343 Because civ {base + step, step} doesn't overflow during loop
5344 iterations, {base, step} will not overflow if we can prove the
5345 operation "base + step" does not overflow. Specifically, we try
5346 to prove below conditions are satisfied:
5348 base <= UPPER_BOUND (type) - step ;;step > 0
5349 base >= LOWER_BOUND (type) - step ;;step < 0
5351 by proving the reverse conditions are false using loop's initial
5352 condition. */
5353 if (POINTER_TYPE_P (TREE_TYPE (base)))
5354 code = POINTER_PLUS_EXPR;
5355 else
5356 code = PLUS_EXPR;
5358 tree stepped = fold_build2 (code, TREE_TYPE (base), base, step);
5359 tree expanded_stepped = fold_build2 (code, TREE_TYPE (base),
5360 expanded_base, step);
5361 if (operand_equal_p (stepped, civ->base, 0)
5362 || operand_equal_p (expanded_stepped, civ->base, 0))
5364 tree extreme;
5366 if (tree_int_cst_sign_bit (step))
5368 code = LT_EXPR;
5369 extreme = lower_bound_in_type (type, type);
5371 else
5373 code = GT_EXPR;
5374 extreme = upper_bound_in_type (type, type);
5376 extreme = fold_build2 (MINUS_EXPR, type, extreme, step);
5377 e = fold_build2 (code, boolean_type_node, base, extreme);
5378 e = simplify_using_initial_conditions (loop, e);
5379 if (integer_zerop (e))
5380 return true;
5385 return false;
5388 /* VAR is scev variable whose evolution part is constant STEP, this function
5389 proves that VAR can't overflow by using value range info. If VAR's value
5390 range is [MIN, MAX], it can be proven by:
5391 MAX + step doesn't overflow ; if step > 0
5393 MIN + step doesn't underflow ; if step < 0.
5395 We can only do this if var is computed in every loop iteration, i.e, var's
5396 definition has to dominate loop latch. Consider below example:
5399 unsigned int i;
5401 <bb 3>:
5403 <bb 4>:
5404 # RANGE [0, 4294967294] NONZERO 65535
5405 # i_21 = PHI <0(3), i_18(9)>
5406 if (i_21 != 0)
5407 goto <bb 6>;
5408 else
5409 goto <bb 8>;
5411 <bb 6>:
5412 # RANGE [0, 65533] NONZERO 65535
5413 _6 = i_21 + 4294967295;
5414 # RANGE [0, 65533] NONZERO 65535
5415 _7 = (long unsigned int) _6;
5416 # RANGE [0, 524264] NONZERO 524280
5417 _8 = _7 * 8;
5418 # PT = nonlocal escaped
5419 _9 = a_14 + _8;
5420 *_9 = 0;
5422 <bb 8>:
5423 # RANGE [1, 65535] NONZERO 65535
5424 i_18 = i_21 + 1;
5425 if (i_18 >= 65535)
5426 goto <bb 10>;
5427 else
5428 goto <bb 9>;
5430 <bb 9>:
5431 goto <bb 4>;
5433 <bb 10>:
5434 return;
5437 VAR _6 doesn't overflow only with pre-condition (i_21 != 0), here we
5438 can't use _6 to prove no-overlfow for _7. In fact, var _7 takes value
5439 sequence (4294967295, 0, 1, ..., 65533) in loop life time, rather than
5440 (4294967295, 4294967296, ...). */
5442 static bool
5443 scev_var_range_cant_overflow (tree var, tree step, class loop *loop)
5445 tree type;
5446 wide_int minv, maxv, diff, step_wi;
5448 if (TREE_CODE (step) != INTEGER_CST || !INTEGRAL_TYPE_P (TREE_TYPE (var)))
5449 return false;
5451 /* Check if VAR evaluates in every loop iteration. It's not the case
5452 if VAR is default definition or does not dominate loop's latch. */
5453 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
5454 if (!def_bb || !dominated_by_p (CDI_DOMINATORS, loop->latch, def_bb))
5455 return false;
5457 int_range_max r (TREE_TYPE (var));
5458 get_range_query (cfun)->range_of_expr (r, var);
5459 if (r.varying_p () || r.undefined_p ())
5460 return false;
5462 /* VAR is a scev whose evolution part is STEP and value range info
5463 is [MIN, MAX], we can prove its no-overflowness by conditions:
5465 type_MAX - MAX >= step ; if step > 0
5466 MIN - type_MIN >= |step| ; if step < 0.
5468 Or VAR must take value outside of value range, which is not true. */
5469 step_wi = wi::to_wide (step);
5470 type = TREE_TYPE (var);
5471 if (tree_int_cst_sign_bit (step))
5473 diff = r.lower_bound () - wi::to_wide (lower_bound_in_type (type, type));
5474 step_wi = - step_wi;
5476 else
5477 diff = wi::to_wide (upper_bound_in_type (type, type)) - r.upper_bound ();
5479 return (wi::geu_p (diff, step_wi));
5482 /* Return false only when the induction variable BASE + STEP * I is
5483 known to not overflow: i.e. when the number of iterations is small
5484 enough with respect to the step and initial condition in order to
5485 keep the evolution confined in TYPEs bounds. Return true when the
5486 iv is known to overflow or when the property is not computable.
5488 USE_OVERFLOW_SEMANTICS is true if this function should assume that
5489 the rules for overflow of the given language apply (e.g., that signed
5490 arithmetics in C does not overflow).
5492 If VAR is a ssa variable, this function also returns false if VAR can
5493 be proven not overflow with value range info. */
5495 bool
5496 scev_probably_wraps_p (tree var, tree base, tree step,
5497 gimple *at_stmt, class loop *loop,
5498 bool use_overflow_semantics)
5500 /* FIXME: We really need something like
5501 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
5503 We used to test for the following situation that frequently appears
5504 during address arithmetics:
5506 D.1621_13 = (long unsigned intD.4) D.1620_12;
5507 D.1622_14 = D.1621_13 * 8;
5508 D.1623_15 = (doubleD.29 *) D.1622_14;
5510 And derived that the sequence corresponding to D_14
5511 can be proved to not wrap because it is used for computing a
5512 memory access; however, this is not really the case -- for example,
5513 if D_12 = (unsigned char) [254,+,1], then D_14 has values
5514 2032, 2040, 0, 8, ..., but the code is still legal. */
5516 if (chrec_contains_undetermined (base)
5517 || chrec_contains_undetermined (step))
5518 return true;
5520 if (integer_zerop (step))
5521 return false;
5523 /* If we can use the fact that signed and pointer arithmetics does not
5524 wrap, we are done. */
5525 if (use_overflow_semantics && nowrap_type_p (TREE_TYPE (base)))
5526 return false;
5528 /* To be able to use estimates on number of iterations of the loop,
5529 we must have an upper bound on the absolute value of the step. */
5530 if (TREE_CODE (step) != INTEGER_CST)
5531 return true;
5533 /* Check if var can be proven not overflow with value range info. */
5534 if (var && TREE_CODE (var) == SSA_NAME
5535 && scev_var_range_cant_overflow (var, step, loop))
5536 return false;
5538 if (loop_exits_before_overflow (base, step, at_stmt, loop))
5539 return false;
5541 /* Check the nonwrapping flag, which may be set by niter analysis (e.g., the
5542 above loop exits before overflow). */
5543 if (var && nonwrapping_chrec_p (analyze_scalar_evolution (loop, var)))
5544 return false;
5546 /* At this point we still don't have a proof that the iv does not
5547 overflow: give up. */
5548 return true;
5551 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
5553 void
5554 free_numbers_of_iterations_estimates (class loop *loop)
5556 struct control_iv *civ;
5557 class nb_iter_bound *bound;
5559 loop->nb_iterations = NULL;
5560 loop->estimate_state = EST_NOT_COMPUTED;
5561 for (bound = loop->bounds; bound;)
5563 class nb_iter_bound *next = bound->next;
5564 ggc_free (bound);
5565 bound = next;
5567 loop->bounds = NULL;
5569 for (civ = loop->control_ivs; civ;)
5571 struct control_iv *next = civ->next;
5572 ggc_free (civ);
5573 civ = next;
5575 loop->control_ivs = NULL;
5578 /* Frees the information on upper bounds on numbers of iterations of loops. */
5580 void
5581 free_numbers_of_iterations_estimates (function *fn)
5583 for (auto loop : loops_list (fn, 0))
5584 free_numbers_of_iterations_estimates (loop);
5587 /* Substitute value VAL for ssa name NAME inside expressions held
5588 at LOOP. */
5590 void
5591 substitute_in_loop_info (class loop *loop, tree name, tree val)
5593 loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);