1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
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 "double-int.h"
34 #include "stor-layout.h"
35 #include "fold-const.h"
38 #include "hard-reg-set.h"
42 #include "statistics.h"
44 #include "fixed-value.h"
45 #include "insn-config.h"
55 #include "dominance.h"
57 #include "basic-block.h"
58 #include "gimple-pretty-print.h"
60 #include "tree-ssa-alias.h"
61 #include "internal-fn.h"
62 #include "gimple-expr.h"
66 #include "gimple-iterator.h"
67 #include "gimple-ssa.h"
69 #include "tree-phinodes.h"
70 #include "ssa-iterators.h"
71 #include "tree-ssa-loop-ivopts.h"
72 #include "tree-ssa-loop-niter.h"
73 #include "tree-ssa-loop.h"
76 #include "tree-chrec.h"
77 #include "tree-scalar-evolution.h"
78 #include "tree-data-ref.h"
80 #include "diagnostic-core.h"
81 #include "tree-inline.h"
82 #include "tree-pass.h"
83 #include "stringpool.h"
84 #include "tree-ssanames.h"
85 #include "wide-int-print.h"
88 #define SWAP(X, Y) do { affine_iv *tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
90 /* The maximum number of dominator BBs we search for conditions
91 of loop header copies we use for simplifying a conditional
93 #define MAX_DOMINATORS_TO_WALK 8
97 Analysis of number of iterations of an affine exit test.
101 /* Bounds on some value, BELOW <= X <= UP. */
109 /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
112 split_to_var_and_offset (tree expr
, tree
*var
, mpz_t offset
)
114 tree type
= TREE_TYPE (expr
);
119 mpz_set_ui (offset
, 0);
121 switch (TREE_CODE (expr
))
128 case POINTER_PLUS_EXPR
:
129 op0
= TREE_OPERAND (expr
, 0);
130 op1
= TREE_OPERAND (expr
, 1);
132 if (TREE_CODE (op1
) != INTEGER_CST
)
136 /* Always sign extend the offset. */
137 wi::to_mpz (op1
, offset
, SIGNED
);
139 mpz_neg (offset
, offset
);
143 *var
= build_int_cst_type (type
, 0);
144 wi::to_mpz (expr
, offset
, TYPE_SIGN (type
));
152 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
153 in TYPE to MIN and MAX. */
156 determine_value_range (struct loop
*loop
, tree type
, tree var
, mpz_t off
,
157 mpz_t min
, mpz_t max
)
160 enum value_range_type rtype
= VR_VARYING
;
162 /* If the expression is a constant, we know its value exactly. */
163 if (integer_zerop (var
))
170 get_type_static_bounds (type
, min
, max
);
172 /* See if we have some range info from VRP. */
173 if (TREE_CODE (var
) == SSA_NAME
&& INTEGRAL_TYPE_P (type
))
175 edge e
= loop_preheader_edge (loop
);
176 signop sgn
= TYPE_SIGN (type
);
179 /* Either for VAR itself... */
180 rtype
= get_range_info (var
, &minv
, &maxv
);
181 /* Or for PHI results in loop->header where VAR is used as
182 PHI argument from the loop preheader edge. */
183 for (gsi
= gsi_start_phis (loop
->header
); !gsi_end_p (gsi
); gsi_next (&gsi
))
185 gphi
*phi
= gsi
.phi ();
187 if (PHI_ARG_DEF_FROM_EDGE (phi
, e
) == var
188 && (get_range_info (gimple_phi_result (phi
), &minc
, &maxc
)
191 if (rtype
!= VR_RANGE
)
199 minv
= wi::max (minv
, minc
, sgn
);
200 maxv
= wi::min (maxv
, maxc
, sgn
);
201 /* If the PHI result range are inconsistent with
202 the VAR range, give up on looking at the PHI
203 results. This can happen if VR_UNDEFINED is
205 if (wi::gt_p (minv
, maxv
, sgn
))
207 rtype
= get_range_info (var
, &minv
, &maxv
);
213 if (rtype
== VR_RANGE
)
216 gcc_assert (wi::le_p (minv
, maxv
, sgn
));
219 wi::to_mpz (minv
, minm
, sgn
);
220 wi::to_mpz (maxv
, maxm
, sgn
);
221 mpz_add (minm
, minm
, off
);
222 mpz_add (maxm
, maxm
, off
);
223 /* If the computation may not wrap or off is zero, then this
224 is always fine. If off is negative and minv + off isn't
225 smaller than type's minimum, or off is positive and
226 maxv + off isn't bigger than type's maximum, use the more
227 precise range too. */
228 if (nowrap_type_p (type
)
229 || mpz_sgn (off
) == 0
230 || (mpz_sgn (off
) < 0 && mpz_cmp (minm
, min
) >= 0)
231 || (mpz_sgn (off
) > 0 && mpz_cmp (maxm
, max
) <= 0))
244 /* If the computation may wrap, we know nothing about the value, except for
245 the range of the type. */
246 if (!nowrap_type_p (type
))
249 /* Since the addition of OFF does not wrap, if OFF is positive, then we may
250 add it to MIN, otherwise to MAX. */
251 if (mpz_sgn (off
) < 0)
252 mpz_add (max
, max
, off
);
254 mpz_add (min
, min
, off
);
257 /* Stores the bounds on the difference of the values of the expressions
258 (var + X) and (var + Y), computed in TYPE, to BNDS. */
261 bound_difference_of_offsetted_base (tree type
, mpz_t x
, mpz_t y
,
264 int rel
= mpz_cmp (x
, y
);
265 bool may_wrap
= !nowrap_type_p (type
);
268 /* If X == Y, then the expressions are always equal.
269 If X > Y, there are the following possibilities:
270 a) neither of var + X and var + Y overflow or underflow, or both of
271 them do. Then their difference is X - Y.
272 b) var + X overflows, and var + Y does not. Then the values of the
273 expressions are var + X - M and var + Y, where M is the range of
274 the type, and their difference is X - Y - M.
275 c) var + Y underflows and var + X does not. Their difference again
277 Therefore, if the arithmetics in type does not overflow, then the
278 bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
279 Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
280 (X - Y, X - Y + M). */
284 mpz_set_ui (bnds
->below
, 0);
285 mpz_set_ui (bnds
->up
, 0);
290 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), m
, UNSIGNED
);
291 mpz_add_ui (m
, m
, 1);
292 mpz_sub (bnds
->up
, x
, y
);
293 mpz_set (bnds
->below
, bnds
->up
);
298 mpz_sub (bnds
->below
, bnds
->below
, m
);
300 mpz_add (bnds
->up
, bnds
->up
, m
);
306 /* From condition C0 CMP C1 derives information regarding the
307 difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
308 and stores it to BNDS. */
311 refine_bounds_using_guard (tree type
, tree varx
, mpz_t offx
,
312 tree vary
, mpz_t offy
,
313 tree c0
, enum tree_code cmp
, tree c1
,
316 tree varc0
, varc1
, tmp
, ctype
;
317 mpz_t offc0
, offc1
, loffx
, loffy
, bnd
;
319 bool no_wrap
= nowrap_type_p (type
);
328 STRIP_SIGN_NOPS (c0
);
329 STRIP_SIGN_NOPS (c1
);
330 ctype
= TREE_TYPE (c0
);
331 if (!useless_type_conversion_p (ctype
, type
))
337 /* We could derive quite precise information from EQ_EXPR, however, such
338 a guard is unlikely to appear, so we do not bother with handling
343 /* NE_EXPR comparisons do not contain much of useful information, except for
344 special case of comparing with the bounds of the type. */
345 if (TREE_CODE (c1
) != INTEGER_CST
346 || !INTEGRAL_TYPE_P (type
))
349 /* Ensure that the condition speaks about an expression in the same type
351 ctype
= TREE_TYPE (c0
);
352 if (TYPE_PRECISION (ctype
) != TYPE_PRECISION (type
))
354 c0
= fold_convert (type
, c0
);
355 c1
= fold_convert (type
, c1
);
357 if (TYPE_MIN_VALUE (type
)
358 && operand_equal_p (c1
, TYPE_MIN_VALUE (type
), 0))
363 if (TYPE_MAX_VALUE (type
)
364 && operand_equal_p (c1
, TYPE_MAX_VALUE (type
), 0))
377 split_to_var_and_offset (expand_simple_operations (c0
), &varc0
, offc0
);
378 split_to_var_and_offset (expand_simple_operations (c1
), &varc1
, offc1
);
380 /* We are only interested in comparisons of expressions based on VARX and
381 VARY. TODO -- we might also be able to derive some bounds from
382 expressions containing just one of the variables. */
384 if (operand_equal_p (varx
, varc1
, 0))
386 tmp
= varc0
; varc0
= varc1
; varc1
= tmp
;
387 mpz_swap (offc0
, offc1
);
388 cmp
= swap_tree_comparison (cmp
);
391 if (!operand_equal_p (varx
, varc0
, 0)
392 || !operand_equal_p (vary
, varc1
, 0))
395 mpz_init_set (loffx
, offx
);
396 mpz_init_set (loffy
, offy
);
398 if (cmp
== GT_EXPR
|| cmp
== GE_EXPR
)
400 tmp
= varx
; varx
= vary
; vary
= tmp
;
401 mpz_swap (offc0
, offc1
);
402 mpz_swap (loffx
, loffy
);
403 cmp
= swap_tree_comparison (cmp
);
407 /* If there is no overflow, the condition implies that
409 (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
411 The overflows and underflows may complicate things a bit; each
412 overflow decreases the appropriate offset by M, and underflow
413 increases it by M. The above inequality would not necessarily be
416 -- VARX + OFFX underflows and VARX + OFFC0 does not, or
417 VARX + OFFC0 overflows, but VARX + OFFX does not.
418 This may only happen if OFFX < OFFC0.
419 -- VARY + OFFY overflows and VARY + OFFC1 does not, or
420 VARY + OFFC1 underflows and VARY + OFFY does not.
421 This may only happen if OFFY > OFFC1. */
430 x_ok
= (integer_zerop (varx
)
431 || mpz_cmp (loffx
, offc0
) >= 0);
432 y_ok
= (integer_zerop (vary
)
433 || mpz_cmp (loffy
, offc1
) <= 0);
439 mpz_sub (bnd
, loffx
, loffy
);
440 mpz_add (bnd
, bnd
, offc1
);
441 mpz_sub (bnd
, bnd
, offc0
);
444 mpz_sub_ui (bnd
, bnd
, 1);
449 if (mpz_cmp (bnds
->below
, bnd
) < 0)
450 mpz_set (bnds
->below
, bnd
);
454 if (mpz_cmp (bnd
, bnds
->up
) < 0)
455 mpz_set (bnds
->up
, bnd
);
467 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
468 The subtraction is considered to be performed in arbitrary precision,
471 We do not attempt to be too clever regarding the value ranges of X and
472 Y; most of the time, they are just integers or ssa names offsetted by
473 integer. However, we try to use the information contained in the
474 comparisons before the loop (usually created by loop header copying). */
477 bound_difference (struct loop
*loop
, tree x
, tree y
, bounds
*bnds
)
479 tree type
= TREE_TYPE (x
);
482 mpz_t minx
, maxx
, miny
, maxy
;
490 /* Get rid of unnecessary casts, but preserve the value of
495 mpz_init (bnds
->below
);
499 split_to_var_and_offset (x
, &varx
, offx
);
500 split_to_var_and_offset (y
, &vary
, offy
);
502 if (!integer_zerop (varx
)
503 && operand_equal_p (varx
, vary
, 0))
505 /* Special case VARX == VARY -- we just need to compare the
506 offsets. The matters are a bit more complicated in the
507 case addition of offsets may wrap. */
508 bound_difference_of_offsetted_base (type
, offx
, offy
, bnds
);
512 /* Otherwise, use the value ranges to determine the initial
513 estimates on below and up. */
518 determine_value_range (loop
, type
, varx
, offx
, minx
, maxx
);
519 determine_value_range (loop
, type
, vary
, offy
, miny
, maxy
);
521 mpz_sub (bnds
->below
, minx
, maxy
);
522 mpz_sub (bnds
->up
, maxx
, miny
);
529 /* If both X and Y are constants, we cannot get any more precise. */
530 if (integer_zerop (varx
) && integer_zerop (vary
))
533 /* Now walk the dominators of the loop header and use the entry
534 guards to refine the estimates. */
535 for (bb
= loop
->header
;
536 bb
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
) && cnt
< MAX_DOMINATORS_TO_WALK
;
537 bb
= get_immediate_dominator (CDI_DOMINATORS
, bb
))
539 if (!single_pred_p (bb
))
541 e
= single_pred_edge (bb
);
543 if (!(e
->flags
& (EDGE_TRUE_VALUE
| EDGE_FALSE_VALUE
)))
546 cond
= last_stmt (e
->src
);
547 c0
= gimple_cond_lhs (cond
);
548 cmp
= gimple_cond_code (cond
);
549 c1
= gimple_cond_rhs (cond
);
551 if (e
->flags
& EDGE_FALSE_VALUE
)
552 cmp
= invert_tree_comparison (cmp
, false);
554 refine_bounds_using_guard (type
, varx
, offx
, vary
, offy
,
564 /* Update the bounds in BNDS that restrict the value of X to the bounds
565 that restrict the value of X + DELTA. X can be obtained as a
566 difference of two values in TYPE. */
569 bounds_add (bounds
*bnds
, const widest_int
&delta
, tree type
)
574 wi::to_mpz (delta
, mdelta
, SIGNED
);
577 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), max
, UNSIGNED
);
579 mpz_add (bnds
->up
, bnds
->up
, mdelta
);
580 mpz_add (bnds
->below
, bnds
->below
, mdelta
);
582 if (mpz_cmp (bnds
->up
, max
) > 0)
583 mpz_set (bnds
->up
, max
);
586 if (mpz_cmp (bnds
->below
, max
) < 0)
587 mpz_set (bnds
->below
, max
);
593 /* Update the bounds in BNDS that restrict the value of X to the bounds
594 that restrict the value of -X. */
597 bounds_negate (bounds
*bnds
)
601 mpz_init_set (tmp
, bnds
->up
);
602 mpz_neg (bnds
->up
, bnds
->below
);
603 mpz_neg (bnds
->below
, tmp
);
607 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
610 inverse (tree x
, tree mask
)
612 tree type
= TREE_TYPE (x
);
614 unsigned ctr
= tree_floor_log2 (mask
);
616 if (TYPE_PRECISION (type
) <= HOST_BITS_PER_WIDE_INT
)
618 unsigned HOST_WIDE_INT ix
;
619 unsigned HOST_WIDE_INT imask
;
620 unsigned HOST_WIDE_INT irslt
= 1;
622 gcc_assert (cst_and_fits_in_hwi (x
));
623 gcc_assert (cst_and_fits_in_hwi (mask
));
625 ix
= int_cst_value (x
);
626 imask
= int_cst_value (mask
);
635 rslt
= build_int_cst_type (type
, irslt
);
639 rslt
= build_int_cst (type
, 1);
642 rslt
= int_const_binop (MULT_EXPR
, rslt
, x
);
643 x
= int_const_binop (MULT_EXPR
, x
, x
);
645 rslt
= int_const_binop (BIT_AND_EXPR
, rslt
, mask
);
651 /* Derives the upper bound BND on the number of executions of loop with exit
652 condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
653 the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
654 that the loop ends through this exit, i.e., the induction variable ever
655 reaches the value of C.
657 The value C is equal to final - base, where final and base are the final and
658 initial value of the actual induction variable in the analysed loop. BNDS
659 bounds the value of this difference when computed in signed type with
660 unbounded range, while the computation of C is performed in an unsigned
661 type with the range matching the range of the type of the induction variable.
662 In particular, BNDS.up contains an upper bound on C in the following cases:
663 -- if the iv must reach its final value without overflow, i.e., if
664 NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
665 -- if final >= base, which we know to hold when BNDS.below >= 0. */
668 number_of_iterations_ne_max (mpz_t bnd
, bool no_overflow
, tree c
, tree s
,
669 bounds
*bnds
, bool exit_must_be_taken
)
673 tree type
= TREE_TYPE (c
);
674 bool bnds_u_valid
= ((no_overflow
&& exit_must_be_taken
)
675 || mpz_sgn (bnds
->below
) >= 0);
678 || (TREE_CODE (c
) == INTEGER_CST
679 && TREE_CODE (s
) == INTEGER_CST
680 && wi::mod_trunc (c
, s
, TYPE_SIGN (type
)) == 0)
681 || (TYPE_OVERFLOW_UNDEFINED (type
)
682 && multiple_of_p (type
, c
, s
)))
684 /* If C is an exact multiple of S, then its value will be reached before
685 the induction variable overflows (unless the loop is exited in some
686 other way before). Note that the actual induction variable in the
687 loop (which ranges from base to final instead of from 0 to C) may
688 overflow, in which case BNDS.up will not be giving a correct upper
689 bound on C; thus, BNDS_U_VALID had to be computed in advance. */
691 exit_must_be_taken
= true;
694 /* If the induction variable can overflow, the number of iterations is at
695 most the period of the control variable (or infinite, but in that case
696 the whole # of iterations analysis will fail). */
699 max
= wi::mask
<widest_int
> (TYPE_PRECISION (type
) - wi::ctz (s
), false);
700 wi::to_mpz (max
, bnd
, UNSIGNED
);
704 /* Now we know that the induction variable does not overflow, so the loop
705 iterates at most (range of type / S) times. */
706 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), bnd
, UNSIGNED
);
708 /* If the induction variable is guaranteed to reach the value of C before
710 if (exit_must_be_taken
)
712 /* ... then we can strengthen this to C / S, and possibly we can use
713 the upper bound on C given by BNDS. */
714 if (TREE_CODE (c
) == INTEGER_CST
)
715 wi::to_mpz (c
, bnd
, UNSIGNED
);
716 else if (bnds_u_valid
)
717 mpz_set (bnd
, bnds
->up
);
721 wi::to_mpz (s
, d
, UNSIGNED
);
722 mpz_fdiv_q (bnd
, bnd
, d
);
726 /* Determines number of iterations of loop whose ending condition
727 is IV <> FINAL. TYPE is the type of the iv. The number of
728 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
729 we know that the exit must be taken eventually, i.e., that the IV
730 ever reaches the value FINAL (we derived this earlier, and possibly set
731 NITER->assumptions to make sure this is the case). BNDS contains the
732 bounds on the difference FINAL - IV->base. */
735 number_of_iterations_ne (tree type
, affine_iv
*iv
, tree final
,
736 struct tree_niter_desc
*niter
, bool exit_must_be_taken
,
739 tree niter_type
= unsigned_type_for (type
);
740 tree s
, c
, d
, bits
, assumption
, tmp
, bound
;
743 niter
->control
= *iv
;
744 niter
->bound
= final
;
745 niter
->cmp
= NE_EXPR
;
747 /* Rearrange the terms so that we get inequality S * i <> C, with S
748 positive. Also cast everything to the unsigned type. If IV does
749 not overflow, BNDS bounds the value of C. Also, this is the
750 case if the computation |FINAL - IV->base| does not overflow, i.e.,
751 if BNDS->below in the result is nonnegative. */
752 if (tree_int_cst_sign_bit (iv
->step
))
754 s
= fold_convert (niter_type
,
755 fold_build1 (NEGATE_EXPR
, type
, iv
->step
));
756 c
= fold_build2 (MINUS_EXPR
, niter_type
,
757 fold_convert (niter_type
, iv
->base
),
758 fold_convert (niter_type
, final
));
759 bounds_negate (bnds
);
763 s
= fold_convert (niter_type
, iv
->step
);
764 c
= fold_build2 (MINUS_EXPR
, niter_type
,
765 fold_convert (niter_type
, final
),
766 fold_convert (niter_type
, iv
->base
));
770 number_of_iterations_ne_max (max
, iv
->no_overflow
, c
, s
, bnds
,
772 niter
->max
= widest_int::from (wi::from_mpz (niter_type
, max
, false),
773 TYPE_SIGN (niter_type
));
776 /* First the trivial cases -- when the step is 1. */
777 if (integer_onep (s
))
783 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
784 is infinite. Otherwise, the number of iterations is
785 (inverse(s/d) * (c/d)) mod (size of mode/d). */
786 bits
= num_ending_zeros (s
);
787 bound
= build_low_bits_mask (niter_type
,
788 (TYPE_PRECISION (niter_type
)
789 - tree_to_uhwi (bits
)));
791 d
= fold_binary_to_constant (LSHIFT_EXPR
, niter_type
,
792 build_int_cst (niter_type
, 1), bits
);
793 s
= fold_binary_to_constant (RSHIFT_EXPR
, niter_type
, s
, bits
);
795 if (!exit_must_be_taken
)
797 /* If we cannot assume that the exit is taken eventually, record the
798 assumptions for divisibility of c. */
799 assumption
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, c
, d
);
800 assumption
= fold_build2 (EQ_EXPR
, boolean_type_node
,
801 assumption
, build_int_cst (niter_type
, 0));
802 if (!integer_nonzerop (assumption
))
803 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
804 niter
->assumptions
, assumption
);
807 c
= fold_build2 (EXACT_DIV_EXPR
, niter_type
, c
, d
);
808 tmp
= fold_build2 (MULT_EXPR
, niter_type
, c
, inverse (s
, bound
));
809 niter
->niter
= fold_build2 (BIT_AND_EXPR
, niter_type
, tmp
, bound
);
813 /* Checks whether we can determine the final value of the control variable
814 of the loop with ending condition IV0 < IV1 (computed in TYPE).
815 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
816 of the step. The assumptions necessary to ensure that the computation
817 of the final value does not overflow are recorded in NITER. If we
818 find the final value, we adjust DELTA and return TRUE. Otherwise
819 we return false. BNDS bounds the value of IV1->base - IV0->base,
820 and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
821 true if we know that the exit must be taken eventually. */
824 number_of_iterations_lt_to_ne (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
825 struct tree_niter_desc
*niter
,
826 tree
*delta
, tree step
,
827 bool exit_must_be_taken
, bounds
*bnds
)
829 tree niter_type
= TREE_TYPE (step
);
830 tree mod
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, *delta
, step
);
833 tree assumption
= boolean_true_node
, bound
, noloop
;
834 bool ret
= false, fv_comp_no_overflow
;
836 if (POINTER_TYPE_P (type
))
839 if (TREE_CODE (mod
) != INTEGER_CST
)
841 if (integer_nonzerop (mod
))
842 mod
= fold_build2 (MINUS_EXPR
, niter_type
, step
, mod
);
843 tmod
= fold_convert (type1
, mod
);
846 wi::to_mpz (mod
, mmod
, UNSIGNED
);
847 mpz_neg (mmod
, mmod
);
849 /* If the induction variable does not overflow and the exit is taken,
850 then the computation of the final value does not overflow. This is
851 also obviously the case if the new final value is equal to the
852 current one. Finally, we postulate this for pointer type variables,
853 as the code cannot rely on the object to that the pointer points being
854 placed at the end of the address space (and more pragmatically,
855 TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
856 if (integer_zerop (mod
) || POINTER_TYPE_P (type
))
857 fv_comp_no_overflow
= true;
858 else if (!exit_must_be_taken
)
859 fv_comp_no_overflow
= false;
861 fv_comp_no_overflow
=
862 (iv0
->no_overflow
&& integer_nonzerop (iv0
->step
))
863 || (iv1
->no_overflow
&& integer_nonzerop (iv1
->step
));
865 if (integer_nonzerop (iv0
->step
))
867 /* The final value of the iv is iv1->base + MOD, assuming that this
868 computation does not overflow, and that
869 iv0->base <= iv1->base + MOD. */
870 if (!fv_comp_no_overflow
)
872 bound
= fold_build2 (MINUS_EXPR
, type1
,
873 TYPE_MAX_VALUE (type1
), tmod
);
874 assumption
= fold_build2 (LE_EXPR
, boolean_type_node
,
876 if (integer_zerop (assumption
))
879 if (mpz_cmp (mmod
, bnds
->below
) < 0)
880 noloop
= boolean_false_node
;
881 else if (POINTER_TYPE_P (type
))
882 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
884 fold_build_pointer_plus (iv1
->base
, tmod
));
886 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
888 fold_build2 (PLUS_EXPR
, type1
,
893 /* The final value of the iv is iv0->base - MOD, assuming that this
894 computation does not overflow, and that
895 iv0->base - MOD <= iv1->base. */
896 if (!fv_comp_no_overflow
)
898 bound
= fold_build2 (PLUS_EXPR
, type1
,
899 TYPE_MIN_VALUE (type1
), tmod
);
900 assumption
= fold_build2 (GE_EXPR
, boolean_type_node
,
902 if (integer_zerop (assumption
))
905 if (mpz_cmp (mmod
, bnds
->below
) < 0)
906 noloop
= boolean_false_node
;
907 else if (POINTER_TYPE_P (type
))
908 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
909 fold_build_pointer_plus (iv0
->base
,
910 fold_build1 (NEGATE_EXPR
,
914 noloop
= fold_build2 (GT_EXPR
, boolean_type_node
,
915 fold_build2 (MINUS_EXPR
, type1
,
920 if (!integer_nonzerop (assumption
))
921 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
924 if (!integer_zerop (noloop
))
925 niter
->may_be_zero
= fold_build2 (TRUTH_OR_EXPR
, boolean_type_node
,
928 bounds_add (bnds
, wi::to_widest (mod
), type
);
929 *delta
= fold_build2 (PLUS_EXPR
, niter_type
, *delta
, mod
);
937 /* Add assertions to NITER that ensure that the control variable of the loop
938 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
939 are TYPE. Returns false if we can prove that there is an overflow, true
940 otherwise. STEP is the absolute value of the step. */
943 assert_no_overflow_lt (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
944 struct tree_niter_desc
*niter
, tree step
)
946 tree bound
, d
, assumption
, diff
;
947 tree niter_type
= TREE_TYPE (step
);
949 if (integer_nonzerop (iv0
->step
))
951 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
952 if (iv0
->no_overflow
)
955 /* If iv0->base is a constant, we can determine the last value before
956 overflow precisely; otherwise we conservatively assume
959 if (TREE_CODE (iv0
->base
) == INTEGER_CST
)
961 d
= fold_build2 (MINUS_EXPR
, niter_type
,
962 fold_convert (niter_type
, TYPE_MAX_VALUE (type
)),
963 fold_convert (niter_type
, iv0
->base
));
964 diff
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, d
, step
);
967 diff
= fold_build2 (MINUS_EXPR
, niter_type
, step
,
968 build_int_cst (niter_type
, 1));
969 bound
= fold_build2 (MINUS_EXPR
, type
,
970 TYPE_MAX_VALUE (type
), fold_convert (type
, diff
));
971 assumption
= fold_build2 (LE_EXPR
, boolean_type_node
,
976 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
977 if (iv1
->no_overflow
)
980 if (TREE_CODE (iv1
->base
) == INTEGER_CST
)
982 d
= fold_build2 (MINUS_EXPR
, niter_type
,
983 fold_convert (niter_type
, iv1
->base
),
984 fold_convert (niter_type
, TYPE_MIN_VALUE (type
)));
985 diff
= fold_build2 (FLOOR_MOD_EXPR
, niter_type
, d
, step
);
988 diff
= fold_build2 (MINUS_EXPR
, niter_type
, step
,
989 build_int_cst (niter_type
, 1));
990 bound
= fold_build2 (PLUS_EXPR
, type
,
991 TYPE_MIN_VALUE (type
), fold_convert (type
, diff
));
992 assumption
= fold_build2 (GE_EXPR
, boolean_type_node
,
996 if (integer_zerop (assumption
))
998 if (!integer_nonzerop (assumption
))
999 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1000 niter
->assumptions
, assumption
);
1002 iv0
->no_overflow
= true;
1003 iv1
->no_overflow
= true;
1007 /* Add an assumption to NITER that a loop whose ending condition
1008 is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
1009 bounds the value of IV1->base - IV0->base. */
1012 assert_loop_rolls_lt (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
1013 struct tree_niter_desc
*niter
, bounds
*bnds
)
1015 tree assumption
= boolean_true_node
, bound
, diff
;
1016 tree mbz
, mbzl
, mbzr
, type1
;
1017 bool rolls_p
, no_overflow_p
;
1021 /* We are going to compute the number of iterations as
1022 (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1023 variant of TYPE. This formula only works if
1025 -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1027 (where MAX is the maximum value of the unsigned variant of TYPE, and
1028 the computations in this formula are performed in full precision,
1029 i.e., without overflows).
1031 Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1032 we have a condition of the form iv0->base - step < iv1->base before the loop,
1033 and for loops iv0->base < iv1->base - step * i the condition
1034 iv0->base < iv1->base + step, due to loop header copying, which enable us
1035 to prove the lower bound.
1037 The upper bound is more complicated. Unless the expressions for initial
1038 and final value themselves contain enough information, we usually cannot
1039 derive it from the context. */
1041 /* First check whether the answer does not follow from the bounds we gathered
1043 if (integer_nonzerop (iv0
->step
))
1044 dstep
= wi::to_widest (iv0
->step
);
1047 dstep
= wi::sext (wi::to_widest (iv1
->step
), TYPE_PRECISION (type
));
1052 wi::to_mpz (dstep
, mstep
, UNSIGNED
);
1053 mpz_neg (mstep
, mstep
);
1054 mpz_add_ui (mstep
, mstep
, 1);
1056 rolls_p
= mpz_cmp (mstep
, bnds
->below
) <= 0;
1059 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type
)), max
, UNSIGNED
);
1060 mpz_add (max
, max
, mstep
);
1061 no_overflow_p
= (mpz_cmp (bnds
->up
, max
) <= 0
1062 /* For pointers, only values lying inside a single object
1063 can be compared or manipulated by pointer arithmetics.
1064 Gcc in general does not allow or handle objects larger
1065 than half of the address space, hence the upper bound
1066 is satisfied for pointers. */
1067 || POINTER_TYPE_P (type
));
1071 if (rolls_p
&& no_overflow_p
)
1075 if (POINTER_TYPE_P (type
))
1078 /* Now the hard part; we must formulate the assumption(s) as expressions, and
1079 we must be careful not to introduce overflow. */
1081 if (integer_nonzerop (iv0
->step
))
1083 diff
= fold_build2 (MINUS_EXPR
, type1
,
1084 iv0
->step
, build_int_cst (type1
, 1));
1086 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1087 0 address never belongs to any object, we can assume this for
1089 if (!POINTER_TYPE_P (type
))
1091 bound
= fold_build2 (PLUS_EXPR
, type1
,
1092 TYPE_MIN_VALUE (type
), diff
);
1093 assumption
= fold_build2 (GE_EXPR
, boolean_type_node
,
1097 /* And then we can compute iv0->base - diff, and compare it with
1099 mbzl
= fold_build2 (MINUS_EXPR
, type1
,
1100 fold_convert (type1
, iv0
->base
), diff
);
1101 mbzr
= fold_convert (type1
, iv1
->base
);
1105 diff
= fold_build2 (PLUS_EXPR
, type1
,
1106 iv1
->step
, build_int_cst (type1
, 1));
1108 if (!POINTER_TYPE_P (type
))
1110 bound
= fold_build2 (PLUS_EXPR
, type1
,
1111 TYPE_MAX_VALUE (type
), diff
);
1112 assumption
= fold_build2 (LE_EXPR
, boolean_type_node
,
1116 mbzl
= fold_convert (type1
, iv0
->base
);
1117 mbzr
= fold_build2 (MINUS_EXPR
, type1
,
1118 fold_convert (type1
, iv1
->base
), diff
);
1121 if (!integer_nonzerop (assumption
))
1122 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1123 niter
->assumptions
, assumption
);
1126 mbz
= fold_build2 (GT_EXPR
, boolean_type_node
, mbzl
, mbzr
);
1127 niter
->may_be_zero
= fold_build2 (TRUTH_OR_EXPR
, boolean_type_node
,
1128 niter
->may_be_zero
, mbz
);
1132 /* Determines number of iterations of loop whose ending condition
1133 is IV0 < IV1. TYPE is the type of the iv. The number of
1134 iterations is stored to NITER. BNDS bounds the difference
1135 IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1136 that the exit must be taken eventually. */
1139 number_of_iterations_lt (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
1140 struct tree_niter_desc
*niter
,
1141 bool exit_must_be_taken
, bounds
*bnds
)
1143 tree niter_type
= unsigned_type_for (type
);
1144 tree delta
, step
, s
;
1147 if (integer_nonzerop (iv0
->step
))
1149 niter
->control
= *iv0
;
1150 niter
->cmp
= LT_EXPR
;
1151 niter
->bound
= iv1
->base
;
1155 niter
->control
= *iv1
;
1156 niter
->cmp
= GT_EXPR
;
1157 niter
->bound
= iv0
->base
;
1160 delta
= fold_build2 (MINUS_EXPR
, niter_type
,
1161 fold_convert (niter_type
, iv1
->base
),
1162 fold_convert (niter_type
, iv0
->base
));
1164 /* First handle the special case that the step is +-1. */
1165 if ((integer_onep (iv0
->step
) && integer_zerop (iv1
->step
))
1166 || (integer_all_onesp (iv1
->step
) && integer_zerop (iv0
->step
)))
1168 /* for (i = iv0->base; i < iv1->base; i++)
1172 for (i = iv1->base; i > iv0->base; i--).
1174 In both cases # of iterations is iv1->base - iv0->base, assuming that
1175 iv1->base >= iv0->base.
1177 First try to derive a lower bound on the value of
1178 iv1->base - iv0->base, computed in full precision. If the difference
1179 is nonnegative, we are done, otherwise we must record the
1182 if (mpz_sgn (bnds
->below
) < 0)
1183 niter
->may_be_zero
= fold_build2 (LT_EXPR
, boolean_type_node
,
1184 iv1
->base
, iv0
->base
);
1185 niter
->niter
= delta
;
1186 niter
->max
= widest_int::from (wi::from_mpz (niter_type
, bnds
->up
, false),
1187 TYPE_SIGN (niter_type
));
1188 niter
->control
.no_overflow
= true;
1192 if (integer_nonzerop (iv0
->step
))
1193 step
= fold_convert (niter_type
, iv0
->step
);
1195 step
= fold_convert (niter_type
,
1196 fold_build1 (NEGATE_EXPR
, type
, iv1
->step
));
1198 /* If we can determine the final value of the control iv exactly, we can
1199 transform the condition to != comparison. In particular, this will be
1200 the case if DELTA is constant. */
1201 if (number_of_iterations_lt_to_ne (type
, iv0
, iv1
, niter
, &delta
, step
,
1202 exit_must_be_taken
, bnds
))
1206 zps
.base
= build_int_cst (niter_type
, 0);
1208 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1209 zps does not overflow. */
1210 zps
.no_overflow
= true;
1212 return number_of_iterations_ne (type
, &zps
, delta
, niter
, true, bnds
);
1215 /* Make sure that the control iv does not overflow. */
1216 if (!assert_no_overflow_lt (type
, iv0
, iv1
, niter
, step
))
1219 /* We determine the number of iterations as (delta + step - 1) / step. For
1220 this to work, we must know that iv1->base >= iv0->base - step + 1,
1221 otherwise the loop does not roll. */
1222 assert_loop_rolls_lt (type
, iv0
, iv1
, niter
, bnds
);
1224 s
= fold_build2 (MINUS_EXPR
, niter_type
,
1225 step
, build_int_cst (niter_type
, 1));
1226 delta
= fold_build2 (PLUS_EXPR
, niter_type
, delta
, s
);
1227 niter
->niter
= fold_build2 (FLOOR_DIV_EXPR
, niter_type
, delta
, step
);
1231 wi::to_mpz (step
, mstep
, UNSIGNED
);
1232 mpz_add (tmp
, bnds
->up
, mstep
);
1233 mpz_sub_ui (tmp
, tmp
, 1);
1234 mpz_fdiv_q (tmp
, tmp
, mstep
);
1235 niter
->max
= widest_int::from (wi::from_mpz (niter_type
, tmp
, false),
1236 TYPE_SIGN (niter_type
));
1243 /* Determines number of iterations of loop whose ending condition
1244 is IV0 <= IV1. TYPE is the type of the iv. The number of
1245 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1246 we know that this condition must eventually become false (we derived this
1247 earlier, and possibly set NITER->assumptions to make sure this
1248 is the case). BNDS bounds the difference IV1->base - IV0->base. */
1251 number_of_iterations_le (tree type
, affine_iv
*iv0
, affine_iv
*iv1
,
1252 struct tree_niter_desc
*niter
, bool exit_must_be_taken
,
1257 if (POINTER_TYPE_P (type
))
1260 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1261 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1262 value of the type. This we must know anyway, since if it is
1263 equal to this value, the loop rolls forever. We do not check
1264 this condition for pointer type ivs, as the code cannot rely on
1265 the object to that the pointer points being placed at the end of
1266 the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1267 not defined for pointers). */
1269 if (!exit_must_be_taken
&& !POINTER_TYPE_P (type
))
1271 if (integer_nonzerop (iv0
->step
))
1272 assumption
= fold_build2 (NE_EXPR
, boolean_type_node
,
1273 iv1
->base
, TYPE_MAX_VALUE (type
));
1275 assumption
= fold_build2 (NE_EXPR
, boolean_type_node
,
1276 iv0
->base
, TYPE_MIN_VALUE (type
));
1278 if (integer_zerop (assumption
))
1280 if (!integer_nonzerop (assumption
))
1281 niter
->assumptions
= fold_build2 (TRUTH_AND_EXPR
, boolean_type_node
,
1282 niter
->assumptions
, assumption
);
1285 if (integer_nonzerop (iv0
->step
))
1287 if (POINTER_TYPE_P (type
))
1288 iv1
->base
= fold_build_pointer_plus_hwi (iv1
->base
, 1);
1290 iv1
->base
= fold_build2 (PLUS_EXPR
, type1
, iv1
->base
,
1291 build_int_cst (type1
, 1));
1293 else if (POINTER_TYPE_P (type
))
1294 iv0
->base
= fold_build_pointer_plus_hwi (iv0
->base
, -1);
1296 iv0
->base
= fold_build2 (MINUS_EXPR
, type1
,
1297 iv0
->base
, build_int_cst (type1
, 1));
1299 bounds_add (bnds
, 1, type1
);
1301 return number_of_iterations_lt (type
, iv0
, iv1
, niter
, exit_must_be_taken
,
1305 /* Dumps description of affine induction variable IV to FILE. */
1308 dump_affine_iv (FILE *file
, affine_iv
*iv
)
1310 if (!integer_zerop (iv
->step
))
1311 fprintf (file
, "[");
1313 print_generic_expr (dump_file
, iv
->base
, TDF_SLIM
);
1315 if (!integer_zerop (iv
->step
))
1317 fprintf (file
, ", + , ");
1318 print_generic_expr (dump_file
, iv
->step
, TDF_SLIM
);
1319 fprintf (file
, "]%s", iv
->no_overflow
? "(no_overflow)" : "");
1323 /* Determine the number of iterations according to condition (for staying
1324 inside loop) which compares two induction variables using comparison
1325 operator CODE. The induction variable on left side of the comparison
1326 is IV0, the right-hand side is IV1. Both induction variables must have
1327 type TYPE, which must be an integer or pointer type. The steps of the
1328 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1330 LOOP is the loop whose number of iterations we are determining.
1332 ONLY_EXIT is true if we are sure this is the only way the loop could be
1333 exited (including possibly non-returning function calls, exceptions, etc.)
1334 -- in this case we can use the information whether the control induction
1335 variables can overflow or not in a more efficient way.
1337 if EVERY_ITERATION is true, we know the test is executed on every iteration.
1339 The results (number of iterations and assumptions as described in
1340 comments at struct tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1341 Returns false if it fails to determine number of iterations, true if it
1342 was determined (possibly with some assumptions). */
1345 number_of_iterations_cond (struct loop
*loop
,
1346 tree type
, affine_iv
*iv0
, enum tree_code code
,
1347 affine_iv
*iv1
, struct tree_niter_desc
*niter
,
1348 bool only_exit
, bool every_iteration
)
1350 bool exit_must_be_taken
= false, ret
;
1353 /* If the test is not executed every iteration, wrapping may make the test
1355 TODO: the overflow case can be still used as unreliable estimate of upper
1356 bound. But we have no API to pass it down to number of iterations code
1357 and, at present, it will not use it anyway. */
1358 if (!every_iteration
1359 && (!iv0
->no_overflow
|| !iv1
->no_overflow
1360 || code
== NE_EXPR
|| code
== EQ_EXPR
))
1363 /* The meaning of these assumptions is this:
1365 then the rest of information does not have to be valid
1366 if may_be_zero then the loop does not roll, even if
1368 niter
->assumptions
= boolean_true_node
;
1369 niter
->may_be_zero
= boolean_false_node
;
1370 niter
->niter
= NULL_TREE
;
1372 niter
->bound
= NULL_TREE
;
1373 niter
->cmp
= ERROR_MARK
;
1375 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1376 the control variable is on lhs. */
1377 if (code
== GE_EXPR
|| code
== GT_EXPR
1378 || (code
== NE_EXPR
&& integer_zerop (iv0
->step
)))
1381 code
= swap_tree_comparison (code
);
1384 if (POINTER_TYPE_P (type
))
1386 /* Comparison of pointers is undefined unless both iv0 and iv1 point
1387 to the same object. If they do, the control variable cannot wrap
1388 (as wrap around the bounds of memory will never return a pointer
1389 that would be guaranteed to point to the same object, even if we
1390 avoid undefined behavior by casting to size_t and back). */
1391 iv0
->no_overflow
= true;
1392 iv1
->no_overflow
= true;
1395 /* If the control induction variable does not overflow and the only exit
1396 from the loop is the one that we analyze, we know it must be taken
1400 if (!integer_zerop (iv0
->step
) && iv0
->no_overflow
)
1401 exit_must_be_taken
= true;
1402 else if (!integer_zerop (iv1
->step
) && iv1
->no_overflow
)
1403 exit_must_be_taken
= true;
1406 /* We can handle the case when neither of the sides of the comparison is
1407 invariant, provided that the test is NE_EXPR. This rarely occurs in
1408 practice, but it is simple enough to manage. */
1409 if (!integer_zerop (iv0
->step
) && !integer_zerop (iv1
->step
))
1411 tree step_type
= POINTER_TYPE_P (type
) ? sizetype
: type
;
1412 if (code
!= NE_EXPR
)
1415 iv0
->step
= fold_binary_to_constant (MINUS_EXPR
, step_type
,
1416 iv0
->step
, iv1
->step
);
1417 iv0
->no_overflow
= false;
1418 iv1
->step
= build_int_cst (step_type
, 0);
1419 iv1
->no_overflow
= true;
1422 /* If the result of the comparison is a constant, the loop is weird. More
1423 precise handling would be possible, but the situation is not common enough
1424 to waste time on it. */
1425 if (integer_zerop (iv0
->step
) && integer_zerop (iv1
->step
))
1428 /* Ignore loops of while (i-- < 10) type. */
1429 if (code
!= NE_EXPR
)
1431 if (iv0
->step
&& tree_int_cst_sign_bit (iv0
->step
))
1434 if (!integer_zerop (iv1
->step
) && !tree_int_cst_sign_bit (iv1
->step
))
1438 /* If the loop exits immediately, there is nothing to do. */
1439 tree tem
= fold_binary (code
, boolean_type_node
, iv0
->base
, iv1
->base
);
1440 if (tem
&& integer_zerop (tem
))
1442 niter
->niter
= build_int_cst (unsigned_type_for (type
), 0);
1447 /* OK, now we know we have a senseful loop. Handle several cases, depending
1448 on what comparison operator is used. */
1449 bound_difference (loop
, iv1
->base
, iv0
->base
, &bnds
);
1451 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1454 "Analyzing # of iterations of loop %d\n", loop
->num
);
1456 fprintf (dump_file
, " exit condition ");
1457 dump_affine_iv (dump_file
, iv0
);
1458 fprintf (dump_file
, " %s ",
1459 code
== NE_EXPR
? "!="
1460 : code
== LT_EXPR
? "<"
1462 dump_affine_iv (dump_file
, iv1
);
1463 fprintf (dump_file
, "\n");
1465 fprintf (dump_file
, " bounds on difference of bases: ");
1466 mpz_out_str (dump_file
, 10, bnds
.below
);
1467 fprintf (dump_file
, " ... ");
1468 mpz_out_str (dump_file
, 10, bnds
.up
);
1469 fprintf (dump_file
, "\n");
1475 gcc_assert (integer_zerop (iv1
->step
));
1476 ret
= number_of_iterations_ne (type
, iv0
, iv1
->base
, niter
,
1477 exit_must_be_taken
, &bnds
);
1481 ret
= number_of_iterations_lt (type
, iv0
, iv1
, niter
, exit_must_be_taken
,
1486 ret
= number_of_iterations_le (type
, iv0
, iv1
, niter
, exit_must_be_taken
,
1494 mpz_clear (bnds
.up
);
1495 mpz_clear (bnds
.below
);
1497 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1501 fprintf (dump_file
, " result:\n");
1502 if (!integer_nonzerop (niter
->assumptions
))
1504 fprintf (dump_file
, " under assumptions ");
1505 print_generic_expr (dump_file
, niter
->assumptions
, TDF_SLIM
);
1506 fprintf (dump_file
, "\n");
1509 if (!integer_zerop (niter
->may_be_zero
))
1511 fprintf (dump_file
, " zero if ");
1512 print_generic_expr (dump_file
, niter
->may_be_zero
, TDF_SLIM
);
1513 fprintf (dump_file
, "\n");
1516 fprintf (dump_file
, " # of iterations ");
1517 print_generic_expr (dump_file
, niter
->niter
, TDF_SLIM
);
1518 fprintf (dump_file
, ", bounded by ");
1519 print_decu (niter
->max
, dump_file
);
1520 fprintf (dump_file
, "\n");
1523 fprintf (dump_file
, " failed\n\n");
1528 /* Substitute NEW for OLD in EXPR and fold the result. */
1531 simplify_replace_tree (tree expr
, tree old
, tree new_tree
)
1534 tree ret
= NULL_TREE
, e
, se
;
1539 /* Do not bother to replace constants. */
1540 if (CONSTANT_CLASS_P (old
))
1544 || operand_equal_p (expr
, old
, 0))
1545 return unshare_expr (new_tree
);
1550 n
= TREE_OPERAND_LENGTH (expr
);
1551 for (i
= 0; i
< n
; i
++)
1553 e
= TREE_OPERAND (expr
, i
);
1554 se
= simplify_replace_tree (e
, old
, new_tree
);
1559 ret
= copy_node (expr
);
1561 TREE_OPERAND (ret
, i
) = se
;
1564 return (ret
? fold (ret
) : expr
);
1567 /* Expand definitions of ssa names in EXPR as long as they are simple
1568 enough, and return the new expression. If STOP is specified, stop
1569 expanding if EXPR equals to it. */
1572 expand_simple_operations (tree expr
, tree stop
)
1575 tree ret
= NULL_TREE
, e
, ee
, e1
;
1576 enum tree_code code
;
1579 if (expr
== NULL_TREE
)
1582 if (is_gimple_min_invariant (expr
))
1585 code
= TREE_CODE (expr
);
1586 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code
)))
1588 n
= TREE_OPERAND_LENGTH (expr
);
1589 for (i
= 0; i
< n
; i
++)
1591 e
= TREE_OPERAND (expr
, i
);
1592 ee
= expand_simple_operations (e
, stop
);
1597 ret
= copy_node (expr
);
1599 TREE_OPERAND (ret
, i
) = ee
;
1605 fold_defer_overflow_warnings ();
1607 fold_undefer_and_ignore_overflow_warnings ();
1611 /* Stop if it's not ssa name or the one we don't want to expand. */
1612 if (TREE_CODE (expr
) != SSA_NAME
|| expr
== stop
)
1615 stmt
= SSA_NAME_DEF_STMT (expr
);
1616 if (gimple_code (stmt
) == GIMPLE_PHI
)
1618 basic_block src
, dest
;
1620 if (gimple_phi_num_args (stmt
) != 1)
1622 e
= PHI_ARG_DEF (stmt
, 0);
1624 /* Avoid propagating through loop exit phi nodes, which
1625 could break loop-closed SSA form restrictions. */
1626 dest
= gimple_bb (stmt
);
1627 src
= single_pred (dest
);
1628 if (TREE_CODE (e
) == SSA_NAME
1629 && src
->loop_father
!= dest
->loop_father
)
1632 return expand_simple_operations (e
, stop
);
1634 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
1637 /* Avoid expanding to expressions that contain SSA names that need
1638 to take part in abnormal coalescing. */
1640 FOR_EACH_SSA_TREE_OPERAND (e
, stmt
, iter
, SSA_OP_USE
)
1641 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e
))
1644 e
= gimple_assign_rhs1 (stmt
);
1645 code
= gimple_assign_rhs_code (stmt
);
1646 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1648 if (is_gimple_min_invariant (e
))
1651 if (code
== SSA_NAME
)
1652 return expand_simple_operations (e
, stop
);
1660 /* Casts are simple. */
1661 ee
= expand_simple_operations (e
, stop
);
1662 return fold_build1 (code
, TREE_TYPE (expr
), ee
);
1666 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr
))
1667 && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr
)))
1670 case POINTER_PLUS_EXPR
:
1671 /* And increments and decrements by a constant are simple. */
1672 e1
= gimple_assign_rhs2 (stmt
);
1673 if (!is_gimple_min_invariant (e1
))
1676 ee
= expand_simple_operations (e
, stop
);
1677 return fold_build2 (code
, TREE_TYPE (expr
), ee
, e1
);
1684 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1685 expression (or EXPR unchanged, if no simplification was possible). */
1688 tree_simplify_using_condition_1 (tree cond
, tree expr
)
1691 tree e
, te
, e0
, e1
, e2
, notcond
;
1692 enum tree_code code
= TREE_CODE (expr
);
1694 if (code
== INTEGER_CST
)
1697 if (code
== TRUTH_OR_EXPR
1698 || code
== TRUTH_AND_EXPR
1699 || code
== COND_EXPR
)
1703 e0
= tree_simplify_using_condition_1 (cond
, TREE_OPERAND (expr
, 0));
1704 if (TREE_OPERAND (expr
, 0) != e0
)
1707 e1
= tree_simplify_using_condition_1 (cond
, TREE_OPERAND (expr
, 1));
1708 if (TREE_OPERAND (expr
, 1) != e1
)
1711 if (code
== COND_EXPR
)
1713 e2
= tree_simplify_using_condition_1 (cond
, TREE_OPERAND (expr
, 2));
1714 if (TREE_OPERAND (expr
, 2) != e2
)
1722 if (code
== COND_EXPR
)
1723 expr
= fold_build3 (code
, boolean_type_node
, e0
, e1
, e2
);
1725 expr
= fold_build2 (code
, boolean_type_node
, e0
, e1
);
1731 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
1732 propagation, and vice versa. Fold does not handle this, since it is
1733 considered too expensive. */
1734 if (TREE_CODE (cond
) == EQ_EXPR
)
1736 e0
= TREE_OPERAND (cond
, 0);
1737 e1
= TREE_OPERAND (cond
, 1);
1739 /* We know that e0 == e1. Check whether we cannot simplify expr
1741 e
= simplify_replace_tree (expr
, e0
, e1
);
1742 if (integer_zerop (e
) || integer_nonzerop (e
))
1745 e
= simplify_replace_tree (expr
, e1
, e0
);
1746 if (integer_zerop (e
) || integer_nonzerop (e
))
1749 if (TREE_CODE (expr
) == EQ_EXPR
)
1751 e0
= TREE_OPERAND (expr
, 0);
1752 e1
= TREE_OPERAND (expr
, 1);
1754 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
1755 e
= simplify_replace_tree (cond
, e0
, e1
);
1756 if (integer_zerop (e
))
1758 e
= simplify_replace_tree (cond
, e1
, e0
);
1759 if (integer_zerop (e
))
1762 if (TREE_CODE (expr
) == NE_EXPR
)
1764 e0
= TREE_OPERAND (expr
, 0);
1765 e1
= TREE_OPERAND (expr
, 1);
1767 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
1768 e
= simplify_replace_tree (cond
, e0
, e1
);
1769 if (integer_zerop (e
))
1770 return boolean_true_node
;
1771 e
= simplify_replace_tree (cond
, e1
, e0
);
1772 if (integer_zerop (e
))
1773 return boolean_true_node
;
1776 te
= expand_simple_operations (expr
);
1778 /* Check whether COND ==> EXPR. */
1779 notcond
= invert_truthvalue (cond
);
1780 e
= fold_binary (TRUTH_OR_EXPR
, boolean_type_node
, notcond
, te
);
1781 if (e
&& integer_nonzerop (e
))
1784 /* Check whether COND ==> not EXPR. */
1785 e
= fold_binary (TRUTH_AND_EXPR
, boolean_type_node
, cond
, te
);
1786 if (e
&& integer_zerop (e
))
1792 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1793 expression (or EXPR unchanged, if no simplification was possible).
1794 Wrapper around tree_simplify_using_condition_1 that ensures that chains
1795 of simple operations in definitions of ssa names in COND are expanded,
1796 so that things like casts or incrementing the value of the bound before
1797 the loop do not cause us to fail. */
1800 tree_simplify_using_condition (tree cond
, tree expr
)
1802 cond
= expand_simple_operations (cond
);
1804 return tree_simplify_using_condition_1 (cond
, expr
);
1807 /* Tries to simplify EXPR using the conditions on entry to LOOP.
1808 Returns the simplified expression (or EXPR unchanged, if no
1809 simplification was possible).*/
1812 simplify_using_initial_conditions (struct loop
*loop
, tree expr
)
1820 if (TREE_CODE (expr
) == INTEGER_CST
)
1823 /* Limit walking the dominators to avoid quadraticness in
1824 the number of BBs times the number of loops in degenerate
1826 for (bb
= loop
->header
;
1827 bb
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
) && cnt
< MAX_DOMINATORS_TO_WALK
;
1828 bb
= get_immediate_dominator (CDI_DOMINATORS
, bb
))
1830 if (!single_pred_p (bb
))
1832 e
= single_pred_edge (bb
);
1834 if (!(e
->flags
& (EDGE_TRUE_VALUE
| EDGE_FALSE_VALUE
)))
1837 stmt
= last_stmt (e
->src
);
1838 cond
= fold_build2 (gimple_cond_code (stmt
),
1840 gimple_cond_lhs (stmt
),
1841 gimple_cond_rhs (stmt
));
1842 if (e
->flags
& EDGE_FALSE_VALUE
)
1843 cond
= invert_truthvalue (cond
);
1844 expr
= tree_simplify_using_condition (cond
, expr
);
1851 /* Tries to simplify EXPR using the evolutions of the loop invariants
1852 in the superloops of LOOP. Returns the simplified expression
1853 (or EXPR unchanged, if no simplification was possible). */
1856 simplify_using_outer_evolutions (struct loop
*loop
, tree expr
)
1858 enum tree_code code
= TREE_CODE (expr
);
1862 if (is_gimple_min_invariant (expr
))
1865 if (code
== TRUTH_OR_EXPR
1866 || code
== TRUTH_AND_EXPR
1867 || code
== COND_EXPR
)
1871 e0
= simplify_using_outer_evolutions (loop
, TREE_OPERAND (expr
, 0));
1872 if (TREE_OPERAND (expr
, 0) != e0
)
1875 e1
= simplify_using_outer_evolutions (loop
, TREE_OPERAND (expr
, 1));
1876 if (TREE_OPERAND (expr
, 1) != e1
)
1879 if (code
== COND_EXPR
)
1881 e2
= simplify_using_outer_evolutions (loop
, TREE_OPERAND (expr
, 2));
1882 if (TREE_OPERAND (expr
, 2) != e2
)
1890 if (code
== COND_EXPR
)
1891 expr
= fold_build3 (code
, boolean_type_node
, e0
, e1
, e2
);
1893 expr
= fold_build2 (code
, boolean_type_node
, e0
, e1
);
1899 e
= instantiate_parameters (loop
, expr
);
1900 if (is_gimple_min_invariant (e
))
1906 /* Returns true if EXIT is the only possible exit from LOOP. */
1909 loop_only_exit_p (const struct loop
*loop
, const_edge exit
)
1912 gimple_stmt_iterator bsi
;
1916 if (exit
!= single_exit (loop
))
1919 body
= get_loop_body (loop
);
1920 for (i
= 0; i
< loop
->num_nodes
; i
++)
1922 for (bsi
= gsi_start_bb (body
[i
]); !gsi_end_p (bsi
); gsi_next (&bsi
))
1924 call
= gsi_stmt (bsi
);
1925 if (gimple_code (call
) != GIMPLE_CALL
)
1928 if (gimple_has_side_effects (call
))
1940 /* Stores description of number of iterations of LOOP derived from
1941 EXIT (an exit edge of the LOOP) in NITER. Returns true if some
1942 useful information could be derived (and fields of NITER has
1943 meaning described in comments at struct tree_niter_desc
1944 declaration), false otherwise. If WARN is true and
1945 -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
1946 potentially unsafe assumptions.
1947 When EVERY_ITERATION is true, only tests that are known to be executed
1948 every iteration are considered (i.e. only test that alone bounds the loop).
1952 number_of_iterations_exit (struct loop
*loop
, edge exit
,
1953 struct tree_niter_desc
*niter
,
1954 bool warn
, bool every_iteration
)
1960 enum tree_code code
;
1964 safe
= dominated_by_p (CDI_DOMINATORS
, loop
->latch
, exit
->src
);
1966 if (every_iteration
&& !safe
)
1969 niter
->assumptions
= boolean_false_node
;
1970 niter
->control
.base
= NULL_TREE
;
1971 niter
->control
.step
= NULL_TREE
;
1972 niter
->control
.no_overflow
= false;
1973 last
= last_stmt (exit
->src
);
1976 stmt
= dyn_cast
<gcond
*> (last
);
1980 /* We want the condition for staying inside loop. */
1981 code
= gimple_cond_code (stmt
);
1982 if (exit
->flags
& EDGE_TRUE_VALUE
)
1983 code
= invert_tree_comparison (code
, false);
1998 op0
= gimple_cond_lhs (stmt
);
1999 op1
= gimple_cond_rhs (stmt
);
2000 type
= TREE_TYPE (op0
);
2002 if (TREE_CODE (type
) != INTEGER_TYPE
2003 && !POINTER_TYPE_P (type
))
2006 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op0
, &iv0
, false))
2008 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op1
, &iv1
, false))
2011 /* We don't want to see undefined signed overflow warnings while
2012 computing the number of iterations. */
2013 fold_defer_overflow_warnings ();
2015 iv0
.base
= expand_simple_operations (iv0
.base
);
2016 iv1
.base
= expand_simple_operations (iv1
.base
);
2017 if (!number_of_iterations_cond (loop
, type
, &iv0
, code
, &iv1
, niter
,
2018 loop_only_exit_p (loop
, exit
), safe
))
2020 fold_undefer_and_ignore_overflow_warnings ();
2026 niter
->assumptions
= simplify_using_outer_evolutions (loop
,
2027 niter
->assumptions
);
2028 niter
->may_be_zero
= simplify_using_outer_evolutions (loop
,
2029 niter
->may_be_zero
);
2030 niter
->niter
= simplify_using_outer_evolutions (loop
, niter
->niter
);
2034 = simplify_using_initial_conditions (loop
,
2035 niter
->assumptions
);
2037 = simplify_using_initial_conditions (loop
,
2038 niter
->may_be_zero
);
2040 fold_undefer_and_ignore_overflow_warnings ();
2042 /* If NITER has simplified into a constant, update MAX. */
2043 if (TREE_CODE (niter
->niter
) == INTEGER_CST
)
2044 niter
->max
= wi::to_widest (niter
->niter
);
2046 if (integer_onep (niter
->assumptions
))
2049 /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
2050 But if we can prove that there is overflow or some other source of weird
2051 behavior, ignore the loop even with -funsafe-loop-optimizations. */
2052 if (integer_zerop (niter
->assumptions
) || !single_exit (loop
))
2055 if (flag_unsafe_loop_optimizations
)
2056 niter
->assumptions
= boolean_true_node
;
2060 const char *wording
;
2061 location_t loc
= gimple_location (stmt
);
2063 /* We can provide a more specific warning if one of the operator is
2064 constant and the other advances by +1 or -1. */
2065 if (!integer_zerop (iv1
.step
)
2066 ? (integer_zerop (iv0
.step
)
2067 && (integer_onep (iv1
.step
) || integer_all_onesp (iv1
.step
)))
2068 : (integer_onep (iv0
.step
) || integer_all_onesp (iv0
.step
)))
2070 flag_unsafe_loop_optimizations
2071 ? N_("assuming that the loop is not infinite")
2072 : N_("cannot optimize possibly infinite loops");
2075 flag_unsafe_loop_optimizations
2076 ? N_("assuming that the loop counter does not overflow")
2077 : N_("cannot optimize loop, the loop counter may overflow");
2079 warning_at ((LOCATION_LINE (loc
) > 0) ? loc
: input_location
,
2080 OPT_Wunsafe_loop_optimizations
, "%s", gettext (wording
));
2083 return flag_unsafe_loop_optimizations
;
2086 /* Try to determine the number of iterations of LOOP. If we succeed,
2087 expression giving number of iterations is returned and *EXIT is
2088 set to the edge from that the information is obtained. Otherwise
2089 chrec_dont_know is returned. */
2092 find_loop_niter (struct loop
*loop
, edge
*exit
)
2095 vec
<edge
> exits
= get_loop_exit_edges (loop
);
2097 tree niter
= NULL_TREE
, aniter
;
2098 struct tree_niter_desc desc
;
2101 FOR_EACH_VEC_ELT (exits
, i
, ex
)
2103 if (!number_of_iterations_exit (loop
, ex
, &desc
, false))
2106 if (integer_nonzerop (desc
.may_be_zero
))
2108 /* We exit in the first iteration through this exit.
2109 We won't find anything better. */
2110 niter
= build_int_cst (unsigned_type_node
, 0);
2115 if (!integer_zerop (desc
.may_be_zero
))
2118 aniter
= desc
.niter
;
2122 /* Nothing recorded yet. */
2128 /* Prefer constants, the lower the better. */
2129 if (TREE_CODE (aniter
) != INTEGER_CST
)
2132 if (TREE_CODE (niter
) != INTEGER_CST
)
2139 if (tree_int_cst_lt (aniter
, niter
))
2148 return niter
? niter
: chrec_dont_know
;
2151 /* Return true if loop is known to have bounded number of iterations. */
2154 finite_loop_p (struct loop
*loop
)
2159 if (flag_unsafe_loop_optimizations
)
2161 flags
= flags_from_decl_or_type (current_function_decl
);
2162 if ((flags
& (ECF_CONST
|ECF_PURE
)) && !(flags
& ECF_LOOPING_CONST_OR_PURE
))
2164 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2165 fprintf (dump_file
, "Found loop %i to be finite: it is within pure or const function.\n",
2170 if (loop
->any_upper_bound
2171 || max_loop_iterations (loop
, &nit
))
2173 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2174 fprintf (dump_file
, "Found loop %i to be finite: upper bound found.\n",
2183 Analysis of a number of iterations of a loop by a brute-force evaluation.
2187 /* Bound on the number of iterations we try to evaluate. */
2189 #define MAX_ITERATIONS_TO_TRACK \
2190 ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
2192 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
2193 result by a chain of operations such that all but exactly one of their
2194 operands are constants. */
2197 chain_of_csts_start (struct loop
*loop
, tree x
)
2199 gimple stmt
= SSA_NAME_DEF_STMT (x
);
2201 basic_block bb
= gimple_bb (stmt
);
2202 enum tree_code code
;
2205 || !flow_bb_inside_loop_p (loop
, bb
))
2208 if (gimple_code (stmt
) == GIMPLE_PHI
)
2210 if (bb
== loop
->header
)
2211 return as_a
<gphi
*> (stmt
);
2216 if (gimple_code (stmt
) != GIMPLE_ASSIGN
2217 || gimple_assign_rhs_class (stmt
) == GIMPLE_TERNARY_RHS
)
2220 code
= gimple_assign_rhs_code (stmt
);
2221 if (gimple_references_memory_p (stmt
)
2222 || TREE_CODE_CLASS (code
) == tcc_reference
2223 || (code
== ADDR_EXPR
2224 && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt
))))
2227 use
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
2228 if (use
== NULL_TREE
)
2231 return chain_of_csts_start (loop
, use
);
2234 /* Determines whether the expression X is derived from a result of a phi node
2235 in header of LOOP such that
2237 * the derivation of X consists only from operations with constants
2238 * the initial value of the phi node is constant
2239 * the value of the phi node in the next iteration can be derived from the
2240 value in the current iteration by a chain of operations with constants.
2242 If such phi node exists, it is returned, otherwise NULL is returned. */
2245 get_base_for (struct loop
*loop
, tree x
)
2250 if (is_gimple_min_invariant (x
))
2253 phi
= chain_of_csts_start (loop
, x
);
2257 init
= PHI_ARG_DEF_FROM_EDGE (phi
, loop_preheader_edge (loop
));
2258 next
= PHI_ARG_DEF_FROM_EDGE (phi
, loop_latch_edge (loop
));
2260 if (TREE_CODE (next
) != SSA_NAME
)
2263 if (!is_gimple_min_invariant (init
))
2266 if (chain_of_csts_start (loop
, next
) != phi
)
2272 /* Given an expression X, then
2274 * if X is NULL_TREE, we return the constant BASE.
2275 * otherwise X is a SSA name, whose value in the considered loop is derived
2276 by a chain of operations with constant from a result of a phi node in
2277 the header of the loop. Then we return value of X when the value of the
2278 result of this phi node is given by the constant BASE. */
2281 get_val_for (tree x
, tree base
)
2285 gcc_checking_assert (is_gimple_min_invariant (base
));
2290 stmt
= SSA_NAME_DEF_STMT (x
);
2291 if (gimple_code (stmt
) == GIMPLE_PHI
)
2294 gcc_checking_assert (is_gimple_assign (stmt
));
2296 /* STMT must be either an assignment of a single SSA name or an
2297 expression involving an SSA name and a constant. Try to fold that
2298 expression using the value for the SSA name. */
2299 if (gimple_assign_ssa_name_copy_p (stmt
))
2300 return get_val_for (gimple_assign_rhs1 (stmt
), base
);
2301 else if (gimple_assign_rhs_class (stmt
) == GIMPLE_UNARY_RHS
2302 && TREE_CODE (gimple_assign_rhs1 (stmt
)) == SSA_NAME
)
2304 return fold_build1 (gimple_assign_rhs_code (stmt
),
2305 gimple_expr_type (stmt
),
2306 get_val_for (gimple_assign_rhs1 (stmt
), base
));
2308 else if (gimple_assign_rhs_class (stmt
) == GIMPLE_BINARY_RHS
)
2310 tree rhs1
= gimple_assign_rhs1 (stmt
);
2311 tree rhs2
= gimple_assign_rhs2 (stmt
);
2312 if (TREE_CODE (rhs1
) == SSA_NAME
)
2313 rhs1
= get_val_for (rhs1
, base
);
2314 else if (TREE_CODE (rhs2
) == SSA_NAME
)
2315 rhs2
= get_val_for (rhs2
, base
);
2318 return fold_build2 (gimple_assign_rhs_code (stmt
),
2319 gimple_expr_type (stmt
), rhs1
, rhs2
);
2326 /* Tries to count the number of iterations of LOOP till it exits by EXIT
2327 by brute force -- i.e. by determining the value of the operands of the
2328 condition at EXIT in first few iterations of the loop (assuming that
2329 these values are constant) and determining the first one in that the
2330 condition is not satisfied. Returns the constant giving the number
2331 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
2334 loop_niter_by_eval (struct loop
*loop
, edge exit
)
2337 tree op
[2], val
[2], next
[2], aval
[2];
2343 cond
= last_stmt (exit
->src
);
2344 if (!cond
|| gimple_code (cond
) != GIMPLE_COND
)
2345 return chrec_dont_know
;
2347 cmp
= gimple_cond_code (cond
);
2348 if (exit
->flags
& EDGE_TRUE_VALUE
)
2349 cmp
= invert_tree_comparison (cmp
, false);
2359 op
[0] = gimple_cond_lhs (cond
);
2360 op
[1] = gimple_cond_rhs (cond
);
2364 return chrec_dont_know
;
2367 for (j
= 0; j
< 2; j
++)
2369 if (is_gimple_min_invariant (op
[j
]))
2372 next
[j
] = NULL_TREE
;
2377 phi
= get_base_for (loop
, op
[j
]);
2379 return chrec_dont_know
;
2380 val
[j
] = PHI_ARG_DEF_FROM_EDGE (phi
, loop_preheader_edge (loop
));
2381 next
[j
] = PHI_ARG_DEF_FROM_EDGE (phi
, loop_latch_edge (loop
));
2385 /* Don't issue signed overflow warnings. */
2386 fold_defer_overflow_warnings ();
2388 for (i
= 0; i
< MAX_ITERATIONS_TO_TRACK
; i
++)
2390 for (j
= 0; j
< 2; j
++)
2391 aval
[j
] = get_val_for (op
[j
], val
[j
]);
2393 acnd
= fold_binary (cmp
, boolean_type_node
, aval
[0], aval
[1]);
2394 if (acnd
&& integer_zerop (acnd
))
2396 fold_undefer_and_ignore_overflow_warnings ();
2397 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2399 "Proved that loop %d iterates %d times using brute force.\n",
2401 return build_int_cst (unsigned_type_node
, i
);
2404 for (j
= 0; j
< 2; j
++)
2406 val
[j
] = get_val_for (next
[j
], val
[j
]);
2407 if (!is_gimple_min_invariant (val
[j
]))
2409 fold_undefer_and_ignore_overflow_warnings ();
2410 return chrec_dont_know
;
2415 fold_undefer_and_ignore_overflow_warnings ();
2417 return chrec_dont_know
;
2420 /* Finds the exit of the LOOP by that the loop exits after a constant
2421 number of iterations and stores the exit edge to *EXIT. The constant
2422 giving the number of iterations of LOOP is returned. The number of
2423 iterations is determined using loop_niter_by_eval (i.e. by brute force
2424 evaluation). If we are unable to find the exit for that loop_niter_by_eval
2425 determines the number of iterations, chrec_dont_know is returned. */
2428 find_loop_niter_by_eval (struct loop
*loop
, edge
*exit
)
2431 vec
<edge
> exits
= get_loop_exit_edges (loop
);
2433 tree niter
= NULL_TREE
, aniter
;
2437 /* Loops with multiple exits are expensive to handle and less important. */
2438 if (!flag_expensive_optimizations
2439 && exits
.length () > 1)
2442 return chrec_dont_know
;
2445 FOR_EACH_VEC_ELT (exits
, i
, ex
)
2447 if (!just_once_each_iteration_p (loop
, ex
->src
))
2450 aniter
= loop_niter_by_eval (loop
, ex
);
2451 if (chrec_contains_undetermined (aniter
))
2455 && !tree_int_cst_lt (aniter
, niter
))
2463 return niter
? niter
: chrec_dont_know
;
2468 Analysis of upper bounds on number of iterations of a loop.
2472 static widest_int
derive_constant_upper_bound_ops (tree
, tree
,
2473 enum tree_code
, tree
);
2475 /* Returns a constant upper bound on the value of the right-hand side of
2476 an assignment statement STMT. */
2479 derive_constant_upper_bound_assign (gimple stmt
)
2481 enum tree_code code
= gimple_assign_rhs_code (stmt
);
2482 tree op0
= gimple_assign_rhs1 (stmt
);
2483 tree op1
= gimple_assign_rhs2 (stmt
);
2485 return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt
)),
2489 /* Returns a constant upper bound on the value of expression VAL. VAL
2490 is considered to be unsigned. If its type is signed, its value must
2494 derive_constant_upper_bound (tree val
)
2496 enum tree_code code
;
2499 extract_ops_from_tree (val
, &code
, &op0
, &op1
);
2500 return derive_constant_upper_bound_ops (TREE_TYPE (val
), op0
, code
, op1
);
2503 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
2504 whose type is TYPE. The expression is considered to be unsigned. If
2505 its type is signed, its value must be nonnegative. */
2508 derive_constant_upper_bound_ops (tree type
, tree op0
,
2509 enum tree_code code
, tree op1
)
2512 widest_int bnd
, max
, mmax
, cst
;
2515 if (INTEGRAL_TYPE_P (type
))
2516 maxt
= TYPE_MAX_VALUE (type
);
2518 maxt
= upper_bound_in_type (type
, type
);
2520 max
= wi::to_widest (maxt
);
2525 return wi::to_widest (op0
);
2528 subtype
= TREE_TYPE (op0
);
2529 if (!TYPE_UNSIGNED (subtype
)
2530 /* If TYPE is also signed, the fact that VAL is nonnegative implies
2531 that OP0 is nonnegative. */
2532 && TYPE_UNSIGNED (type
)
2533 && !tree_expr_nonnegative_p (op0
))
2535 /* If we cannot prove that the casted expression is nonnegative,
2536 we cannot establish more useful upper bound than the precision
2537 of the type gives us. */
2541 /* We now know that op0 is an nonnegative value. Try deriving an upper
2543 bnd
= derive_constant_upper_bound (op0
);
2545 /* If the bound does not fit in TYPE, max. value of TYPE could be
2547 if (wi::ltu_p (max
, bnd
))
2553 case POINTER_PLUS_EXPR
:
2555 if (TREE_CODE (op1
) != INTEGER_CST
2556 || !tree_expr_nonnegative_p (op0
))
2559 /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
2560 choose the most logical way how to treat this constant regardless
2561 of the signedness of the type. */
2562 cst
= wi::sext (wi::to_widest (op1
), TYPE_PRECISION (type
));
2563 if (code
!= MINUS_EXPR
)
2566 bnd
= derive_constant_upper_bound (op0
);
2568 if (wi::neg_p (cst
))
2571 /* Avoid CST == 0x80000... */
2572 if (wi::neg_p (cst
))
2575 /* OP0 + CST. We need to check that
2576 BND <= MAX (type) - CST. */
2579 if (wi::ltu_p (bnd
, max
))
2586 /* OP0 - CST, where CST >= 0.
2588 If TYPE is signed, we have already verified that OP0 >= 0, and we
2589 know that the result is nonnegative. This implies that
2592 If TYPE is unsigned, we must additionally know that OP0 >= CST,
2593 otherwise the operation underflows.
2596 /* This should only happen if the type is unsigned; however, for
2597 buggy programs that use overflowing signed arithmetics even with
2598 -fno-wrapv, this condition may also be true for signed values. */
2599 if (wi::ltu_p (bnd
, cst
))
2602 if (TYPE_UNSIGNED (type
))
2604 tree tem
= fold_binary (GE_EXPR
, boolean_type_node
, op0
,
2605 wide_int_to_tree (type
, cst
));
2606 if (!tem
|| integer_nonzerop (tem
))
2615 case FLOOR_DIV_EXPR
:
2616 case EXACT_DIV_EXPR
:
2617 if (TREE_CODE (op1
) != INTEGER_CST
2618 || tree_int_cst_sign_bit (op1
))
2621 bnd
= derive_constant_upper_bound (op0
);
2622 return wi::udiv_floor (bnd
, wi::to_widest (op1
));
2625 if (TREE_CODE (op1
) != INTEGER_CST
2626 || tree_int_cst_sign_bit (op1
))
2628 return wi::to_widest (op1
);
2631 stmt
= SSA_NAME_DEF_STMT (op0
);
2632 if (gimple_code (stmt
) != GIMPLE_ASSIGN
2633 || gimple_assign_lhs (stmt
) != op0
)
2635 return derive_constant_upper_bound_assign (stmt
);
2642 /* Emit a -Waggressive-loop-optimizations warning if needed. */
2645 do_warn_aggressive_loop_optimizations (struct loop
*loop
,
2646 widest_int i_bound
, gimple stmt
)
2648 /* Don't warn if the loop doesn't have known constant bound. */
2649 if (!loop
->nb_iterations
2650 || TREE_CODE (loop
->nb_iterations
) != INTEGER_CST
2651 || !warn_aggressive_loop_optimizations
2652 /* To avoid warning multiple times for the same loop,
2653 only start warning when we preserve loops. */
2654 || (cfun
->curr_properties
& PROP_loops
) == 0
2655 /* Only warn once per loop. */
2656 || loop
->warned_aggressive_loop_optimizations
2657 /* Only warn if undefined behavior gives us lower estimate than the
2658 known constant bound. */
2659 || wi::cmpu (i_bound
, wi::to_widest (loop
->nb_iterations
)) >= 0
2660 /* And undefined behavior happens unconditionally. */
2661 || !dominated_by_p (CDI_DOMINATORS
, loop
->latch
, gimple_bb (stmt
)))
2664 edge e
= single_exit (loop
);
2668 gimple estmt
= last_stmt (e
->src
);
2669 if (warning_at (gimple_location (stmt
), OPT_Waggressive_loop_optimizations
,
2670 "iteration %E invokes undefined behavior",
2671 wide_int_to_tree (TREE_TYPE (loop
->nb_iterations
),
2673 inform (gimple_location (estmt
), "containing loop");
2674 loop
->warned_aggressive_loop_optimizations
= true;
2677 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
2678 is true if the loop is exited immediately after STMT, and this exit
2679 is taken at last when the STMT is executed BOUND + 1 times.
2680 REALISTIC is true if BOUND is expected to be close to the real number
2681 of iterations. UPPER is true if we are sure the loop iterates at most
2682 BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
2685 record_estimate (struct loop
*loop
, tree bound
, const widest_int
&i_bound
,
2686 gimple at_stmt
, bool is_exit
, bool realistic
, bool upper
)
2690 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2692 fprintf (dump_file
, "Statement %s", is_exit
? "(exit)" : "");
2693 print_gimple_stmt (dump_file
, at_stmt
, 0, TDF_SLIM
);
2694 fprintf (dump_file
, " is %sexecuted at most ",
2695 upper
? "" : "probably ");
2696 print_generic_expr (dump_file
, bound
, TDF_SLIM
);
2697 fprintf (dump_file
, " (bounded by ");
2698 print_decu (i_bound
, dump_file
);
2699 fprintf (dump_file
, ") + 1 times in loop %d.\n", loop
->num
);
2702 /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
2703 real number of iterations. */
2704 if (TREE_CODE (bound
) != INTEGER_CST
)
2707 gcc_checking_assert (i_bound
== wi::to_widest (bound
));
2708 if (!upper
&& !realistic
)
2711 /* If we have a guaranteed upper bound, record it in the appropriate
2712 list, unless this is an !is_exit bound (i.e. undefined behavior in
2713 at_stmt) in a loop with known constant number of iterations. */
2716 || loop
->nb_iterations
== NULL_TREE
2717 || TREE_CODE (loop
->nb_iterations
) != INTEGER_CST
))
2719 struct nb_iter_bound
*elt
= ggc_alloc
<nb_iter_bound
> ();
2721 elt
->bound
= i_bound
;
2722 elt
->stmt
= at_stmt
;
2723 elt
->is_exit
= is_exit
;
2724 elt
->next
= loop
->bounds
;
2728 /* If statement is executed on every path to the loop latch, we can directly
2729 infer the upper bound on the # of iterations of the loop. */
2730 if (!dominated_by_p (CDI_DOMINATORS
, loop
->latch
, gimple_bb (at_stmt
)))
2733 /* Update the number of iteration estimates according to the bound.
2734 If at_stmt is an exit then the loop latch is executed at most BOUND times,
2735 otherwise it can be executed BOUND + 1 times. We will lower the estimate
2736 later if such statement must be executed on last iteration */
2741 widest_int new_i_bound
= i_bound
+ delta
;
2743 /* If an overflow occurred, ignore the result. */
2744 if (wi::ltu_p (new_i_bound
, delta
))
2747 if (upper
&& !is_exit
)
2748 do_warn_aggressive_loop_optimizations (loop
, new_i_bound
, at_stmt
);
2749 record_niter_bound (loop
, new_i_bound
, realistic
, upper
);
2752 /* Records the control iv analyzed in NITER for LOOP if the iv is valid
2753 and doesn't overflow. */
2756 record_control_iv (struct loop
*loop
, struct tree_niter_desc
*niter
)
2758 struct control_iv
*iv
;
2760 if (!niter
->control
.base
|| !niter
->control
.step
)
2763 if (!integer_onep (niter
->assumptions
) || !niter
->control
.no_overflow
)
2766 iv
= ggc_alloc
<control_iv
> ();
2767 iv
->base
= niter
->control
.base
;
2768 iv
->step
= niter
->control
.step
;
2769 iv
->next
= loop
->control_ivs
;
2770 loop
->control_ivs
= iv
;
2775 /* Record the estimate on number of iterations of LOOP based on the fact that
2776 the induction variable BASE + STEP * i evaluated in STMT does not wrap and
2777 its values belong to the range <LOW, HIGH>. REALISTIC is true if the
2778 estimated number of iterations is expected to be close to the real one.
2779 UPPER is true if we are sure the induction variable does not wrap. */
2782 record_nonwrapping_iv (struct loop
*loop
, tree base
, tree step
, gimple stmt
,
2783 tree low
, tree high
, bool realistic
, bool upper
)
2785 tree niter_bound
, extreme
, delta
;
2786 tree type
= TREE_TYPE (base
), unsigned_type
;
2787 tree orig_base
= base
;
2789 if (TREE_CODE (step
) != INTEGER_CST
|| integer_zerop (step
))
2792 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2794 fprintf (dump_file
, "Induction variable (");
2795 print_generic_expr (dump_file
, TREE_TYPE (base
), TDF_SLIM
);
2796 fprintf (dump_file
, ") ");
2797 print_generic_expr (dump_file
, base
, TDF_SLIM
);
2798 fprintf (dump_file
, " + ");
2799 print_generic_expr (dump_file
, step
, TDF_SLIM
);
2800 fprintf (dump_file
, " * iteration does not wrap in statement ");
2801 print_gimple_stmt (dump_file
, stmt
, 0, TDF_SLIM
);
2802 fprintf (dump_file
, " in loop %d.\n", loop
->num
);
2805 unsigned_type
= unsigned_type_for (type
);
2806 base
= fold_convert (unsigned_type
, base
);
2807 step
= fold_convert (unsigned_type
, step
);
2809 if (tree_int_cst_sign_bit (step
))
2812 extreme
= fold_convert (unsigned_type
, low
);
2813 if (TREE_CODE (orig_base
) == SSA_NAME
2814 && TREE_CODE (high
) == INTEGER_CST
2815 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base
))
2816 && get_range_info (orig_base
, &min
, &max
) == VR_RANGE
2817 && wi::gts_p (high
, max
))
2818 base
= wide_int_to_tree (unsigned_type
, max
);
2819 else if (TREE_CODE (base
) != INTEGER_CST
)
2820 base
= fold_convert (unsigned_type
, high
);
2821 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, base
, extreme
);
2822 step
= fold_build1 (NEGATE_EXPR
, unsigned_type
, step
);
2827 extreme
= fold_convert (unsigned_type
, high
);
2828 if (TREE_CODE (orig_base
) == SSA_NAME
2829 && TREE_CODE (low
) == INTEGER_CST
2830 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base
))
2831 && get_range_info (orig_base
, &min
, &max
) == VR_RANGE
2832 && wi::gts_p (min
, low
))
2833 base
= wide_int_to_tree (unsigned_type
, min
);
2834 else if (TREE_CODE (base
) != INTEGER_CST
)
2835 base
= fold_convert (unsigned_type
, low
);
2836 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, extreme
, base
);
2839 /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
2840 would get out of the range. */
2841 niter_bound
= fold_build2 (FLOOR_DIV_EXPR
, unsigned_type
, delta
, step
);
2842 widest_int max
= derive_constant_upper_bound (niter_bound
);
2843 record_estimate (loop
, niter_bound
, max
, stmt
, false, realistic
, upper
);
2846 /* Determine information about number of iterations a LOOP from the index
2847 IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
2848 guaranteed to be executed in every iteration of LOOP. Callback for
2858 idx_infer_loop_bounds (tree base
, tree
*idx
, void *dta
)
2860 struct ilb_data
*data
= (struct ilb_data
*) dta
;
2861 tree ev
, init
, step
;
2862 tree low
, high
, type
, next
;
2863 bool sign
, upper
= true, at_end
= false;
2864 struct loop
*loop
= data
->loop
;
2865 bool reliable
= true;
2867 if (TREE_CODE (base
) != ARRAY_REF
)
2870 /* For arrays at the end of the structure, we are not guaranteed that they
2871 do not really extend over their declared size. However, for arrays of
2872 size greater than one, this is unlikely to be intended. */
2873 if (array_at_struct_end_p (base
))
2879 struct loop
*dloop
= loop_containing_stmt (data
->stmt
);
2883 ev
= analyze_scalar_evolution (dloop
, *idx
);
2884 ev
= instantiate_parameters (loop
, ev
);
2885 init
= initial_condition (ev
);
2886 step
= evolution_part_in_loop_num (ev
, loop
->num
);
2890 || TREE_CODE (step
) != INTEGER_CST
2891 || integer_zerop (step
)
2892 || tree_contains_chrecs (init
, NULL
)
2893 || chrec_contains_symbols_defined_in_loop (init
, loop
->num
))
2896 low
= array_ref_low_bound (base
);
2897 high
= array_ref_up_bound (base
);
2899 /* The case of nonconstant bounds could be handled, but it would be
2901 if (TREE_CODE (low
) != INTEGER_CST
2903 || TREE_CODE (high
) != INTEGER_CST
)
2905 sign
= tree_int_cst_sign_bit (step
);
2906 type
= TREE_TYPE (step
);
2908 /* The array of length 1 at the end of a structure most likely extends
2909 beyond its bounds. */
2911 && operand_equal_p (low
, high
, 0))
2914 /* In case the relevant bound of the array does not fit in type, or
2915 it does, but bound + step (in type) still belongs into the range of the
2916 array, the index may wrap and still stay within the range of the array
2917 (consider e.g. if the array is indexed by the full range of
2920 To make things simpler, we require both bounds to fit into type, although
2921 there are cases where this would not be strictly necessary. */
2922 if (!int_fits_type_p (high
, type
)
2923 || !int_fits_type_p (low
, type
))
2925 low
= fold_convert (type
, low
);
2926 high
= fold_convert (type
, high
);
2929 next
= fold_binary (PLUS_EXPR
, type
, low
, step
);
2931 next
= fold_binary (PLUS_EXPR
, type
, high
, step
);
2933 if (tree_int_cst_compare (low
, next
) <= 0
2934 && tree_int_cst_compare (next
, high
) <= 0)
2937 /* If access is not executed on every iteration, we must ensure that overlow may
2938 not make the access valid later. */
2939 if (!dominated_by_p (CDI_DOMINATORS
, loop
->latch
, gimple_bb (data
->stmt
))
2940 && scev_probably_wraps_p (initial_condition_in_loop_num (ev
, loop
->num
),
2941 step
, data
->stmt
, loop
, true))
2944 record_nonwrapping_iv (loop
, init
, step
, data
->stmt
, low
, high
, reliable
, upper
);
2948 /* Determine information about number of iterations a LOOP from the bounds
2949 of arrays in the data reference REF accessed in STMT. RELIABLE is true if
2950 STMT is guaranteed to be executed in every iteration of LOOP.*/
2953 infer_loop_bounds_from_ref (struct loop
*loop
, gimple stmt
, tree ref
)
2955 struct ilb_data data
;
2959 for_each_index (&ref
, idx_infer_loop_bounds
, &data
);
2962 /* Determine information about number of iterations of a LOOP from the way
2963 arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
2964 executed in every iteration of LOOP. */
2967 infer_loop_bounds_from_array (struct loop
*loop
, gimple stmt
)
2969 if (is_gimple_assign (stmt
))
2971 tree op0
= gimple_assign_lhs (stmt
);
2972 tree op1
= gimple_assign_rhs1 (stmt
);
2974 /* For each memory access, analyze its access function
2975 and record a bound on the loop iteration domain. */
2976 if (REFERENCE_CLASS_P (op0
))
2977 infer_loop_bounds_from_ref (loop
, stmt
, op0
);
2979 if (REFERENCE_CLASS_P (op1
))
2980 infer_loop_bounds_from_ref (loop
, stmt
, op1
);
2982 else if (is_gimple_call (stmt
))
2985 unsigned i
, n
= gimple_call_num_args (stmt
);
2987 lhs
= gimple_call_lhs (stmt
);
2988 if (lhs
&& REFERENCE_CLASS_P (lhs
))
2989 infer_loop_bounds_from_ref (loop
, stmt
, lhs
);
2991 for (i
= 0; i
< n
; i
++)
2993 arg
= gimple_call_arg (stmt
, i
);
2994 if (REFERENCE_CLASS_P (arg
))
2995 infer_loop_bounds_from_ref (loop
, stmt
, arg
);
3000 /* Determine information about number of iterations of a LOOP from the fact
3001 that pointer arithmetics in STMT does not overflow. */
3004 infer_loop_bounds_from_pointer_arith (struct loop
*loop
, gimple stmt
)
3006 tree def
, base
, step
, scev
, type
, low
, high
;
3009 if (!is_gimple_assign (stmt
)
3010 || gimple_assign_rhs_code (stmt
) != POINTER_PLUS_EXPR
)
3013 def
= gimple_assign_lhs (stmt
);
3014 if (TREE_CODE (def
) != SSA_NAME
)
3017 type
= TREE_TYPE (def
);
3018 if (!nowrap_type_p (type
))
3021 ptr
= gimple_assign_rhs1 (stmt
);
3022 if (!expr_invariant_in_loop_p (loop
, ptr
))
3025 var
= gimple_assign_rhs2 (stmt
);
3026 if (TYPE_PRECISION (type
) != TYPE_PRECISION (TREE_TYPE (var
)))
3029 scev
= instantiate_parameters (loop
, analyze_scalar_evolution (loop
, def
));
3030 if (chrec_contains_undetermined (scev
))
3033 base
= initial_condition_in_loop_num (scev
, loop
->num
);
3034 step
= evolution_part_in_loop_num (scev
, loop
->num
);
3037 || TREE_CODE (step
) != INTEGER_CST
3038 || tree_contains_chrecs (base
, NULL
)
3039 || chrec_contains_symbols_defined_in_loop (base
, loop
->num
))
3042 low
= lower_bound_in_type (type
, type
);
3043 high
= upper_bound_in_type (type
, type
);
3045 /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
3046 produce a NULL pointer. The contrary would mean NULL points to an object,
3047 while NULL is supposed to compare unequal with the address of all objects.
3048 Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
3049 NULL pointer since that would mean wrapping, which we assume here not to
3050 happen. So, we can exclude NULL from the valid range of pointer
3052 if (flag_delete_null_pointer_checks
&& int_cst_value (low
) == 0)
3053 low
= build_int_cstu (TREE_TYPE (low
), TYPE_ALIGN_UNIT (TREE_TYPE (type
)));
3055 record_nonwrapping_iv (loop
, base
, step
, stmt
, low
, high
, false, true);
3058 /* Determine information about number of iterations of a LOOP from the fact
3059 that signed arithmetics in STMT does not overflow. */
3062 infer_loop_bounds_from_signedness (struct loop
*loop
, gimple stmt
)
3064 tree def
, base
, step
, scev
, type
, low
, high
;
3066 if (gimple_code (stmt
) != GIMPLE_ASSIGN
)
3069 def
= gimple_assign_lhs (stmt
);
3071 if (TREE_CODE (def
) != SSA_NAME
)
3074 type
= TREE_TYPE (def
);
3075 if (!INTEGRAL_TYPE_P (type
)
3076 || !TYPE_OVERFLOW_UNDEFINED (type
))
3079 scev
= instantiate_parameters (loop
, analyze_scalar_evolution (loop
, def
));
3080 if (chrec_contains_undetermined (scev
))
3083 base
= initial_condition_in_loop_num (scev
, loop
->num
);
3084 step
= evolution_part_in_loop_num (scev
, loop
->num
);
3087 || TREE_CODE (step
) != INTEGER_CST
3088 || tree_contains_chrecs (base
, NULL
)
3089 || chrec_contains_symbols_defined_in_loop (base
, loop
->num
))
3092 low
= lower_bound_in_type (type
, type
);
3093 high
= upper_bound_in_type (type
, type
);
3095 record_nonwrapping_iv (loop
, base
, step
, stmt
, low
, high
, false, true);
3098 /* The following analyzers are extracting informations on the bounds
3099 of LOOP from the following undefined behaviors:
3101 - data references should not access elements over the statically
3104 - signed variables should not overflow when flag_wrapv is not set.
3108 infer_loop_bounds_from_undefined (struct loop
*loop
)
3112 gimple_stmt_iterator bsi
;
3116 bbs
= get_loop_body (loop
);
3118 for (i
= 0; i
< loop
->num_nodes
; i
++)
3122 /* If BB is not executed in each iteration of the loop, we cannot
3123 use the operations in it to infer reliable upper bound on the
3124 # of iterations of the loop. However, we can use it as a guess.
3125 Reliable guesses come only from array bounds. */
3126 reliable
= dominated_by_p (CDI_DOMINATORS
, loop
->latch
, bb
);
3128 for (bsi
= gsi_start_bb (bb
); !gsi_end_p (bsi
); gsi_next (&bsi
))
3130 gimple stmt
= gsi_stmt (bsi
);
3132 infer_loop_bounds_from_array (loop
, stmt
);
3136 infer_loop_bounds_from_signedness (loop
, stmt
);
3137 infer_loop_bounds_from_pointer_arith (loop
, stmt
);
3146 /* Compare wide ints, callback for qsort. */
3149 wide_int_cmp (const void *p1
, const void *p2
)
3151 const widest_int
*d1
= (const widest_int
*) p1
;
3152 const widest_int
*d2
= (const widest_int
*) p2
;
3153 return wi::cmpu (*d1
, *d2
);
3156 /* Return index of BOUND in BOUNDS array sorted in increasing order.
3157 Lookup by binary search. */
3160 bound_index (vec
<widest_int
> bounds
, const widest_int
&bound
)
3162 unsigned int end
= bounds
.length ();
3163 unsigned int begin
= 0;
3165 /* Find a matching index by means of a binary search. */
3166 while (begin
!= end
)
3168 unsigned int middle
= (begin
+ end
) / 2;
3169 widest_int index
= bounds
[middle
];
3173 else if (wi::ltu_p (index
, bound
))
3181 /* We recorded loop bounds only for statements dominating loop latch (and thus
3182 executed each loop iteration). If there are any bounds on statements not
3183 dominating the loop latch we can improve the estimate by walking the loop
3184 body and seeing if every path from loop header to loop latch contains
3185 some bounded statement. */
3188 discover_iteration_bound_by_body_walk (struct loop
*loop
)
3190 struct nb_iter_bound
*elt
;
3191 vec
<widest_int
> bounds
= vNULL
;
3192 vec
<vec
<basic_block
> > queues
= vNULL
;
3193 vec
<basic_block
> queue
= vNULL
;
3194 ptrdiff_t queue_index
;
3195 ptrdiff_t latch_index
= 0;
3197 /* Discover what bounds may interest us. */
3198 for (elt
= loop
->bounds
; elt
; elt
= elt
->next
)
3200 widest_int bound
= elt
->bound
;
3202 /* Exit terminates loop at given iteration, while non-exits produce undefined
3203 effect on the next iteration. */
3207 /* If an overflow occurred, ignore the result. */
3212 if (!loop
->any_upper_bound
3213 || wi::ltu_p (bound
, loop
->nb_iterations_upper_bound
))
3214 bounds
.safe_push (bound
);
3217 /* Exit early if there is nothing to do. */
3218 if (!bounds
.exists ())
3221 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3222 fprintf (dump_file
, " Trying to walk loop body to reduce the bound.\n");
3224 /* Sort the bounds in decreasing order. */
3225 bounds
.qsort (wide_int_cmp
);
3227 /* For every basic block record the lowest bound that is guaranteed to
3228 terminate the loop. */
3230 hash_map
<basic_block
, ptrdiff_t> bb_bounds
;
3231 for (elt
= loop
->bounds
; elt
; elt
= elt
->next
)
3233 widest_int bound
= elt
->bound
;
3237 /* If an overflow occurred, ignore the result. */
3242 if (!loop
->any_upper_bound
3243 || wi::ltu_p (bound
, loop
->nb_iterations_upper_bound
))
3245 ptrdiff_t index
= bound_index (bounds
, bound
);
3246 ptrdiff_t *entry
= bb_bounds
.get (gimple_bb (elt
->stmt
));
3248 bb_bounds
.put (gimple_bb (elt
->stmt
), index
);
3249 else if ((ptrdiff_t)*entry
> index
)
3254 hash_map
<basic_block
, ptrdiff_t> block_priority
;
3256 /* Perform shortest path discovery loop->header ... loop->latch.
3258 The "distance" is given by the smallest loop bound of basic block
3259 present in the path and we look for path with largest smallest bound
3262 To avoid the need for fibonacci heap on double ints we simply compress
3263 double ints into indexes to BOUNDS array and then represent the queue
3264 as arrays of queues for every index.
3265 Index of BOUNDS.length() means that the execution of given BB has
3266 no bounds determined.
3268 VISITED is a pointer map translating basic block into smallest index
3269 it was inserted into the priority queue with. */
3272 /* Start walk in loop header with index set to infinite bound. */
3273 queue_index
= bounds
.length ();
3274 queues
.safe_grow_cleared (queue_index
+ 1);
3275 queue
.safe_push (loop
->header
);
3276 queues
[queue_index
] = queue
;
3277 block_priority
.put (loop
->header
, queue_index
);
3279 for (; queue_index
>= 0; queue_index
--)
3281 if (latch_index
< queue_index
)
3283 while (queues
[queue_index
].length ())
3286 ptrdiff_t bound_index
= queue_index
;
3290 queue
= queues
[queue_index
];
3293 /* OK, we later inserted the BB with lower priority, skip it. */
3294 if (*block_priority
.get (bb
) > queue_index
)
3297 /* See if we can improve the bound. */
3298 ptrdiff_t *entry
= bb_bounds
.get (bb
);
3299 if (entry
&& *entry
< bound_index
)
3300 bound_index
= *entry
;
3302 /* Insert succesors into the queue, watch for latch edge
3303 and record greatest index we saw. */
3304 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3306 bool insert
= false;
3308 if (loop_exit_edge_p (loop
, e
))
3311 if (e
== loop_latch_edge (loop
)
3312 && latch_index
< bound_index
)
3313 latch_index
= bound_index
;
3314 else if (!(entry
= block_priority
.get (e
->dest
)))
3317 block_priority
.put (e
->dest
, bound_index
);
3319 else if (*entry
< bound_index
)
3322 *entry
= bound_index
;
3326 queues
[bound_index
].safe_push (e
->dest
);
3330 queues
[queue_index
].release ();
3333 gcc_assert (latch_index
>= 0);
3334 if ((unsigned)latch_index
< bounds
.length ())
3336 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3338 fprintf (dump_file
, "Found better loop bound ");
3339 print_decu (bounds
[latch_index
], dump_file
);
3340 fprintf (dump_file
, "\n");
3342 record_niter_bound (loop
, bounds
[latch_index
], false, true);
3349 /* See if every path cross the loop goes through a statement that is known
3350 to not execute at the last iteration. In that case we can decrese iteration
3354 maybe_lower_iteration_bound (struct loop
*loop
)
3356 hash_set
<gimple
> *not_executed_last_iteration
= NULL
;
3357 struct nb_iter_bound
*elt
;
3358 bool found_exit
= false;
3359 vec
<basic_block
> queue
= vNULL
;
3362 /* Collect all statements with interesting (i.e. lower than
3363 nb_iterations_upper_bound) bound on them.
3365 TODO: Due to the way record_estimate choose estimates to store, the bounds
3366 will be always nb_iterations_upper_bound-1. We can change this to record
3367 also statements not dominating the loop latch and update the walk bellow
3368 to the shortest path algorthm. */
3369 for (elt
= loop
->bounds
; elt
; elt
= elt
->next
)
3372 && wi::ltu_p (elt
->bound
, loop
->nb_iterations_upper_bound
))
3374 if (!not_executed_last_iteration
)
3375 not_executed_last_iteration
= new hash_set
<gimple
>;
3376 not_executed_last_iteration
->add (elt
->stmt
);
3379 if (!not_executed_last_iteration
)
3382 /* Start DFS walk in the loop header and see if we can reach the
3383 loop latch or any of the exits (including statements with side
3384 effects that may terminate the loop otherwise) without visiting
3385 any of the statements known to have undefined effect on the last
3387 queue
.safe_push (loop
->header
);
3388 visited
= BITMAP_ALLOC (NULL
);
3389 bitmap_set_bit (visited
, loop
->header
->index
);
3394 basic_block bb
= queue
.pop ();
3395 gimple_stmt_iterator gsi
;
3396 bool stmt_found
= false;
3398 /* Loop for possible exits and statements bounding the execution. */
3399 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
3401 gimple stmt
= gsi_stmt (gsi
);
3402 if (not_executed_last_iteration
->contains (stmt
))
3407 if (gimple_has_side_effects (stmt
))
3416 /* If no bounding statement is found, continue the walk. */
3422 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3424 if (loop_exit_edge_p (loop
, e
)
3425 || e
== loop_latch_edge (loop
))
3430 if (bitmap_set_bit (visited
, e
->dest
->index
))
3431 queue
.safe_push (e
->dest
);
3435 while (queue
.length () && !found_exit
);
3437 /* If every path through the loop reach bounding statement before exit,
3438 then we know the last iteration of the loop will have undefined effect
3439 and we can decrease number of iterations. */
3443 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3444 fprintf (dump_file
, "Reducing loop iteration estimate by 1; "
3445 "undefined statement must be executed at the last iteration.\n");
3446 record_niter_bound (loop
, loop
->nb_iterations_upper_bound
- 1,
3450 BITMAP_FREE (visited
);
3452 delete not_executed_last_iteration
;
3455 /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
3456 is true also use estimates derived from undefined behavior. */
3459 estimate_numbers_of_iterations_loop (struct loop
*loop
)
3464 struct tree_niter_desc niter_desc
;
3469 /* Give up if we already have tried to compute an estimation. */
3470 if (loop
->estimate_state
!= EST_NOT_COMPUTED
)
3473 loop
->estimate_state
= EST_AVAILABLE
;
3474 /* Force estimate compuation but leave any existing upper bound in place. */
3475 loop
->any_estimate
= false;
3477 /* Ensure that loop->nb_iterations is computed if possible. If it turns out
3478 to be constant, we avoid undefined behavior implied bounds and instead
3479 diagnose those loops with -Waggressive-loop-optimizations. */
3480 number_of_latch_executions (loop
);
3482 exits
= get_loop_exit_edges (loop
);
3483 likely_exit
= single_likely_exit (loop
);
3484 FOR_EACH_VEC_ELT (exits
, i
, ex
)
3486 if (!number_of_iterations_exit (loop
, ex
, &niter_desc
, false, false))
3489 niter
= niter_desc
.niter
;
3490 type
= TREE_TYPE (niter
);
3491 if (TREE_CODE (niter_desc
.may_be_zero
) != INTEGER_CST
)
3492 niter
= build3 (COND_EXPR
, type
, niter_desc
.may_be_zero
,
3493 build_int_cst (type
, 0),
3495 record_estimate (loop
, niter
, niter_desc
.max
,
3496 last_stmt (ex
->src
),
3497 true, ex
== likely_exit
, true);
3498 record_control_iv (loop
, &niter_desc
);
3502 if (flag_aggressive_loop_optimizations
)
3503 infer_loop_bounds_from_undefined (loop
);
3505 discover_iteration_bound_by_body_walk (loop
);
3507 maybe_lower_iteration_bound (loop
);
3509 /* If we have a measured profile, use it to estimate the number of
3511 if (loop
->header
->count
!= 0)
3513 gcov_type nit
= expected_loop_iterations_unbounded (loop
) + 1;
3514 bound
= gcov_type_to_wide_int (nit
);
3515 record_niter_bound (loop
, bound
, true, false);
3518 /* If we know the exact number of iterations of this loop, try to
3519 not break code with undefined behavior by not recording smaller
3520 maximum number of iterations. */
3521 if (loop
->nb_iterations
3522 && TREE_CODE (loop
->nb_iterations
) == INTEGER_CST
)
3524 loop
->any_upper_bound
= true;
3525 loop
->nb_iterations_upper_bound
= wi::to_widest (loop
->nb_iterations
);
3529 /* Sets NIT to the estimated number of executions of the latch of the
3530 LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
3531 large as the number of iterations. If we have no reliable estimate,
3532 the function returns false, otherwise returns true. */
3535 estimated_loop_iterations (struct loop
*loop
, widest_int
*nit
)
3537 /* When SCEV information is available, try to update loop iterations
3538 estimate. Otherwise just return whatever we recorded earlier. */
3539 if (scev_initialized_p ())
3540 estimate_numbers_of_iterations_loop (loop
);
3542 return (get_estimated_loop_iterations (loop
, nit
));
3545 /* Similar to estimated_loop_iterations, but returns the estimate only
3546 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3547 on the number of iterations of LOOP could not be derived, returns -1. */
3550 estimated_loop_iterations_int (struct loop
*loop
)
3553 HOST_WIDE_INT hwi_nit
;
3555 if (!estimated_loop_iterations (loop
, &nit
))
3558 if (!wi::fits_shwi_p (nit
))
3560 hwi_nit
= nit
.to_shwi ();
3562 return hwi_nit
< 0 ? -1 : hwi_nit
;
3566 /* Sets NIT to an upper bound for the maximum number of executions of the
3567 latch of the LOOP. If we have no reliable estimate, the function returns
3568 false, otherwise returns true. */
3571 max_loop_iterations (struct loop
*loop
, widest_int
*nit
)
3573 /* When SCEV information is available, try to update loop iterations
3574 estimate. Otherwise just return whatever we recorded earlier. */
3575 if (scev_initialized_p ())
3576 estimate_numbers_of_iterations_loop (loop
);
3578 return get_max_loop_iterations (loop
, nit
);
3581 /* Similar to max_loop_iterations, but returns the estimate only
3582 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3583 on the number of iterations of LOOP could not be derived, returns -1. */
3586 max_loop_iterations_int (struct loop
*loop
)
3589 HOST_WIDE_INT hwi_nit
;
3591 if (!max_loop_iterations (loop
, &nit
))
3594 if (!wi::fits_shwi_p (nit
))
3596 hwi_nit
= nit
.to_shwi ();
3598 return hwi_nit
< 0 ? -1 : hwi_nit
;
3601 /* Returns an estimate for the number of executions of statements
3602 in the LOOP. For statements before the loop exit, this exceeds
3603 the number of execution of the latch by one. */
3606 estimated_stmt_executions_int (struct loop
*loop
)
3608 HOST_WIDE_INT nit
= estimated_loop_iterations_int (loop
);
3614 snit
= (HOST_WIDE_INT
) ((unsigned HOST_WIDE_INT
) nit
+ 1);
3616 /* If the computation overflows, return -1. */
3617 return snit
< 0 ? -1 : snit
;
3620 /* Sets NIT to the estimated maximum number of executions of the latch of the
3621 LOOP, plus one. If we have no reliable estimate, the function returns
3622 false, otherwise returns true. */
3625 max_stmt_executions (struct loop
*loop
, widest_int
*nit
)
3627 widest_int nit_minus_one
;
3629 if (!max_loop_iterations (loop
, nit
))
3632 nit_minus_one
= *nit
;
3636 return wi::gtu_p (*nit
, nit_minus_one
);
3639 /* Sets NIT to the estimated number of executions of the latch of the
3640 LOOP, plus one. If we have no reliable estimate, the function returns
3641 false, otherwise returns true. */
3644 estimated_stmt_executions (struct loop
*loop
, widest_int
*nit
)
3646 widest_int nit_minus_one
;
3648 if (!estimated_loop_iterations (loop
, nit
))
3651 nit_minus_one
= *nit
;
3655 return wi::gtu_p (*nit
, nit_minus_one
);
3658 /* Records estimates on numbers of iterations of loops. */
3661 estimate_numbers_of_iterations (void)
3665 /* We don't want to issue signed overflow warnings while getting
3666 loop iteration estimates. */
3667 fold_defer_overflow_warnings ();
3669 FOR_EACH_LOOP (loop
, 0)
3671 estimate_numbers_of_iterations_loop (loop
);
3674 fold_undefer_and_ignore_overflow_warnings ();
3677 /* Returns true if statement S1 dominates statement S2. */
3680 stmt_dominates_stmt_p (gimple s1
, gimple s2
)
3682 basic_block bb1
= gimple_bb (s1
), bb2
= gimple_bb (s2
);
3690 gimple_stmt_iterator bsi
;
3692 if (gimple_code (s2
) == GIMPLE_PHI
)
3695 if (gimple_code (s1
) == GIMPLE_PHI
)
3698 for (bsi
= gsi_start_bb (bb1
); gsi_stmt (bsi
) != s2
; gsi_next (&bsi
))
3699 if (gsi_stmt (bsi
) == s1
)
3705 return dominated_by_p (CDI_DOMINATORS
, bb2
, bb1
);
3708 /* Returns true when we can prove that the number of executions of
3709 STMT in the loop is at most NITER, according to the bound on
3710 the number of executions of the statement NITER_BOUND->stmt recorded in
3711 NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
3713 ??? This code can become quite a CPU hog - we can have many bounds,
3714 and large basic block forcing stmt_dominates_stmt_p to be queried
3715 many times on a large basic blocks, so the whole thing is O(n^2)
3716 for scev_probably_wraps_p invocation (that can be done n times).
3718 It would make more sense (and give better answers) to remember BB
3719 bounds computed by discover_iteration_bound_by_body_walk. */
3722 n_of_executions_at_most (gimple stmt
,
3723 struct nb_iter_bound
*niter_bound
,
3726 widest_int bound
= niter_bound
->bound
;
3727 tree nit_type
= TREE_TYPE (niter
), e
;
3730 gcc_assert (TYPE_UNSIGNED (nit_type
));
3732 /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
3733 the number of iterations is small. */
3734 if (!wi::fits_to_tree_p (bound
, nit_type
))
3737 /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
3738 times. This means that:
3740 -- if NITER_BOUND->is_exit is true, then everything after
3741 it at most NITER_BOUND->bound times.
3743 -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
3744 is executed, then NITER_BOUND->stmt is executed as well in the same
3745 iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
3747 If we can determine that NITER_BOUND->stmt is always executed
3748 after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
3749 We conclude that if both statements belong to the same
3750 basic block and STMT is before NITER_BOUND->stmt and there are no
3751 statements with side effects in between. */
3753 if (niter_bound
->is_exit
)
3755 if (stmt
== niter_bound
->stmt
3756 || !stmt_dominates_stmt_p (niter_bound
->stmt
, stmt
))
3762 if (!stmt_dominates_stmt_p (niter_bound
->stmt
, stmt
))
3764 gimple_stmt_iterator bsi
;
3765 if (gimple_bb (stmt
) != gimple_bb (niter_bound
->stmt
)
3766 || gimple_code (stmt
) == GIMPLE_PHI
3767 || gimple_code (niter_bound
->stmt
) == GIMPLE_PHI
)
3770 /* By stmt_dominates_stmt_p we already know that STMT appears
3771 before NITER_BOUND->STMT. Still need to test that the loop
3772 can not be terinated by a side effect in between. */
3773 for (bsi
= gsi_for_stmt (stmt
); gsi_stmt (bsi
) != niter_bound
->stmt
;
3775 if (gimple_has_side_effects (gsi_stmt (bsi
)))
3779 || !wi::fits_to_tree_p (bound
, nit_type
))
3785 e
= fold_binary (cmp
, boolean_type_node
,
3786 niter
, wide_int_to_tree (nit_type
, bound
));
3787 return e
&& integer_nonzerop (e
);
3790 /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
3793 nowrap_type_p (tree type
)
3795 if (INTEGRAL_TYPE_P (type
)
3796 && TYPE_OVERFLOW_UNDEFINED (type
))
3799 if (POINTER_TYPE_P (type
))
3805 /* Return true if we can prove LOOP is exited before evolution of induction
3806 variabled {BASE, STEP} overflows with respect to its type bound. */
3809 loop_exits_before_overflow (tree base
, tree step
,
3810 gimple at_stmt
, struct loop
*loop
)
3813 struct control_iv
*civ
;
3814 struct nb_iter_bound
*bound
;
3815 tree e
, delta
, step_abs
, unsigned_base
;
3816 tree type
= TREE_TYPE (step
);
3817 tree unsigned_type
, valid_niter
;
3819 /* Don't issue signed overflow warnings. */
3820 fold_defer_overflow_warnings ();
3822 /* Compute the number of iterations before we reach the bound of the
3823 type, and verify that the loop is exited before this occurs. */
3824 unsigned_type
= unsigned_type_for (type
);
3825 unsigned_base
= fold_convert (unsigned_type
, base
);
3827 if (tree_int_cst_sign_bit (step
))
3829 tree extreme
= fold_convert (unsigned_type
,
3830 lower_bound_in_type (type
, type
));
3831 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, unsigned_base
, extreme
);
3832 step_abs
= fold_build1 (NEGATE_EXPR
, unsigned_type
,
3833 fold_convert (unsigned_type
, step
));
3837 tree extreme
= fold_convert (unsigned_type
,
3838 upper_bound_in_type (type
, type
));
3839 delta
= fold_build2 (MINUS_EXPR
, unsigned_type
, extreme
, unsigned_base
);
3840 step_abs
= fold_convert (unsigned_type
, step
);
3843 valid_niter
= fold_build2 (FLOOR_DIV_EXPR
, unsigned_type
, delta
, step_abs
);
3845 estimate_numbers_of_iterations_loop (loop
);
3847 if (max_loop_iterations (loop
, &niter
)
3848 && wi::fits_to_tree_p (niter
, TREE_TYPE (valid_niter
))
3849 && (e
= fold_binary (GT_EXPR
, boolean_type_node
, valid_niter
,
3850 wide_int_to_tree (TREE_TYPE (valid_niter
),
3852 && integer_nonzerop (e
))
3854 fold_undefer_and_ignore_overflow_warnings ();
3858 for (bound
= loop
->bounds
; bound
; bound
= bound
->next
)
3860 if (n_of_executions_at_most (at_stmt
, bound
, valid_niter
))
3862 fold_undefer_and_ignore_overflow_warnings ();
3866 fold_undefer_and_ignore_overflow_warnings ();
3868 /* Try to prove loop is exited before {base, step} overflows with the
3869 help of analyzed loop control IV. This is done only for IVs with
3870 constant step because otherwise we don't have the information. */
3871 if (TREE_CODE (step
) == INTEGER_CST
)
3872 for (civ
= loop
->control_ivs
; civ
; civ
= civ
->next
)
3874 enum tree_code code
;
3875 tree stepped
, extreme
, civ_type
= TREE_TYPE (civ
->step
);
3877 /* Have to consider type difference because operand_equal_p ignores
3878 that for constants. */
3879 if (TYPE_UNSIGNED (type
) != TYPE_UNSIGNED (civ_type
)
3880 || element_precision (type
) != element_precision (civ_type
))
3883 /* Only consider control IV with same step. */
3884 if (!operand_equal_p (step
, civ
->step
, 0))
3887 /* Done proving if this is a no-overflow control IV. */
3888 if (operand_equal_p (base
, civ
->base
, 0))
3891 /* If this is a before stepping control IV, in other words, we have
3893 {civ_base, step} = {base + step, step}
3895 Because civ {base + step, step} doesn't overflow during loop
3896 iterations, {base, step} will not overflow if we can prove the
3897 operation "base + step" does not overflow. Specifically, we try
3898 to prove below conditions are satisfied:
3900 base <= UPPER_BOUND (type) - step ;;step > 0
3901 base >= LOWER_BOUND (type) - step ;;step < 0
3903 by proving the reverse conditions are false using loop's initial
3905 stepped
= fold_build2 (PLUS_EXPR
, TREE_TYPE (base
), base
, step
);
3906 if (operand_equal_p (stepped
, civ
->base
, 0))
3908 if (tree_int_cst_sign_bit (step
))
3911 extreme
= lower_bound_in_type (type
, type
);
3916 extreme
= upper_bound_in_type (type
, type
);
3918 extreme
= fold_build2 (MINUS_EXPR
, type
, extreme
, step
);
3919 e
= fold_build2 (code
, boolean_type_node
, base
, extreme
);
3920 e
= simplify_using_initial_conditions (loop
, e
);
3921 if (integer_zerop (e
))
3927 /* Similar to above, only in this case we have:
3929 {civ_base, step} = {(signed T)((unsigned T)base + step), step}
3930 && TREE_TYPE (civ_base) = signed T.
3932 We prove that below condition is satisfied:
3934 (signed T)((unsigned T)base + step)
3935 == (signed T)(unsigned T)base + step
3938 because of exact the same reason as above. This also proves
3939 there is no overflow in the operation "base + step", thus the
3940 induction variable {base, step} during loop iterations.
3942 This is necessary to handle cases as below:
3944 int foo (int *a, signed char s, signed char l)
3947 for (i = s; i < l; i++)
3952 The variable I is firstly converted to type unsigned char,
3953 incremented, then converted back to type signed char. */
3954 if (!CONVERT_EXPR_P (civ
->base
) || TREE_TYPE (civ
->base
) != type
)
3956 e
= TREE_OPERAND (civ
->base
, 0);
3957 if (TREE_CODE (e
) != PLUS_EXPR
3958 || TREE_CODE (TREE_OPERAND (e
, 1)) != INTEGER_CST
3959 || !operand_equal_p (step
,
3961 TREE_OPERAND (e
, 1)), 0))
3963 e
= TREE_OPERAND (e
, 0);
3964 if (!CONVERT_EXPR_P (e
) || !operand_equal_p (e
, unsigned_base
, 0))
3966 e
= TREE_OPERAND (e
, 0);
3967 gcc_assert (operand_equal_p (e
, base
, 0));
3968 if (tree_int_cst_sign_bit (step
))
3971 extreme
= lower_bound_in_type (type
, type
);
3976 extreme
= upper_bound_in_type (type
, type
);
3978 extreme
= fold_build2 (MINUS_EXPR
, type
, extreme
, step
);
3979 e
= fold_build2 (code
, boolean_type_node
, base
, extreme
);
3980 e
= simplify_using_initial_conditions (loop
, e
);
3981 if (integer_zerop (e
))
3988 /* Return false only when the induction variable BASE + STEP * I is
3989 known to not overflow: i.e. when the number of iterations is small
3990 enough with respect to the step and initial condition in order to
3991 keep the evolution confined in TYPEs bounds. Return true when the
3992 iv is known to overflow or when the property is not computable.
3994 USE_OVERFLOW_SEMANTICS is true if this function should assume that
3995 the rules for overflow of the given language apply (e.g., that signed
3996 arithmetics in C does not overflow). */
3999 scev_probably_wraps_p (tree base
, tree step
,
4000 gimple at_stmt
, struct loop
*loop
,
4001 bool use_overflow_semantics
)
4003 /* FIXME: We really need something like
4004 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
4006 We used to test for the following situation that frequently appears
4007 during address arithmetics:
4009 D.1621_13 = (long unsigned intD.4) D.1620_12;
4010 D.1622_14 = D.1621_13 * 8;
4011 D.1623_15 = (doubleD.29 *) D.1622_14;
4013 And derived that the sequence corresponding to D_14
4014 can be proved to not wrap because it is used for computing a
4015 memory access; however, this is not really the case -- for example,
4016 if D_12 = (unsigned char) [254,+,1], then D_14 has values
4017 2032, 2040, 0, 8, ..., but the code is still legal. */
4019 if (chrec_contains_undetermined (base
)
4020 || chrec_contains_undetermined (step
))
4023 if (integer_zerop (step
))
4026 /* If we can use the fact that signed and pointer arithmetics does not
4027 wrap, we are done. */
4028 if (use_overflow_semantics
&& nowrap_type_p (TREE_TYPE (base
)))
4031 /* To be able to use estimates on number of iterations of the loop,
4032 we must have an upper bound on the absolute value of the step. */
4033 if (TREE_CODE (step
) != INTEGER_CST
)
4036 if (loop_exits_before_overflow (base
, step
, at_stmt
, loop
))
4039 /* At this point we still don't have a proof that the iv does not
4040 overflow: give up. */
4044 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
4047 free_numbers_of_iterations_estimates_loop (struct loop
*loop
)
4049 struct control_iv
*civ
;
4050 struct nb_iter_bound
*bound
;
4052 loop
->nb_iterations
= NULL
;
4053 loop
->estimate_state
= EST_NOT_COMPUTED
;
4054 for (bound
= loop
->bounds
; bound
;)
4056 struct nb_iter_bound
*next
= bound
->next
;
4060 loop
->bounds
= NULL
;
4062 for (civ
= loop
->control_ivs
; civ
;)
4064 struct control_iv
*next
= civ
->next
;
4068 loop
->control_ivs
= NULL
;
4071 /* Frees the information on upper bounds on numbers of iterations of loops. */
4074 free_numbers_of_iterations_estimates (void)
4078 FOR_EACH_LOOP (loop
, 0)
4080 free_numbers_of_iterations_estimates_loop (loop
);
4084 /* Substitute value VAL for ssa name NAME inside expressions held
4088 substitute_in_loop_info (struct loop
*loop
, tree name
, tree val
)
4090 loop
->nb_iterations
= simplify_replace_tree (loop
->nb_iterations
, name
, val
);