1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004-2023 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
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
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/>. */
22 #include "coretypes.h"
27 #include "tree-pass.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "stor-layout.h"
32 #include "fold-const.h"
36 #include "gimple-iterator.h"
38 #include "tree-ssa-loop-ivopts.h"
39 #include "tree-ssa-loop-niter.h"
40 #include "tree-ssa-loop.h"
42 #include "tree-chrec.h"
43 #include "tree-scalar-evolution.h"
45 #include "gimple-range.h"
48 /* The maximum number of dominator BBs we search for conditions
49 of loop header copies we use for simplifying a conditional
51 #define MAX_DOMINATORS_TO_WALK 8
55 Analysis of number of iterations of an affine exit test.
59 /* Bounds on some value, BELOW <= X <= UP. */
66 /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
69 split_to_var_and_offset (tree expr
, tree
*var
, mpz_t offset
)
71 tree type
= TREE_TYPE (expr
);
76 mpz_set_ui (offset
, 0);
78 switch (TREE_CODE (expr
))
85 case POINTER_PLUS_EXPR
:
86 op0
= TREE_OPERAND (expr
, 0);
87 op1
= TREE_OPERAND (expr
, 1);
89 if (TREE_CODE (op1
) != INTEGER_CST
)
93 /* Always sign extend the offset. */
94 wi::to_mpz (wi::to_wide (op1
), offset
, SIGNED
);
96 mpz_neg (offset
, offset
);
100 *var
= build_int_cst_type (type
, 0);
101 wi::to_mpz (wi::to_wide (expr
), offset
, TYPE_SIGN (type
));
109 /* From condition C0 CMP C1 derives information regarding the value range
110 of VAR, which is of TYPE. Results are stored in to BELOW and UP. */
113 refine_value_range_using_guard (tree type
, tree var
,
114 tree c0
, enum tree_code cmp
, tree c1
,
115 mpz_t below
, mpz_t up
)
117 tree varc0
, varc1
, ctype
;
119 mpz_t mint
, maxt
, minc1
, maxc1
;
120 bool no_wrap
= nowrap_type_p (type
);
122 signop sgn
= TYPE_SIGN (type
);
130 STRIP_SIGN_NOPS (c0
);
131 STRIP_SIGN_NOPS (c1
);
132 ctype
= TREE_TYPE (c0
);
133 if (!useless_type_conversion_p (ctype
, type
))
139 /* We could derive quite precise information from EQ_EXPR, however,
140 such a guard is unlikely to appear, so we do not bother with
145 /* NE_EXPR comparisons do not contain much of useful information,
146 except for cases of comparing with bounds. */
147 if (TREE_CODE (c1
) != INTEGER_CST
148 || !INTEGRAL_TYPE_P (type
))
151 /* Ensure that the condition speaks about an expression in the same
153 ctype
= TREE_TYPE (c0
);
154 if (TYPE_PRECISION (ctype
) != TYPE_PRECISION (type
))
156 c0
= fold_convert (type
, c0
);
157 c1
= fold_convert (type
, c1
);
159 if (operand_equal_p (var
, c0
, 0))
163 /* Case of comparing VAR with its below/up bounds. */
165 wi::to_mpz (wi::to_wide (c1
), valc1
, TYPE_SIGN (type
));
166 if (mpz_cmp (valc1
, below
) == 0)
168 if (mpz_cmp (valc1
, up
) == 0)
175 /* Case of comparing with the bounds of the type. */
176 wide_int min
= wi::min_value (type
);
177 wide_int max
= wi::max_value (type
);
179 if (wi::to_wide (c1
) == min
)
181 if (wi::to_wide (c1
) == max
)
185 /* Quick return if no useful information. */
197 split_to_var_and_offset (expand_simple_operations (c0
), &varc0
, offc0
);
198 split_to_var_and_offset (expand_simple_operations (c1
), &varc1
, offc1
);
200 /* We are only interested in comparisons of expressions based on VAR. */
201 if (operand_equal_p (var
, varc1
, 0))
203 std::swap (varc0
, varc1
);
204 mpz_swap (offc0
, offc1
);
205 cmp
= swap_tree_comparison (cmp
);
207 else if (!operand_equal_p (var
, varc0
, 0))
216 get_type_static_bounds (type
, mint
, maxt
);
219 Value_Range
r (TREE_TYPE (varc1
));
220 /* Setup range information for varc1. */
221 if (integer_zerop (varc1
))
223 wi::to_mpz (0, minc1
, TYPE_SIGN (type
));
224 wi::to_mpz (0, maxc1
, TYPE_SIGN (type
));
226 else if (TREE_CODE (varc1
) == SSA_NAME
227 && INTEGRAL_TYPE_P (type
)
228 && get_range_query (cfun
)->range_of_expr (r
, varc1
)
229 && r
.kind () == VR_RANGE
)
231 gcc_assert (wi::le_p (r
.lower_bound (), r
.upper_bound (), sgn
));
232 wi::to_mpz (r
.lower_bound (), minc1
, sgn
);
233 wi::to_mpz (r
.upper_bound (), maxc1
, sgn
);
237 mpz_set (minc1
, mint
);
238 mpz_set (maxc1
, maxt
);
241 /* Compute valid range information for varc1 + offc1. Note nothing
242 useful can be derived if it overflows or underflows. Overflow or
243 underflow could happen when:
245 offc1 > 0 && varc1 + offc1 > MAX_VAL (type)
246 offc1 < 0 && varc1 + offc1 < MIN_VAL (type). */
247 mpz_add (minc1
, minc1
, offc1
);
248 mpz_add (maxc1
, maxc1
, offc1
);
250 || mpz_sgn (offc1
) == 0
251 || (mpz_sgn (offc1
) < 0 && mpz_cmp (minc1
, mint
) >= 0)
252 || (mpz_sgn (offc1
) > 0 && mpz_cmp (maxc1
, maxt
) <= 0));
256 if (mpz_cmp (minc1
, mint
) < 0)
257 mpz_set (minc1
, mint
);
258 if (mpz_cmp (maxc1
, maxt
) > 0)
259 mpz_set (maxc1
, maxt
);
264 mpz_sub_ui (maxc1
, maxc1
, 1);
269 mpz_add_ui (minc1
, minc1
, 1);
272 /* Compute range information for varc0. If there is no overflow,
273 the condition implied that
275 (varc0) cmp (varc1 + offc1 - offc0)
277 We can possibly improve the upper bound of varc0 if cmp is LE_EXPR,
278 or the below bound if cmp is GE_EXPR.
280 To prove there is no overflow/underflow, we need to check below
282 1) cmp == LE_EXPR && offc0 > 0
284 (varc0 + offc0) doesn't overflow
285 && (varc1 + offc1 - offc0) doesn't underflow
287 2) cmp == LE_EXPR && offc0 < 0
289 (varc0 + offc0) doesn't underflow
290 && (varc1 + offc1 - offc0) doesn't overfloe
292 In this case, (varc0 + offc0) will never underflow if we can
293 prove (varc1 + offc1 - offc0) doesn't overflow.
295 3) cmp == GE_EXPR && offc0 < 0
297 (varc0 + offc0) doesn't underflow
298 && (varc1 + offc1 - offc0) doesn't overflow
300 4) cmp == GE_EXPR && offc0 > 0
302 (varc0 + offc0) doesn't overflow
303 && (varc1 + offc1 - offc0) doesn't underflow
305 In this case, (varc0 + offc0) will never overflow if we can
306 prove (varc1 + offc1 - offc0) doesn't underflow.
308 Note we only handle case 2 and 4 in below code. */
310 mpz_sub (minc1
, minc1
, offc0
);
311 mpz_sub (maxc1
, maxc1
, offc0
);
313 || mpz_sgn (offc0
) == 0
315 && mpz_sgn (offc0
) < 0 && mpz_cmp (maxc1
, maxt
) <= 0)
317 && mpz_sgn (offc0
) > 0 && mpz_cmp (minc1
, mint
) >= 0));
323 if (mpz_cmp (up
, maxc1
) > 0)
328 if (mpz_cmp (below
, minc1
) < 0)
329 mpz_set (below
, minc1
);
341 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
342 in TYPE to MIN and MAX. */
345 determine_value_range (class loop
*loop
, tree type
, tree var
, mpz_t off
,
346 mpz_t min
, mpz_t max
)
352 enum value_range_kind rtype
= VR_VARYING
;
354 /* If the expression is a constant, we know its value exactly. */
355 if (integer_zerop (var
))
362 get_type_static_bounds (type
, min
, max
);
364 /* See if we have some range info from VRP. */
365 if (TREE_CODE (var
) == SSA_NAME
&& INTEGRAL_TYPE_P (type
))
367 edge e
= loop_preheader_edge (loop
);
368 signop sgn
= TYPE_SIGN (type
);
371 /* Either for VAR itself... */
372 Value_Range
var_range (TREE_TYPE (var
));
373 get_range_query (cfun
)->range_of_expr (var_range
, var
);
374 rtype
= var_range
.kind ();
375 if (!var_range
.undefined_p ())
377 minv
= var_range
.lower_bound ();
378 maxv
= var_range
.upper_bound ();
381 /* Or for PHI results in loop->header where VAR is used as
382 PHI argument from the loop preheader edge. */
383 Value_Range
phi_range (TREE_TYPE (var
));
384 for (gsi
= gsi_start_phis (loop
->header
); !gsi_end_p (gsi
); gsi_next (&gsi
))
386 gphi
*phi
= gsi
.phi ();
387 if (PHI_ARG_DEF_FROM_EDGE (phi
, e
) == var
388 && get_range_query (cfun
)->range_of_expr (phi_range
,
389 gimple_phi_result (phi
))
390 && phi_range
.kind () == VR_RANGE
)
392 if (rtype
!= VR_RANGE
)
395 minv
= phi_range
.lower_bound ();
396 maxv
= phi_range
.upper_bound ();
400 minv
= wi::max (minv
, phi_range
.lower_bound (), sgn
);
401 maxv
= wi::min (maxv
, phi_range
.upper_bound (), sgn
);
402 /* If the PHI result range are inconsistent with
403 the VAR range, give up on looking at the PHI
404 results. This can happen if VR_UNDEFINED is
406 if (wi::gt_p (minv
, maxv
, sgn
))
408 Value_Range
vr (TREE_TYPE (var
));
409 get_range_query (cfun
)->range_of_expr (vr
, var
);
411 if (!vr
.undefined_p ())
413 minv
= vr
.lower_bound ();
414 maxv
= vr
.upper_bound ();
423 if (rtype
!= VR_RANGE
)
430 gcc_assert (wi::le_p (minv
, maxv
, sgn
));
431 wi::to_mpz (minv
, minm
, sgn
);
432 wi::to_mpz (maxv
, maxm
, sgn
);
434 /* Now walk the dominators of the loop header and use the entry
435 guards to refine the estimates. */
436 for (bb
= loop
->header
;
437 bb
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
) && cnt
< MAX_DOMINATORS_TO_WALK
;
438 bb
= get_immediate_dominator (CDI_DOMINATORS
, bb
))
445 if (!single_pred_p (bb
))
447 e
= single_pred_edge (bb
);
449 if (!(e
->flags
& (EDGE_TRUE_VALUE
| EDGE_FALSE_VALUE
)))
452 cond
= last_stmt (e
->src
);
453 c0
= gimple_cond_lhs (cond
);
454 cmp
= gimple_cond_code (cond
);
455 c1
= gimple_cond_rhs (cond
);
457 if (e
->flags
& EDGE_FALSE_VALUE
)
458 cmp
= invert_tree_comparison (cmp
, false);
460 refine_value_range_using_guard (type
, var
, c0
, cmp
, c1
, minm
, maxm
);
464 mpz_add (minm
, minm
, off
);
465 mpz_add (maxm
, maxm
, off
);
466 /* If the computation may not wrap or off is zero, then this
467 is always fine. If off is negative and minv + off isn't
468 smaller than type's minimum, or off is positive and
469 maxv + off isn't bigger than type's maximum, use the more
470 precise range too. */
471 if (nowrap_type_p (type
)
472 || mpz_sgn (off
) == 0
473 || (mpz_sgn (off
) < 0 && mpz_cmp (minm
, min
) >= 0)
474 || (mpz_sgn (off
) > 0 && mpz_cmp (maxm
, max
) <= 0))
486 /* If the computation may wrap, we know nothing about the value, except for
487 the range of the type. */
488 if (!nowrap_type_p (type
))
491 /* Since the addition of OFF does not wrap, if OFF is positive, then we may
492 add it to MIN, otherwise to MAX. */
493 if (mpz_sgn (off
) < 0)
494 mpz_add (max
, max
, off
);
496 mpz_add (min
, min
, off
);
499 /* Stores the bounds on the difference of the values of the expressions
500 (var + X) and (var + Y), computed in TYPE, to BNDS. */
503 bound_difference_of_offsetted_base (tree type
, mpz_t x
, mpz_t y
,
506 int rel
= mpz_cmp (x
, y
);
507 bool may_wrap
= !nowrap_type_p (type
);
510 /* If X == Y, then the expressions are always equal.
511 If X > Y, there are the following possibilities:
512 a) neither of var + X and var + Y overflow or underflow, or both of
513 them do. Then their difference is X - Y.
514 b) var + X overflows, and var + Y does not. Then the values of the
515 expressions are var + X - M and var + Y, where M is the range of
516 the type, and their difference is X - Y - M.
517 c) var + Y underflows and var + X does not. Their difference again
519 Therefore, if the arithmetics in type does not overflow, then the
520 bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
521 Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
522 (X - Y, X - Y + M). */
526 mpz_set_ui (bnds
->below
, 0);
527 mpz_set_ui (bnds
->up
, 0);
532 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), m
, UNSIGNED
);
533 mpz_add_ui (m
, m
, 1);
534 mpz_sub (bnds
->up
, x
, y
);
535 mpz_set (bnds
->below
, bnds
->up
);
540 mpz_sub (bnds
->below
, bnds
->below
, m
);
542 mpz_add (bnds
->up
, bnds
->up
, m
);
548 /* From condition C0 CMP C1 derives information regarding the
549 difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
550 and stores it to BNDS. */
553 refine_bounds_using_guard (tree type
, tree varx
, mpz_t offx
,
554 tree vary
, mpz_t offy
,
555 tree c0
, enum tree_code cmp
, tree c1
,
558 tree varc0
, varc1
, ctype
;
559 mpz_t offc0
, offc1
, loffx
, loffy
, bnd
;
561 bool no_wrap
= nowrap_type_p (type
);
570 STRIP_SIGN_NOPS (c0
);
571 STRIP_SIGN_NOPS (c1
);
572 ctype
= TREE_TYPE (c0
);
573 if (!useless_type_conversion_p (ctype
, type
))
579 /* We could derive quite precise information from EQ_EXPR, however, such
580 a guard is unlikely to appear, so we do not bother with handling
585 /* NE_EXPR comparisons do not contain much of useful information, except for
586 special case of comparing with the bounds of the type. */
587 if (TREE_CODE (c1
) != INTEGER_CST
588 || !INTEGRAL_TYPE_P (type
))
591 /* Ensure that the condition speaks about an expression in the same type
593 ctype
= TREE_TYPE (c0
);
594 if (TYPE_PRECISION (ctype
) != TYPE_PRECISION (type
))
596 c0
= fold_convert (type
, c0
);
597 c1
= fold_convert (type
, c1
);
599 if (TYPE_MIN_VALUE (type
)
600 && operand_equal_p (c1
, TYPE_MIN_VALUE (type
), 0))
605 if (TYPE_MAX_VALUE (type
)
606 && operand_equal_p (c1
, TYPE_MAX_VALUE (type
), 0))
619 split_to_var_and_offset (expand_simple_operations (c0
), &varc0
, offc0
);
620 split_to_var_and_offset (expand_simple_operations (c1
), &varc1
, offc1
);
622 /* We are only interested in comparisons of expressions based on VARX and
623 VARY. TODO -- we might also be able to derive some bounds from
624 expressions containing just one of the variables. */
626 if (operand_equal_p (varx
, varc1
, 0))
628 std::swap (varc0
, varc1
);
629 mpz_swap (offc0
, offc1
);
630 cmp
= swap_tree_comparison (cmp
);
633 if (!operand_equal_p (varx
, varc0
, 0)
634 || !operand_equal_p (vary
, varc1
, 0))
637 mpz_init_set (loffx
, offx
);
638 mpz_init_set (loffy
, offy
);
640 if (cmp
== GT_EXPR
|| cmp
== GE_EXPR
)
642 std::swap (varx
, vary
);
643 mpz_swap (offc0
, offc1
);
644 mpz_swap (loffx
, loffy
);
645 cmp
= swap_tree_comparison (cmp
);
649 /* If there is no overflow, the condition implies that
651 (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
653 The overflows and underflows may complicate things a bit; each
654 overflow decreases the appropriate offset by M, and underflow
655 increases it by M. The above inequality would not necessarily be
658 -- VARX + OFFX underflows and VARX + OFFC0 does not, or
659 VARX + OFFC0 overflows, but VARX + OFFX does not.
660 This may only happen if OFFX < OFFC0.
661 -- VARY + OFFY overflows and VARY + OFFC1 does not, or
662 VARY + OFFC1 underflows and VARY + OFFY does not.
663 This may only happen if OFFY > OFFC1. */
672 x_ok
= (integer_zerop (varx
)
673 || mpz_cmp (loffx
, offc0
) >= 0);
674 y_ok
= (integer_zerop (vary
)
675 || mpz_cmp (loffy
, offc1
) <= 0);
681 mpz_sub (bnd
, loffx
, loffy
);
682 mpz_add (bnd
, bnd
, offc1
);
683 mpz_sub (bnd
, bnd
, offc0
);
686 mpz_sub_ui (bnd
, bnd
, 1);
691 if (mpz_cmp (bnds
->below
, bnd
) < 0)
692 mpz_set (bnds
->below
, bnd
);
696 if (mpz_cmp (bnd
, bnds
->up
) < 0)
697 mpz_set (bnds
->up
, bnd
);
709 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
710 The subtraction is considered to be performed in arbitrary precision,
713 We do not attempt to be too clever regarding the value ranges of X and
714 Y; most of the time, they are just integers or ssa names offsetted by
715 integer. However, we try to use the information contained in the
716 comparisons before the loop (usually created by loop header copying). */
719 bound_difference (class loop
*loop
, tree x
, tree y
, bounds
*bnds
)
721 tree type
= TREE_TYPE (x
);
724 mpz_t minx
, maxx
, miny
, maxy
;
732 /* Get rid of unnecessary casts, but preserve the value of
737 mpz_init (bnds
->below
);
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
);
754 /* Otherwise, use the value ranges to determine the initial
755 estimates on below and up. */
760 determine_value_range (loop
, type
, varx
, offx
, minx
, maxx
);
761 determine_value_range (loop
, type
, vary
, offy
, miny
, maxy
);
763 mpz_sub (bnds
->below
, minx
, maxy
);
764 mpz_sub (bnds
->up
, maxx
, miny
);
771 /* If both X and Y are constants, we cannot get any more precise. */
772 if (integer_zerop (varx
) && integer_zerop (vary
))
775 /* Now walk the dominators of the loop header and use the entry
776 guards to refine the estimates. */
777 for (bb
= loop
->header
;
778 bb
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
) && cnt
< MAX_DOMINATORS_TO_WALK
;
779 bb
= get_immediate_dominator (CDI_DOMINATORS
, bb
))
781 if (!single_pred_p (bb
))
783 e
= single_pred_edge (bb
);
785 if (!(e
->flags
& (EDGE_TRUE_VALUE
| EDGE_FALSE_VALUE
)))
788 cond
= last_stmt (e
->src
);
789 c0
= gimple_cond_lhs (cond
);
790 cmp
= gimple_cond_code (cond
);
791 c1
= gimple_cond_rhs (cond
);
793 if (e
->flags
& EDGE_FALSE_VALUE
)
794 cmp
= invert_tree_comparison (cmp
, false);
796 refine_bounds_using_guard (type
, varx
, offx
, vary
, offy
,
806 /* Update the bounds in BNDS that restrict the value of X to the bounds
807 that restrict the value of X + DELTA. X can be obtained as a
808 difference of two values in TYPE. */
811 bounds_add (bounds
*bnds
, const widest_int
&delta
, tree type
)
816 wi::to_mpz (delta
, mdelta
, SIGNED
);
819 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), max
, UNSIGNED
);
821 mpz_add (bnds
->up
, bnds
->up
, mdelta
);
822 mpz_add (bnds
->below
, bnds
->below
, mdelta
);
824 if (mpz_cmp (bnds
->up
, max
) > 0)
825 mpz_set (bnds
->up
, max
);
828 if (mpz_cmp (bnds
->below
, max
) < 0)
829 mpz_set (bnds
->below
, max
);
835 /* Update the bounds in BNDS that restrict the value of X to the bounds
836 that restrict the value of -X. */
839 bounds_negate (bounds
*bnds
)
843 mpz_init_set (tmp
, bnds
->up
);
844 mpz_neg (bnds
->up
, bnds
->below
);
845 mpz_neg (bnds
->below
, tmp
);
849 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
852 inverse (tree x
, tree mask
)
854 tree type
= TREE_TYPE (x
);
856 unsigned ctr
= tree_floor_log2 (mask
);
858 if (TYPE_PRECISION (type
) <= HOST_BITS_PER_WIDE_INT
)
860 unsigned HOST_WIDE_INT ix
;
861 unsigned HOST_WIDE_INT imask
;
862 unsigned HOST_WIDE_INT irslt
= 1;
864 gcc_assert (cst_and_fits_in_hwi (x
));
865 gcc_assert (cst_and_fits_in_hwi (mask
));
867 ix
= int_cst_value (x
);
868 imask
= int_cst_value (mask
);
877 rslt
= build_int_cst_type (type
, irslt
);
881 rslt
= build_int_cst (type
, 1);
884 rslt
= int_const_binop (MULT_EXPR
, rslt
, x
);
885 x
= int_const_binop (MULT_EXPR
, x
, x
);
887 rslt
= int_const_binop (BIT_AND_EXPR
, rslt
, mask
);
893 /* Derives the upper bound BND on the number of executions of loop with exit
894 condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
895 the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
896 that the loop ends through this exit, i.e., the induction variable ever
897 reaches the value of C.
899 The value C is equal to final - base, where final and base are the final and
900 initial value of the actual induction variable in the analysed loop. BNDS
901 bounds the value of this difference when computed in signed type with
902 unbounded range, while the computation of C is performed in an unsigned
903 type with the range matching the range of the type of the induction variable.
904 In particular, BNDS.up contains an upper bound on C in the following cases:
905 -- if the iv must reach its final value without overflow, i.e., if
906 NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
907 -- if final >= base, which we know to hold when BNDS.below >= 0. */
910 number_of_iterations_ne_max (mpz_t bnd
, bool no_overflow
, tree c
, tree s
,
911 bounds
*bnds
, bool exit_must_be_taken
)
915 tree type
= TREE_TYPE (c
);
916 bool bnds_u_valid
= ((no_overflow
&& exit_must_be_taken
)
917 || mpz_sgn (bnds
->below
) >= 0);
920 || (TREE_CODE (c
) == INTEGER_CST
921 && TREE_CODE (s
) == INTEGER_CST
922 && wi::mod_trunc (wi::to_wide (c
), wi::to_wide (s
),
923 TYPE_SIGN (type
)) == 0)
924 || (TYPE_OVERFLOW_UNDEFINED (type
)
925 && multiple_of_p (type
, c
, s
)))
927 /* If C is an exact multiple of S, then its value will be reached before
928 the induction variable overflows (unless the loop is exited in some
929 other way before). Note that the actual induction variable in the
930 loop (which ranges from base to final instead of from 0 to C) may
931 overflow, in which case BNDS.up will not be giving a correct upper
932 bound on C; thus, BNDS_U_VALID had to be computed in advance. */
934 exit_must_be_taken
= true;
937 /* If the induction variable can overflow, the number of iterations is at
938 most the period of the control variable (or infinite, but in that case
939 the whole # of iterations analysis will fail). */
942 max
= wi::mask
<widest_int
> (TYPE_PRECISION (type
)
943 - wi::ctz (wi::to_wide (s
)), false);
944 wi::to_mpz (max
, bnd
, UNSIGNED
);
948 /* Now we know that the induction variable does not overflow, so the loop
949 iterates at most (range of type / S) times. */
950 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), bnd
, UNSIGNED
);
952 /* If the induction variable is guaranteed to reach the value of C before
954 if (exit_must_be_taken
)
956 /* ... then we can strengthen this to C / S, and possibly we can use
957 the upper bound on C given by BNDS. */
958 if (TREE_CODE (c
) == INTEGER_CST
)
959 wi::to_mpz (wi::to_wide (c
), bnd
, UNSIGNED
);
960 else if (bnds_u_valid
)
961 mpz_set (bnd
, bnds
->up
);
965 wi::to_mpz (wi::to_wide (s
), d
, UNSIGNED
);
966 mpz_fdiv_q (bnd
, bnd
, d
);
970 /* Determines number of iterations of loop whose ending condition
971 is IV <> FINAL. TYPE is the type of the iv. The number of
972 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
973 we know that the exit must be taken eventually, i.e., that the IV
974 ever reaches the value FINAL (we derived this earlier, and possibly set
975 NITER->assumptions to make sure this is the case). BNDS contains the
976 bounds on the difference FINAL - IV->base. */
979 number_of_iterations_ne (class loop
*loop
, tree type
, affine_iv
*iv
,
980 tree final
, class tree_niter_desc
*niter
,
981 bool exit_must_be_taken
, bounds
*bnds
)
983 tree niter_type
= unsigned_type_for (type
);
984 tree s
, c
, d
, bits
, assumption
, tmp
, bound
;
987 niter
->control
= *iv
;
988 niter
->bound
= final
;
989 niter
->cmp
= NE_EXPR
;
991 /* Rearrange the terms so that we get inequality S * i <> C, with S
992 positive. Also cast everything to the unsigned type. If IV does
993 not overflow, BNDS bounds the value of C. Also, this is the
994 case if the computation |FINAL - IV->base| does not overflow, i.e.,
995 if BNDS->below in the result is nonnegative. */
996 if (tree_int_cst_sign_bit (iv
->step
))
998 s
= fold_convert (niter_type
,
999 fold_build1 (NEGATE_EXPR
, type
, iv
->step
));
1000 c
= fold_build2 (MINUS_EXPR
, niter_type
,
1001 fold_convert (niter_type
, iv
->base
),
1002 fold_convert (niter_type
, final
));
1003 bounds_negate (bnds
);
1007 s
= fold_convert (niter_type
, iv
->step
);
1008 c
= fold_build2 (MINUS_EXPR
, niter_type
,
1009 fold_convert (niter_type
, final
),
1010 fold_convert (niter_type
, iv
->base
));
1014 number_of_iterations_ne_max (max
, iv
->no_overflow
, c
, s
, bnds
,
1015 exit_must_be_taken
);
1016 niter
->max
= widest_int::from (wi::from_mpz (niter_type
, max
, false),
1017 TYPE_SIGN (niter_type
));
1020 /* Compute no-overflow information for the control iv. This can be
1021 proven when below two conditions are satisfied:
1023 1) IV evaluates toward FINAL at beginning, i.e:
1024 base <= FINAL ; step > 0
1025 base >= FINAL ; step < 0
1027 2) |FINAL - base| is an exact multiple of step.
1029 Unfortunately, it's hard to prove above conditions after pass loop-ch
1030 because loop with exit condition (IV != FINAL) usually will be guarded
1031 by initial-condition (IV.base - IV.step != FINAL). In this case, we
1032 can alternatively try to prove below conditions:
1034 1') IV evaluates toward FINAL at beginning, i.e:
1035 new_base = base - step < FINAL ; step > 0
1036 && base - step doesn't underflow
1037 new_base = base - step > FINAL ; step < 0
1038 && base - step doesn't overflow
1040 Please refer to PR34114 as an example of loop-ch's impact.
1042 Note, for NE_EXPR, base equals to FINAL is a special case, in
1043 which the loop exits immediately, and the iv does not overflow.
1045 Also note, we prove condition 2) by checking base and final seperately
1046 along with condition 1) or 1'). Since we ensure the difference
1047 computation of c does not wrap with cond below and the adjusted s
1048 will fit a signed type as well as an unsigned we can safely do
1049 this using the type of the IV if it is not pointer typed. */
1051 if (POINTER_TYPE_P (type
))
1053 if (!niter
->control
.no_overflow
1054 && (integer_onep (s
)
1055 || (multiple_of_p (mtype
, fold_convert (mtype
, iv
->base
),
1056 fold_convert (mtype
, s
), false)
1057 && multiple_of_p (mtype
, fold_convert (mtype
, final
),
1058 fold_convert (mtype
, s
), false))))
1060 tree t
, cond
, relaxed_cond
= boolean_false_node
;
1062 if (tree_int_cst_sign_bit (iv
->step
))
1064 cond
= fold_build2 (GE_EXPR
, boolean_type_node
, iv
->base
, final
);
1065 if (TREE_CODE (type
) == INTEGER_TYPE
)
1067 /* Only when base - step doesn't overflow. */
1068 t
= TYPE_MAX_VALUE (type
);
1069 t
= fold_build2 (PLUS_EXPR
, type
, t
, iv
->step
);
1070 t
= fold_build2 (GE_EXPR
, boolean_type_node
, t
, iv
->base
);
1071 if (integer_nonzerop (t
))
1073 t
= fold_build2 (MINUS_EXPR
, type
, iv
->base
, iv
->step
);
1074 relaxed_cond
= fold_build2 (GT_EXPR
, boolean_type_node
, t
,
1081 cond
= fold_build2 (LE_EXPR
, boolean_type_node
, iv
->base
, final
);
1082 if (TREE_CODE (type
) == INTEGER_TYPE
)
1084 /* Only when base - step doesn't underflow. */
1085 t
= TYPE_MIN_VALUE (type
);
1086 t
= fold_build2 (PLUS_EXPR
, type
, t
, iv
->step
);
1087 t
= fold_build2 (LE_EXPR
, boolean_type_node
, t
, iv
->base
);
1088 if (integer_nonzerop (t
))
1090 t
= fold_build2 (MINUS_EXPR
, type
, iv
->base
, iv
->step
);
1091 relaxed_cond
= fold_build2 (LT_EXPR
, boolean_type_node
, t
,
1097 t
= simplify_using_initial_conditions (loop
, cond
);
1098 if (!t
|| !integer_onep (t
))
1099 t
= simplify_using_initial_conditions (loop
, relaxed_cond
);
1101 if (t
&& integer_onep (t
))
1103 niter
->control
.no_overflow
= true;
1104 niter
->niter
= fold_build2 (EXACT_DIV_EXPR
, niter_type
, c
, s
);
1109 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
1110 is infinite. Otherwise, the number of iterations is
1111 (inverse(s/d) * (c/d)) mod (size of mode/d). */
1112 bits
= num_ending_zeros (s
);
1113 bound
= build_low_bits_mask (niter_type
,
1114 (TYPE_PRECISION (niter_type
)
1115 - tree_to_uhwi (bits
)));
1117 d
= fold_binary_to_constant (LSHIFT_EXPR
, niter_type
,
1118 build_int_cst (niter_type
, 1), bits
);
1119 s
= fold_binary_to_constant (RSHIFT_EXPR
, niter_type
, s
, bits
);
1121 if (!exit_must_be_taken
)
1123 /* If we cannot assume that the exit is taken eventually, record the
1124 assumptions for divisibility of c. */
1125 assumption
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, c
, d
);
1126 assumption
= fold_build2 (EQ_EXPR
, boolean_type_node
,
1127 assumption
, build_int_cst (niter_type
, 0));
1128 if (!integer_nonzerop (assumption
))
1129 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1130 niter
->assumptions
, assumption
);
1133 c
= fold_build2 (EXACT_DIV_EXPR
, niter_type
, c
, d
);
1134 if (integer_onep (s
))
1140 tmp
= fold_build2 (MULT_EXPR
, niter_type
, c
, inverse (s
, bound
));
1141 niter
->niter
= fold_build2 (BIT_AND_EXPR
, niter_type
, tmp
, bound
);
1146 /* Checks whether we can determine the final value of the control variable
1147 of the loop with ending condition IV0 < IV1 (computed in TYPE).
1148 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
1149 of the step. The assumptions necessary to ensure that the computation
1150 of the final value does not overflow are recorded in NITER. If we
1151 find the final value, we adjust DELTA and return TRUE. Otherwise
1152 we return false. BNDS bounds the value of IV1->base - IV0->base,
1153 and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
1154 true if we know that the exit must be taken eventually. */
1157 number_of_iterations_lt_to_ne (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
1158 class tree_niter_desc
*niter
,
1159 tree
*delta
, tree step
,
1160 bool exit_must_be_taken
, bounds
*bnds
)
1162 tree niter_type
= TREE_TYPE (step
);
1163 tree mod
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, *delta
, step
);
1166 tree assumption
= boolean_true_node
, bound
, noloop
;
1167 bool ret
= false, fv_comp_no_overflow
;
1169 if (POINTER_TYPE_P (type
))
1172 if (TREE_CODE (mod
) != INTEGER_CST
)
1174 if (integer_nonzerop (mod
))
1175 mod
= fold_build2 (MINUS_EXPR
, niter_type
, step
, mod
);
1176 tmod
= fold_convert (type1
, mod
);
1179 wi::to_mpz (wi::to_wide (mod
), mmod
, UNSIGNED
);
1180 mpz_neg (mmod
, mmod
);
1182 /* If the induction variable does not overflow and the exit is taken,
1183 then the computation of the final value does not overflow. This is
1184 also obviously the case if the new final value is equal to the
1185 current one. Finally, we postulate this for pointer type variables,
1186 as the code cannot rely on the object to that the pointer points being
1187 placed at the end of the address space (and more pragmatically,
1188 TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
1189 if (integer_zerop (mod
) || POINTER_TYPE_P (type
))
1190 fv_comp_no_overflow
= true;
1191 else if (!exit_must_be_taken
)
1192 fv_comp_no_overflow
= false;
1194 fv_comp_no_overflow
=
1195 (iv0
->no_overflow
&& integer_nonzerop (iv0
->step
))
1196 || (iv1
->no_overflow
&& integer_nonzerop (iv1
->step
));
1198 if (integer_nonzerop (iv0
->step
))
1200 /* The final value of the iv is iv1->base + MOD, assuming that this
1201 computation does not overflow, and that
1202 iv0->base <= iv1->base + MOD. */
1203 if (!fv_comp_no_overflow
)
1205 bound
= fold_build2 (MINUS_EXPR
, type1
,
1206 TYPE_MAX_VALUE (type1
), tmod
);
1207 assumption
= fold_build2 (LE_EXPR
, boolean_type_node
,
1209 if (integer_zerop (assumption
))
1212 if (mpz_cmp (mmod
, bnds
->below
) < 0)
1213 noloop
= boolean_false_node
;
1214 else if (POINTER_TYPE_P (type
))
1215 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
1217 fold_build_pointer_plus (iv1
->base
, tmod
));
1219 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
1221 fold_build2 (PLUS_EXPR
, type1
,
1226 /* The final value of the iv is iv0->base - MOD, assuming that this
1227 computation does not overflow, and that
1228 iv0->base - MOD <= iv1->base. */
1229 if (!fv_comp_no_overflow
)
1231 bound
= fold_build2 (PLUS_EXPR
, type1
,
1232 TYPE_MIN_VALUE (type1
), tmod
);
1233 assumption
= fold_build2 (GE_EXPR
, boolean_type_node
,
1235 if (integer_zerop (assumption
))
1238 if (mpz_cmp (mmod
, bnds
->below
) < 0)
1239 noloop
= boolean_false_node
;
1240 else if (POINTER_TYPE_P (type
))
1241 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
1242 fold_build_pointer_plus (iv0
->base
,
1243 fold_build1 (NEGATE_EXPR
,
1247 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
1248 fold_build2 (MINUS_EXPR
, type1
,
1253 if (!integer_nonzerop (assumption
))
1254 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1257 if (!integer_zerop (noloop
))
1258 niter
->may_be_zero
= fold_build2 (TRUTH_OR_EXPR
, boolean_type_node
,
1261 bounds_add (bnds
, wi::to_widest (mod
), type
);
1262 *delta
= fold_build2 (PLUS_EXPR
, niter_type
, *delta
, mod
);
1270 /* Add assertions to NITER that ensure that the control variable of the loop
1271 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
1272 are TYPE. Returns false if we can prove that there is an overflow, true
1273 otherwise. STEP is the absolute value of the step. */
1276 assert_no_overflow_lt (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
1277 class tree_niter_desc
*niter
, tree step
)
1279 tree bound
, d
, assumption
, diff
;
1280 tree niter_type
= TREE_TYPE (step
);
1282 if (integer_nonzerop (iv0
->step
))
1284 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
1285 if (iv0
->no_overflow
)
1288 /* If iv0->base is a constant, we can determine the last value before
1289 overflow precisely; otherwise we conservatively assume
1292 if (TREE_CODE (iv0
->base
) == INTEGER_CST
)
1294 d
= fold_build2 (MINUS_EXPR
, niter_type
,
1295 fold_convert (niter_type
, TYPE_MAX_VALUE (type
)),
1296 fold_convert (niter_type
, iv0
->base
));
1297 diff
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, d
, step
);
1300 diff
= fold_build2 (MINUS_EXPR
, niter_type
, step
,
1301 build_int_cst (niter_type
, 1));
1302 bound
= fold_build2 (MINUS_EXPR
, type
,
1303 TYPE_MAX_VALUE (type
), fold_convert (type
, diff
));
1304 assumption
= fold_build2 (LE_EXPR
, boolean_type_node
,
1309 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
1310 if (iv1
->no_overflow
)
1313 if (TREE_CODE (iv1
->base
) == INTEGER_CST
)
1315 d
= fold_build2 (MINUS_EXPR
, niter_type
,
1316 fold_convert (niter_type
, iv1
->base
),
1317 fold_convert (niter_type
, TYPE_MIN_VALUE (type
)));
1318 diff
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, d
, step
);
1321 diff
= fold_build2 (MINUS_EXPR
, niter_type
, step
,
1322 build_int_cst (niter_type
, 1));
1323 bound
= fold_build2 (PLUS_EXPR
, type
,
1324 TYPE_MIN_VALUE (type
), fold_convert (type
, diff
));
1325 assumption
= fold_build2 (GE_EXPR
, boolean_type_node
,
1329 if (integer_zerop (assumption
))
1331 if (!integer_nonzerop (assumption
))
1332 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1333 niter
->assumptions
, assumption
);
1335 iv0
->no_overflow
= true;
1336 iv1
->no_overflow
= true;
1340 /* Add an assumption to NITER that a loop whose ending condition
1341 is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
1342 bounds the value of IV1->base - IV0->base. */
1345 assert_loop_rolls_lt (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
1346 class tree_niter_desc
*niter
, bounds
*bnds
)
1348 tree assumption
= boolean_true_node
, bound
, diff
;
1349 tree mbz
, mbzl
, mbzr
, type1
;
1350 bool rolls_p
, no_overflow_p
;
1354 /* We are going to compute the number of iterations as
1355 (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1356 variant of TYPE. This formula only works if
1358 -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1360 (where MAX is the maximum value of the unsigned variant of TYPE, and
1361 the computations in this formula are performed in full precision,
1362 i.e., without overflows).
1364 Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1365 we have a condition of the form iv0->base - step < iv1->base before the loop,
1366 and for loops iv0->base < iv1->base - step * i the condition
1367 iv0->base < iv1->base + step, due to loop header copying, which enable us
1368 to prove the lower bound.
1370 The upper bound is more complicated. Unless the expressions for initial
1371 and final value themselves contain enough information, we usually cannot
1372 derive it from the context. */
1374 /* First check whether the answer does not follow from the bounds we gathered
1376 if (integer_nonzerop (iv0
->step
))
1377 dstep
= wi::to_widest (iv0
->step
);
1380 dstep
= wi::sext (wi::to_widest (iv1
->step
), TYPE_PRECISION (type
));
1385 wi::to_mpz (dstep
, mstep
, UNSIGNED
);
1386 mpz_neg (mstep
, mstep
);
1387 mpz_add_ui (mstep
, mstep
, 1);
1389 rolls_p
= mpz_cmp (mstep
, bnds
->below
) <= 0;
1392 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), max
, UNSIGNED
);
1393 mpz_add (max
, max
, mstep
);
1394 no_overflow_p
= (mpz_cmp (bnds
->up
, max
) <= 0
1395 /* For pointers, only values lying inside a single object
1396 can be compared or manipulated by pointer arithmetics.
1397 Gcc in general does not allow or handle objects larger
1398 than half of the address space, hence the upper bound
1399 is satisfied for pointers. */
1400 || POINTER_TYPE_P (type
));
1404 if (rolls_p
&& no_overflow_p
)
1408 if (POINTER_TYPE_P (type
))
1411 /* Now the hard part; we must formulate the assumption(s) as expressions, and
1412 we must be careful not to introduce overflow. */
1414 if (integer_nonzerop (iv0
->step
))
1416 diff
= fold_build2 (MINUS_EXPR
, type1
,
1417 iv0
->step
, build_int_cst (type1
, 1));
1419 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1420 0 address never belongs to any object, we can assume this for
1422 if (!POINTER_TYPE_P (type
))
1424 bound
= fold_build2 (PLUS_EXPR
, type1
,
1425 TYPE_MIN_VALUE (type
), diff
);
1426 assumption
= fold_build2 (GE_EXPR
, boolean_type_node
,
1430 /* And then we can compute iv0->base - diff, and compare it with
1432 mbzl
= fold_build2 (MINUS_EXPR
, type1
,
1433 fold_convert (type1
, iv0
->base
), diff
);
1434 mbzr
= fold_convert (type1
, iv1
->base
);
1438 diff
= fold_build2 (PLUS_EXPR
, type1
,
1439 iv1
->step
, build_int_cst (type1
, 1));
1441 if (!POINTER_TYPE_P (type
))
1443 bound
= fold_build2 (PLUS_EXPR
, type1
,
1444 TYPE_MAX_VALUE (type
), diff
);
1445 assumption
= fold_build2 (LE_EXPR
, boolean_type_node
,
1449 mbzl
= fold_convert (type1
, iv0
->base
);
1450 mbzr
= fold_build2 (MINUS_EXPR
, type1
,
1451 fold_convert (type1
, iv1
->base
), diff
);
1454 if (!integer_nonzerop (assumption
))
1455 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1456 niter
->assumptions
, assumption
);
1459 mbz
= fold_build2 (GT_EXPR
, boolean_type_node
, mbzl
, mbzr
);
1460 niter
->may_be_zero
= fold_build2 (TRUTH_OR_EXPR
, boolean_type_node
,
1461 niter
->may_be_zero
, mbz
);
1465 /* Determines number of iterations of loop whose ending condition
1466 is IV0 < IV1 which likes: {base, -C} < n, or n < {base, C}.
1467 The number of iterations is stored to NITER. */
1470 number_of_iterations_until_wrap (class loop
*loop
, tree type
, affine_iv
*iv0
,
1471 affine_iv
*iv1
, class tree_niter_desc
*niter
)
1473 tree niter_type
= unsigned_type_for (type
);
1474 tree step
, num
, assumptions
, may_be_zero
, span
;
1475 wide_int high
, low
, max
, min
;
1477 may_be_zero
= fold_build2 (LE_EXPR
, boolean_type_node
, iv1
->base
, iv0
->base
);
1478 if (integer_onep (may_be_zero
))
1481 int prec
= TYPE_PRECISION (type
);
1482 signop sgn
= TYPE_SIGN (type
);
1483 min
= wi::min_value (prec
, sgn
);
1484 max
= wi::max_value (prec
, sgn
);
1486 /* n < {base, C}. */
1487 if (integer_zerop (iv0
->step
) && !tree_int_cst_sign_bit (iv1
->step
))
1490 /* MIN + C - 1 <= n. */
1491 tree last
= wide_int_to_tree (type
, min
+ wi::to_wide (step
) - 1);
1492 assumptions
= fold_build2 (LE_EXPR
, boolean_type_node
, last
, iv0
->base
);
1493 if (integer_zerop (assumptions
))
1496 num
= fold_build2 (MINUS_EXPR
, niter_type
, wide_int_to_tree (type
, max
),
1499 /* When base has the form iv + 1, if we know iv >= n, then iv + 1 < n
1500 only when iv + 1 overflows, i.e. when iv == TYPE_VALUE_MAX. */
1502 && integer_onep (step
)
1503 && TREE_CODE (iv1
->base
) == PLUS_EXPR
1504 && integer_onep (TREE_OPERAND (iv1
->base
, 1)))
1506 tree cond
= fold_build2 (GE_EXPR
, boolean_type_node
,
1507 TREE_OPERAND (iv1
->base
, 0), iv0
->base
);
1508 cond
= simplify_using_initial_conditions (loop
, cond
);
1509 if (integer_onep (cond
))
1510 may_be_zero
= fold_build2 (EQ_EXPR
, boolean_type_node
,
1511 TREE_OPERAND (iv1
->base
, 0),
1512 TYPE_MAX_VALUE (type
));
1516 if (TREE_CODE (iv1
->base
) == INTEGER_CST
)
1517 low
= wi::to_wide (iv1
->base
) - 1;
1518 else if (TREE_CODE (iv0
->base
) == INTEGER_CST
)
1519 low
= wi::to_wide (iv0
->base
);
1523 /* {base, -C} < n. */
1524 else if (tree_int_cst_sign_bit (iv0
->step
) && integer_zerop (iv1
->step
))
1526 step
= fold_build1 (NEGATE_EXPR
, TREE_TYPE (iv0
->step
), iv0
->step
);
1527 /* MAX - C + 1 >= n. */
1528 tree last
= wide_int_to_tree (type
, max
- wi::to_wide (step
) + 1);
1529 assumptions
= fold_build2 (GE_EXPR
, boolean_type_node
, last
, iv1
->base
);
1530 if (integer_zerop (assumptions
))
1533 num
= fold_build2 (MINUS_EXPR
, niter_type
, iv0
->base
,
1534 wide_int_to_tree (type
, min
));
1536 if (TREE_CODE (iv0
->base
) == INTEGER_CST
)
1537 high
= wi::to_wide (iv0
->base
) + 1;
1538 else if (TREE_CODE (iv1
->base
) == INTEGER_CST
)
1539 high
= wi::to_wide (iv1
->base
);
1546 /* (delta + step - 1) / step */
1547 step
= fold_convert (niter_type
, step
);
1548 num
= fold_convert (niter_type
, num
);
1549 num
= fold_build2 (PLUS_EXPR
, niter_type
, num
, step
);
1550 niter
->niter
= fold_build2 (FLOOR_DIV_EXPR
, niter_type
, num
, step
);
1552 widest_int delta
, s
;
1553 delta
= widest_int::from (high
, sgn
) - widest_int::from (low
, sgn
);
1554 s
= wi::to_widest (step
);
1555 delta
= delta
+ s
- 1;
1556 niter
->max
= wi::udiv_floor (delta
, s
);
1558 niter
->may_be_zero
= may_be_zero
;
1560 if (!integer_nonzerop (assumptions
))
1561 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1562 niter
->assumptions
, assumptions
);
1564 niter
->control
.no_overflow
= false;
1566 /* Update bound and exit condition as:
1567 bound = niter * STEP + (IVbase - STEP).
1568 { IVbase - STEP, +, STEP } != bound
1569 Here, biasing IVbase by 1 step makes 'bound' be the value before wrap.
1571 tree base_type
= TREE_TYPE (niter
->control
.base
);
1572 if (POINTER_TYPE_P (base_type
))
1574 tree utype
= unsigned_type_for (base_type
);
1576 = fold_build2 (MINUS_EXPR
, utype
,
1577 fold_convert (utype
, niter
->control
.base
),
1578 fold_convert (utype
, niter
->control
.step
));
1579 niter
->control
.base
= fold_convert (base_type
, niter
->control
.base
);
1583 = fold_build2 (MINUS_EXPR
, base_type
, niter
->control
.base
,
1584 niter
->control
.step
);
1586 span
= fold_build2 (MULT_EXPR
, niter_type
, niter
->niter
,
1587 fold_convert (niter_type
, niter
->control
.step
));
1588 niter
->bound
= fold_build2 (PLUS_EXPR
, niter_type
, span
,
1589 fold_convert (niter_type
, niter
->control
.base
));
1590 niter
->bound
= fold_convert (type
, niter
->bound
);
1591 niter
->cmp
= NE_EXPR
;
1596 /* Determines number of iterations of loop whose ending condition
1597 is IV0 < IV1. TYPE is the type of the iv. The number of
1598 iterations is stored to NITER. BNDS bounds the difference
1599 IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1600 that the exit must be taken eventually. */
1603 number_of_iterations_lt (class loop
*loop
, tree type
, affine_iv
*iv0
,
1604 affine_iv
*iv1
, class tree_niter_desc
*niter
,
1605 bool exit_must_be_taken
, bounds
*bnds
)
1607 tree niter_type
= unsigned_type_for (type
);
1608 tree delta
, step
, s
;
1611 if (integer_nonzerop (iv0
->step
))
1613 niter
->control
= *iv0
;
1614 niter
->cmp
= LT_EXPR
;
1615 niter
->bound
= iv1
->base
;
1619 niter
->control
= *iv1
;
1620 niter
->cmp
= GT_EXPR
;
1621 niter
->bound
= iv0
->base
;
1624 /* {base, -C} < n, or n < {base, C} */
1625 if (tree_int_cst_sign_bit (iv0
->step
)
1626 || (!integer_zerop (iv1
->step
) && !tree_int_cst_sign_bit (iv1
->step
)))
1627 return number_of_iterations_until_wrap (loop
, type
, iv0
, iv1
, niter
);
1629 delta
= fold_build2 (MINUS_EXPR
, niter_type
,
1630 fold_convert (niter_type
, iv1
->base
),
1631 fold_convert (niter_type
, iv0
->base
));
1633 /* First handle the special case that the step is +-1. */
1634 if ((integer_onep (iv0
->step
) && integer_zerop (iv1
->step
))
1635 || (integer_all_onesp (iv1
->step
) && integer_zerop (iv0
->step
)))
1637 /* for (i = iv0->base; i < iv1->base; i++)
1641 for (i = iv1->base; i > iv0->base; i--).
1643 In both cases # of iterations is iv1->base - iv0->base, assuming that
1644 iv1->base >= iv0->base.
1646 First try to derive a lower bound on the value of
1647 iv1->base - iv0->base, computed in full precision. If the difference
1648 is nonnegative, we are done, otherwise we must record the
1651 if (mpz_sgn (bnds
->below
) < 0)
1652 niter
->may_be_zero
= fold_build2 (LT_EXPR
, boolean_type_node
,
1653 iv1
->base
, iv0
->base
);
1654 niter
->niter
= delta
;
1655 niter
->max
= widest_int::from (wi::from_mpz (niter_type
, bnds
->up
, false),
1656 TYPE_SIGN (niter_type
));
1657 niter
->control
.no_overflow
= true;
1661 if (integer_nonzerop (iv0
->step
))
1662 step
= fold_convert (niter_type
, iv0
->step
);
1664 step
= fold_convert (niter_type
,
1665 fold_build1 (NEGATE_EXPR
, type
, iv1
->step
));
1667 /* If we can determine the final value of the control iv exactly, we can
1668 transform the condition to != comparison. In particular, this will be
1669 the case if DELTA is constant. */
1670 if (number_of_iterations_lt_to_ne (type
, iv0
, iv1
, niter
, &delta
, step
,
1671 exit_must_be_taken
, bnds
))
1675 zps
.base
= build_int_cst (niter_type
, 0);
1677 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1678 zps does not overflow. */
1679 zps
.no_overflow
= true;
1681 return number_of_iterations_ne (loop
, type
, &zps
,
1682 delta
, niter
, true, bnds
);
1685 /* Make sure that the control iv does not overflow. */
1686 if (!assert_no_overflow_lt (type
, iv0
, iv1
, niter
, step
))
1689 /* We determine the number of iterations as (delta + step - 1) / step. For
1690 this to work, we must know that iv1->base >= iv0->base - step + 1,
1691 otherwise the loop does not roll. */
1692 assert_loop_rolls_lt (type
, iv0
, iv1
, niter
, bnds
);
1694 s
= fold_build2 (MINUS_EXPR
, niter_type
,
1695 step
, build_int_cst (niter_type
, 1));
1696 delta
= fold_build2 (PLUS_EXPR
, niter_type
, delta
, s
);
1697 niter
->niter
= fold_build2 (FLOOR_DIV_EXPR
, niter_type
, delta
, step
);
1701 wi::to_mpz (wi::to_wide (step
), mstep
, UNSIGNED
);
1702 mpz_add (tmp
, bnds
->up
, mstep
);
1703 mpz_sub_ui (tmp
, tmp
, 1);
1704 mpz_fdiv_q (tmp
, tmp
, mstep
);
1705 niter
->max
= widest_int::from (wi::from_mpz (niter_type
, tmp
, false),
1706 TYPE_SIGN (niter_type
));
1713 /* Determines number of iterations of loop whose ending condition
1714 is IV0 <= IV1. TYPE is the type of the iv. The number of
1715 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1716 we know that this condition must eventually become false (we derived this
1717 earlier, and possibly set NITER->assumptions to make sure this
1718 is the case). BNDS bounds the difference IV1->base - IV0->base. */
1721 number_of_iterations_le (class loop
*loop
, tree type
, affine_iv
*iv0
,
1722 affine_iv
*iv1
, class tree_niter_desc
*niter
,
1723 bool exit_must_be_taken
, bounds
*bnds
)
1727 if (POINTER_TYPE_P (type
))
1730 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1731 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1732 value of the type. This we must know anyway, since if it is
1733 equal to this value, the loop rolls forever. We do not check
1734 this condition for pointer type ivs, as the code cannot rely on
1735 the object to that the pointer points being placed at the end of
1736 the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1737 not defined for pointers). */
1739 if (!exit_must_be_taken
&& !POINTER_TYPE_P (type
))
1741 if (integer_nonzerop (iv0
->step
))
1742 assumption
= fold_build2 (NE_EXPR
, boolean_type_node
,
1743 iv1
->base
, TYPE_MAX_VALUE (type
));
1745 assumption
= fold_build2 (NE_EXPR
, boolean_type_node
,
1746 iv0
->base
, TYPE_MIN_VALUE (type
));
1748 if (integer_zerop (assumption
))
1750 if (!integer_nonzerop (assumption
))
1751 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1752 niter
->assumptions
, assumption
);
1755 if (integer_nonzerop (iv0
->step
))
1757 if (POINTER_TYPE_P (type
))
1758 iv1
->base
= fold_build_pointer_plus_hwi (iv1
->base
, 1);
1760 iv1
->base
= fold_build2 (PLUS_EXPR
, type1
, iv1
->base
,
1761 build_int_cst (type1
, 1));
1763 else if (POINTER_TYPE_P (type
))
1764 iv0
->base
= fold_build_pointer_plus_hwi (iv0
->base
, -1);
1766 iv0
->base
= fold_build2 (MINUS_EXPR
, type1
,
1767 iv0
->base
, build_int_cst (type1
, 1));
1769 bounds_add (bnds
, 1, type1
);
1771 return number_of_iterations_lt (loop
, type
, iv0
, iv1
, niter
, exit_must_be_taken
,
1775 /* Dumps description of affine induction variable IV to FILE. */
1778 dump_affine_iv (FILE *file
, affine_iv
*iv
)
1780 if (!integer_zerop (iv
->step
))
1781 fprintf (file
, "[");
1783 print_generic_expr (dump_file
, iv
->base
, TDF_SLIM
);
1785 if (!integer_zerop (iv
->step
))
1787 fprintf (file
, ", + , ");
1788 print_generic_expr (dump_file
, iv
->step
, TDF_SLIM
);
1789 fprintf (file
, "]%s", iv
->no_overflow
? "(no_overflow)" : "");
1793 /* Determine the number of iterations according to condition (for staying
1794 inside loop) which compares two induction variables using comparison
1795 operator CODE. The induction variable on left side of the comparison
1796 is IV0, the right-hand side is IV1. Both induction variables must have
1797 type TYPE, which must be an integer or pointer type. The steps of the
1798 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1800 LOOP is the loop whose number of iterations we are determining.
1802 ONLY_EXIT is true if we are sure this is the only way the loop could be
1803 exited (including possibly non-returning function calls, exceptions, etc.)
1804 -- in this case we can use the information whether the control induction
1805 variables can overflow or not in a more efficient way.
1807 if EVERY_ITERATION is true, we know the test is executed on every iteration.
1809 The results (number of iterations and assumptions as described in
1810 comments at class tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1811 Returns false if it fails to determine number of iterations, true if it
1812 was determined (possibly with some assumptions). */
1815 number_of_iterations_cond (class loop
*loop
,
1816 tree type
, affine_iv
*iv0
, enum tree_code code
,
1817 affine_iv
*iv1
, class tree_niter_desc
*niter
,
1818 bool only_exit
, bool every_iteration
)
1820 bool exit_must_be_taken
= false, ret
;
1823 /* If the test is not executed every iteration, wrapping may make the test
1825 TODO: the overflow case can be still used as unreliable estimate of upper
1826 bound. But we have no API to pass it down to number of iterations code
1827 and, at present, it will not use it anyway. */
1828 if (!every_iteration
1829 && (!iv0
->no_overflow
|| !iv1
->no_overflow
1830 || code
== NE_EXPR
|| code
== EQ_EXPR
))
1833 /* The meaning of these assumptions is this:
1835 then the rest of information does not have to be valid
1836 if may_be_zero then the loop does not roll, even if
1838 niter
->assumptions
= boolean_true_node
;
1839 niter
->may_be_zero
= boolean_false_node
;
1840 niter
->niter
= NULL_TREE
;
1842 niter
->bound
= NULL_TREE
;
1843 niter
->cmp
= ERROR_MARK
;
1845 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1846 the control variable is on lhs. */
1847 if (code
== GE_EXPR
|| code
== GT_EXPR
1848 || (code
== NE_EXPR
&& integer_zerop (iv0
->step
)))
1850 std::swap (iv0
, iv1
);
1851 code
= swap_tree_comparison (code
);
1854 if (POINTER_TYPE_P (type
))
1856 /* Comparison of pointers is undefined unless both iv0 and iv1 point
1857 to the same object. If they do, the control variable cannot wrap
1858 (as wrap around the bounds of memory will never return a pointer
1859 that would be guaranteed to point to the same object, even if we
1860 avoid undefined behavior by casting to size_t and back). */
1861 iv0
->no_overflow
= true;
1862 iv1
->no_overflow
= true;
1865 /* If the control induction variable does not overflow and the only exit
1866 from the loop is the one that we analyze, we know it must be taken
1870 if (!integer_zerop (iv0
->step
) && iv0
->no_overflow
)
1871 exit_must_be_taken
= true;
1872 else if (!integer_zerop (iv1
->step
) && iv1
->no_overflow
)
1873 exit_must_be_taken
= true;
1876 /* We can handle cases which neither of the sides of the comparison is
1879 {iv0.base, iv0.step} cmp_code {iv1.base, iv1.step}
1881 {iv0.base, iv0.step - iv1.step} cmp_code {iv1.base, 0}
1883 provided that either below condition is satisfied:
1885 a) the test is NE_EXPR;
1886 b) iv0 and iv1 do not overflow and iv0.step - iv1.step is of
1887 the same sign and of less or equal magnitude than iv0.step
1889 This rarely occurs in practice, but it is simple enough to manage. */
1890 if (!integer_zerop (iv0
->step
) && !integer_zerop (iv1
->step
))
1892 tree step_type
= POINTER_TYPE_P (type
) ? sizetype
: type
;
1893 tree step
= fold_binary_to_constant (MINUS_EXPR
, step_type
,
1894 iv0
->step
, iv1
->step
);
1896 /* For code other than NE_EXPR we have to ensure moving the evolution
1897 of IV1 to that of IV0 does not introduce overflow. */
1898 if (TREE_CODE (step
) != INTEGER_CST
1899 || !iv0
->no_overflow
|| !iv1
->no_overflow
)
1901 if (code
!= NE_EXPR
)
1903 iv0
->no_overflow
= false;
1905 /* If the new step of IV0 has changed sign or is of greater
1906 magnitude then we do not know whether IV0 does overflow
1907 and thus the transform is not valid for code other than NE_EXPR. */
1908 else if (tree_int_cst_sign_bit (step
) != tree_int_cst_sign_bit (iv0
->step
)
1909 || wi::gtu_p (wi::abs (wi::to_widest (step
)),
1910 wi::abs (wi::to_widest (iv0
->step
))))
1912 if (POINTER_TYPE_P (type
) && code
!= NE_EXPR
)
1913 /* For relational pointer compares we have further guarantees
1914 that the pointers always point to the same object (or one
1915 after it) and that objects do not cross the zero page. So
1916 not only is the transform always valid for relational
1917 pointer compares, we also know the resulting IV does not
1920 else if (code
!= NE_EXPR
)
1923 iv0
->no_overflow
= false;
1927 iv1
->step
= build_int_cst (step_type
, 0);
1928 iv1
->no_overflow
= true;
1931 /* If the result of the comparison is a constant, the loop is weird. More
1932 precise handling would be possible, but the situation is not common enough
1933 to waste time on it. */
1934 if (integer_zerop (iv0
->step
) && integer_zerop (iv1
->step
))
1937 /* If the loop exits immediately, there is nothing to do. */
1938 tree tem
= fold_binary (code
, boolean_type_node
, iv0
->base
, iv1
->base
);
1939 if (tem
&& integer_zerop (tem
))
1941 if (!every_iteration
)
1943 niter
->niter
= build_int_cst (unsigned_type_for (type
), 0);
1948 /* OK, now we know we have a senseful loop. Handle several cases, depending
1949 on what comparison operator is used. */
1950 bound_difference (loop
, iv1
->base
, iv0
->base
, &bnds
);
1952 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1955 "Analyzing # of iterations of loop %d\n", loop
->num
);
1957 fprintf (dump_file
, " exit condition ");
1958 dump_affine_iv (dump_file
, iv0
);
1959 fprintf (dump_file
, " %s ",
1960 code
== NE_EXPR
? "!="
1961 : code
== LT_EXPR
? "<"
1963 dump_affine_iv (dump_file
, iv1
);
1964 fprintf (dump_file
, "\n");
1966 fprintf (dump_file
, " bounds on difference of bases: ");
1967 mpz_out_str (dump_file
, 10, bnds
.below
);
1968 fprintf (dump_file
, " ... ");
1969 mpz_out_str (dump_file
, 10, bnds
.up
);
1970 fprintf (dump_file
, "\n");
1976 gcc_assert (integer_zerop (iv1
->step
));
1977 ret
= number_of_iterations_ne (loop
, type
, iv0
, iv1
->base
, niter
,
1978 exit_must_be_taken
, &bnds
);
1982 ret
= number_of_iterations_lt (loop
, type
, iv0
, iv1
, niter
,
1983 exit_must_be_taken
, &bnds
);
1987 ret
= number_of_iterations_le (loop
, type
, iv0
, iv1
, niter
,
1988 exit_must_be_taken
, &bnds
);
1995 mpz_clear (bnds
.up
);
1996 mpz_clear (bnds
.below
);
1998 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2002 fprintf (dump_file
, " result:\n");
2003 if (!integer_nonzerop (niter
->assumptions
))
2005 fprintf (dump_file
, " under assumptions ");
2006 print_generic_expr (dump_file
, niter
->assumptions
, TDF_SLIM
);
2007 fprintf (dump_file
, "\n");
2010 if (!integer_zerop (niter
->may_be_zero
))
2012 fprintf (dump_file
, " zero if ");
2013 print_generic_expr (dump_file
, niter
->may_be_zero
, TDF_SLIM
);
2014 fprintf (dump_file
, "\n");
2017 fprintf (dump_file
, " # of iterations ");
2018 print_generic_expr (dump_file
, niter
->niter
, TDF_SLIM
);
2019 fprintf (dump_file
, ", bounded by ");
2020 print_decu (niter
->max
, dump_file
);
2021 fprintf (dump_file
, "\n");
2024 fprintf (dump_file
, " failed\n\n");
2029 /* Return an expression that computes the popcount of src. */
2032 build_popcount_expr (tree src
)
2035 int prec
= TYPE_PRECISION (TREE_TYPE (src
));
2036 int i_prec
= TYPE_PRECISION (integer_type_node
);
2037 int li_prec
= TYPE_PRECISION (long_integer_type_node
);
2038 int lli_prec
= TYPE_PRECISION (long_long_integer_type_node
);
2040 fn
= builtin_decl_implicit (BUILT_IN_POPCOUNT
);
2041 else if (prec
== li_prec
)
2042 fn
= builtin_decl_implicit (BUILT_IN_POPCOUNTL
);
2043 else if (prec
== lli_prec
|| prec
== 2 * lli_prec
)
2044 fn
= builtin_decl_implicit (BUILT_IN_POPCOUNTLL
);
2048 tree utype
= unsigned_type_for (TREE_TYPE (src
));
2049 src
= fold_convert (utype
, src
);
2051 src
= fold_convert (unsigned_type_node
, src
);
2053 if (prec
== 2 * lli_prec
)
2055 tree src1
= fold_convert (long_long_unsigned_type_node
,
2056 fold_build2 (RSHIFT_EXPR
, TREE_TYPE (src
),
2058 build_int_cst (integer_type_node
,
2060 tree src2
= fold_convert (long_long_unsigned_type_node
, src
);
2061 tree call1
= build_call_expr (fn
, 1, src1
);
2062 tree call2
= build_call_expr (fn
, 1, src2
);
2063 call
= fold_build2 (PLUS_EXPR
, integer_type_node
, call1
, call2
);
2066 call
= build_call_expr (fn
, 1, src
);
2071 /* Utility function to check if OP is defined by a stmt
2072 that is a val - 1. */
2075 ssa_defined_by_minus_one_stmt_p (tree op
, tree val
)
2078 return (TREE_CODE (op
) == SSA_NAME
2079 && (stmt
= SSA_NAME_DEF_STMT (op
))
2080 && is_gimple_assign (stmt
)
2081 && (gimple_assign_rhs_code (stmt
) == PLUS_EXPR
)
2082 && val
== gimple_assign_rhs1 (stmt
)
2083 && integer_minus_onep (gimple_assign_rhs2 (stmt
)));
2086 /* See comment below for number_of_iterations_bitcount.
2087 For popcount, we have:
2102 number_of_iterations_popcount (loop_p loop
, edge exit
,
2103 enum tree_code code
,
2104 class tree_niter_desc
*niter
)
2106 bool modify_before_test
= true;
2109 /* Check that condition for staying inside the loop is like
2111 gimple
*cond_stmt
= last_stmt (exit
->src
);
2113 || gimple_code (cond_stmt
) != GIMPLE_COND
2115 || !integer_zerop (gimple_cond_rhs (cond_stmt
))
2116 || TREE_CODE (gimple_cond_lhs (cond_stmt
)) != SSA_NAME
)
2119 tree iv_2
= gimple_cond_lhs (cond_stmt
);
2120 gimple
*iv_2_stmt
= SSA_NAME_DEF_STMT (iv_2
);
2122 /* If the test comes before the iv modification, then these will actually be
2123 iv_1 and a phi node. */
2124 if (gimple_code (iv_2_stmt
) == GIMPLE_PHI
2125 && gimple_bb (iv_2_stmt
) == loop
->header
2126 && gimple_phi_num_args (iv_2_stmt
) == 2
2127 && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt
,
2128 loop_latch_edge (loop
)->dest_idx
))
2131 /* iv_2 is actually one of the inputs to the phi. */
2132 iv_2
= gimple_phi_arg_def (iv_2_stmt
, loop_latch_edge (loop
)->dest_idx
);
2133 iv_2_stmt
= SSA_NAME_DEF_STMT (iv_2
);
2134 modify_before_test
= false;
2137 /* Make sure iv_2_stmt is an and stmt (iv_2 = _1 & iv_1). */
2138 if (!is_gimple_assign (iv_2_stmt
)
2139 || gimple_assign_rhs_code (iv_2_stmt
) != BIT_AND_EXPR
)
2142 tree iv_1
= gimple_assign_rhs1 (iv_2_stmt
);
2143 tree _1
= gimple_assign_rhs2 (iv_2_stmt
);
2145 /* Check that _1 is defined by (_1 = iv_1 + -1).
2146 Also make sure that _1 is the same in and_stmt and _1 defining stmt.
2147 Also canonicalize if _1 and _b11 are revrsed. */
2148 if (ssa_defined_by_minus_one_stmt_p (iv_1
, _1
))
2149 std::swap (iv_1
, _1
);
2150 else if (ssa_defined_by_minus_one_stmt_p (_1
, iv_1
))
2155 /* Check the recurrence. */
2156 gimple
*phi
= SSA_NAME_DEF_STMT (iv_1
);
2157 if (gimple_code (phi
) != GIMPLE_PHI
2158 || (gimple_bb (phi
) != loop_latch_edge (loop
)->dest
)
2159 || (iv_2
!= gimple_phi_arg_def (phi
, loop_latch_edge (loop
)->dest_idx
)))
2162 /* We found a match. */
2163 tree src
= gimple_phi_arg_def (phi
, loop_preheader_edge (loop
)->dest_idx
);
2164 int src_precision
= TYPE_PRECISION (TREE_TYPE (src
));
2166 /* Get the corresponding popcount builtin. */
2167 tree expr
= build_popcount_expr (src
);
2172 max
= src_precision
;
2174 tree may_be_zero
= boolean_false_node
;
2176 if (modify_before_test
)
2178 expr
= fold_build2 (MINUS_EXPR
, integer_type_node
, expr
,
2181 may_be_zero
= fold_build2 (EQ_EXPR
, boolean_type_node
, src
,
2182 build_zero_cst (TREE_TYPE (src
)));
2185 expr
= fold_convert (unsigned_type_node
, expr
);
2187 niter
->assumptions
= boolean_true_node
;
2188 niter
->may_be_zero
= simplify_using_initial_conditions (loop
, may_be_zero
);
2189 niter
->niter
= simplify_using_initial_conditions(loop
, expr
);
2191 if (TREE_CODE (niter
->niter
) == INTEGER_CST
)
2192 niter
->max
= tree_to_uhwi (niter
->niter
);
2196 niter
->bound
= NULL_TREE
;
2197 niter
->cmp
= ERROR_MARK
;
2201 /* See if LOOP contains a bit counting idiom. The idiom consists of two parts:
2202 1. A modification to the induction variabler;.
2203 2. A test to determine whether or not to exit the loop.
2205 These can come in either order - i.e.:
2208 iv_1 = PHI <src(2), iv_2(4)>
2215 iv_2 = modify (iv_1)
2221 iv_1 = PHI <src(2), iv_2(4)>
2222 iv_2 = modify (iv_1)
2230 The second form can be generated by copying the loop header out of the loop.
2232 In the first case, the number of latch executions will be equal to the
2233 number of induction variable modifications required before the test fails.
2235 In the second case (modify_before_test), if we assume that the number of
2236 modifications required before the test fails is nonzero, then the number of
2237 latch executions will be one less than this number.
2239 If we recognise the pattern, then we update niter accordingly, and return
2243 number_of_iterations_bitcount (loop_p loop
, edge exit
,
2244 enum tree_code code
,
2245 class tree_niter_desc
*niter
)
2247 return number_of_iterations_popcount (loop
, exit
, code
, niter
);
2250 /* Substitute NEW_TREE for OLD in EXPR and fold the result.
2251 If VALUEIZE is non-NULL then OLD and NEW_TREE are ignored and instead
2252 all SSA names are replaced with the result of calling the VALUEIZE
2253 function with the SSA name as argument. */
2256 simplify_replace_tree (tree expr
, tree old
, tree new_tree
,
2257 tree (*valueize
) (tree
, void*), void *context
,
2261 tree ret
= NULL_TREE
, e
, se
;
2266 /* Do not bother to replace constants. */
2267 if (CONSTANT_CLASS_P (expr
))
2272 if (TREE_CODE (expr
) == SSA_NAME
)
2274 new_tree
= valueize (expr
, context
);
2275 if (new_tree
!= expr
)
2279 else if (expr
== old
2280 || operand_equal_p (expr
, old
, 0))
2281 return unshare_expr (new_tree
);
2286 n
= TREE_OPERAND_LENGTH (expr
);
2287 for (i
= 0; i
< n
; i
++)
2289 e
= TREE_OPERAND (expr
, i
);
2290 se
= simplify_replace_tree (e
, old
, new_tree
, valueize
, context
, do_fold
);
2295 ret
= copy_node (expr
);
2297 TREE_OPERAND (ret
, i
) = se
;
2300 return (ret
? (do_fold
? fold (ret
) : ret
) : expr
);
2303 /* Expand definitions of ssa names in EXPR as long as they are simple
2304 enough, and return the new expression. If STOP is specified, stop
2305 expanding if EXPR equals to it. */
2308 expand_simple_operations (tree expr
, tree stop
, hash_map
<tree
, tree
> &cache
)
2311 tree ret
= NULL_TREE
, e
, ee
, e1
;
2312 enum tree_code code
;
2315 if (expr
== NULL_TREE
)
2318 if (is_gimple_min_invariant (expr
))
2321 code
= TREE_CODE (expr
);
2322 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code
)))
2324 n
= TREE_OPERAND_LENGTH (expr
);
2325 for (i
= 0; i
< n
; i
++)
2327 e
= TREE_OPERAND (expr
, i
);
2330 /* SCEV analysis feeds us with a proper expression
2331 graph matching the SSA graph. Avoid turning it
2332 into a tree here, thus handle tree sharing
2334 ??? The SSA walk below still turns the SSA graph
2335 into a tree but until we find a testcase do not
2336 introduce additional tree sharing here. */
2338 tree
&cee
= cache
.get_or_insert (e
, &existed_p
);
2344 ee
= expand_simple_operations (e
, stop
, cache
);
2346 *cache
.get (e
) = ee
;
2352 ret
= copy_node (expr
);
2354 TREE_OPERAND (ret
, i
) = ee
;
2360 fold_defer_overflow_warnings ();
2362 fold_undefer_and_ignore_overflow_warnings ();
2366 /* Stop if it's not ssa name or the one we don't want to expand. */
2367 if (TREE_CODE (expr
) != SSA_NAME
|| expr
== stop
)
2370 stmt
= SSA_NAME_DEF_STMT (expr
);
2371 if (gimple_code (stmt
) == GIMPLE_PHI
)
2373 basic_block src
, dest
;
2375 if (gimple_phi_num_args (stmt
) != 1)
2377 e
= PHI_ARG_DEF (stmt
, 0);
2379 /* Avoid propagating through loop exit phi nodes, which
2380 could break loop-closed SSA form restrictions. */
2381 dest
= gimple_bb (stmt
);
2382 src
= single_pred (dest
);
2383 if (TREE_CODE (e
) == SSA_NAME
2384 && src
->loop_father
!= dest
->loop_father
)
2387 return expand_simple_operations (e
, stop
, cache
);
2389 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
2392 /* Avoid expanding to expressions that contain SSA names that need
2393 to take part in abnormal coalescing. */
2395 FOR_EACH_SSA_TREE_OPERAND (e
, stmt
, iter
, SSA_OP_USE
)
2396 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e
))
2399 e
= gimple_assign_rhs1 (stmt
);
2400 code
= gimple_assign_rhs_code (stmt
);
2401 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
2403 if (is_gimple_min_invariant (e
))
2406 if (code
== SSA_NAME
)
2407 return expand_simple_operations (e
, stop
, cache
);
2408 else if (code
== ADDR_EXPR
)
2411 tree base
= get_addr_base_and_unit_offset (TREE_OPERAND (e
, 0),
2414 && TREE_CODE (base
) == MEM_REF
)
2416 ee
= expand_simple_operations (TREE_OPERAND (base
, 0), stop
,
2418 return fold_build2 (POINTER_PLUS_EXPR
, TREE_TYPE (expr
), ee
,
2419 wide_int_to_tree (sizetype
,
2420 mem_ref_offset (base
)
2431 /* Casts are simple. */
2432 ee
= expand_simple_operations (e
, stop
, cache
);
2433 return fold_build1 (code
, TREE_TYPE (expr
), ee
);
2438 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr
))
2439 && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr
)))
2442 case POINTER_PLUS_EXPR
:
2443 /* And increments and decrements by a constant are simple. */
2444 e1
= gimple_assign_rhs2 (stmt
);
2445 if (!is_gimple_min_invariant (e1
))
2448 ee
= expand_simple_operations (e
, stop
, cache
);
2449 return fold_build2 (code
, TREE_TYPE (expr
), ee
, e1
);
2457 expand_simple_operations (tree expr
, tree stop
)
2459 hash_map
<tree
, tree
> cache
;
2460 return expand_simple_operations (expr
, stop
, cache
);
2463 /* Tries to simplify EXPR using the condition COND. Returns the simplified
2464 expression (or EXPR unchanged, if no simplification was possible). */
2467 tree_simplify_using_condition_1 (tree cond
, tree expr
)
2470 tree e
, e0
, e1
, e2
, notcond
;
2471 enum tree_code code
= TREE_CODE (expr
);
2473 if (code
== INTEGER_CST
)
2476 if (code
== TRUTH_OR_EXPR
2477 || code
== TRUTH_AND_EXPR
2478 || code
== COND_EXPR
)
2482 e0
= tree_simplify_using_condition_1 (cond
, TREE_OPERAND (expr
, 0));
2483 if (TREE_OPERAND (expr
, 0) != e0
)
2486 e1
= tree_simplify_using_condition_1 (cond
, TREE_OPERAND (expr
, 1));
2487 if (TREE_OPERAND (expr
, 1) != e1
)
2490 if (code
== COND_EXPR
)
2492 e2
= tree_simplify_using_condition_1 (cond
, TREE_OPERAND (expr
, 2));
2493 if (TREE_OPERAND (expr
, 2) != e2
)
2501 if (code
== COND_EXPR
)
2502 expr
= fold_build3 (code
, boolean_type_node
, e0
, e1
, e2
);
2504 expr
= fold_build2 (code
, boolean_type_node
, e0
, e1
);
2510 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
2511 propagation, and vice versa. Fold does not handle this, since it is
2512 considered too expensive. */
2513 if (TREE_CODE (cond
) == EQ_EXPR
)
2515 e0
= TREE_OPERAND (cond
, 0);
2516 e1
= TREE_OPERAND (cond
, 1);
2518 /* We know that e0 == e1. Check whether we cannot simplify expr
2520 e
= simplify_replace_tree (expr
, e0
, e1
);
2521 if (integer_zerop (e
) || integer_nonzerop (e
))
2524 e
= simplify_replace_tree (expr
, e1
, e0
);
2525 if (integer_zerop (e
) || integer_nonzerop (e
))
2528 if (TREE_CODE (expr
) == EQ_EXPR
)
2530 e0
= TREE_OPERAND (expr
, 0);
2531 e1
= TREE_OPERAND (expr
, 1);
2533 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
2534 e
= simplify_replace_tree (cond
, e0
, e1
);
2535 if (integer_zerop (e
))
2537 e
= simplify_replace_tree (cond
, e1
, e0
);
2538 if (integer_zerop (e
))
2541 if (TREE_CODE (expr
) == NE_EXPR
)
2543 e0
= TREE_OPERAND (expr
, 0);
2544 e1
= TREE_OPERAND (expr
, 1);
2546 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
2547 e
= simplify_replace_tree (cond
, e0
, e1
);
2548 if (integer_zerop (e
))
2549 return boolean_true_node
;
2550 e
= simplify_replace_tree (cond
, e1
, e0
);
2551 if (integer_zerop (e
))
2552 return boolean_true_node
;
2555 /* Check whether COND ==> EXPR. */
2556 notcond
= invert_truthvalue (cond
);
2557 e
= fold_binary (TRUTH_OR_EXPR
, boolean_type_node
, notcond
, expr
);
2558 if (e
&& integer_nonzerop (e
))
2561 /* Check whether COND ==> not EXPR. */
2562 e
= fold_binary (TRUTH_AND_EXPR
, boolean_type_node
, cond
, expr
);
2563 if (e
&& integer_zerop (e
))
2569 /* Tries to simplify EXPR using the condition COND. Returns the simplified
2570 expression (or EXPR unchanged, if no simplification was possible).
2571 Wrapper around tree_simplify_using_condition_1 that ensures that chains
2572 of simple operations in definitions of ssa names in COND are expanded,
2573 so that things like casts or incrementing the value of the bound before
2574 the loop do not cause us to fail. */
2577 tree_simplify_using_condition (tree cond
, tree expr
)
2579 cond
= expand_simple_operations (cond
);
2581 return tree_simplify_using_condition_1 (cond
, expr
);
2584 /* Tries to simplify EXPR using the conditions on entry to LOOP.
2585 Returns the simplified expression (or EXPR unchanged, if no
2586 simplification was possible). */
2589 simplify_using_initial_conditions (class loop
*loop
, tree expr
)
2594 tree cond
, expanded
, backup
;
2597 if (TREE_CODE (expr
) == INTEGER_CST
)
2600 backup
= expanded
= expand_simple_operations (expr
);
2602 /* Limit walking the dominators to avoid quadraticness in
2603 the number of BBs times the number of loops in degenerate
2605 for (bb
= loop
->header
;
2606 bb
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
) && cnt
< MAX_DOMINATORS_TO_WALK
;
2607 bb
= get_immediate_dominator (CDI_DOMINATORS
, bb
))
2609 if (!single_pred_p (bb
))
2611 e
= single_pred_edge (bb
);
2613 if (!(e
->flags
& (EDGE_TRUE_VALUE
| EDGE_FALSE_VALUE
)))
2616 stmt
= last_stmt (e
->src
);
2617 cond
= fold_build2 (gimple_cond_code (stmt
),
2619 gimple_cond_lhs (stmt
),
2620 gimple_cond_rhs (stmt
));
2621 if (e
->flags
& EDGE_FALSE_VALUE
)
2622 cond
= invert_truthvalue (cond
);
2623 expanded
= tree_simplify_using_condition (cond
, expanded
);
2624 /* Break if EXPR is simplified to const values. */
2626 && (integer_zerop (expanded
) || integer_nonzerop (expanded
)))
2632 /* Return the original expression if no simplification is done. */
2633 return operand_equal_p (backup
, expanded
, 0) ? expr
: expanded
;
2636 /* Tries to simplify EXPR using the evolutions of the loop invariants
2637 in the superloops of LOOP. Returns the simplified expression
2638 (or EXPR unchanged, if no simplification was possible). */
2641 simplify_using_outer_evolutions (class loop
*loop
, tree expr
)
2643 enum tree_code code
= TREE_CODE (expr
);
2647 if (is_gimple_min_invariant (expr
))
2650 if (code
== TRUTH_OR_EXPR
2651 || code
== TRUTH_AND_EXPR
2652 || code
== COND_EXPR
)
2656 e0
= simplify_using_outer_evolutions (loop
, TREE_OPERAND (expr
, 0));
2657 if (TREE_OPERAND (expr
, 0) != e0
)
2660 e1
= simplify_using_outer_evolutions (loop
, TREE_OPERAND (expr
, 1));
2661 if (TREE_OPERAND (expr
, 1) != e1
)
2664 if (code
== COND_EXPR
)
2666 e2
= simplify_using_outer_evolutions (loop
, TREE_OPERAND (expr
, 2));
2667 if (TREE_OPERAND (expr
, 2) != e2
)
2675 if (code
== COND_EXPR
)
2676 expr
= fold_build3 (code
, boolean_type_node
, e0
, e1
, e2
);
2678 expr
= fold_build2 (code
, boolean_type_node
, e0
, e1
);
2684 e
= instantiate_parameters (loop
, expr
);
2685 if (is_gimple_min_invariant (e
))
2691 /* Returns true if EXIT is the only possible exit from LOOP. */
2694 loop_only_exit_p (const class loop
*loop
, basic_block
*body
, const_edge exit
)
2696 gimple_stmt_iterator bsi
;
2699 if (exit
!= single_exit (loop
))
2702 for (i
= 0; i
< loop
->num_nodes
; i
++)
2703 for (bsi
= gsi_start_bb (body
[i
]); !gsi_end_p (bsi
); gsi_next (&bsi
))
2704 if (stmt_can_terminate_bb_p (gsi_stmt (bsi
)))
2710 /* Stores description of number of iterations of LOOP derived from
2711 EXIT (an exit edge of the LOOP) in NITER. Returns true if some useful
2712 information could be derived (and fields of NITER have meaning described
2713 in comments at class tree_niter_desc declaration), false otherwise.
2714 When EVERY_ITERATION is true, only tests that are known to be executed
2715 every iteration are considered (i.e. only test that alone bounds the loop).
2716 If AT_STMT is not NULL, this function stores LOOP's condition statement in
2717 it when returning true. */
2720 number_of_iterations_exit_assumptions (class loop
*loop
, edge exit
,
2721 class tree_niter_desc
*niter
,
2722 gcond
**at_stmt
, bool every_iteration
,
2729 enum tree_code code
;
2733 /* The condition at a fake exit (if it exists) does not control its
2735 if (exit
->flags
& EDGE_FAKE
)
2738 /* Nothing to analyze if the loop is known to be infinite. */
2739 if (loop_constraint_set_p (loop
, LOOP_C_INFINITE
))
2742 safe
= dominated_by_p (CDI_DOMINATORS
, loop
->latch
, exit
->src
);
2744 if (every_iteration
&& !safe
)
2747 niter
->assumptions
= boolean_false_node
;
2748 niter
->control
.base
= NULL_TREE
;
2749 niter
->control
.step
= NULL_TREE
;
2750 niter
->control
.no_overflow
= false;
2751 last
= last_stmt (exit
->src
);
2754 stmt
= dyn_cast
<gcond
*> (last
);
2761 /* We want the condition for staying inside loop. */
2762 code
= gimple_cond_code (stmt
);
2763 if (exit
->flags
& EDGE_TRUE_VALUE
)
2764 code
= invert_tree_comparison (code
, false);
2779 op0
= gimple_cond_lhs (stmt
);
2780 op1
= gimple_cond_rhs (stmt
);
2781 type
= TREE_TYPE (op0
);
2783 if (TREE_CODE (type
) != INTEGER_TYPE
2784 && !POINTER_TYPE_P (type
))
2787 tree iv0_niters
= NULL_TREE
;
2788 if (!simple_iv_with_niters (loop
, loop_containing_stmt (stmt
),
2789 op0
, &iv0
, safe
? &iv0_niters
: NULL
, false))
2790 return number_of_iterations_bitcount (loop
, exit
, code
, niter
);
2791 tree iv1_niters
= NULL_TREE
;
2792 if (!simple_iv_with_niters (loop
, loop_containing_stmt (stmt
),
2793 op1
, &iv1
, safe
? &iv1_niters
: NULL
, false))
2795 /* Give up on complicated case. */
2796 if (iv0_niters
&& iv1_niters
)
2799 /* We don't want to see undefined signed overflow warnings while
2800 computing the number of iterations. */
2801 fold_defer_overflow_warnings ();
2803 iv0
.base
= expand_simple_operations (iv0
.base
);
2804 iv1
.base
= expand_simple_operations (iv1
.base
);
2805 bool body_from_caller
= true;
2808 body
= get_loop_body (loop
);
2809 body_from_caller
= false;
2811 bool only_exit_p
= loop_only_exit_p (loop
, body
, exit
);
2812 if (!body_from_caller
)
2814 if (!number_of_iterations_cond (loop
, type
, &iv0
, code
, &iv1
, niter
,
2817 fold_undefer_and_ignore_overflow_warnings ();
2821 /* Incorporate additional assumption implied by control iv. */
2822 tree iv_niters
= iv0_niters
? iv0_niters
: iv1_niters
;
2825 tree assumption
= fold_build2 (LE_EXPR
, boolean_type_node
, niter
->niter
,
2826 fold_convert (TREE_TYPE (niter
->niter
),
2829 if (!integer_nonzerop (assumption
))
2830 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
2831 niter
->assumptions
, assumption
);
2833 /* Refine upper bound if possible. */
2834 if (TREE_CODE (iv_niters
) == INTEGER_CST
2835 && niter
->max
> wi::to_widest (iv_niters
))
2836 niter
->max
= wi::to_widest (iv_niters
);
2839 /* There is no assumptions if the loop is known to be finite. */
2840 if (!integer_zerop (niter
->assumptions
)
2841 && loop_constraint_set_p (loop
, LOOP_C_FINITE
))
2842 niter
->assumptions
= boolean_true_node
;
2846 niter
->assumptions
= simplify_using_outer_evolutions (loop
,
2847 niter
->assumptions
);
2848 niter
->may_be_zero
= simplify_using_outer_evolutions (loop
,
2849 niter
->may_be_zero
);
2850 niter
->niter
= simplify_using_outer_evolutions (loop
, niter
->niter
);
2854 = simplify_using_initial_conditions (loop
,
2855 niter
->assumptions
);
2857 = simplify_using_initial_conditions (loop
,
2858 niter
->may_be_zero
);
2860 fold_undefer_and_ignore_overflow_warnings ();
2862 /* If NITER has simplified into a constant, update MAX. */
2863 if (TREE_CODE (niter
->niter
) == INTEGER_CST
)
2864 niter
->max
= wi::to_widest (niter
->niter
);
2866 return (!integer_zerop (niter
->assumptions
));
2869 /* Like number_of_iterations_exit_assumptions, but return TRUE only if
2870 the niter information holds unconditionally. */
2873 number_of_iterations_exit (class loop
*loop
, edge exit
,
2874 class tree_niter_desc
*niter
,
2875 bool warn
, bool every_iteration
,
2879 if (!number_of_iterations_exit_assumptions (loop
, exit
, niter
,
2880 &stmt
, every_iteration
, body
))
2883 if (integer_nonzerop (niter
->assumptions
))
2886 if (warn
&& dump_enabled_p ())
2887 dump_printf_loc (MSG_MISSED_OPTIMIZATION
, stmt
,
2888 "missed loop optimization: niters analysis ends up "
2889 "with assumptions.\n");
2894 /* Try to determine the number of iterations of LOOP. If we succeed,
2895 expression giving number of iterations is returned and *EXIT is
2896 set to the edge from that the information is obtained. Otherwise
2897 chrec_dont_know is returned. */
2900 find_loop_niter (class loop
*loop
, edge
*exit
)
2903 auto_vec
<edge
> exits
= get_loop_exit_edges (loop
);
2905 tree niter
= NULL_TREE
, aniter
;
2906 class tree_niter_desc desc
;
2909 FOR_EACH_VEC_ELT (exits
, i
, ex
)
2911 if (!number_of_iterations_exit (loop
, ex
, &desc
, false))
2914 if (integer_nonzerop (desc
.may_be_zero
))
2916 /* We exit in the first iteration through this exit.
2917 We won't find anything better. */
2918 niter
= build_int_cst (unsigned_type_node
, 0);
2923 if (!integer_zerop (desc
.may_be_zero
))
2926 aniter
= desc
.niter
;
2930 /* Nothing recorded yet. */
2936 /* Prefer constants, the lower the better. */
2937 if (TREE_CODE (aniter
) != INTEGER_CST
)
2940 if (TREE_CODE (niter
) != INTEGER_CST
)
2947 if (tree_int_cst_lt (aniter
, niter
))
2955 return niter
? niter
: chrec_dont_know
;
2958 /* Return true if loop is known to have bounded number of iterations. */
2961 finite_loop_p (class loop
*loop
)
2966 flags
= flags_from_decl_or_type (current_function_decl
);
2967 if ((flags
& (ECF_CONST
|ECF_PURE
)) && !(flags
& ECF_LOOPING_CONST_OR_PURE
))
2969 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2970 fprintf (dump_file
, "Found loop %i to be finite: it is within pure or const function.\n",
2975 if (loop
->any_upper_bound
2976 || max_loop_iterations (loop
, &nit
))
2978 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2979 fprintf (dump_file
, "Found loop %i to be finite: upper bound found.\n",
2987 auto_vec
<edge
> exits
= get_loop_exit_edges (loop
);
2990 /* If the loop has a normal exit, we can assume it will terminate. */
2991 FOR_EACH_VEC_ELT (exits
, i
, ex
)
2992 if (!(ex
->flags
& (EDGE_EH
| EDGE_ABNORMAL
| EDGE_FAKE
)))
2995 fprintf (dump_file
, "Assume loop %i to be finite: it has an exit "
2996 "and -ffinite-loops is on.\n", loop
->num
);
3006 Analysis of a number of iterations of a loop by a brute-force evaluation.
3010 /* Bound on the number of iterations we try to evaluate. */
3012 #define MAX_ITERATIONS_TO_TRACK \
3013 ((unsigned) param_max_iterations_to_track)
3015 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
3016 result by a chain of operations such that all but exactly one of their
3017 operands are constants. */
3020 chain_of_csts_start (class loop
*loop
, tree x
)
3022 gimple
*stmt
= SSA_NAME_DEF_STMT (x
);
3024 basic_block bb
= gimple_bb (stmt
);
3025 enum tree_code code
;
3028 || !flow_bb_inside_loop_p (loop
, bb
))
3031 if (gimple_code (stmt
) == GIMPLE_PHI
)
3033 if (bb
== loop
->header
)
3034 return as_a
<gphi
*> (stmt
);
3039 if (gimple_code (stmt
) != GIMPLE_ASSIGN
3040 || gimple_assign_rhs_class (stmt
) == GIMPLE_TERNARY_RHS
)
3043 code
= gimple_assign_rhs_code (stmt
);
3044 if (gimple_references_memory_p (stmt
)
3045 || TREE_CODE_CLASS (code
) == tcc_reference
3046 || (code
== ADDR_EXPR
3047 && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt
))))
3050 use
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
3051 if (use
== NULL_TREE
)
3054 return chain_of_csts_start (loop
, use
);
3057 /* Determines whether the expression X is derived from a result of a phi node
3058 in header of LOOP such that
3060 * the derivation of X consists only from operations with constants
3061 * the initial value of the phi node is constant
3062 * the value of the phi node in the next iteration can be derived from the
3063 value in the current iteration by a chain of operations with constants,
3064 or is also a constant
3066 If such phi node exists, it is returned, otherwise NULL is returned. */
3069 get_base_for (class loop
*loop
, tree x
)
3074 if (is_gimple_min_invariant (x
))
3077 phi
= chain_of_csts_start (loop
, x
);
3081 init
= PHI_ARG_DEF_FROM_EDGE (phi
, loop_preheader_edge (loop
));
3082 next
= PHI_ARG_DEF_FROM_EDGE (phi
, loop_latch_edge (loop
));
3084 if (!is_gimple_min_invariant (init
))
3087 if (TREE_CODE (next
) == SSA_NAME
3088 && chain_of_csts_start (loop
, next
) != phi
)
3094 /* Given an expression X, then
3096 * if X is NULL_TREE, we return the constant BASE.
3097 * if X is a constant, we return the constant X.
3098 * otherwise X is a SSA name, whose value in the considered loop is derived
3099 by a chain of operations with constant from a result of a phi node in
3100 the header of the loop. Then we return value of X when the value of the
3101 result of this phi node is given by the constant BASE. */
3104 get_val_for (tree x
, tree base
)
3108 gcc_checking_assert (is_gimple_min_invariant (base
));
3112 else if (is_gimple_min_invariant (x
))
3115 stmt
= SSA_NAME_DEF_STMT (x
);
3116 if (gimple_code (stmt
) == GIMPLE_PHI
)
3119 gcc_checking_assert (is_gimple_assign (stmt
));
3121 /* STMT must be either an assignment of a single SSA name or an
3122 expression involving an SSA name and a constant. Try to fold that
3123 expression using the value for the SSA name. */
3124 if (gimple_assign_ssa_name_copy_p (stmt
))
3125 return get_val_for (gimple_assign_rhs1 (stmt
), base
);
3126 else if (gimple_assign_rhs_class (stmt
) == GIMPLE_UNARY_RHS
3127 && TREE_CODE (gimple_assign_rhs1 (stmt
)) == SSA_NAME
)
3128 return fold_build1 (gimple_assign_rhs_code (stmt
),
3129 TREE_TYPE (gimple_assign_lhs (stmt
)),
3130 get_val_for (gimple_assign_rhs1 (stmt
), base
));
3131 else if (gimple_assign_rhs_class (stmt
) == GIMPLE_BINARY_RHS
)
3133 tree rhs1
= gimple_assign_rhs1 (stmt
);
3134 tree rhs2
= gimple_assign_rhs2 (stmt
);
3135 if (TREE_CODE (rhs1
) == SSA_NAME
)
3136 rhs1
= get_val_for (rhs1
, base
);
3137 else if (TREE_CODE (rhs2
) == SSA_NAME
)
3138 rhs2
= get_val_for (rhs2
, base
);
3141 return fold_build2 (gimple_assign_rhs_code (stmt
),
3142 TREE_TYPE (gimple_assign_lhs (stmt
)), rhs1
, rhs2
);
3149 /* Tries to count the number of iterations of LOOP till it exits by EXIT
3150 by brute force -- i.e. by determining the value of the operands of the
3151 condition at EXIT in first few iterations of the loop (assuming that
3152 these values are constant) and determining the first one in that the
3153 condition is not satisfied. Returns the constant giving the number
3154 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
3157 loop_niter_by_eval (class loop
*loop
, edge exit
)
3160 tree op
[2], val
[2], next
[2], aval
[2];
3166 cond
= last_stmt (exit
->src
);
3167 if (!cond
|| gimple_code (cond
) != GIMPLE_COND
)
3168 return chrec_dont_know
;
3170 cmp
= gimple_cond_code (cond
);
3171 if (exit
->flags
& EDGE_TRUE_VALUE
)
3172 cmp
= invert_tree_comparison (cmp
, false);
3182 op
[0] = gimple_cond_lhs (cond
);
3183 op
[1] = gimple_cond_rhs (cond
);
3187 return chrec_dont_know
;
3190 for (j
= 0; j
< 2; j
++)
3192 if (is_gimple_min_invariant (op
[j
]))
3195 next
[j
] = NULL_TREE
;
3200 phi
= get_base_for (loop
, op
[j
]);
3202 return chrec_dont_know
;
3203 val
[j
] = PHI_ARG_DEF_FROM_EDGE (phi
, loop_preheader_edge (loop
));
3204 next
[j
] = PHI_ARG_DEF_FROM_EDGE (phi
, loop_latch_edge (loop
));
3208 /* Don't issue signed overflow warnings. */
3209 fold_defer_overflow_warnings ();
3211 for (i
= 0; i
< MAX_ITERATIONS_TO_TRACK
; i
++)
3213 for (j
= 0; j
< 2; j
++)
3214 aval
[j
] = get_val_for (op
[j
], val
[j
]);
3216 acnd
= fold_binary (cmp
, boolean_type_node
, aval
[0], aval
[1]);
3217 if (acnd
&& integer_zerop (acnd
))
3219 fold_undefer_and_ignore_overflow_warnings ();
3220 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3222 "Proved that loop %d iterates %d times using brute force.\n",
3224 return build_int_cst (unsigned_type_node
, i
);
3227 for (j
= 0; j
< 2; j
++)
3230 val
[j
] = get_val_for (next
[j
], val
[j
]);
3231 if (!is_gimple_min_invariant (val
[j
]))
3233 fold_undefer_and_ignore_overflow_warnings ();
3234 return chrec_dont_know
;
3238 /* If the next iteration would use the same base values
3239 as the current one, there is no point looping further,
3240 all following iterations will be the same as this one. */
3241 if (val
[0] == aval
[0] && val
[1] == aval
[1])
3245 fold_undefer_and_ignore_overflow_warnings ();
3247 return chrec_dont_know
;
3250 /* Finds the exit of the LOOP by that the loop exits after a constant
3251 number of iterations and stores the exit edge to *EXIT. The constant
3252 giving the number of iterations of LOOP is returned. The number of
3253 iterations is determined using loop_niter_by_eval (i.e. by brute force
3254 evaluation). If we are unable to find the exit for that loop_niter_by_eval
3255 determines the number of iterations, chrec_dont_know is returned. */
3258 find_loop_niter_by_eval (class loop
*loop
, edge
*exit
)
3261 auto_vec
<edge
> exits
= get_loop_exit_edges (loop
);
3263 tree niter
= NULL_TREE
, aniter
;
3267 /* Loops with multiple exits are expensive to handle and less important. */
3268 if (!flag_expensive_optimizations
3269 && exits
.length () > 1)
3270 return chrec_dont_know
;
3272 FOR_EACH_VEC_ELT (exits
, i
, ex
)
3274 if (!just_once_each_iteration_p (loop
, ex
->src
))
3277 aniter
= loop_niter_by_eval (loop
, ex
);
3278 if (chrec_contains_undetermined (aniter
))
3282 && !tree_int_cst_lt (aniter
, niter
))
3289 return niter
? niter
: chrec_dont_know
;
3294 Analysis of upper bounds on number of iterations of a loop.
3298 static widest_int
derive_constant_upper_bound_ops (tree
, tree
,
3299 enum tree_code
, tree
);
3301 /* Returns a constant upper bound on the value of the right-hand side of
3302 an assignment statement STMT. */
3305 derive_constant_upper_bound_assign (gimple
*stmt
)
3307 enum tree_code code
= gimple_assign_rhs_code (stmt
);
3308 tree op0
= gimple_assign_rhs1 (stmt
);
3309 tree op1
= gimple_assign_rhs2 (stmt
);
3311 return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt
)),
3315 /* Returns a constant upper bound on the value of expression VAL. VAL
3316 is considered to be unsigned. If its type is signed, its value must
3320 derive_constant_upper_bound (tree val
)
3322 enum tree_code code
;
3325 extract_ops_from_tree (val
, &code
, &op0
, &op1
, &op2
);
3326 return derive_constant_upper_bound_ops (TREE_TYPE (val
), op0
, code
, op1
);
3329 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
3330 whose type is TYPE. The expression is considered to be unsigned. If
3331 its type is signed, its value must be nonnegative. */
3334 derive_constant_upper_bound_ops (tree type
, tree op0
,
3335 enum tree_code code
, tree op1
)
3338 widest_int bnd
, max
, cst
;
3341 if (INTEGRAL_TYPE_P (type
))
3342 maxt
= TYPE_MAX_VALUE (type
);
3344 maxt
= upper_bound_in_type (type
, type
);
3346 max
= wi::to_widest (maxt
);
3351 return wi::to_widest (op0
);
3354 subtype
= TREE_TYPE (op0
);
3355 if (!TYPE_UNSIGNED (subtype
)
3356 /* If TYPE is also signed, the fact that VAL is nonnegative implies
3357 that OP0 is nonnegative. */
3358 && TYPE_UNSIGNED (type
)
3359 && !tree_expr_nonnegative_p (op0
))
3361 /* If we cannot prove that the casted expression is nonnegative,
3362 we cannot establish more useful upper bound than the precision
3363 of the type gives us. */
3367 /* We now know that op0 is an nonnegative value. Try deriving an upper
3369 bnd
= derive_constant_upper_bound (op0
);
3371 /* If the bound does not fit in TYPE, max. value of TYPE could be
3373 if (wi::ltu_p (max
, bnd
))
3379 case POINTER_PLUS_EXPR
:
3381 if (TREE_CODE (op1
) != INTEGER_CST
3382 || !tree_expr_nonnegative_p (op0
))
3385 /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
3386 choose the most logical way how to treat this constant regardless
3387 of the signedness of the type. */
3388 cst
= wi::sext (wi::to_widest (op1
), TYPE_PRECISION (type
));
3389 if (code
!= MINUS_EXPR
)
3392 bnd
= derive_constant_upper_bound (op0
);
3394 if (wi::neg_p (cst
))
3397 /* Avoid CST == 0x80000... */
3398 if (wi::neg_p (cst
))
3401 /* OP0 + CST. We need to check that
3402 BND <= MAX (type) - CST. */
3404 widest_int mmax
= max
- cst
;
3405 if (wi::leu_p (bnd
, mmax
))
3412 /* OP0 - CST, where CST >= 0.
3414 If TYPE is signed, we have already verified that OP0 >= 0, and we
3415 know that the result is nonnegative. This implies that
3418 If TYPE is unsigned, we must additionally know that OP0 >= CST,
3419 otherwise the operation underflows.
3422 /* This should only happen if the type is unsigned; however, for
3423 buggy programs that use overflowing signed arithmetics even with
3424 -fno-wrapv, this condition may also be true for signed values. */
3425 if (wi::ltu_p (bnd
, cst
))
3428 if (TYPE_UNSIGNED (type
))
3430 tree tem
= fold_binary (GE_EXPR
, boolean_type_node
, op0
,
3431 wide_int_to_tree (type
, cst
));
3432 if (!tem
|| integer_nonzerop (tem
))
3441 case FLOOR_DIV_EXPR
:
3442 case EXACT_DIV_EXPR
:
3443 if (TREE_CODE (op1
) != INTEGER_CST
3444 || tree_int_cst_sign_bit (op1
))
3447 bnd
= derive_constant_upper_bound (op0
);
3448 return wi::udiv_floor (bnd
, wi::to_widest (op1
));
3451 if (TREE_CODE (op1
) != INTEGER_CST
3452 || tree_int_cst_sign_bit (op1
))
3454 return wi::to_widest (op1
);
3457 stmt
= SSA_NAME_DEF_STMT (op0
);
3458 if (gimple_code (stmt
) != GIMPLE_ASSIGN
3459 || gimple_assign_lhs (stmt
) != op0
)
3461 return derive_constant_upper_bound_assign (stmt
);
3468 /* Emit a -Waggressive-loop-optimizations warning if needed. */
3471 do_warn_aggressive_loop_optimizations (class loop
*loop
,
3472 widest_int i_bound
, gimple
*stmt
)
3474 /* Don't warn if the loop doesn't have known constant bound. */
3475 if (!loop
->nb_iterations
3476 || TREE_CODE (loop
->nb_iterations
) != INTEGER_CST
3477 || !warn_aggressive_loop_optimizations
3478 /* To avoid warning multiple times for the same loop,
3479 only start warning when we preserve loops. */
3480 || (cfun
->curr_properties
& PROP_loops
) == 0
3481 /* Only warn once per loop. */
3482 || loop
->warned_aggressive_loop_optimizations
3483 /* Only warn if undefined behavior gives us lower estimate than the
3484 known constant bound. */
3485 || wi::cmpu (i_bound
, wi::to_widest (loop
->nb_iterations
)) >= 0
3486 /* And undefined behavior happens unconditionally. */
3487 || !dominated_by_p (CDI_DOMINATORS
, loop
->latch
, gimple_bb (stmt
)))
3490 edge e
= single_exit (loop
);
3494 gimple
*estmt
= last_stmt (e
->src
);
3495 char buf
[WIDE_INT_PRINT_BUFFER_SIZE
];
3496 print_dec (i_bound
, buf
, TYPE_UNSIGNED (TREE_TYPE (loop
->nb_iterations
))
3497 ? UNSIGNED
: SIGNED
);
3498 auto_diagnostic_group d
;
3499 if (warning_at (gimple_location (stmt
), OPT_Waggressive_loop_optimizations
,
3500 "iteration %s invokes undefined behavior", buf
))
3501 inform (gimple_location (estmt
), "within this loop");
3502 loop
->warned_aggressive_loop_optimizations
= true;
3505 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
3506 is true if the loop is exited immediately after STMT, and this exit
3507 is taken at last when the STMT is executed BOUND + 1 times.
3508 REALISTIC is true if BOUND is expected to be close to the real number
3509 of iterations. UPPER is true if we are sure the loop iterates at most
3510 BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
3513 record_estimate (class loop
*loop
, tree bound
, const widest_int
&i_bound
,
3514 gimple
*at_stmt
, bool is_exit
, bool realistic
, bool upper
)
3518 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3520 fprintf (dump_file
, "Statement %s", is_exit
? "(exit)" : "");
3521 print_gimple_stmt (dump_file
, at_stmt
, 0, TDF_SLIM
);
3522 fprintf (dump_file
, " is %sexecuted at most ",
3523 upper
? "" : "probably ");
3524 print_generic_expr (dump_file
, bound
, TDF_SLIM
);
3525 fprintf (dump_file
, " (bounded by ");
3526 print_decu (i_bound
, dump_file
);
3527 fprintf (dump_file
, ") + 1 times in loop %d.\n", loop
->num
);
3530 /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
3531 real number of iterations. */
3532 if (TREE_CODE (bound
) != INTEGER_CST
)
3535 gcc_checking_assert (i_bound
== wi::to_widest (bound
));
3537 /* If we have a guaranteed upper bound, record it in the appropriate
3538 list, unless this is an !is_exit bound (i.e. undefined behavior in
3539 at_stmt) in a loop with known constant number of iterations. */
3542 || loop
->nb_iterations
== NULL_TREE
3543 || TREE_CODE (loop
->nb_iterations
) != INTEGER_CST
))
3545 class nb_iter_bound
*elt
= ggc_alloc
<nb_iter_bound
> ();
3547 elt
->bound
= i_bound
;
3548 elt
->stmt
= at_stmt
;
3549 elt
->is_exit
= is_exit
;
3550 elt
->next
= loop
->bounds
;
3554 /* If statement is executed on every path to the loop latch, we can directly
3555 infer the upper bound on the # of iterations of the loop. */
3556 if (!dominated_by_p (CDI_DOMINATORS
, loop
->latch
, gimple_bb (at_stmt
)))
3559 /* Update the number of iteration estimates according to the bound.
3560 If at_stmt is an exit then the loop latch is executed at most BOUND times,
3561 otherwise it can be executed BOUND + 1 times. We will lower the estimate
3562 later if such statement must be executed on last iteration */
3567 widest_int new_i_bound
= i_bound
+ delta
;
3569 /* If an overflow occurred, ignore the result. */
3570 if (wi::ltu_p (new_i_bound
, delta
))
3573 if (upper
&& !is_exit
)
3574 do_warn_aggressive_loop_optimizations (loop
, new_i_bound
, at_stmt
);
3575 record_niter_bound (loop
, new_i_bound
, realistic
, upper
);
3578 /* Records the control iv analyzed in NITER for LOOP if the iv is valid
3579 and doesn't overflow. */
3582 record_control_iv (class loop
*loop
, class tree_niter_desc
*niter
)
3584 struct control_iv
*iv
;
3586 if (!niter
->control
.base
|| !niter
->control
.step
)
3589 if (!integer_onep (niter
->assumptions
) || !niter
->control
.no_overflow
)
3592 iv
= ggc_alloc
<control_iv
> ();
3593 iv
->base
= niter
->control
.base
;
3594 iv
->step
= niter
->control
.step
;
3595 iv
->next
= loop
->control_ivs
;
3596 loop
->control_ivs
= iv
;
3601 /* This function returns TRUE if below conditions are satisfied:
3602 1) VAR is SSA variable.
3603 2) VAR is an IV:{base, step} in its defining loop.
3604 3) IV doesn't overflow.
3605 4) Both base and step are integer constants.
3606 5) Base is the MIN/MAX value depends on IS_MIN.
3607 Store value of base to INIT correspondingly. */
3610 get_cst_init_from_scev (tree var
, wide_int
*init
, bool is_min
)
3612 if (TREE_CODE (var
) != SSA_NAME
)
3615 gimple
*def_stmt
= SSA_NAME_DEF_STMT (var
);
3616 class loop
*loop
= loop_containing_stmt (def_stmt
);
3622 if (!simple_iv (loop
, loop
, var
, &iv
, false))
3625 if (!iv
.no_overflow
)
3628 if (TREE_CODE (iv
.base
) != INTEGER_CST
|| TREE_CODE (iv
.step
) != INTEGER_CST
)
3631 if (is_min
== tree_int_cst_sign_bit (iv
.step
))
3634 *init
= wi::to_wide (iv
.base
);
3638 /* Record the estimate on number of iterations of LOOP based on the fact that
3639 the induction variable BASE + STEP * i evaluated in STMT does not wrap and
3640 its values belong to the range <LOW, HIGH>. REALISTIC is true if the
3641 estimated number of iterations is expected to be close to the real one.
3642 UPPER is true if we are sure the induction variable does not wrap. */
3645 record_nonwrapping_iv (class loop
*loop
, tree base
, tree step
, gimple
*stmt
,
3646 tree low
, tree high
, bool realistic
, bool upper
)
3648 tree niter_bound
, extreme
, delta
;
3649 tree type
= TREE_TYPE (base
), unsigned_type
;
3650 tree orig_base
= base
;
3652 if (TREE_CODE (step
) != INTEGER_CST
|| integer_zerop (step
))
3655 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3657 fprintf (dump_file
, "Induction variable (");
3658 print_generic_expr (dump_file
, TREE_TYPE (base
), TDF_SLIM
);
3659 fprintf (dump_file
, ") ");
3660 print_generic_expr (dump_file
, base
, TDF_SLIM
);
3661 fprintf (dump_file
, " + ");
3662 print_generic_expr (dump_file
, step
, TDF_SLIM
);
3663 fprintf (dump_file
, " * iteration does not wrap in statement ");
3664 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
3665 fprintf (dump_file
, " in loop %d.\n", loop
->num
);
3668 unsigned_type
= unsigned_type_for (type
);
3669 base
= fold_convert (unsigned_type
, base
);
3670 step
= fold_convert (unsigned_type
, step
);
3672 if (tree_int_cst_sign_bit (step
))
3675 Value_Range
base_range (TREE_TYPE (orig_base
));
3676 if (get_range_query (cfun
)->range_of_expr (base_range
, orig_base
)
3677 && !base_range
.undefined_p ())
3678 max
= base_range
.upper_bound ();
3679 extreme
= fold_convert (unsigned_type
, low
);
3680 if (TREE_CODE (orig_base
) == SSA_NAME
3681 && TREE_CODE (high
) == INTEGER_CST
3682 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base
))
3683 && (base_range
.kind () == VR_RANGE
3684 || get_cst_init_from_scev (orig_base
, &max
, false))
3685 && wi::gts_p (wi::to_wide (high
), max
))
3686 base
= wide_int_to_tree (unsigned_type
, max
);
3687 else if (TREE_CODE (base
) != INTEGER_CST
3688 && dominated_by_p (CDI_DOMINATORS
,
3689 loop
->latch
, gimple_bb (stmt
)))
3690 base
= fold_convert (unsigned_type
, high
);
3691 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, base
, extreme
);
3692 step
= fold_build1 (NEGATE_EXPR
, unsigned_type
, step
);
3697 Value_Range
base_range (TREE_TYPE (orig_base
));
3698 if (get_range_query (cfun
)->range_of_expr (base_range
, orig_base
)
3699 && !base_range
.undefined_p ())
3700 min
= base_range
.lower_bound ();
3701 extreme
= fold_convert (unsigned_type
, high
);
3702 if (TREE_CODE (orig_base
) == SSA_NAME
3703 && TREE_CODE (low
) == INTEGER_CST
3704 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base
))
3705 && (base_range
.kind () == VR_RANGE
3706 || get_cst_init_from_scev (orig_base
, &min
, true))
3707 && wi::gts_p (min
, wi::to_wide (low
)))
3708 base
= wide_int_to_tree (unsigned_type
, min
);
3709 else if (TREE_CODE (base
) != INTEGER_CST
3710 && dominated_by_p (CDI_DOMINATORS
,
3711 loop
->latch
, gimple_bb (stmt
)))
3712 base
= fold_convert (unsigned_type
, low
);
3713 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, extreme
, base
);
3716 /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
3717 would get out of the range. */
3718 niter_bound
= fold_build2 (FLOOR_DIV_EXPR
, unsigned_type
, delta
, step
);
3719 widest_int max
= derive_constant_upper_bound (niter_bound
);
3720 record_estimate (loop
, niter_bound
, max
, stmt
, false, realistic
, upper
);
3723 /* Determine information about number of iterations a LOOP from the index
3724 IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
3725 guaranteed to be executed in every iteration of LOOP. Callback for
3735 idx_infer_loop_bounds (tree base
, tree
*idx
, void *dta
)
3737 struct ilb_data
*data
= (struct ilb_data
*) dta
;
3738 tree ev
, init
, step
;
3739 tree low
, high
, type
, next
;
3740 bool sign
, upper
= true, has_flexible_size
= false;
3741 class loop
*loop
= data
->loop
;
3743 if (TREE_CODE (base
) != ARRAY_REF
)
3746 /* For arrays that might have flexible sizes, it is not guaranteed that they
3747 do not really extend over their declared size. */
3748 if (array_ref_flexible_size_p (base
))
3750 has_flexible_size
= true;
3754 class loop
*dloop
= loop_containing_stmt (data
->stmt
);
3758 ev
= analyze_scalar_evolution (dloop
, *idx
);
3759 ev
= instantiate_parameters (loop
, ev
);
3760 init
= initial_condition (ev
);
3761 step
= evolution_part_in_loop_num (ev
, loop
->num
);
3765 || TREE_CODE (step
) != INTEGER_CST
3766 || integer_zerop (step
)
3767 || tree_contains_chrecs (init
, NULL
)
3768 || chrec_contains_symbols_defined_in_loop (init
, loop
->num
))
3771 low
= array_ref_low_bound (base
);
3772 high
= array_ref_up_bound (base
);
3774 /* The case of nonconstant bounds could be handled, but it would be
3776 if (TREE_CODE (low
) != INTEGER_CST
3778 || TREE_CODE (high
) != INTEGER_CST
)
3780 sign
= tree_int_cst_sign_bit (step
);
3781 type
= TREE_TYPE (step
);
3783 /* The array that might have flexible size most likely extends
3784 beyond its bounds. */
3785 if (has_flexible_size
3786 && operand_equal_p (low
, high
, 0))
3789 /* In case the relevant bound of the array does not fit in type, or
3790 it does, but bound + step (in type) still belongs into the range of the
3791 array, the index may wrap and still stay within the range of the array
3792 (consider e.g. if the array is indexed by the full range of
3795 To make things simpler, we require both bounds to fit into type, although
3796 there are cases where this would not be strictly necessary. */
3797 if (!int_fits_type_p (high
, type
)
3798 || !int_fits_type_p (low
, type
))
3800 low
= fold_convert (type
, low
);
3801 high
= fold_convert (type
, high
);
3804 next
= fold_binary (PLUS_EXPR
, type
, low
, step
);
3806 next
= fold_binary (PLUS_EXPR
, type
, high
, step
);
3808 if (tree_int_cst_compare (low
, next
) <= 0
3809 && tree_int_cst_compare (next
, high
) <= 0)
3812 /* If access is not executed on every iteration, we must ensure that overlow
3813 may not make the access valid later. */
3814 if (!dominated_by_p (CDI_DOMINATORS
, loop
->latch
, gimple_bb (data
->stmt
))
3815 && scev_probably_wraps_p (NULL_TREE
,
3816 initial_condition_in_loop_num (ev
, loop
->num
),
3817 step
, data
->stmt
, loop
, true))
3820 record_nonwrapping_iv (loop
, init
, step
, data
->stmt
, low
, high
, false, upper
);
3824 /* Determine information about number of iterations a LOOP from the bounds
3825 of arrays in the data reference REF accessed in STMT. RELIABLE is true if
3826 STMT is guaranteed to be executed in every iteration of LOOP.*/
3829 infer_loop_bounds_from_ref (class loop
*loop
, gimple
*stmt
, tree ref
)
3831 struct ilb_data data
;
3835 for_each_index (&ref
, idx_infer_loop_bounds
, &data
);
3838 /* Determine information about number of iterations of a LOOP from the way
3839 arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
3840 executed in every iteration of LOOP. */
3843 infer_loop_bounds_from_array (class loop
*loop
, gimple
*stmt
)
3845 if (is_gimple_assign (stmt
))
3847 tree op0
= gimple_assign_lhs (stmt
);
3848 tree op1
= gimple_assign_rhs1 (stmt
);
3850 /* For each memory access, analyze its access function
3851 and record a bound on the loop iteration domain. */
3852 if (REFERENCE_CLASS_P (op0
))
3853 infer_loop_bounds_from_ref (loop
, stmt
, op0
);
3855 if (REFERENCE_CLASS_P (op1
))
3856 infer_loop_bounds_from_ref (loop
, stmt
, op1
);
3858 else if (is_gimple_call (stmt
))
3861 unsigned i
, n
= gimple_call_num_args (stmt
);
3863 lhs
= gimple_call_lhs (stmt
);
3864 if (lhs
&& REFERENCE_CLASS_P (lhs
))
3865 infer_loop_bounds_from_ref (loop
, stmt
, lhs
);
3867 for (i
= 0; i
< n
; i
++)
3869 arg
= gimple_call_arg (stmt
, i
);
3870 if (REFERENCE_CLASS_P (arg
))
3871 infer_loop_bounds_from_ref (loop
, stmt
, arg
);
3876 /* Determine information about number of iterations of a LOOP from the fact
3877 that pointer arithmetics in STMT does not overflow. */
3880 infer_loop_bounds_from_pointer_arith (class loop
*loop
, gimple
*stmt
)
3882 tree def
, base
, step
, scev
, type
, low
, high
;
3885 if (!is_gimple_assign (stmt
)
3886 || gimple_assign_rhs_code (stmt
) != POINTER_PLUS_EXPR
)
3889 def
= gimple_assign_lhs (stmt
);
3890 if (TREE_CODE (def
) != SSA_NAME
)
3893 type
= TREE_TYPE (def
);
3894 if (!nowrap_type_p (type
))
3897 ptr
= gimple_assign_rhs1 (stmt
);
3898 if (!expr_invariant_in_loop_p (loop
, ptr
))
3901 var
= gimple_assign_rhs2 (stmt
);
3902 if (TYPE_PRECISION (type
) != TYPE_PRECISION (TREE_TYPE (var
)))
3905 class loop
*uloop
= loop_containing_stmt (stmt
);
3906 scev
= instantiate_parameters (loop
, analyze_scalar_evolution (uloop
, def
));
3907 if (chrec_contains_undetermined (scev
))
3910 base
= initial_condition_in_loop_num (scev
, loop
->num
);
3911 step
= evolution_part_in_loop_num (scev
, loop
->num
);
3914 || TREE_CODE (step
) != INTEGER_CST
3915 || tree_contains_chrecs (base
, NULL
)
3916 || chrec_contains_symbols_defined_in_loop (base
, loop
->num
))
3919 low
= lower_bound_in_type (type
, type
);
3920 high
= upper_bound_in_type (type
, type
);
3922 /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
3923 produce a NULL pointer. The contrary would mean NULL points to an object,
3924 while NULL is supposed to compare unequal with the address of all objects.
3925 Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
3926 NULL pointer since that would mean wrapping, which we assume here not to
3927 happen. So, we can exclude NULL from the valid range of pointer
3929 if (flag_delete_null_pointer_checks
&& int_cst_value (low
) == 0)
3930 low
= build_int_cstu (TREE_TYPE (low
), TYPE_ALIGN_UNIT (TREE_TYPE (type
)));
3932 record_nonwrapping_iv (loop
, base
, step
, stmt
, low
, high
, false, true);
3935 /* Determine information about number of iterations of a LOOP from the fact
3936 that signed arithmetics in STMT does not overflow. */
3939 infer_loop_bounds_from_signedness (class loop
*loop
, gimple
*stmt
)
3941 tree def
, base
, step
, scev
, type
, low
, high
;
3943 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
3946 def
= gimple_assign_lhs (stmt
);
3948 if (TREE_CODE (def
) != SSA_NAME
)
3951 type
= TREE_TYPE (def
);
3952 if (!INTEGRAL_TYPE_P (type
)
3953 || !TYPE_OVERFLOW_UNDEFINED (type
))
3956 scev
= instantiate_parameters (loop
, analyze_scalar_evolution (loop
, def
));
3957 if (chrec_contains_undetermined (scev
))
3960 base
= initial_condition_in_loop_num (scev
, loop
->num
);
3961 step
= evolution_part_in_loop_num (scev
, loop
->num
);
3964 || TREE_CODE (step
) != INTEGER_CST
3965 || tree_contains_chrecs (base
, NULL
)
3966 || chrec_contains_symbols_defined_in_loop (base
, loop
->num
))
3969 low
= lower_bound_in_type (type
, type
);
3970 high
= upper_bound_in_type (type
, type
);
3971 Value_Range
r (TREE_TYPE (def
));
3972 get_range_query (cfun
)->range_of_expr (r
, def
);
3973 if (r
.kind () == VR_RANGE
)
3975 low
= wide_int_to_tree (type
, r
.lower_bound ());
3976 high
= wide_int_to_tree (type
, r
.upper_bound ());
3979 record_nonwrapping_iv (loop
, base
, step
, stmt
, low
, high
, false, true);
3982 /* The following analyzers are extracting informations on the bounds
3983 of LOOP from the following undefined behaviors:
3985 - data references should not access elements over the statically
3988 - signed variables should not overflow when flag_wrapv is not set.
3992 infer_loop_bounds_from_undefined (class loop
*loop
, basic_block
*bbs
)
3995 gimple_stmt_iterator bsi
;
3999 for (i
= 0; i
< loop
->num_nodes
; i
++)
4003 /* If BB is not executed in each iteration of the loop, we cannot
4004 use the operations in it to infer reliable upper bound on the
4005 # of iterations of the loop. However, we can use it as a guess.
4006 Reliable guesses come only from array bounds. */
4007 reliable
= dominated_by_p (CDI_DOMINATORS
, loop
->latch
, bb
);
4009 for (bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
4011 gimple
*stmt
= gsi_stmt (bsi
);
4013 infer_loop_bounds_from_array (loop
, stmt
);
4017 infer_loop_bounds_from_signedness (loop
, stmt
);
4018 infer_loop_bounds_from_pointer_arith (loop
, stmt
);
4025 /* Compare wide ints, callback for qsort. */
4028 wide_int_cmp (const void *p1
, const void *p2
)
4030 const widest_int
*d1
= (const widest_int
*) p1
;
4031 const widest_int
*d2
= (const widest_int
*) p2
;
4032 return wi::cmpu (*d1
, *d2
);
4035 /* Return index of BOUND in BOUNDS array sorted in increasing order.
4036 Lookup by binary search. */
4039 bound_index (const vec
<widest_int
> &bounds
, const widest_int
&bound
)
4041 unsigned int end
= bounds
.length ();
4042 unsigned int begin
= 0;
4044 /* Find a matching index by means of a binary search. */
4045 while (begin
!= end
)
4047 unsigned int middle
= (begin
+ end
) / 2;
4048 widest_int index
= bounds
[middle
];
4052 else if (wi::ltu_p (index
, bound
))
4060 /* We recorded loop bounds only for statements dominating loop latch (and thus
4061 executed each loop iteration). If there are any bounds on statements not
4062 dominating the loop latch we can improve the estimate by walking the loop
4063 body and seeing if every path from loop header to loop latch contains
4064 some bounded statement. */
4067 discover_iteration_bound_by_body_walk (class loop
*loop
)
4069 class nb_iter_bound
*elt
;
4070 auto_vec
<widest_int
> bounds
;
4071 vec
<vec
<basic_block
> > queues
= vNULL
;
4072 vec
<basic_block
> queue
= vNULL
;
4073 ptrdiff_t queue_index
;
4074 ptrdiff_t latch_index
= 0;
4076 /* Discover what bounds may interest us. */
4077 for (elt
= loop
->bounds
; elt
; elt
= elt
->next
)
4079 widest_int bound
= elt
->bound
;
4081 /* Exit terminates loop at given iteration, while non-exits produce undefined
4082 effect on the next iteration. */
4086 /* If an overflow occurred, ignore the result. */
4091 if (!loop
->any_upper_bound
4092 || wi::ltu_p (bound
, loop
->nb_iterations_upper_bound
))
4093 bounds
.safe_push (bound
);
4096 /* Exit early if there is nothing to do. */
4097 if (!bounds
.exists ())
4100 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4101 fprintf (dump_file
, " Trying to walk loop body to reduce the bound.\n");
4103 /* Sort the bounds in decreasing order. */
4104 bounds
.qsort (wide_int_cmp
);
4106 /* For every basic block record the lowest bound that is guaranteed to
4107 terminate the loop. */
4109 hash_map
<basic_block
, ptrdiff_t> bb_bounds
;
4110 for (elt
= loop
->bounds
; elt
; elt
= elt
->next
)
4112 widest_int bound
= elt
->bound
;
4116 /* If an overflow occurred, ignore the result. */
4121 if (!loop
->any_upper_bound
4122 || wi::ltu_p (bound
, loop
->nb_iterations_upper_bound
))
4124 ptrdiff_t index
= bound_index (bounds
, bound
);
4125 ptrdiff_t *entry
= bb_bounds
.get (gimple_bb (elt
->stmt
));
4127 bb_bounds
.put (gimple_bb (elt
->stmt
), index
);
4128 else if ((ptrdiff_t)*entry
> index
)
4133 hash_map
<basic_block
, ptrdiff_t> block_priority
;
4135 /* Perform shortest path discovery loop->header ... loop->latch.
4137 The "distance" is given by the smallest loop bound of basic block
4138 present in the path and we look for path with largest smallest bound
4141 To avoid the need for fibonacci heap on double ints we simply compress
4142 double ints into indexes to BOUNDS array and then represent the queue
4143 as arrays of queues for every index.
4144 Index of BOUNDS.length() means that the execution of given BB has
4145 no bounds determined.
4147 VISITED is a pointer map translating basic block into smallest index
4148 it was inserted into the priority queue with. */
4151 /* Start walk in loop header with index set to infinite bound. */
4152 queue_index
= bounds
.length ();
4153 queues
.safe_grow_cleared (queue_index
+ 1, true);
4154 queue
.safe_push (loop
->header
);
4155 queues
[queue_index
] = queue
;
4156 block_priority
.put (loop
->header
, queue_index
);
4158 for (; queue_index
>= 0; queue_index
--)
4160 if (latch_index
< queue_index
)
4162 while (queues
[queue_index
].length ())
4165 ptrdiff_t bound_index
= queue_index
;
4169 queue
= queues
[queue_index
];
4172 /* OK, we later inserted the BB with lower priority, skip it. */
4173 if (*block_priority
.get (bb
) > queue_index
)
4176 /* See if we can improve the bound. */
4177 ptrdiff_t *entry
= bb_bounds
.get (bb
);
4178 if (entry
&& *entry
< bound_index
)
4179 bound_index
= *entry
;
4181 /* Insert succesors into the queue, watch for latch edge
4182 and record greatest index we saw. */
4183 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
4185 bool insert
= false;
4187 if (loop_exit_edge_p (loop
, e
))
4190 if (e
== loop_latch_edge (loop
)
4191 && latch_index
< bound_index
)
4192 latch_index
= bound_index
;
4193 else if (!(entry
= block_priority
.get (e
->dest
)))
4196 block_priority
.put (e
->dest
, bound_index
);
4198 else if (*entry
< bound_index
)
4201 *entry
= bound_index
;
4205 queues
[bound_index
].safe_push (e
->dest
);
4209 queues
[queue_index
].release ();
4212 gcc_assert (latch_index
>= 0);
4213 if ((unsigned)latch_index
< bounds
.length ())
4215 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4217 fprintf (dump_file
, "Found better loop bound ");
4218 print_decu (bounds
[latch_index
], dump_file
);
4219 fprintf (dump_file
, "\n");
4221 record_niter_bound (loop
, bounds
[latch_index
], false, true);
4227 /* See if every path cross the loop goes through a statement that is known
4228 to not execute at the last iteration. In that case we can decrese iteration
4232 maybe_lower_iteration_bound (class loop
*loop
)
4234 hash_set
<gimple
*> *not_executed_last_iteration
= NULL
;
4235 class nb_iter_bound
*elt
;
4236 bool found_exit
= false;
4237 auto_vec
<basic_block
> queue
;
4240 /* Collect all statements with interesting (i.e. lower than
4241 nb_iterations_upper_bound) bound on them.
4243 TODO: Due to the way record_estimate choose estimates to store, the bounds
4244 will be always nb_iterations_upper_bound-1. We can change this to record
4245 also statements not dominating the loop latch and update the walk bellow
4246 to the shortest path algorithm. */
4247 for (elt
= loop
->bounds
; elt
; elt
= elt
->next
)
4250 && wi::ltu_p (elt
->bound
, loop
->nb_iterations_upper_bound
))
4252 if (!not_executed_last_iteration
)
4253 not_executed_last_iteration
= new hash_set
<gimple
*>;
4254 not_executed_last_iteration
->add (elt
->stmt
);
4257 if (!not_executed_last_iteration
)
4260 /* Start DFS walk in the loop header and see if we can reach the
4261 loop latch or any of the exits (including statements with side
4262 effects that may terminate the loop otherwise) without visiting
4263 any of the statements known to have undefined effect on the last
4265 queue
.safe_push (loop
->header
);
4266 visited
= BITMAP_ALLOC (NULL
);
4267 bitmap_set_bit (visited
, loop
->header
->index
);
4272 basic_block bb
= queue
.pop ();
4273 gimple_stmt_iterator gsi
;
4274 bool stmt_found
= false;
4276 /* Loop for possible exits and statements bounding the execution. */
4277 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
4279 gimple
*stmt
= gsi_stmt (gsi
);
4280 if (not_executed_last_iteration
->contains (stmt
))
4285 if (gimple_has_side_effects (stmt
))
4294 /* If no bounding statement is found, continue the walk. */
4300 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
4302 if (loop_exit_edge_p (loop
, e
)
4303 || e
== loop_latch_edge (loop
))
4308 if (bitmap_set_bit (visited
, e
->dest
->index
))
4309 queue
.safe_push (e
->dest
);
4313 while (queue
.length () && !found_exit
);
4315 /* If every path through the loop reach bounding statement before exit,
4316 then we know the last iteration of the loop will have undefined effect
4317 and we can decrease number of iterations. */
4321 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4322 fprintf (dump_file
, "Reducing loop iteration estimate by 1; "
4323 "undefined statement must be executed at the last iteration.\n");
4324 record_niter_bound (loop
, loop
->nb_iterations_upper_bound
- 1,
4328 BITMAP_FREE (visited
);
4329 delete not_executed_last_iteration
;
4332 /* Get expected upper bound for number of loop iterations for
4333 BUILT_IN_EXPECT_WITH_PROBABILITY for a condition COND. */
4336 get_upper_bound_based_on_builtin_expr_with_prob (gcond
*cond
)
4341 tree lhs
= gimple_cond_lhs (cond
);
4342 if (TREE_CODE (lhs
) != SSA_NAME
)
4345 gimple
*stmt
= SSA_NAME_DEF_STMT (gimple_cond_lhs (cond
));
4346 gcall
*def
= dyn_cast
<gcall
*> (stmt
);
4350 tree decl
= gimple_call_fndecl (def
);
4352 || !fndecl_built_in_p (decl
, BUILT_IN_EXPECT_WITH_PROBABILITY
)
4353 || gimple_call_num_args (stmt
) != 3)
4356 tree c
= gimple_call_arg (def
, 1);
4357 tree condt
= TREE_TYPE (lhs
);
4358 tree res
= fold_build2 (gimple_cond_code (cond
),
4360 gimple_cond_rhs (cond
));
4361 if (TREE_CODE (res
) != INTEGER_CST
)
4365 tree prob
= gimple_call_arg (def
, 2);
4366 tree t
= TREE_TYPE (prob
);
4368 = build_real_from_int_cst (t
,
4370 if (integer_zerop (res
))
4371 prob
= fold_build2 (MINUS_EXPR
, t
, one
, prob
);
4372 tree r
= fold_build2 (RDIV_EXPR
, t
, one
, prob
);
4373 if (TREE_CODE (r
) != REAL_CST
)
4377 = real_to_integer (TREE_REAL_CST_PTR (r
));
4378 return build_int_cst (condt
, probi
);
4381 /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
4382 is true also use estimates derived from undefined behavior. */
4385 estimate_numbers_of_iterations (class loop
*loop
)
4389 class tree_niter_desc niter_desc
;
4394 /* Give up if we already have tried to compute an estimation. */
4395 if (loop
->estimate_state
!= EST_NOT_COMPUTED
)
4398 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4399 fprintf (dump_file
, "Estimating # of iterations of loop %d\n", loop
->num
);
4401 loop
->estimate_state
= EST_AVAILABLE
;
4403 /* If we have a measured profile, use it to estimate the number of
4404 iterations. Normally this is recorded by branch_prob right after
4405 reading the profile. In case we however found a new loop, record the
4408 Explicitly check for profile status so we do not report
4409 wrong prediction hitrates for guessed loop iterations heuristics.
4410 Do not recompute already recorded bounds - we ought to be better on
4411 updating iteration bounds than updating profile in general and thus
4412 recomputing iteration bounds later in the compilation process will just
4413 introduce random roundoff errors. */
4414 if (!loop
->any_estimate
4415 && loop
->header
->count
.reliable_p ())
4417 gcov_type nit
= expected_loop_iterations_unbounded (loop
);
4418 bound
= gcov_type_to_wide_int (nit
);
4419 record_niter_bound (loop
, bound
, true, false);
4422 /* Ensure that loop->nb_iterations is computed if possible. If it turns out
4423 to be constant, we avoid undefined behavior implied bounds and instead
4424 diagnose those loops with -Waggressive-loop-optimizations. */
4425 number_of_latch_executions (loop
);
4427 basic_block
*body
= get_loop_body (loop
);
4428 auto_vec
<edge
> exits
= get_loop_exit_edges (loop
, body
);
4429 likely_exit
= single_likely_exit (loop
, exits
);
4430 FOR_EACH_VEC_ELT (exits
, i
, ex
)
4432 if (ex
== likely_exit
)
4434 gimple
*stmt
= last_stmt (ex
->src
);
4437 gcond
*cond
= dyn_cast
<gcond
*> (stmt
);
4439 = get_upper_bound_based_on_builtin_expr_with_prob (cond
);
4440 if (niter_bound
!= NULL_TREE
)
4442 widest_int max
= derive_constant_upper_bound (niter_bound
);
4443 record_estimate (loop
, niter_bound
, max
, cond
,
4449 if (!number_of_iterations_exit (loop
, ex
, &niter_desc
,
4450 false, false, body
))
4453 niter
= niter_desc
.niter
;
4454 type
= TREE_TYPE (niter
);
4455 if (TREE_CODE (niter_desc
.may_be_zero
) != INTEGER_CST
)
4456 niter
= build3 (COND_EXPR
, type
, niter_desc
.may_be_zero
,
4457 build_int_cst (type
, 0),
4459 record_estimate (loop
, niter
, niter_desc
.max
,
4460 last_stmt (ex
->src
),
4461 true, ex
== likely_exit
, true);
4462 record_control_iv (loop
, &niter_desc
);
4465 if (flag_aggressive_loop_optimizations
)
4466 infer_loop_bounds_from_undefined (loop
, body
);
4469 discover_iteration_bound_by_body_walk (loop
);
4471 maybe_lower_iteration_bound (loop
);
4473 /* If we know the exact number of iterations of this loop, try to
4474 not break code with undefined behavior by not recording smaller
4475 maximum number of iterations. */
4476 if (loop
->nb_iterations
4477 && TREE_CODE (loop
->nb_iterations
) == INTEGER_CST
)
4479 loop
->any_upper_bound
= true;
4480 loop
->nb_iterations_upper_bound
= wi::to_widest (loop
->nb_iterations
);
4484 /* Sets NIT to the estimated number of executions of the latch of the
4485 LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
4486 large as the number of iterations. If we have no reliable estimate,
4487 the function returns false, otherwise returns true. */
4490 estimated_loop_iterations (class loop
*loop
, widest_int
*nit
)
4492 /* When SCEV information is available, try to update loop iterations
4493 estimate. Otherwise just return whatever we recorded earlier. */
4494 if (scev_initialized_p ())
4495 estimate_numbers_of_iterations (loop
);
4497 return (get_estimated_loop_iterations (loop
, nit
));
4500 /* Similar to estimated_loop_iterations, but returns the estimate only
4501 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4502 on the number of iterations of LOOP could not be derived, returns -1. */
4505 estimated_loop_iterations_int (class loop
*loop
)
4508 HOST_WIDE_INT hwi_nit
;
4510 if (!estimated_loop_iterations (loop
, &nit
))
4513 if (!wi::fits_shwi_p (nit
))
4515 hwi_nit
= nit
.to_shwi ();
4517 return hwi_nit
< 0 ? -1 : hwi_nit
;
4521 /* Sets NIT to an upper bound for the maximum number of executions of the
4522 latch of the LOOP. If we have no reliable estimate, the function returns
4523 false, otherwise returns true. */
4526 max_loop_iterations (class loop
*loop
, widest_int
*nit
)
4528 /* When SCEV information is available, try to update loop iterations
4529 estimate. Otherwise just return whatever we recorded earlier. */
4530 if (scev_initialized_p ())
4531 estimate_numbers_of_iterations (loop
);
4533 return get_max_loop_iterations (loop
, nit
);
4536 /* Similar to max_loop_iterations, but returns the estimate only
4537 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4538 on the number of iterations of LOOP could not be derived, returns -1. */
4541 max_loop_iterations_int (class loop
*loop
)
4544 HOST_WIDE_INT hwi_nit
;
4546 if (!max_loop_iterations (loop
, &nit
))
4549 if (!wi::fits_shwi_p (nit
))
4551 hwi_nit
= nit
.to_shwi ();
4553 return hwi_nit
< 0 ? -1 : hwi_nit
;
4556 /* Sets NIT to an likely upper bound for the maximum number of executions of the
4557 latch of the LOOP. If we have no reliable estimate, the function returns
4558 false, otherwise returns true. */
4561 likely_max_loop_iterations (class loop
*loop
, widest_int
*nit
)
4563 /* When SCEV information is available, try to update loop iterations
4564 estimate. Otherwise just return whatever we recorded earlier. */
4565 if (scev_initialized_p ())
4566 estimate_numbers_of_iterations (loop
);
4568 return get_likely_max_loop_iterations (loop
, nit
);
4571 /* Similar to max_loop_iterations, but returns the estimate only
4572 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4573 on the number of iterations of LOOP could not be derived, returns -1. */
4576 likely_max_loop_iterations_int (class loop
*loop
)
4579 HOST_WIDE_INT hwi_nit
;
4581 if (!likely_max_loop_iterations (loop
, &nit
))
4584 if (!wi::fits_shwi_p (nit
))
4586 hwi_nit
= nit
.to_shwi ();
4588 return hwi_nit
< 0 ? -1 : hwi_nit
;
4591 /* Returns an estimate for the number of executions of statements
4592 in the LOOP. For statements before the loop exit, this exceeds
4593 the number of execution of the latch by one. */
4596 estimated_stmt_executions_int (class loop
*loop
)
4598 HOST_WIDE_INT nit
= estimated_loop_iterations_int (loop
);
4604 snit
= (HOST_WIDE_INT
) ((unsigned HOST_WIDE_INT
) nit
+ 1);
4606 /* If the computation overflows, return -1. */
4607 return snit
< 0 ? -1 : snit
;
4610 /* Sets NIT to the maximum number of executions of the latch of the
4611 LOOP, plus one. If we have no reliable estimate, the function returns
4612 false, otherwise returns true. */
4615 max_stmt_executions (class loop
*loop
, widest_int
*nit
)
4617 widest_int nit_minus_one
;
4619 if (!max_loop_iterations (loop
, nit
))
4622 nit_minus_one
= *nit
;
4626 return wi::gtu_p (*nit
, nit_minus_one
);
4629 /* Sets NIT to the estimated maximum number of executions of the latch of the
4630 LOOP, plus one. If we have no likely estimate, the function returns
4631 false, otherwise returns true. */
4634 likely_max_stmt_executions (class loop
*loop
, widest_int
*nit
)
4636 widest_int nit_minus_one
;
4638 if (!likely_max_loop_iterations (loop
, nit
))
4641 nit_minus_one
= *nit
;
4645 return wi::gtu_p (*nit
, nit_minus_one
);
4648 /* Sets NIT to the estimated number of executions of the latch of the
4649 LOOP, plus one. If we have no reliable estimate, the function returns
4650 false, otherwise returns true. */
4653 estimated_stmt_executions (class loop
*loop
, widest_int
*nit
)
4655 widest_int nit_minus_one
;
4657 if (!estimated_loop_iterations (loop
, nit
))
4660 nit_minus_one
= *nit
;
4664 return wi::gtu_p (*nit
, nit_minus_one
);
4667 /* Records estimates on numbers of iterations of loops. */
4670 estimate_numbers_of_iterations (function
*fn
)
4672 /* We don't want to issue signed overflow warnings while getting
4673 loop iteration estimates. */
4674 fold_defer_overflow_warnings ();
4676 for (auto loop
: loops_list (fn
, 0))
4677 estimate_numbers_of_iterations (loop
);
4679 fold_undefer_and_ignore_overflow_warnings ();
4682 /* Returns true if statement S1 dominates statement S2. */
4685 stmt_dominates_stmt_p (gimple
*s1
, gimple
*s2
)
4687 basic_block bb1
= gimple_bb (s1
), bb2
= gimple_bb (s2
);
4695 gimple_stmt_iterator bsi
;
4697 if (gimple_code (s2
) == GIMPLE_PHI
)
4700 if (gimple_code (s1
) == GIMPLE_PHI
)
4703 for (bsi
= gsi_start_bb (bb1
); gsi_stmt (bsi
) != s2
; gsi_next (&bsi
))
4704 if (gsi_stmt (bsi
) == s1
)
4710 return dominated_by_p (CDI_DOMINATORS
, bb2
, bb1
);
4713 /* Returns true when we can prove that the number of executions of
4714 STMT in the loop is at most NITER, according to the bound on
4715 the number of executions of the statement NITER_BOUND->stmt recorded in
4716 NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
4718 ??? This code can become quite a CPU hog - we can have many bounds,
4719 and large basic block forcing stmt_dominates_stmt_p to be queried
4720 many times on a large basic blocks, so the whole thing is O(n^2)
4721 for scev_probably_wraps_p invocation (that can be done n times).
4723 It would make more sense (and give better answers) to remember BB
4724 bounds computed by discover_iteration_bound_by_body_walk. */
4727 n_of_executions_at_most (gimple
*stmt
,
4728 class nb_iter_bound
*niter_bound
,
4731 widest_int bound
= niter_bound
->bound
;
4732 tree nit_type
= TREE_TYPE (niter
), e
;
4735 gcc_assert (TYPE_UNSIGNED (nit_type
));
4737 /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
4738 the number of iterations is small. */
4739 if (!wi::fits_to_tree_p (bound
, nit_type
))
4742 /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
4743 times. This means that:
4745 -- if NITER_BOUND->is_exit is true, then everything after
4746 it at most NITER_BOUND->bound times.
4748 -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
4749 is executed, then NITER_BOUND->stmt is executed as well in the same
4750 iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
4752 If we can determine that NITER_BOUND->stmt is always executed
4753 after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
4754 We conclude that if both statements belong to the same
4755 basic block and STMT is before NITER_BOUND->stmt and there are no
4756 statements with side effects in between. */
4758 if (niter_bound
->is_exit
)
4760 if (stmt
== niter_bound
->stmt
4761 || !stmt_dominates_stmt_p (niter_bound
->stmt
, stmt
))
4767 if (!stmt_dominates_stmt_p (niter_bound
->stmt
, stmt
))
4769 gimple_stmt_iterator bsi
;
4770 if (gimple_bb (stmt
) != gimple_bb (niter_bound
->stmt
)
4771 || gimple_code (stmt
) == GIMPLE_PHI
4772 || gimple_code (niter_bound
->stmt
) == GIMPLE_PHI
)
4775 /* By stmt_dominates_stmt_p we already know that STMT appears
4776 before NITER_BOUND->STMT. Still need to test that the loop
4777 cannot be terinated by a side effect in between. */
4778 for (bsi
= gsi_for_stmt (stmt
); gsi_stmt (bsi
) != niter_bound
->stmt
;
4780 if (gimple_has_side_effects (gsi_stmt (bsi
)))
4784 || !wi::fits_to_tree_p (bound
, nit_type
))
4790 e
= fold_binary (cmp
, boolean_type_node
,
4791 niter
, wide_int_to_tree (nit_type
, bound
));
4792 return e
&& integer_nonzerop (e
);
4795 /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
4798 nowrap_type_p (tree type
)
4800 if (ANY_INTEGRAL_TYPE_P (type
)
4801 && TYPE_OVERFLOW_UNDEFINED (type
))
4804 if (POINTER_TYPE_P (type
))
4810 /* Return true if we can prove LOOP is exited before evolution of induction
4811 variable {BASE, STEP} overflows with respect to its type bound. */
4814 loop_exits_before_overflow (tree base
, tree step
,
4815 gimple
*at_stmt
, class loop
*loop
)
4818 struct control_iv
*civ
;
4819 class nb_iter_bound
*bound
;
4820 tree e
, delta
, step_abs
, unsigned_base
;
4821 tree type
= TREE_TYPE (step
);
4822 tree unsigned_type
, valid_niter
;
4824 /* Don't issue signed overflow warnings. */
4825 fold_defer_overflow_warnings ();
4827 /* Compute the number of iterations before we reach the bound of the
4828 type, and verify that the loop is exited before this occurs. */
4829 unsigned_type
= unsigned_type_for (type
);
4830 unsigned_base
= fold_convert (unsigned_type
, base
);
4832 if (tree_int_cst_sign_bit (step
))
4834 tree extreme
= fold_convert (unsigned_type
,
4835 lower_bound_in_type (type
, type
));
4836 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, unsigned_base
, extreme
);
4837 step_abs
= fold_build1 (NEGATE_EXPR
, unsigned_type
,
4838 fold_convert (unsigned_type
, step
));
4842 tree extreme
= fold_convert (unsigned_type
,
4843 upper_bound_in_type (type
, type
));
4844 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, extreme
, unsigned_base
);
4845 step_abs
= fold_convert (unsigned_type
, step
);
4848 valid_niter
= fold_build2 (FLOOR_DIV_EXPR
, unsigned_type
, delta
, step_abs
);
4850 estimate_numbers_of_iterations (loop
);
4852 if (max_loop_iterations (loop
, &niter
)
4853 && wi::fits_to_tree_p (niter
, TREE_TYPE (valid_niter
))
4854 && (e
= fold_binary (GT_EXPR
, boolean_type_node
, valid_niter
,
4855 wide_int_to_tree (TREE_TYPE (valid_niter
),
4857 && integer_nonzerop (e
))
4859 fold_undefer_and_ignore_overflow_warnings ();
4863 for (bound
= loop
->bounds
; bound
; bound
= bound
->next
)
4865 if (n_of_executions_at_most (at_stmt
, bound
, valid_niter
))
4867 fold_undefer_and_ignore_overflow_warnings ();
4871 fold_undefer_and_ignore_overflow_warnings ();
4873 /* Try to prove loop is exited before {base, step} overflows with the
4874 help of analyzed loop control IV. This is done only for IVs with
4875 constant step because otherwise we don't have the information. */
4876 if (TREE_CODE (step
) == INTEGER_CST
)
4878 for (civ
= loop
->control_ivs
; civ
; civ
= civ
->next
)
4880 enum tree_code code
;
4881 tree civ_type
= TREE_TYPE (civ
->step
);
4883 /* Have to consider type difference because operand_equal_p ignores
4884 that for constants. */
4885 if (TYPE_UNSIGNED (type
) != TYPE_UNSIGNED (civ_type
)
4886 || element_precision (type
) != element_precision (civ_type
))
4889 /* Only consider control IV with same step. */
4890 if (!operand_equal_p (step
, civ
->step
, 0))
4893 /* Done proving if this is a no-overflow control IV. */
4894 if (operand_equal_p (base
, civ
->base
, 0))
4897 /* Control IV is recorded after expanding simple operations,
4898 Here we expand base and compare it too. */
4899 tree expanded_base
= expand_simple_operations (base
);
4900 if (operand_equal_p (expanded_base
, civ
->base
, 0))
4903 /* If this is a before stepping control IV, in other words, we have
4905 {civ_base, step} = {base + step, step}
4907 Because civ {base + step, step} doesn't overflow during loop
4908 iterations, {base, step} will not overflow if we can prove the
4909 operation "base + step" does not overflow. Specifically, we try
4910 to prove below conditions are satisfied:
4912 base <= UPPER_BOUND (type) - step ;;step > 0
4913 base >= LOWER_BOUND (type) - step ;;step < 0
4915 by proving the reverse conditions are false using loop's initial
4917 if (POINTER_TYPE_P (TREE_TYPE (base
)))
4918 code
= POINTER_PLUS_EXPR
;
4922 tree stepped
= fold_build2 (code
, TREE_TYPE (base
), base
, step
);
4923 tree expanded_stepped
= fold_build2 (code
, TREE_TYPE (base
),
4924 expanded_base
, step
);
4925 if (operand_equal_p (stepped
, civ
->base
, 0)
4926 || operand_equal_p (expanded_stepped
, civ
->base
, 0))
4930 if (tree_int_cst_sign_bit (step
))
4933 extreme
= lower_bound_in_type (type
, type
);
4938 extreme
= upper_bound_in_type (type
, type
);
4940 extreme
= fold_build2 (MINUS_EXPR
, type
, extreme
, step
);
4941 e
= fold_build2 (code
, boolean_type_node
, base
, extreme
);
4942 e
= simplify_using_initial_conditions (loop
, e
);
4943 if (integer_zerop (e
))
4952 /* VAR is scev variable whose evolution part is constant STEP, this function
4953 proves that VAR can't overflow by using value range info. If VAR's value
4954 range is [MIN, MAX], it can be proven by:
4955 MAX + step doesn't overflow ; if step > 0
4957 MIN + step doesn't underflow ; if step < 0.
4959 We can only do this if var is computed in every loop iteration, i.e, var's
4960 definition has to dominate loop latch. Consider below example:
4968 # RANGE [0, 4294967294] NONZERO 65535
4969 # i_21 = PHI <0(3), i_18(9)>
4976 # RANGE [0, 65533] NONZERO 65535
4977 _6 = i_21 + 4294967295;
4978 # RANGE [0, 65533] NONZERO 65535
4979 _7 = (long unsigned int) _6;
4980 # RANGE [0, 524264] NONZERO 524280
4982 # PT = nonlocal escaped
4987 # RANGE [1, 65535] NONZERO 65535
5001 VAR _6 doesn't overflow only with pre-condition (i_21 != 0), here we
5002 can't use _6 to prove no-overlfow for _7. In fact, var _7 takes value
5003 sequence (4294967295, 0, 1, ..., 65533) in loop life time, rather than
5004 (4294967295, 4294967296, ...). */
5007 scev_var_range_cant_overflow (tree var
, tree step
, class loop
*loop
)
5010 wide_int minv
, maxv
, diff
, step_wi
;
5012 if (TREE_CODE (step
) != INTEGER_CST
|| !INTEGRAL_TYPE_P (TREE_TYPE (var
)))
5015 /* Check if VAR evaluates in every loop iteration. It's not the case
5016 if VAR is default definition or does not dominate loop's latch. */
5017 basic_block def_bb
= gimple_bb (SSA_NAME_DEF_STMT (var
));
5018 if (!def_bb
|| !dominated_by_p (CDI_DOMINATORS
, loop
->latch
, def_bb
))
5021 Value_Range
r (TREE_TYPE (var
));
5022 get_range_query (cfun
)->range_of_expr (r
, var
);
5023 if (r
.kind () != VR_RANGE
)
5026 /* VAR is a scev whose evolution part is STEP and value range info
5027 is [MIN, MAX], we can prove its no-overflowness by conditions:
5029 type_MAX - MAX >= step ; if step > 0
5030 MIN - type_MIN >= |step| ; if step < 0.
5032 Or VAR must take value outside of value range, which is not true. */
5033 step_wi
= wi::to_wide (step
);
5034 type
= TREE_TYPE (var
);
5035 if (tree_int_cst_sign_bit (step
))
5037 diff
= r
.lower_bound () - wi::to_wide (lower_bound_in_type (type
, type
));
5038 step_wi
= - step_wi
;
5041 diff
= wi::to_wide (upper_bound_in_type (type
, type
)) - r
.upper_bound ();
5043 return (wi::geu_p (diff
, step_wi
));
5046 /* Return false only when the induction variable BASE + STEP * I is
5047 known to not overflow: i.e. when the number of iterations is small
5048 enough with respect to the step and initial condition in order to
5049 keep the evolution confined in TYPEs bounds. Return true when the
5050 iv is known to overflow or when the property is not computable.
5052 USE_OVERFLOW_SEMANTICS is true if this function should assume that
5053 the rules for overflow of the given language apply (e.g., that signed
5054 arithmetics in C does not overflow).
5056 If VAR is a ssa variable, this function also returns false if VAR can
5057 be proven not overflow with value range info. */
5060 scev_probably_wraps_p (tree var
, tree base
, tree step
,
5061 gimple
*at_stmt
, class loop
*loop
,
5062 bool use_overflow_semantics
)
5064 /* FIXME: We really need something like
5065 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
5067 We used to test for the following situation that frequently appears
5068 during address arithmetics:
5070 D.1621_13 = (long unsigned intD.4) D.1620_12;
5071 D.1622_14 = D.1621_13 * 8;
5072 D.1623_15 = (doubleD.29 *) D.1622_14;
5074 And derived that the sequence corresponding to D_14
5075 can be proved to not wrap because it is used for computing a
5076 memory access; however, this is not really the case -- for example,
5077 if D_12 = (unsigned char) [254,+,1], then D_14 has values
5078 2032, 2040, 0, 8, ..., but the code is still legal. */
5080 if (chrec_contains_undetermined (base
)
5081 || chrec_contains_undetermined (step
))
5084 if (integer_zerop (step
))
5087 /* If we can use the fact that signed and pointer arithmetics does not
5088 wrap, we are done. */
5089 if (use_overflow_semantics
&& nowrap_type_p (TREE_TYPE (base
)))
5092 /* To be able to use estimates on number of iterations of the loop,
5093 we must have an upper bound on the absolute value of the step. */
5094 if (TREE_CODE (step
) != INTEGER_CST
)
5097 /* Check if var can be proven not overflow with value range info. */
5098 if (var
&& TREE_CODE (var
) == SSA_NAME
5099 && scev_var_range_cant_overflow (var
, step
, loop
))
5102 if (loop_exits_before_overflow (base
, step
, at_stmt
, loop
))
5105 /* At this point we still don't have a proof that the iv does not
5106 overflow: give up. */
5110 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
5113 free_numbers_of_iterations_estimates (class loop
*loop
)
5115 struct control_iv
*civ
;
5116 class nb_iter_bound
*bound
;
5118 loop
->nb_iterations
= NULL
;
5119 loop
->estimate_state
= EST_NOT_COMPUTED
;
5120 for (bound
= loop
->bounds
; bound
;)
5122 class nb_iter_bound
*next
= bound
->next
;
5126 loop
->bounds
= NULL
;
5128 for (civ
= loop
->control_ivs
; civ
;)
5130 struct control_iv
*next
= civ
->next
;
5134 loop
->control_ivs
= NULL
;
5137 /* Frees the information on upper bounds on numbers of iterations of loops. */
5140 free_numbers_of_iterations_estimates (function
*fn
)
5142 for (auto loop
: loops_list (fn
, 0))
5143 free_numbers_of_iterations_estimates (loop
);
5146 /* Substitute value VAL for ssa name NAME inside expressions held
5150 substitute_in_loop_info (class loop
*loop
, tree name
, tree val
)
5152 loop
->nb_iterations
= simplify_replace_tree (loop
->nb_iterations
, name
, val
);