re PR testsuite/63439 (FAIL: gcc.dg/vect/vect-33.c scan-tree-dump vect "Alignment...
[gcc.git] / gcc / tree-ssa-loop-niter.c
1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
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/>. */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "hash-set.h"
25 #include "machmode.h"
26 #include "vec.h"
27 #include "double-int.h"
28 #include "input.h"
29 #include "alias.h"
30 #include "symtab.h"
31 #include "wide-int.h"
32 #include "inchash.h"
33 #include "tree.h"
34 #include "fold-const.h"
35 #include "calls.h"
36 #include "hashtab.h"
37 #include "hard-reg-set.h"
38 #include "function.h"
39 #include "rtl.h"
40 #include "flags.h"
41 #include "statistics.h"
42 #include "real.h"
43 #include "fixed-value.h"
44 #include "insn-config.h"
45 #include "expmed.h"
46 #include "dojump.h"
47 #include "explow.h"
48 #include "emit-rtl.h"
49 #include "varasm.h"
50 #include "stmt.h"
51 #include "expr.h"
52 #include "tm_p.h"
53 #include "predict.h"
54 #include "dominance.h"
55 #include "cfg.h"
56 #include "basic-block.h"
57 #include "gimple-pretty-print.h"
58 #include "intl.h"
59 #include "tree-ssa-alias.h"
60 #include "internal-fn.h"
61 #include "gimple-expr.h"
62 #include "is-a.h"
63 #include "gimple.h"
64 #include "gimplify.h"
65 #include "gimple-iterator.h"
66 #include "gimple-ssa.h"
67 #include "tree-cfg.h"
68 #include "tree-phinodes.h"
69 #include "ssa-iterators.h"
70 #include "tree-ssa-loop-ivopts.h"
71 #include "tree-ssa-loop-niter.h"
72 #include "tree-ssa-loop.h"
73 #include "dumpfile.h"
74 #include "cfgloop.h"
75 #include "tree-chrec.h"
76 #include "tree-scalar-evolution.h"
77 #include "tree-data-ref.h"
78 #include "params.h"
79 #include "diagnostic-core.h"
80 #include "tree-inline.h"
81 #include "tree-pass.h"
82 #include "stringpool.h"
83 #include "tree-ssanames.h"
84 #include "wide-int-print.h"
85
86
87 #define SWAP(X, Y) do { affine_iv *tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
88
89 /* The maximum number of dominator BBs we search for conditions
90 of loop header copies we use for simplifying a conditional
91 expression. */
92 #define MAX_DOMINATORS_TO_WALK 8
93
94 /*
95
96 Analysis of number of iterations of an affine exit test.
97
98 */
99
100 /* Bounds on some value, BELOW <= X <= UP. */
101
102 typedef struct
103 {
104 mpz_t below, up;
105 } bounds;
106
107
108 /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
109
110 static void
111 split_to_var_and_offset (tree expr, tree *var, mpz_t offset)
112 {
113 tree type = TREE_TYPE (expr);
114 tree op0, op1;
115 bool negate = false;
116
117 *var = expr;
118 mpz_set_ui (offset, 0);
119
120 switch (TREE_CODE (expr))
121 {
122 case MINUS_EXPR:
123 negate = true;
124 /* Fallthru. */
125
126 case PLUS_EXPR:
127 case POINTER_PLUS_EXPR:
128 op0 = TREE_OPERAND (expr, 0);
129 op1 = TREE_OPERAND (expr, 1);
130
131 if (TREE_CODE (op1) != INTEGER_CST)
132 break;
133
134 *var = op0;
135 /* Always sign extend the offset. */
136 wi::to_mpz (op1, offset, SIGNED);
137 if (negate)
138 mpz_neg (offset, offset);
139 break;
140
141 case INTEGER_CST:
142 *var = build_int_cst_type (type, 0);
143 wi::to_mpz (expr, offset, TYPE_SIGN (type));
144 break;
145
146 default:
147 break;
148 }
149 }
150
151 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
152 in TYPE to MIN and MAX. */
153
154 static void
155 determine_value_range (struct loop *loop, tree type, tree var, mpz_t off,
156 mpz_t min, mpz_t max)
157 {
158 wide_int minv, maxv;
159 enum value_range_type rtype = VR_VARYING;
160
161 /* If the expression is a constant, we know its value exactly. */
162 if (integer_zerop (var))
163 {
164 mpz_set (min, off);
165 mpz_set (max, off);
166 return;
167 }
168
169 get_type_static_bounds (type, min, max);
170
171 /* See if we have some range info from VRP. */
172 if (TREE_CODE (var) == SSA_NAME && INTEGRAL_TYPE_P (type))
173 {
174 edge e = loop_preheader_edge (loop);
175 signop sgn = TYPE_SIGN (type);
176 gphi_iterator gsi;
177
178 /* Either for VAR itself... */
179 rtype = get_range_info (var, &minv, &maxv);
180 /* Or for PHI results in loop->header where VAR is used as
181 PHI argument from the loop preheader edge. */
182 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
183 {
184 gphi *phi = gsi.phi ();
185 wide_int minc, maxc;
186 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var
187 && (get_range_info (gimple_phi_result (phi), &minc, &maxc)
188 == VR_RANGE))
189 {
190 if (rtype != VR_RANGE)
191 {
192 rtype = VR_RANGE;
193 minv = minc;
194 maxv = maxc;
195 }
196 else
197 {
198 minv = wi::max (minv, minc, sgn);
199 maxv = wi::min (maxv, maxc, sgn);
200 /* If the PHI result range are inconsistent with
201 the VAR range, give up on looking at the PHI
202 results. This can happen if VR_UNDEFINED is
203 involved. */
204 if (wi::gt_p (minv, maxv, sgn))
205 {
206 rtype = get_range_info (var, &minv, &maxv);
207 break;
208 }
209 }
210 }
211 }
212 if (rtype == VR_RANGE)
213 {
214 mpz_t minm, maxm;
215 gcc_assert (wi::le_p (minv, maxv, sgn));
216 mpz_init (minm);
217 mpz_init (maxm);
218 wi::to_mpz (minv, minm, sgn);
219 wi::to_mpz (maxv, maxm, sgn);
220 mpz_add (minm, minm, off);
221 mpz_add (maxm, maxm, off);
222 /* If the computation may not wrap or off is zero, then this
223 is always fine. If off is negative and minv + off isn't
224 smaller than type's minimum, or off is positive and
225 maxv + off isn't bigger than type's maximum, use the more
226 precise range too. */
227 if (nowrap_type_p (type)
228 || mpz_sgn (off) == 0
229 || (mpz_sgn (off) < 0 && mpz_cmp (minm, min) >= 0)
230 || (mpz_sgn (off) > 0 && mpz_cmp (maxm, max) <= 0))
231 {
232 mpz_set (min, minm);
233 mpz_set (max, maxm);
234 mpz_clear (minm);
235 mpz_clear (maxm);
236 return;
237 }
238 mpz_clear (minm);
239 mpz_clear (maxm);
240 }
241 }
242
243 /* If the computation may wrap, we know nothing about the value, except for
244 the range of the type. */
245 if (!nowrap_type_p (type))
246 return;
247
248 /* Since the addition of OFF does not wrap, if OFF is positive, then we may
249 add it to MIN, otherwise to MAX. */
250 if (mpz_sgn (off) < 0)
251 mpz_add (max, max, off);
252 else
253 mpz_add (min, min, off);
254 }
255
256 /* Stores the bounds on the difference of the values of the expressions
257 (var + X) and (var + Y), computed in TYPE, to BNDS. */
258
259 static void
260 bound_difference_of_offsetted_base (tree type, mpz_t x, mpz_t y,
261 bounds *bnds)
262 {
263 int rel = mpz_cmp (x, y);
264 bool may_wrap = !nowrap_type_p (type);
265 mpz_t m;
266
267 /* If X == Y, then the expressions are always equal.
268 If X > Y, there are the following possibilities:
269 a) neither of var + X and var + Y overflow or underflow, or both of
270 them do. Then their difference is X - Y.
271 b) var + X overflows, and var + Y does not. Then the values of the
272 expressions are var + X - M and var + Y, where M is the range of
273 the type, and their difference is X - Y - M.
274 c) var + Y underflows and var + X does not. Their difference again
275 is M - X + Y.
276 Therefore, if the arithmetics in type does not overflow, then the
277 bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
278 Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
279 (X - Y, X - Y + M). */
280
281 if (rel == 0)
282 {
283 mpz_set_ui (bnds->below, 0);
284 mpz_set_ui (bnds->up, 0);
285 return;
286 }
287
288 mpz_init (m);
289 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), m, UNSIGNED);
290 mpz_add_ui (m, m, 1);
291 mpz_sub (bnds->up, x, y);
292 mpz_set (bnds->below, bnds->up);
293
294 if (may_wrap)
295 {
296 if (rel > 0)
297 mpz_sub (bnds->below, bnds->below, m);
298 else
299 mpz_add (bnds->up, bnds->up, m);
300 }
301
302 mpz_clear (m);
303 }
304
305 /* From condition C0 CMP C1 derives information regarding the
306 difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
307 and stores it to BNDS. */
308
309 static void
310 refine_bounds_using_guard (tree type, tree varx, mpz_t offx,
311 tree vary, mpz_t offy,
312 tree c0, enum tree_code cmp, tree c1,
313 bounds *bnds)
314 {
315 tree varc0, varc1, tmp, ctype;
316 mpz_t offc0, offc1, loffx, loffy, bnd;
317 bool lbound = false;
318 bool no_wrap = nowrap_type_p (type);
319 bool x_ok, y_ok;
320
321 switch (cmp)
322 {
323 case LT_EXPR:
324 case LE_EXPR:
325 case GT_EXPR:
326 case GE_EXPR:
327 STRIP_SIGN_NOPS (c0);
328 STRIP_SIGN_NOPS (c1);
329 ctype = TREE_TYPE (c0);
330 if (!useless_type_conversion_p (ctype, type))
331 return;
332
333 break;
334
335 case EQ_EXPR:
336 /* We could derive quite precise information from EQ_EXPR, however, such
337 a guard is unlikely to appear, so we do not bother with handling
338 it. */
339 return;
340
341 case NE_EXPR:
342 /* NE_EXPR comparisons do not contain much of useful information, except for
343 special case of comparing with the bounds of the type. */
344 if (TREE_CODE (c1) != INTEGER_CST
345 || !INTEGRAL_TYPE_P (type))
346 return;
347
348 /* Ensure that the condition speaks about an expression in the same type
349 as X and Y. */
350 ctype = TREE_TYPE (c0);
351 if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
352 return;
353 c0 = fold_convert (type, c0);
354 c1 = fold_convert (type, c1);
355
356 if (TYPE_MIN_VALUE (type)
357 && operand_equal_p (c1, TYPE_MIN_VALUE (type), 0))
358 {
359 cmp = GT_EXPR;
360 break;
361 }
362 if (TYPE_MAX_VALUE (type)
363 && operand_equal_p (c1, TYPE_MAX_VALUE (type), 0))
364 {
365 cmp = LT_EXPR;
366 break;
367 }
368
369 return;
370 default:
371 return;
372 }
373
374 mpz_init (offc0);
375 mpz_init (offc1);
376 split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
377 split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
378
379 /* We are only interested in comparisons of expressions based on VARX and
380 VARY. TODO -- we might also be able to derive some bounds from
381 expressions containing just one of the variables. */
382
383 if (operand_equal_p (varx, varc1, 0))
384 {
385 tmp = varc0; varc0 = varc1; varc1 = tmp;
386 mpz_swap (offc0, offc1);
387 cmp = swap_tree_comparison (cmp);
388 }
389
390 if (!operand_equal_p (varx, varc0, 0)
391 || !operand_equal_p (vary, varc1, 0))
392 goto end;
393
394 mpz_init_set (loffx, offx);
395 mpz_init_set (loffy, offy);
396
397 if (cmp == GT_EXPR || cmp == GE_EXPR)
398 {
399 tmp = varx; varx = vary; vary = tmp;
400 mpz_swap (offc0, offc1);
401 mpz_swap (loffx, loffy);
402 cmp = swap_tree_comparison (cmp);
403 lbound = true;
404 }
405
406 /* If there is no overflow, the condition implies that
407
408 (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
409
410 The overflows and underflows may complicate things a bit; each
411 overflow decreases the appropriate offset by M, and underflow
412 increases it by M. The above inequality would not necessarily be
413 true if
414
415 -- VARX + OFFX underflows and VARX + OFFC0 does not, or
416 VARX + OFFC0 overflows, but VARX + OFFX does not.
417 This may only happen if OFFX < OFFC0.
418 -- VARY + OFFY overflows and VARY + OFFC1 does not, or
419 VARY + OFFC1 underflows and VARY + OFFY does not.
420 This may only happen if OFFY > OFFC1. */
421
422 if (no_wrap)
423 {
424 x_ok = true;
425 y_ok = true;
426 }
427 else
428 {
429 x_ok = (integer_zerop (varx)
430 || mpz_cmp (loffx, offc0) >= 0);
431 y_ok = (integer_zerop (vary)
432 || mpz_cmp (loffy, offc1) <= 0);
433 }
434
435 if (x_ok && y_ok)
436 {
437 mpz_init (bnd);
438 mpz_sub (bnd, loffx, loffy);
439 mpz_add (bnd, bnd, offc1);
440 mpz_sub (bnd, bnd, offc0);
441
442 if (cmp == LT_EXPR)
443 mpz_sub_ui (bnd, bnd, 1);
444
445 if (lbound)
446 {
447 mpz_neg (bnd, bnd);
448 if (mpz_cmp (bnds->below, bnd) < 0)
449 mpz_set (bnds->below, bnd);
450 }
451 else
452 {
453 if (mpz_cmp (bnd, bnds->up) < 0)
454 mpz_set (bnds->up, bnd);
455 }
456 mpz_clear (bnd);
457 }
458
459 mpz_clear (loffx);
460 mpz_clear (loffy);
461 end:
462 mpz_clear (offc0);
463 mpz_clear (offc1);
464 }
465
466 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
467 The subtraction is considered to be performed in arbitrary precision,
468 without overflows.
469
470 We do not attempt to be too clever regarding the value ranges of X and
471 Y; most of the time, they are just integers or ssa names offsetted by
472 integer. However, we try to use the information contained in the
473 comparisons before the loop (usually created by loop header copying). */
474
475 static void
476 bound_difference (struct loop *loop, tree x, tree y, bounds *bnds)
477 {
478 tree type = TREE_TYPE (x);
479 tree varx, vary;
480 mpz_t offx, offy;
481 mpz_t minx, maxx, miny, maxy;
482 int cnt = 0;
483 edge e;
484 basic_block bb;
485 tree c0, c1;
486 gimple cond;
487 enum tree_code cmp;
488
489 /* Get rid of unnecessary casts, but preserve the value of
490 the expressions. */
491 STRIP_SIGN_NOPS (x);
492 STRIP_SIGN_NOPS (y);
493
494 mpz_init (bnds->below);
495 mpz_init (bnds->up);
496 mpz_init (offx);
497 mpz_init (offy);
498 split_to_var_and_offset (x, &varx, offx);
499 split_to_var_and_offset (y, &vary, offy);
500
501 if (!integer_zerop (varx)
502 && operand_equal_p (varx, vary, 0))
503 {
504 /* Special case VARX == VARY -- we just need to compare the
505 offsets. The matters are a bit more complicated in the
506 case addition of offsets may wrap. */
507 bound_difference_of_offsetted_base (type, offx, offy, bnds);
508 }
509 else
510 {
511 /* Otherwise, use the value ranges to determine the initial
512 estimates on below and up. */
513 mpz_init (minx);
514 mpz_init (maxx);
515 mpz_init (miny);
516 mpz_init (maxy);
517 determine_value_range (loop, type, varx, offx, minx, maxx);
518 determine_value_range (loop, type, vary, offy, miny, maxy);
519
520 mpz_sub (bnds->below, minx, maxy);
521 mpz_sub (bnds->up, maxx, miny);
522 mpz_clear (minx);
523 mpz_clear (maxx);
524 mpz_clear (miny);
525 mpz_clear (maxy);
526 }
527
528 /* If both X and Y are constants, we cannot get any more precise. */
529 if (integer_zerop (varx) && integer_zerop (vary))
530 goto end;
531
532 /* Now walk the dominators of the loop header and use the entry
533 guards to refine the estimates. */
534 for (bb = loop->header;
535 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
536 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
537 {
538 if (!single_pred_p (bb))
539 continue;
540 e = single_pred_edge (bb);
541
542 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
543 continue;
544
545 cond = last_stmt (e->src);
546 c0 = gimple_cond_lhs (cond);
547 cmp = gimple_cond_code (cond);
548 c1 = gimple_cond_rhs (cond);
549
550 if (e->flags & EDGE_FALSE_VALUE)
551 cmp = invert_tree_comparison (cmp, false);
552
553 refine_bounds_using_guard (type, varx, offx, vary, offy,
554 c0, cmp, c1, bnds);
555 ++cnt;
556 }
557
558 end:
559 mpz_clear (offx);
560 mpz_clear (offy);
561 }
562
563 /* Update the bounds in BNDS that restrict the value of X to the bounds
564 that restrict the value of X + DELTA. X can be obtained as a
565 difference of two values in TYPE. */
566
567 static void
568 bounds_add (bounds *bnds, const widest_int &delta, tree type)
569 {
570 mpz_t mdelta, max;
571
572 mpz_init (mdelta);
573 wi::to_mpz (delta, mdelta, SIGNED);
574
575 mpz_init (max);
576 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
577
578 mpz_add (bnds->up, bnds->up, mdelta);
579 mpz_add (bnds->below, bnds->below, mdelta);
580
581 if (mpz_cmp (bnds->up, max) > 0)
582 mpz_set (bnds->up, max);
583
584 mpz_neg (max, max);
585 if (mpz_cmp (bnds->below, max) < 0)
586 mpz_set (bnds->below, max);
587
588 mpz_clear (mdelta);
589 mpz_clear (max);
590 }
591
592 /* Update the bounds in BNDS that restrict the value of X to the bounds
593 that restrict the value of -X. */
594
595 static void
596 bounds_negate (bounds *bnds)
597 {
598 mpz_t tmp;
599
600 mpz_init_set (tmp, bnds->up);
601 mpz_neg (bnds->up, bnds->below);
602 mpz_neg (bnds->below, tmp);
603 mpz_clear (tmp);
604 }
605
606 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
607
608 static tree
609 inverse (tree x, tree mask)
610 {
611 tree type = TREE_TYPE (x);
612 tree rslt;
613 unsigned ctr = tree_floor_log2 (mask);
614
615 if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
616 {
617 unsigned HOST_WIDE_INT ix;
618 unsigned HOST_WIDE_INT imask;
619 unsigned HOST_WIDE_INT irslt = 1;
620
621 gcc_assert (cst_and_fits_in_hwi (x));
622 gcc_assert (cst_and_fits_in_hwi (mask));
623
624 ix = int_cst_value (x);
625 imask = int_cst_value (mask);
626
627 for (; ctr; ctr--)
628 {
629 irslt *= ix;
630 ix *= ix;
631 }
632 irslt &= imask;
633
634 rslt = build_int_cst_type (type, irslt);
635 }
636 else
637 {
638 rslt = build_int_cst (type, 1);
639 for (; ctr; ctr--)
640 {
641 rslt = int_const_binop (MULT_EXPR, rslt, x);
642 x = int_const_binop (MULT_EXPR, x, x);
643 }
644 rslt = int_const_binop (BIT_AND_EXPR, rslt, mask);
645 }
646
647 return rslt;
648 }
649
650 /* Derives the upper bound BND on the number of executions of loop with exit
651 condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
652 the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
653 that the loop ends through this exit, i.e., the induction variable ever
654 reaches the value of C.
655
656 The value C is equal to final - base, where final and base are the final and
657 initial value of the actual induction variable in the analysed loop. BNDS
658 bounds the value of this difference when computed in signed type with
659 unbounded range, while the computation of C is performed in an unsigned
660 type with the range matching the range of the type of the induction variable.
661 In particular, BNDS.up contains an upper bound on C in the following cases:
662 -- if the iv must reach its final value without overflow, i.e., if
663 NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
664 -- if final >= base, which we know to hold when BNDS.below >= 0. */
665
666 static void
667 number_of_iterations_ne_max (mpz_t bnd, bool no_overflow, tree c, tree s,
668 bounds *bnds, bool exit_must_be_taken)
669 {
670 widest_int max;
671 mpz_t d;
672 tree type = TREE_TYPE (c);
673 bool bnds_u_valid = ((no_overflow && exit_must_be_taken)
674 || mpz_sgn (bnds->below) >= 0);
675
676 if (integer_onep (s)
677 || (TREE_CODE (c) == INTEGER_CST
678 && TREE_CODE (s) == INTEGER_CST
679 && wi::mod_trunc (c, s, TYPE_SIGN (type)) == 0)
680 || (TYPE_OVERFLOW_UNDEFINED (type)
681 && multiple_of_p (type, c, s)))
682 {
683 /* If C is an exact multiple of S, then its value will be reached before
684 the induction variable overflows (unless the loop is exited in some
685 other way before). Note that the actual induction variable in the
686 loop (which ranges from base to final instead of from 0 to C) may
687 overflow, in which case BNDS.up will not be giving a correct upper
688 bound on C; thus, BNDS_U_VALID had to be computed in advance. */
689 no_overflow = true;
690 exit_must_be_taken = true;
691 }
692
693 /* If the induction variable can overflow, the number of iterations is at
694 most the period of the control variable (or infinite, but in that case
695 the whole # of iterations analysis will fail). */
696 if (!no_overflow)
697 {
698 max = wi::mask <widest_int> (TYPE_PRECISION (type) - wi::ctz (s), false);
699 wi::to_mpz (max, bnd, UNSIGNED);
700 return;
701 }
702
703 /* Now we know that the induction variable does not overflow, so the loop
704 iterates at most (range of type / S) times. */
705 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), bnd, UNSIGNED);
706
707 /* If the induction variable is guaranteed to reach the value of C before
708 overflow, ... */
709 if (exit_must_be_taken)
710 {
711 /* ... then we can strengthen this to C / S, and possibly we can use
712 the upper bound on C given by BNDS. */
713 if (TREE_CODE (c) == INTEGER_CST)
714 wi::to_mpz (c, bnd, UNSIGNED);
715 else if (bnds_u_valid)
716 mpz_set (bnd, bnds->up);
717 }
718
719 mpz_init (d);
720 wi::to_mpz (s, d, UNSIGNED);
721 mpz_fdiv_q (bnd, bnd, d);
722 mpz_clear (d);
723 }
724
725 /* Determines number of iterations of loop whose ending condition
726 is IV <> FINAL. TYPE is the type of the iv. The number of
727 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
728 we know that the exit must be taken eventually, i.e., that the IV
729 ever reaches the value FINAL (we derived this earlier, and possibly set
730 NITER->assumptions to make sure this is the case). BNDS contains the
731 bounds on the difference FINAL - IV->base. */
732
733 static bool
734 number_of_iterations_ne (tree type, affine_iv *iv, tree final,
735 struct tree_niter_desc *niter, bool exit_must_be_taken,
736 bounds *bnds)
737 {
738 tree niter_type = unsigned_type_for (type);
739 tree s, c, d, bits, assumption, tmp, bound;
740 mpz_t max;
741
742 niter->control = *iv;
743 niter->bound = final;
744 niter->cmp = NE_EXPR;
745
746 /* Rearrange the terms so that we get inequality S * i <> C, with S
747 positive. Also cast everything to the unsigned type. If IV does
748 not overflow, BNDS bounds the value of C. Also, this is the
749 case if the computation |FINAL - IV->base| does not overflow, i.e.,
750 if BNDS->below in the result is nonnegative. */
751 if (tree_int_cst_sign_bit (iv->step))
752 {
753 s = fold_convert (niter_type,
754 fold_build1 (NEGATE_EXPR, type, iv->step));
755 c = fold_build2 (MINUS_EXPR, niter_type,
756 fold_convert (niter_type, iv->base),
757 fold_convert (niter_type, final));
758 bounds_negate (bnds);
759 }
760 else
761 {
762 s = fold_convert (niter_type, iv->step);
763 c = fold_build2 (MINUS_EXPR, niter_type,
764 fold_convert (niter_type, final),
765 fold_convert (niter_type, iv->base));
766 }
767
768 mpz_init (max);
769 number_of_iterations_ne_max (max, iv->no_overflow, c, s, bnds,
770 exit_must_be_taken);
771 niter->max = widest_int::from (wi::from_mpz (niter_type, max, false),
772 TYPE_SIGN (niter_type));
773 mpz_clear (max);
774
775 /* First the trivial cases -- when the step is 1. */
776 if (integer_onep (s))
777 {
778 niter->niter = c;
779 return true;
780 }
781
782 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
783 is infinite. Otherwise, the number of iterations is
784 (inverse(s/d) * (c/d)) mod (size of mode/d). */
785 bits = num_ending_zeros (s);
786 bound = build_low_bits_mask (niter_type,
787 (TYPE_PRECISION (niter_type)
788 - tree_to_uhwi (bits)));
789
790 d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
791 build_int_cst (niter_type, 1), bits);
792 s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
793
794 if (!exit_must_be_taken)
795 {
796 /* If we cannot assume that the exit is taken eventually, record the
797 assumptions for divisibility of c. */
798 assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
799 assumption = fold_build2 (EQ_EXPR, boolean_type_node,
800 assumption, build_int_cst (niter_type, 0));
801 if (!integer_nonzerop (assumption))
802 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
803 niter->assumptions, assumption);
804 }
805
806 c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
807 tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
808 niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
809 return true;
810 }
811
812 /* Checks whether we can determine the final value of the control variable
813 of the loop with ending condition IV0 < IV1 (computed in TYPE).
814 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
815 of the step. The assumptions necessary to ensure that the computation
816 of the final value does not overflow are recorded in NITER. If we
817 find the final value, we adjust DELTA and return TRUE. Otherwise
818 we return false. BNDS bounds the value of IV1->base - IV0->base,
819 and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
820 true if we know that the exit must be taken eventually. */
821
822 static bool
823 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
824 struct tree_niter_desc *niter,
825 tree *delta, tree step,
826 bool exit_must_be_taken, bounds *bnds)
827 {
828 tree niter_type = TREE_TYPE (step);
829 tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
830 tree tmod;
831 mpz_t mmod;
832 tree assumption = boolean_true_node, bound, noloop;
833 bool ret = false, fv_comp_no_overflow;
834 tree type1 = type;
835 if (POINTER_TYPE_P (type))
836 type1 = sizetype;
837
838 if (TREE_CODE (mod) != INTEGER_CST)
839 return false;
840 if (integer_nonzerop (mod))
841 mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
842 tmod = fold_convert (type1, mod);
843
844 mpz_init (mmod);
845 wi::to_mpz (mod, mmod, UNSIGNED);
846 mpz_neg (mmod, mmod);
847
848 /* If the induction variable does not overflow and the exit is taken,
849 then the computation of the final value does not overflow. This is
850 also obviously the case if the new final value is equal to the
851 current one. Finally, we postulate this for pointer type variables,
852 as the code cannot rely on the object to that the pointer points being
853 placed at the end of the address space (and more pragmatically,
854 TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
855 if (integer_zerop (mod) || POINTER_TYPE_P (type))
856 fv_comp_no_overflow = true;
857 else if (!exit_must_be_taken)
858 fv_comp_no_overflow = false;
859 else
860 fv_comp_no_overflow =
861 (iv0->no_overflow && integer_nonzerop (iv0->step))
862 || (iv1->no_overflow && integer_nonzerop (iv1->step));
863
864 if (integer_nonzerop (iv0->step))
865 {
866 /* The final value of the iv is iv1->base + MOD, assuming that this
867 computation does not overflow, and that
868 iv0->base <= iv1->base + MOD. */
869 if (!fv_comp_no_overflow)
870 {
871 bound = fold_build2 (MINUS_EXPR, type1,
872 TYPE_MAX_VALUE (type1), tmod);
873 assumption = fold_build2 (LE_EXPR, boolean_type_node,
874 iv1->base, bound);
875 if (integer_zerop (assumption))
876 goto end;
877 }
878 if (mpz_cmp (mmod, bnds->below) < 0)
879 noloop = boolean_false_node;
880 else if (POINTER_TYPE_P (type))
881 noloop = fold_build2 (GT_EXPR, boolean_type_node,
882 iv0->base,
883 fold_build_pointer_plus (iv1->base, tmod));
884 else
885 noloop = fold_build2 (GT_EXPR, boolean_type_node,
886 iv0->base,
887 fold_build2 (PLUS_EXPR, type1,
888 iv1->base, tmod));
889 }
890 else
891 {
892 /* The final value of the iv is iv0->base - MOD, assuming that this
893 computation does not overflow, and that
894 iv0->base - MOD <= iv1->base. */
895 if (!fv_comp_no_overflow)
896 {
897 bound = fold_build2 (PLUS_EXPR, type1,
898 TYPE_MIN_VALUE (type1), tmod);
899 assumption = fold_build2 (GE_EXPR, boolean_type_node,
900 iv0->base, bound);
901 if (integer_zerop (assumption))
902 goto end;
903 }
904 if (mpz_cmp (mmod, bnds->below) < 0)
905 noloop = boolean_false_node;
906 else if (POINTER_TYPE_P (type))
907 noloop = fold_build2 (GT_EXPR, boolean_type_node,
908 fold_build_pointer_plus (iv0->base,
909 fold_build1 (NEGATE_EXPR,
910 type1, tmod)),
911 iv1->base);
912 else
913 noloop = fold_build2 (GT_EXPR, boolean_type_node,
914 fold_build2 (MINUS_EXPR, type1,
915 iv0->base, tmod),
916 iv1->base);
917 }
918
919 if (!integer_nonzerop (assumption))
920 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
921 niter->assumptions,
922 assumption);
923 if (!integer_zerop (noloop))
924 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
925 niter->may_be_zero,
926 noloop);
927 bounds_add (bnds, wi::to_widest (mod), type);
928 *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
929
930 ret = true;
931 end:
932 mpz_clear (mmod);
933 return ret;
934 }
935
936 /* Add assertions to NITER that ensure that the control variable of the loop
937 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
938 are TYPE. Returns false if we can prove that there is an overflow, true
939 otherwise. STEP is the absolute value of the step. */
940
941 static bool
942 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
943 struct tree_niter_desc *niter, tree step)
944 {
945 tree bound, d, assumption, diff;
946 tree niter_type = TREE_TYPE (step);
947
948 if (integer_nonzerop (iv0->step))
949 {
950 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
951 if (iv0->no_overflow)
952 return true;
953
954 /* If iv0->base is a constant, we can determine the last value before
955 overflow precisely; otherwise we conservatively assume
956 MAX - STEP + 1. */
957
958 if (TREE_CODE (iv0->base) == INTEGER_CST)
959 {
960 d = fold_build2 (MINUS_EXPR, niter_type,
961 fold_convert (niter_type, TYPE_MAX_VALUE (type)),
962 fold_convert (niter_type, iv0->base));
963 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
964 }
965 else
966 diff = fold_build2 (MINUS_EXPR, niter_type, step,
967 build_int_cst (niter_type, 1));
968 bound = fold_build2 (MINUS_EXPR, type,
969 TYPE_MAX_VALUE (type), fold_convert (type, diff));
970 assumption = fold_build2 (LE_EXPR, boolean_type_node,
971 iv1->base, bound);
972 }
973 else
974 {
975 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
976 if (iv1->no_overflow)
977 return true;
978
979 if (TREE_CODE (iv1->base) == INTEGER_CST)
980 {
981 d = fold_build2 (MINUS_EXPR, niter_type,
982 fold_convert (niter_type, iv1->base),
983 fold_convert (niter_type, TYPE_MIN_VALUE (type)));
984 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
985 }
986 else
987 diff = fold_build2 (MINUS_EXPR, niter_type, step,
988 build_int_cst (niter_type, 1));
989 bound = fold_build2 (PLUS_EXPR, type,
990 TYPE_MIN_VALUE (type), fold_convert (type, diff));
991 assumption = fold_build2 (GE_EXPR, boolean_type_node,
992 iv0->base, bound);
993 }
994
995 if (integer_zerop (assumption))
996 return false;
997 if (!integer_nonzerop (assumption))
998 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
999 niter->assumptions, assumption);
1000
1001 iv0->no_overflow = true;
1002 iv1->no_overflow = true;
1003 return true;
1004 }
1005
1006 /* Add an assumption to NITER that a loop whose ending condition
1007 is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
1008 bounds the value of IV1->base - IV0->base. */
1009
1010 static void
1011 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1012 struct tree_niter_desc *niter, bounds *bnds)
1013 {
1014 tree assumption = boolean_true_node, bound, diff;
1015 tree mbz, mbzl, mbzr, type1;
1016 bool rolls_p, no_overflow_p;
1017 widest_int dstep;
1018 mpz_t mstep, max;
1019
1020 /* We are going to compute the number of iterations as
1021 (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1022 variant of TYPE. This formula only works if
1023
1024 -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1025
1026 (where MAX is the maximum value of the unsigned variant of TYPE, and
1027 the computations in this formula are performed in full precision,
1028 i.e., without overflows).
1029
1030 Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1031 we have a condition of the form iv0->base - step < iv1->base before the loop,
1032 and for loops iv0->base < iv1->base - step * i the condition
1033 iv0->base < iv1->base + step, due to loop header copying, which enable us
1034 to prove the lower bound.
1035
1036 The upper bound is more complicated. Unless the expressions for initial
1037 and final value themselves contain enough information, we usually cannot
1038 derive it from the context. */
1039
1040 /* First check whether the answer does not follow from the bounds we gathered
1041 before. */
1042 if (integer_nonzerop (iv0->step))
1043 dstep = wi::to_widest (iv0->step);
1044 else
1045 {
1046 dstep = wi::sext (wi::to_widest (iv1->step), TYPE_PRECISION (type));
1047 dstep = -dstep;
1048 }
1049
1050 mpz_init (mstep);
1051 wi::to_mpz (dstep, mstep, UNSIGNED);
1052 mpz_neg (mstep, mstep);
1053 mpz_add_ui (mstep, mstep, 1);
1054
1055 rolls_p = mpz_cmp (mstep, bnds->below) <= 0;
1056
1057 mpz_init (max);
1058 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
1059 mpz_add (max, max, mstep);
1060 no_overflow_p = (mpz_cmp (bnds->up, max) <= 0
1061 /* For pointers, only values lying inside a single object
1062 can be compared or manipulated by pointer arithmetics.
1063 Gcc in general does not allow or handle objects larger
1064 than half of the address space, hence the upper bound
1065 is satisfied for pointers. */
1066 || POINTER_TYPE_P (type));
1067 mpz_clear (mstep);
1068 mpz_clear (max);
1069
1070 if (rolls_p && no_overflow_p)
1071 return;
1072
1073 type1 = type;
1074 if (POINTER_TYPE_P (type))
1075 type1 = sizetype;
1076
1077 /* Now the hard part; we must formulate the assumption(s) as expressions, and
1078 we must be careful not to introduce overflow. */
1079
1080 if (integer_nonzerop (iv0->step))
1081 {
1082 diff = fold_build2 (MINUS_EXPR, type1,
1083 iv0->step, build_int_cst (type1, 1));
1084
1085 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1086 0 address never belongs to any object, we can assume this for
1087 pointers. */
1088 if (!POINTER_TYPE_P (type))
1089 {
1090 bound = fold_build2 (PLUS_EXPR, type1,
1091 TYPE_MIN_VALUE (type), diff);
1092 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1093 iv0->base, bound);
1094 }
1095
1096 /* And then we can compute iv0->base - diff, and compare it with
1097 iv1->base. */
1098 mbzl = fold_build2 (MINUS_EXPR, type1,
1099 fold_convert (type1, iv0->base), diff);
1100 mbzr = fold_convert (type1, iv1->base);
1101 }
1102 else
1103 {
1104 diff = fold_build2 (PLUS_EXPR, type1,
1105 iv1->step, build_int_cst (type1, 1));
1106
1107 if (!POINTER_TYPE_P (type))
1108 {
1109 bound = fold_build2 (PLUS_EXPR, type1,
1110 TYPE_MAX_VALUE (type), diff);
1111 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1112 iv1->base, bound);
1113 }
1114
1115 mbzl = fold_convert (type1, iv0->base);
1116 mbzr = fold_build2 (MINUS_EXPR, type1,
1117 fold_convert (type1, iv1->base), diff);
1118 }
1119
1120 if (!integer_nonzerop (assumption))
1121 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1122 niter->assumptions, assumption);
1123 if (!rolls_p)
1124 {
1125 mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
1126 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1127 niter->may_be_zero, mbz);
1128 }
1129 }
1130
1131 /* Determines number of iterations of loop whose ending condition
1132 is IV0 < IV1. TYPE is the type of the iv. The number of
1133 iterations is stored to NITER. BNDS bounds the difference
1134 IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1135 that the exit must be taken eventually. */
1136
1137 static bool
1138 number_of_iterations_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1139 struct tree_niter_desc *niter,
1140 bool exit_must_be_taken, bounds *bnds)
1141 {
1142 tree niter_type = unsigned_type_for (type);
1143 tree delta, step, s;
1144 mpz_t mstep, tmp;
1145
1146 if (integer_nonzerop (iv0->step))
1147 {
1148 niter->control = *iv0;
1149 niter->cmp = LT_EXPR;
1150 niter->bound = iv1->base;
1151 }
1152 else
1153 {
1154 niter->control = *iv1;
1155 niter->cmp = GT_EXPR;
1156 niter->bound = iv0->base;
1157 }
1158
1159 delta = fold_build2 (MINUS_EXPR, niter_type,
1160 fold_convert (niter_type, iv1->base),
1161 fold_convert (niter_type, iv0->base));
1162
1163 /* First handle the special case that the step is +-1. */
1164 if ((integer_onep (iv0->step) && integer_zerop (iv1->step))
1165 || (integer_all_onesp (iv1->step) && integer_zerop (iv0->step)))
1166 {
1167 /* for (i = iv0->base; i < iv1->base; i++)
1168
1169 or
1170
1171 for (i = iv1->base; i > iv0->base; i--).
1172
1173 In both cases # of iterations is iv1->base - iv0->base, assuming that
1174 iv1->base >= iv0->base.
1175
1176 First try to derive a lower bound on the value of
1177 iv1->base - iv0->base, computed in full precision. If the difference
1178 is nonnegative, we are done, otherwise we must record the
1179 condition. */
1180
1181 if (mpz_sgn (bnds->below) < 0)
1182 niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
1183 iv1->base, iv0->base);
1184 niter->niter = delta;
1185 niter->max = widest_int::from (wi::from_mpz (niter_type, bnds->up, false),
1186 TYPE_SIGN (niter_type));
1187 return true;
1188 }
1189
1190 if (integer_nonzerop (iv0->step))
1191 step = fold_convert (niter_type, iv0->step);
1192 else
1193 step = fold_convert (niter_type,
1194 fold_build1 (NEGATE_EXPR, type, iv1->step));
1195
1196 /* If we can determine the final value of the control iv exactly, we can
1197 transform the condition to != comparison. In particular, this will be
1198 the case if DELTA is constant. */
1199 if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step,
1200 exit_must_be_taken, bnds))
1201 {
1202 affine_iv zps;
1203
1204 zps.base = build_int_cst (niter_type, 0);
1205 zps.step = step;
1206 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1207 zps does not overflow. */
1208 zps.no_overflow = true;
1209
1210 return number_of_iterations_ne (type, &zps, delta, niter, true, bnds);
1211 }
1212
1213 /* Make sure that the control iv does not overflow. */
1214 if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
1215 return false;
1216
1217 /* We determine the number of iterations as (delta + step - 1) / step. For
1218 this to work, we must know that iv1->base >= iv0->base - step + 1,
1219 otherwise the loop does not roll. */
1220 assert_loop_rolls_lt (type, iv0, iv1, niter, bnds);
1221
1222 s = fold_build2 (MINUS_EXPR, niter_type,
1223 step, build_int_cst (niter_type, 1));
1224 delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
1225 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
1226
1227 mpz_init (mstep);
1228 mpz_init (tmp);
1229 wi::to_mpz (step, mstep, UNSIGNED);
1230 mpz_add (tmp, bnds->up, mstep);
1231 mpz_sub_ui (tmp, tmp, 1);
1232 mpz_fdiv_q (tmp, tmp, mstep);
1233 niter->max = widest_int::from (wi::from_mpz (niter_type, tmp, false),
1234 TYPE_SIGN (niter_type));
1235 mpz_clear (mstep);
1236 mpz_clear (tmp);
1237
1238 return true;
1239 }
1240
1241 /* Determines number of iterations of loop whose ending condition
1242 is IV0 <= IV1. TYPE is the type of the iv. The number of
1243 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1244 we know that this condition must eventually become false (we derived this
1245 earlier, and possibly set NITER->assumptions to make sure this
1246 is the case). BNDS bounds the difference IV1->base - IV0->base. */
1247
1248 static bool
1249 number_of_iterations_le (tree type, affine_iv *iv0, affine_iv *iv1,
1250 struct tree_niter_desc *niter, bool exit_must_be_taken,
1251 bounds *bnds)
1252 {
1253 tree assumption;
1254 tree type1 = type;
1255 if (POINTER_TYPE_P (type))
1256 type1 = sizetype;
1257
1258 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1259 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1260 value of the type. This we must know anyway, since if it is
1261 equal to this value, the loop rolls forever. We do not check
1262 this condition for pointer type ivs, as the code cannot rely on
1263 the object to that the pointer points being placed at the end of
1264 the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1265 not defined for pointers). */
1266
1267 if (!exit_must_be_taken && !POINTER_TYPE_P (type))
1268 {
1269 if (integer_nonzerop (iv0->step))
1270 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1271 iv1->base, TYPE_MAX_VALUE (type));
1272 else
1273 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1274 iv0->base, TYPE_MIN_VALUE (type));
1275
1276 if (integer_zerop (assumption))
1277 return false;
1278 if (!integer_nonzerop (assumption))
1279 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1280 niter->assumptions, assumption);
1281 }
1282
1283 if (integer_nonzerop (iv0->step))
1284 {
1285 if (POINTER_TYPE_P (type))
1286 iv1->base = fold_build_pointer_plus_hwi (iv1->base, 1);
1287 else
1288 iv1->base = fold_build2 (PLUS_EXPR, type1, iv1->base,
1289 build_int_cst (type1, 1));
1290 }
1291 else if (POINTER_TYPE_P (type))
1292 iv0->base = fold_build_pointer_plus_hwi (iv0->base, -1);
1293 else
1294 iv0->base = fold_build2 (MINUS_EXPR, type1,
1295 iv0->base, build_int_cst (type1, 1));
1296
1297 bounds_add (bnds, 1, type1);
1298
1299 return number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1300 bnds);
1301 }
1302
1303 /* Dumps description of affine induction variable IV to FILE. */
1304
1305 static void
1306 dump_affine_iv (FILE *file, affine_iv *iv)
1307 {
1308 if (!integer_zerop (iv->step))
1309 fprintf (file, "[");
1310
1311 print_generic_expr (dump_file, iv->base, TDF_SLIM);
1312
1313 if (!integer_zerop (iv->step))
1314 {
1315 fprintf (file, ", + , ");
1316 print_generic_expr (dump_file, iv->step, TDF_SLIM);
1317 fprintf (file, "]%s", iv->no_overflow ? "(no_overflow)" : "");
1318 }
1319 }
1320
1321 /* Determine the number of iterations according to condition (for staying
1322 inside loop) which compares two induction variables using comparison
1323 operator CODE. The induction variable on left side of the comparison
1324 is IV0, the right-hand side is IV1. Both induction variables must have
1325 type TYPE, which must be an integer or pointer type. The steps of the
1326 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1327
1328 LOOP is the loop whose number of iterations we are determining.
1329
1330 ONLY_EXIT is true if we are sure this is the only way the loop could be
1331 exited (including possibly non-returning function calls, exceptions, etc.)
1332 -- in this case we can use the information whether the control induction
1333 variables can overflow or not in a more efficient way.
1334
1335 if EVERY_ITERATION is true, we know the test is executed on every iteration.
1336
1337 The results (number of iterations and assumptions as described in
1338 comments at struct tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1339 Returns false if it fails to determine number of iterations, true if it
1340 was determined (possibly with some assumptions). */
1341
1342 static bool
1343 number_of_iterations_cond (struct loop *loop,
1344 tree type, affine_iv *iv0, enum tree_code code,
1345 affine_iv *iv1, struct tree_niter_desc *niter,
1346 bool only_exit, bool every_iteration)
1347 {
1348 bool exit_must_be_taken = false, ret;
1349 bounds bnds;
1350
1351 /* If the test is not executed every iteration, wrapping may make the test
1352 to pass again.
1353 TODO: the overflow case can be still used as unreliable estimate of upper
1354 bound. But we have no API to pass it down to number of iterations code
1355 and, at present, it will not use it anyway. */
1356 if (!every_iteration
1357 && (!iv0->no_overflow || !iv1->no_overflow
1358 || code == NE_EXPR || code == EQ_EXPR))
1359 return false;
1360
1361 /* The meaning of these assumptions is this:
1362 if !assumptions
1363 then the rest of information does not have to be valid
1364 if may_be_zero then the loop does not roll, even if
1365 niter != 0. */
1366 niter->assumptions = boolean_true_node;
1367 niter->may_be_zero = boolean_false_node;
1368 niter->niter = NULL_TREE;
1369 niter->max = 0;
1370 niter->bound = NULL_TREE;
1371 niter->cmp = ERROR_MARK;
1372
1373 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1374 the control variable is on lhs. */
1375 if (code == GE_EXPR || code == GT_EXPR
1376 || (code == NE_EXPR && integer_zerop (iv0->step)))
1377 {
1378 SWAP (iv0, iv1);
1379 code = swap_tree_comparison (code);
1380 }
1381
1382 if (POINTER_TYPE_P (type))
1383 {
1384 /* Comparison of pointers is undefined unless both iv0 and iv1 point
1385 to the same object. If they do, the control variable cannot wrap
1386 (as wrap around the bounds of memory will never return a pointer
1387 that would be guaranteed to point to the same object, even if we
1388 avoid undefined behavior by casting to size_t and back). */
1389 iv0->no_overflow = true;
1390 iv1->no_overflow = true;
1391 }
1392
1393 /* If the control induction variable does not overflow and the only exit
1394 from the loop is the one that we analyze, we know it must be taken
1395 eventually. */
1396 if (only_exit)
1397 {
1398 if (!integer_zerop (iv0->step) && iv0->no_overflow)
1399 exit_must_be_taken = true;
1400 else if (!integer_zerop (iv1->step) && iv1->no_overflow)
1401 exit_must_be_taken = true;
1402 }
1403
1404 /* We can handle the case when neither of the sides of the comparison is
1405 invariant, provided that the test is NE_EXPR. This rarely occurs in
1406 practice, but it is simple enough to manage. */
1407 if (!integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1408 {
1409 tree step_type = POINTER_TYPE_P (type) ? sizetype : type;
1410 if (code != NE_EXPR)
1411 return false;
1412
1413 iv0->step = fold_binary_to_constant (MINUS_EXPR, step_type,
1414 iv0->step, iv1->step);
1415 iv0->no_overflow = false;
1416 iv1->step = build_int_cst (step_type, 0);
1417 iv1->no_overflow = true;
1418 }
1419
1420 /* If the result of the comparison is a constant, the loop is weird. More
1421 precise handling would be possible, but the situation is not common enough
1422 to waste time on it. */
1423 if (integer_zerop (iv0->step) && integer_zerop (iv1->step))
1424 return false;
1425
1426 /* Ignore loops of while (i-- < 10) type. */
1427 if (code != NE_EXPR)
1428 {
1429 if (iv0->step && tree_int_cst_sign_bit (iv0->step))
1430 return false;
1431
1432 if (!integer_zerop (iv1->step) && !tree_int_cst_sign_bit (iv1->step))
1433 return false;
1434 }
1435
1436 /* If the loop exits immediately, there is nothing to do. */
1437 tree tem = fold_binary (code, boolean_type_node, iv0->base, iv1->base);
1438 if (tem && integer_zerop (tem))
1439 {
1440 niter->niter = build_int_cst (unsigned_type_for (type), 0);
1441 niter->max = 0;
1442 return true;
1443 }
1444
1445 /* OK, now we know we have a senseful loop. Handle several cases, depending
1446 on what comparison operator is used. */
1447 bound_difference (loop, iv1->base, iv0->base, &bnds);
1448
1449 if (dump_file && (dump_flags & TDF_DETAILS))
1450 {
1451 fprintf (dump_file,
1452 "Analyzing # of iterations of loop %d\n", loop->num);
1453
1454 fprintf (dump_file, " exit condition ");
1455 dump_affine_iv (dump_file, iv0);
1456 fprintf (dump_file, " %s ",
1457 code == NE_EXPR ? "!="
1458 : code == LT_EXPR ? "<"
1459 : "<=");
1460 dump_affine_iv (dump_file, iv1);
1461 fprintf (dump_file, "\n");
1462
1463 fprintf (dump_file, " bounds on difference of bases: ");
1464 mpz_out_str (dump_file, 10, bnds.below);
1465 fprintf (dump_file, " ... ");
1466 mpz_out_str (dump_file, 10, bnds.up);
1467 fprintf (dump_file, "\n");
1468 }
1469
1470 switch (code)
1471 {
1472 case NE_EXPR:
1473 gcc_assert (integer_zerop (iv1->step));
1474 ret = number_of_iterations_ne (type, iv0, iv1->base, niter,
1475 exit_must_be_taken, &bnds);
1476 break;
1477
1478 case LT_EXPR:
1479 ret = number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1480 &bnds);
1481 break;
1482
1483 case LE_EXPR:
1484 ret = number_of_iterations_le (type, iv0, iv1, niter, exit_must_be_taken,
1485 &bnds);
1486 break;
1487
1488 default:
1489 gcc_unreachable ();
1490 }
1491
1492 mpz_clear (bnds.up);
1493 mpz_clear (bnds.below);
1494
1495 if (dump_file && (dump_flags & TDF_DETAILS))
1496 {
1497 if (ret)
1498 {
1499 fprintf (dump_file, " result:\n");
1500 if (!integer_nonzerop (niter->assumptions))
1501 {
1502 fprintf (dump_file, " under assumptions ");
1503 print_generic_expr (dump_file, niter->assumptions, TDF_SLIM);
1504 fprintf (dump_file, "\n");
1505 }
1506
1507 if (!integer_zerop (niter->may_be_zero))
1508 {
1509 fprintf (dump_file, " zero if ");
1510 print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1511 fprintf (dump_file, "\n");
1512 }
1513
1514 fprintf (dump_file, " # of iterations ");
1515 print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1516 fprintf (dump_file, ", bounded by ");
1517 print_decu (niter->max, dump_file);
1518 fprintf (dump_file, "\n");
1519 }
1520 else
1521 fprintf (dump_file, " failed\n\n");
1522 }
1523 return ret;
1524 }
1525
1526 /* Substitute NEW for OLD in EXPR and fold the result. */
1527
1528 static tree
1529 simplify_replace_tree (tree expr, tree old, tree new_tree)
1530 {
1531 unsigned i, n;
1532 tree ret = NULL_TREE, e, se;
1533
1534 if (!expr)
1535 return NULL_TREE;
1536
1537 /* Do not bother to replace constants. */
1538 if (CONSTANT_CLASS_P (old))
1539 return expr;
1540
1541 if (expr == old
1542 || operand_equal_p (expr, old, 0))
1543 return unshare_expr (new_tree);
1544
1545 if (!EXPR_P (expr))
1546 return expr;
1547
1548 n = TREE_OPERAND_LENGTH (expr);
1549 for (i = 0; i < n; i++)
1550 {
1551 e = TREE_OPERAND (expr, i);
1552 se = simplify_replace_tree (e, old, new_tree);
1553 if (e == se)
1554 continue;
1555
1556 if (!ret)
1557 ret = copy_node (expr);
1558
1559 TREE_OPERAND (ret, i) = se;
1560 }
1561
1562 return (ret ? fold (ret) : expr);
1563 }
1564
1565 /* Expand definitions of ssa names in EXPR as long as they are simple
1566 enough, and return the new expression. */
1567
1568 tree
1569 expand_simple_operations (tree expr)
1570 {
1571 unsigned i, n;
1572 tree ret = NULL_TREE, e, ee, e1;
1573 enum tree_code code;
1574 gimple stmt;
1575
1576 if (expr == NULL_TREE)
1577 return expr;
1578
1579 if (is_gimple_min_invariant (expr))
1580 return expr;
1581
1582 code = TREE_CODE (expr);
1583 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1584 {
1585 n = TREE_OPERAND_LENGTH (expr);
1586 for (i = 0; i < n; i++)
1587 {
1588 e = TREE_OPERAND (expr, i);
1589 ee = expand_simple_operations (e);
1590 if (e == ee)
1591 continue;
1592
1593 if (!ret)
1594 ret = copy_node (expr);
1595
1596 TREE_OPERAND (ret, i) = ee;
1597 }
1598
1599 if (!ret)
1600 return expr;
1601
1602 fold_defer_overflow_warnings ();
1603 ret = fold (ret);
1604 fold_undefer_and_ignore_overflow_warnings ();
1605 return ret;
1606 }
1607
1608 if (TREE_CODE (expr) != SSA_NAME)
1609 return expr;
1610
1611 stmt = SSA_NAME_DEF_STMT (expr);
1612 if (gimple_code (stmt) == GIMPLE_PHI)
1613 {
1614 basic_block src, dest;
1615
1616 if (gimple_phi_num_args (stmt) != 1)
1617 return expr;
1618 e = PHI_ARG_DEF (stmt, 0);
1619
1620 /* Avoid propagating through loop exit phi nodes, which
1621 could break loop-closed SSA form restrictions. */
1622 dest = gimple_bb (stmt);
1623 src = single_pred (dest);
1624 if (TREE_CODE (e) == SSA_NAME
1625 && src->loop_father != dest->loop_father)
1626 return expr;
1627
1628 return expand_simple_operations (e);
1629 }
1630 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1631 return expr;
1632
1633 /* Avoid expanding to expressions that contain SSA names that need
1634 to take part in abnormal coalescing. */
1635 ssa_op_iter iter;
1636 FOR_EACH_SSA_TREE_OPERAND (e, stmt, iter, SSA_OP_USE)
1637 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e))
1638 return expr;
1639
1640 e = gimple_assign_rhs1 (stmt);
1641 code = gimple_assign_rhs_code (stmt);
1642 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1643 {
1644 if (is_gimple_min_invariant (e))
1645 return e;
1646
1647 if (code == SSA_NAME)
1648 return expand_simple_operations (e);
1649
1650 return expr;
1651 }
1652
1653 switch (code)
1654 {
1655 CASE_CONVERT:
1656 /* Casts are simple. */
1657 ee = expand_simple_operations (e);
1658 return fold_build1 (code, TREE_TYPE (expr), ee);
1659
1660 case PLUS_EXPR:
1661 case MINUS_EXPR:
1662 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr))
1663 && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr)))
1664 return expr;
1665 /* Fallthru. */
1666 case POINTER_PLUS_EXPR:
1667 /* And increments and decrements by a constant are simple. */
1668 e1 = gimple_assign_rhs2 (stmt);
1669 if (!is_gimple_min_invariant (e1))
1670 return expr;
1671
1672 ee = expand_simple_operations (e);
1673 return fold_build2 (code, TREE_TYPE (expr), ee, e1);
1674
1675 default:
1676 return expr;
1677 }
1678 }
1679
1680 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1681 expression (or EXPR unchanged, if no simplification was possible). */
1682
1683 static tree
1684 tree_simplify_using_condition_1 (tree cond, tree expr)
1685 {
1686 bool changed;
1687 tree e, te, e0, e1, e2, notcond;
1688 enum tree_code code = TREE_CODE (expr);
1689
1690 if (code == INTEGER_CST)
1691 return expr;
1692
1693 if (code == TRUTH_OR_EXPR
1694 || code == TRUTH_AND_EXPR
1695 || code == COND_EXPR)
1696 {
1697 changed = false;
1698
1699 e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
1700 if (TREE_OPERAND (expr, 0) != e0)
1701 changed = true;
1702
1703 e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
1704 if (TREE_OPERAND (expr, 1) != e1)
1705 changed = true;
1706
1707 if (code == COND_EXPR)
1708 {
1709 e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
1710 if (TREE_OPERAND (expr, 2) != e2)
1711 changed = true;
1712 }
1713 else
1714 e2 = NULL_TREE;
1715
1716 if (changed)
1717 {
1718 if (code == COND_EXPR)
1719 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1720 else
1721 expr = fold_build2 (code, boolean_type_node, e0, e1);
1722 }
1723
1724 return expr;
1725 }
1726
1727 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
1728 propagation, and vice versa. Fold does not handle this, since it is
1729 considered too expensive. */
1730 if (TREE_CODE (cond) == EQ_EXPR)
1731 {
1732 e0 = TREE_OPERAND (cond, 0);
1733 e1 = TREE_OPERAND (cond, 1);
1734
1735 /* We know that e0 == e1. Check whether we cannot simplify expr
1736 using this fact. */
1737 e = simplify_replace_tree (expr, e0, e1);
1738 if (integer_zerop (e) || integer_nonzerop (e))
1739 return e;
1740
1741 e = simplify_replace_tree (expr, e1, e0);
1742 if (integer_zerop (e) || integer_nonzerop (e))
1743 return e;
1744 }
1745 if (TREE_CODE (expr) == EQ_EXPR)
1746 {
1747 e0 = TREE_OPERAND (expr, 0);
1748 e1 = TREE_OPERAND (expr, 1);
1749
1750 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
1751 e = simplify_replace_tree (cond, e0, e1);
1752 if (integer_zerop (e))
1753 return e;
1754 e = simplify_replace_tree (cond, e1, e0);
1755 if (integer_zerop (e))
1756 return e;
1757 }
1758 if (TREE_CODE (expr) == NE_EXPR)
1759 {
1760 e0 = TREE_OPERAND (expr, 0);
1761 e1 = TREE_OPERAND (expr, 1);
1762
1763 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
1764 e = simplify_replace_tree (cond, e0, e1);
1765 if (integer_zerop (e))
1766 return boolean_true_node;
1767 e = simplify_replace_tree (cond, e1, e0);
1768 if (integer_zerop (e))
1769 return boolean_true_node;
1770 }
1771
1772 te = expand_simple_operations (expr);
1773
1774 /* Check whether COND ==> EXPR. */
1775 notcond = invert_truthvalue (cond);
1776 e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, te);
1777 if (e && integer_nonzerop (e))
1778 return e;
1779
1780 /* Check whether COND ==> not EXPR. */
1781 e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, te);
1782 if (e && integer_zerop (e))
1783 return e;
1784
1785 return expr;
1786 }
1787
1788 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1789 expression (or EXPR unchanged, if no simplification was possible).
1790 Wrapper around tree_simplify_using_condition_1 that ensures that chains
1791 of simple operations in definitions of ssa names in COND are expanded,
1792 so that things like casts or incrementing the value of the bound before
1793 the loop do not cause us to fail. */
1794
1795 static tree
1796 tree_simplify_using_condition (tree cond, tree expr)
1797 {
1798 cond = expand_simple_operations (cond);
1799
1800 return tree_simplify_using_condition_1 (cond, expr);
1801 }
1802
1803 /* Tries to simplify EXPR using the conditions on entry to LOOP.
1804 Returns the simplified expression (or EXPR unchanged, if no
1805 simplification was possible).*/
1806
1807 static tree
1808 simplify_using_initial_conditions (struct loop *loop, tree expr)
1809 {
1810 edge e;
1811 basic_block bb;
1812 gimple stmt;
1813 tree cond;
1814 int cnt = 0;
1815
1816 if (TREE_CODE (expr) == INTEGER_CST)
1817 return expr;
1818
1819 /* Limit walking the dominators to avoid quadraticness in
1820 the number of BBs times the number of loops in degenerate
1821 cases. */
1822 for (bb = loop->header;
1823 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
1824 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
1825 {
1826 if (!single_pred_p (bb))
1827 continue;
1828 e = single_pred_edge (bb);
1829
1830 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
1831 continue;
1832
1833 stmt = last_stmt (e->src);
1834 cond = fold_build2 (gimple_cond_code (stmt),
1835 boolean_type_node,
1836 gimple_cond_lhs (stmt),
1837 gimple_cond_rhs (stmt));
1838 if (e->flags & EDGE_FALSE_VALUE)
1839 cond = invert_truthvalue (cond);
1840 expr = tree_simplify_using_condition (cond, expr);
1841 ++cnt;
1842 }
1843
1844 return expr;
1845 }
1846
1847 /* Tries to simplify EXPR using the evolutions of the loop invariants
1848 in the superloops of LOOP. Returns the simplified expression
1849 (or EXPR unchanged, if no simplification was possible). */
1850
1851 static tree
1852 simplify_using_outer_evolutions (struct loop *loop, tree expr)
1853 {
1854 enum tree_code code = TREE_CODE (expr);
1855 bool changed;
1856 tree e, e0, e1, e2;
1857
1858 if (is_gimple_min_invariant (expr))
1859 return expr;
1860
1861 if (code == TRUTH_OR_EXPR
1862 || code == TRUTH_AND_EXPR
1863 || code == COND_EXPR)
1864 {
1865 changed = false;
1866
1867 e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
1868 if (TREE_OPERAND (expr, 0) != e0)
1869 changed = true;
1870
1871 e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
1872 if (TREE_OPERAND (expr, 1) != e1)
1873 changed = true;
1874
1875 if (code == COND_EXPR)
1876 {
1877 e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
1878 if (TREE_OPERAND (expr, 2) != e2)
1879 changed = true;
1880 }
1881 else
1882 e2 = NULL_TREE;
1883
1884 if (changed)
1885 {
1886 if (code == COND_EXPR)
1887 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1888 else
1889 expr = fold_build2 (code, boolean_type_node, e0, e1);
1890 }
1891
1892 return expr;
1893 }
1894
1895 e = instantiate_parameters (loop, expr);
1896 if (is_gimple_min_invariant (e))
1897 return e;
1898
1899 return expr;
1900 }
1901
1902 /* Returns true if EXIT is the only possible exit from LOOP. */
1903
1904 bool
1905 loop_only_exit_p (const struct loop *loop, const_edge exit)
1906 {
1907 basic_block *body;
1908 gimple_stmt_iterator bsi;
1909 unsigned i;
1910 gimple call;
1911
1912 if (exit != single_exit (loop))
1913 return false;
1914
1915 body = get_loop_body (loop);
1916 for (i = 0; i < loop->num_nodes; i++)
1917 {
1918 for (bsi = gsi_start_bb (body[i]); !gsi_end_p (bsi); gsi_next (&bsi))
1919 {
1920 call = gsi_stmt (bsi);
1921 if (gimple_code (call) != GIMPLE_CALL)
1922 continue;
1923
1924 if (gimple_has_side_effects (call))
1925 {
1926 free (body);
1927 return false;
1928 }
1929 }
1930 }
1931
1932 free (body);
1933 return true;
1934 }
1935
1936 /* Stores description of number of iterations of LOOP derived from
1937 EXIT (an exit edge of the LOOP) in NITER. Returns true if some
1938 useful information could be derived (and fields of NITER has
1939 meaning described in comments at struct tree_niter_desc
1940 declaration), false otherwise. If WARN is true and
1941 -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
1942 potentially unsafe assumptions.
1943 When EVERY_ITERATION is true, only tests that are known to be executed
1944 every iteration are considered (i.e. only test that alone bounds the loop).
1945 */
1946
1947 bool
1948 number_of_iterations_exit (struct loop *loop, edge exit,
1949 struct tree_niter_desc *niter,
1950 bool warn, bool every_iteration)
1951 {
1952 gimple last;
1953 gcond *stmt;
1954 tree type;
1955 tree op0, op1;
1956 enum tree_code code;
1957 affine_iv iv0, iv1;
1958 bool safe;
1959
1960 safe = dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src);
1961
1962 if (every_iteration && !safe)
1963 return false;
1964
1965 niter->assumptions = boolean_false_node;
1966 last = last_stmt (exit->src);
1967 if (!last)
1968 return false;
1969 stmt = dyn_cast <gcond *> (last);
1970 if (!stmt)
1971 return false;
1972
1973 /* We want the condition for staying inside loop. */
1974 code = gimple_cond_code (stmt);
1975 if (exit->flags & EDGE_TRUE_VALUE)
1976 code = invert_tree_comparison (code, false);
1977
1978 switch (code)
1979 {
1980 case GT_EXPR:
1981 case GE_EXPR:
1982 case LT_EXPR:
1983 case LE_EXPR:
1984 case NE_EXPR:
1985 break;
1986
1987 default:
1988 return false;
1989 }
1990
1991 op0 = gimple_cond_lhs (stmt);
1992 op1 = gimple_cond_rhs (stmt);
1993 type = TREE_TYPE (op0);
1994
1995 if (TREE_CODE (type) != INTEGER_TYPE
1996 && !POINTER_TYPE_P (type))
1997 return false;
1998
1999 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, false))
2000 return false;
2001 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, false))
2002 return false;
2003
2004 /* We don't want to see undefined signed overflow warnings while
2005 computing the number of iterations. */
2006 fold_defer_overflow_warnings ();
2007
2008 iv0.base = expand_simple_operations (iv0.base);
2009 iv1.base = expand_simple_operations (iv1.base);
2010 if (!number_of_iterations_cond (loop, type, &iv0, code, &iv1, niter,
2011 loop_only_exit_p (loop, exit), safe))
2012 {
2013 fold_undefer_and_ignore_overflow_warnings ();
2014 return false;
2015 }
2016
2017 if (optimize >= 3)
2018 {
2019 niter->assumptions = simplify_using_outer_evolutions (loop,
2020 niter->assumptions);
2021 niter->may_be_zero = simplify_using_outer_evolutions (loop,
2022 niter->may_be_zero);
2023 niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
2024 }
2025
2026 niter->assumptions
2027 = simplify_using_initial_conditions (loop,
2028 niter->assumptions);
2029 niter->may_be_zero
2030 = simplify_using_initial_conditions (loop,
2031 niter->may_be_zero);
2032
2033 fold_undefer_and_ignore_overflow_warnings ();
2034
2035 /* If NITER has simplified into a constant, update MAX. */
2036 if (TREE_CODE (niter->niter) == INTEGER_CST)
2037 niter->max = wi::to_widest (niter->niter);
2038
2039 if (integer_onep (niter->assumptions))
2040 return true;
2041
2042 /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
2043 But if we can prove that there is overflow or some other source of weird
2044 behavior, ignore the loop even with -funsafe-loop-optimizations. */
2045 if (integer_zerop (niter->assumptions) || !single_exit (loop))
2046 return false;
2047
2048 if (flag_unsafe_loop_optimizations)
2049 niter->assumptions = boolean_true_node;
2050
2051 if (warn)
2052 {
2053 const char *wording;
2054 location_t loc = gimple_location (stmt);
2055
2056 /* We can provide a more specific warning if one of the operator is
2057 constant and the other advances by +1 or -1. */
2058 if (!integer_zerop (iv1.step)
2059 ? (integer_zerop (iv0.step)
2060 && (integer_onep (iv1.step) || integer_all_onesp (iv1.step)))
2061 : (integer_onep (iv0.step) || integer_all_onesp (iv0.step)))
2062 wording =
2063 flag_unsafe_loop_optimizations
2064 ? N_("assuming that the loop is not infinite")
2065 : N_("cannot optimize possibly infinite loops");
2066 else
2067 wording =
2068 flag_unsafe_loop_optimizations
2069 ? N_("assuming that the loop counter does not overflow")
2070 : N_("cannot optimize loop, the loop counter may overflow");
2071
2072 warning_at ((LOCATION_LINE (loc) > 0) ? loc : input_location,
2073 OPT_Wunsafe_loop_optimizations, "%s", gettext (wording));
2074 }
2075
2076 return flag_unsafe_loop_optimizations;
2077 }
2078
2079 /* Try to determine the number of iterations of LOOP. If we succeed,
2080 expression giving number of iterations is returned and *EXIT is
2081 set to the edge from that the information is obtained. Otherwise
2082 chrec_dont_know is returned. */
2083
2084 tree
2085 find_loop_niter (struct loop *loop, edge *exit)
2086 {
2087 unsigned i;
2088 vec<edge> exits = get_loop_exit_edges (loop);
2089 edge ex;
2090 tree niter = NULL_TREE, aniter;
2091 struct tree_niter_desc desc;
2092
2093 *exit = NULL;
2094 FOR_EACH_VEC_ELT (exits, i, ex)
2095 {
2096 if (!number_of_iterations_exit (loop, ex, &desc, false))
2097 continue;
2098
2099 if (integer_nonzerop (desc.may_be_zero))
2100 {
2101 /* We exit in the first iteration through this exit.
2102 We won't find anything better. */
2103 niter = build_int_cst (unsigned_type_node, 0);
2104 *exit = ex;
2105 break;
2106 }
2107
2108 if (!integer_zerop (desc.may_be_zero))
2109 continue;
2110
2111 aniter = desc.niter;
2112
2113 if (!niter)
2114 {
2115 /* Nothing recorded yet. */
2116 niter = aniter;
2117 *exit = ex;
2118 continue;
2119 }
2120
2121 /* Prefer constants, the lower the better. */
2122 if (TREE_CODE (aniter) != INTEGER_CST)
2123 continue;
2124
2125 if (TREE_CODE (niter) != INTEGER_CST)
2126 {
2127 niter = aniter;
2128 *exit = ex;
2129 continue;
2130 }
2131
2132 if (tree_int_cst_lt (aniter, niter))
2133 {
2134 niter = aniter;
2135 *exit = ex;
2136 continue;
2137 }
2138 }
2139 exits.release ();
2140
2141 return niter ? niter : chrec_dont_know;
2142 }
2143
2144 /* Return true if loop is known to have bounded number of iterations. */
2145
2146 bool
2147 finite_loop_p (struct loop *loop)
2148 {
2149 widest_int nit;
2150 int flags;
2151
2152 if (flag_unsafe_loop_optimizations)
2153 return true;
2154 flags = flags_from_decl_or_type (current_function_decl);
2155 if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
2156 {
2157 if (dump_file && (dump_flags & TDF_DETAILS))
2158 fprintf (dump_file, "Found loop %i to be finite: it is within pure or const function.\n",
2159 loop->num);
2160 return true;
2161 }
2162
2163 if (loop->any_upper_bound
2164 || max_loop_iterations (loop, &nit))
2165 {
2166 if (dump_file && (dump_flags & TDF_DETAILS))
2167 fprintf (dump_file, "Found loop %i to be finite: upper bound found.\n",
2168 loop->num);
2169 return true;
2170 }
2171 return false;
2172 }
2173
2174 /*
2175
2176 Analysis of a number of iterations of a loop by a brute-force evaluation.
2177
2178 */
2179
2180 /* Bound on the number of iterations we try to evaluate. */
2181
2182 #define MAX_ITERATIONS_TO_TRACK \
2183 ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
2184
2185 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
2186 result by a chain of operations such that all but exactly one of their
2187 operands are constants. */
2188
2189 static gphi *
2190 chain_of_csts_start (struct loop *loop, tree x)
2191 {
2192 gimple stmt = SSA_NAME_DEF_STMT (x);
2193 tree use;
2194 basic_block bb = gimple_bb (stmt);
2195 enum tree_code code;
2196
2197 if (!bb
2198 || !flow_bb_inside_loop_p (loop, bb))
2199 return NULL;
2200
2201 if (gimple_code (stmt) == GIMPLE_PHI)
2202 {
2203 if (bb == loop->header)
2204 return as_a <gphi *> (stmt);
2205
2206 return NULL;
2207 }
2208
2209 if (gimple_code (stmt) != GIMPLE_ASSIGN
2210 || gimple_assign_rhs_class (stmt) == GIMPLE_TERNARY_RHS)
2211 return NULL;
2212
2213 code = gimple_assign_rhs_code (stmt);
2214 if (gimple_references_memory_p (stmt)
2215 || TREE_CODE_CLASS (code) == tcc_reference
2216 || (code == ADDR_EXPR
2217 && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
2218 return NULL;
2219
2220 use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
2221 if (use == NULL_TREE)
2222 return NULL;
2223
2224 return chain_of_csts_start (loop, use);
2225 }
2226
2227 /* Determines whether the expression X is derived from a result of a phi node
2228 in header of LOOP such that
2229
2230 * the derivation of X consists only from operations with constants
2231 * the initial value of the phi node is constant
2232 * the value of the phi node in the next iteration can be derived from the
2233 value in the current iteration by a chain of operations with constants.
2234
2235 If such phi node exists, it is returned, otherwise NULL is returned. */
2236
2237 static gphi *
2238 get_base_for (struct loop *loop, tree x)
2239 {
2240 gphi *phi;
2241 tree init, next;
2242
2243 if (is_gimple_min_invariant (x))
2244 return NULL;
2245
2246 phi = chain_of_csts_start (loop, x);
2247 if (!phi)
2248 return NULL;
2249
2250 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2251 next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2252
2253 if (TREE_CODE (next) != SSA_NAME)
2254 return NULL;
2255
2256 if (!is_gimple_min_invariant (init))
2257 return NULL;
2258
2259 if (chain_of_csts_start (loop, next) != phi)
2260 return NULL;
2261
2262 return phi;
2263 }
2264
2265 /* Given an expression X, then
2266
2267 * if X is NULL_TREE, we return the constant BASE.
2268 * otherwise X is a SSA name, whose value in the considered loop is derived
2269 by a chain of operations with constant from a result of a phi node in
2270 the header of the loop. Then we return value of X when the value of the
2271 result of this phi node is given by the constant BASE. */
2272
2273 static tree
2274 get_val_for (tree x, tree base)
2275 {
2276 gimple stmt;
2277
2278 gcc_checking_assert (is_gimple_min_invariant (base));
2279
2280 if (!x)
2281 return base;
2282
2283 stmt = SSA_NAME_DEF_STMT (x);
2284 if (gimple_code (stmt) == GIMPLE_PHI)
2285 return base;
2286
2287 gcc_checking_assert (is_gimple_assign (stmt));
2288
2289 /* STMT must be either an assignment of a single SSA name or an
2290 expression involving an SSA name and a constant. Try to fold that
2291 expression using the value for the SSA name. */
2292 if (gimple_assign_ssa_name_copy_p (stmt))
2293 return get_val_for (gimple_assign_rhs1 (stmt), base);
2294 else if (gimple_assign_rhs_class (stmt) == GIMPLE_UNARY_RHS
2295 && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
2296 {
2297 return fold_build1 (gimple_assign_rhs_code (stmt),
2298 gimple_expr_type (stmt),
2299 get_val_for (gimple_assign_rhs1 (stmt), base));
2300 }
2301 else if (gimple_assign_rhs_class (stmt) == GIMPLE_BINARY_RHS)
2302 {
2303 tree rhs1 = gimple_assign_rhs1 (stmt);
2304 tree rhs2 = gimple_assign_rhs2 (stmt);
2305 if (TREE_CODE (rhs1) == SSA_NAME)
2306 rhs1 = get_val_for (rhs1, base);
2307 else if (TREE_CODE (rhs2) == SSA_NAME)
2308 rhs2 = get_val_for (rhs2, base);
2309 else
2310 gcc_unreachable ();
2311 return fold_build2 (gimple_assign_rhs_code (stmt),
2312 gimple_expr_type (stmt), rhs1, rhs2);
2313 }
2314 else
2315 gcc_unreachable ();
2316 }
2317
2318
2319 /* Tries to count the number of iterations of LOOP till it exits by EXIT
2320 by brute force -- i.e. by determining the value of the operands of the
2321 condition at EXIT in first few iterations of the loop (assuming that
2322 these values are constant) and determining the first one in that the
2323 condition is not satisfied. Returns the constant giving the number
2324 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
2325
2326 tree
2327 loop_niter_by_eval (struct loop *loop, edge exit)
2328 {
2329 tree acnd;
2330 tree op[2], val[2], next[2], aval[2];
2331 gphi *phi;
2332 gimple cond;
2333 unsigned i, j;
2334 enum tree_code cmp;
2335
2336 cond = last_stmt (exit->src);
2337 if (!cond || gimple_code (cond) != GIMPLE_COND)
2338 return chrec_dont_know;
2339
2340 cmp = gimple_cond_code (cond);
2341 if (exit->flags & EDGE_TRUE_VALUE)
2342 cmp = invert_tree_comparison (cmp, false);
2343
2344 switch (cmp)
2345 {
2346 case EQ_EXPR:
2347 case NE_EXPR:
2348 case GT_EXPR:
2349 case GE_EXPR:
2350 case LT_EXPR:
2351 case LE_EXPR:
2352 op[0] = gimple_cond_lhs (cond);
2353 op[1] = gimple_cond_rhs (cond);
2354 break;
2355
2356 default:
2357 return chrec_dont_know;
2358 }
2359
2360 for (j = 0; j < 2; j++)
2361 {
2362 if (is_gimple_min_invariant (op[j]))
2363 {
2364 val[j] = op[j];
2365 next[j] = NULL_TREE;
2366 op[j] = NULL_TREE;
2367 }
2368 else
2369 {
2370 phi = get_base_for (loop, op[j]);
2371 if (!phi)
2372 return chrec_dont_know;
2373 val[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2374 next[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2375 }
2376 }
2377
2378 /* Don't issue signed overflow warnings. */
2379 fold_defer_overflow_warnings ();
2380
2381 for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
2382 {
2383 for (j = 0; j < 2; j++)
2384 aval[j] = get_val_for (op[j], val[j]);
2385
2386 acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
2387 if (acnd && integer_zerop (acnd))
2388 {
2389 fold_undefer_and_ignore_overflow_warnings ();
2390 if (dump_file && (dump_flags & TDF_DETAILS))
2391 fprintf (dump_file,
2392 "Proved that loop %d iterates %d times using brute force.\n",
2393 loop->num, i);
2394 return build_int_cst (unsigned_type_node, i);
2395 }
2396
2397 for (j = 0; j < 2; j++)
2398 {
2399 val[j] = get_val_for (next[j], val[j]);
2400 if (!is_gimple_min_invariant (val[j]))
2401 {
2402 fold_undefer_and_ignore_overflow_warnings ();
2403 return chrec_dont_know;
2404 }
2405 }
2406 }
2407
2408 fold_undefer_and_ignore_overflow_warnings ();
2409
2410 return chrec_dont_know;
2411 }
2412
2413 /* Finds the exit of the LOOP by that the loop exits after a constant
2414 number of iterations and stores the exit edge to *EXIT. The constant
2415 giving the number of iterations of LOOP is returned. The number of
2416 iterations is determined using loop_niter_by_eval (i.e. by brute force
2417 evaluation). If we are unable to find the exit for that loop_niter_by_eval
2418 determines the number of iterations, chrec_dont_know is returned. */
2419
2420 tree
2421 find_loop_niter_by_eval (struct loop *loop, edge *exit)
2422 {
2423 unsigned i;
2424 vec<edge> exits = get_loop_exit_edges (loop);
2425 edge ex;
2426 tree niter = NULL_TREE, aniter;
2427
2428 *exit = NULL;
2429
2430 /* Loops with multiple exits are expensive to handle and less important. */
2431 if (!flag_expensive_optimizations
2432 && exits.length () > 1)
2433 {
2434 exits.release ();
2435 return chrec_dont_know;
2436 }
2437
2438 FOR_EACH_VEC_ELT (exits, i, ex)
2439 {
2440 if (!just_once_each_iteration_p (loop, ex->src))
2441 continue;
2442
2443 aniter = loop_niter_by_eval (loop, ex);
2444 if (chrec_contains_undetermined (aniter))
2445 continue;
2446
2447 if (niter
2448 && !tree_int_cst_lt (aniter, niter))
2449 continue;
2450
2451 niter = aniter;
2452 *exit = ex;
2453 }
2454 exits.release ();
2455
2456 return niter ? niter : chrec_dont_know;
2457 }
2458
2459 /*
2460
2461 Analysis of upper bounds on number of iterations of a loop.
2462
2463 */
2464
2465 static widest_int derive_constant_upper_bound_ops (tree, tree,
2466 enum tree_code, tree);
2467
2468 /* Returns a constant upper bound on the value of the right-hand side of
2469 an assignment statement STMT. */
2470
2471 static widest_int
2472 derive_constant_upper_bound_assign (gimple stmt)
2473 {
2474 enum tree_code code = gimple_assign_rhs_code (stmt);
2475 tree op0 = gimple_assign_rhs1 (stmt);
2476 tree op1 = gimple_assign_rhs2 (stmt);
2477
2478 return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt)),
2479 op0, code, op1);
2480 }
2481
2482 /* Returns a constant upper bound on the value of expression VAL. VAL
2483 is considered to be unsigned. If its type is signed, its value must
2484 be nonnegative. */
2485
2486 static widest_int
2487 derive_constant_upper_bound (tree val)
2488 {
2489 enum tree_code code;
2490 tree op0, op1;
2491
2492 extract_ops_from_tree (val, &code, &op0, &op1);
2493 return derive_constant_upper_bound_ops (TREE_TYPE (val), op0, code, op1);
2494 }
2495
2496 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
2497 whose type is TYPE. The expression is considered to be unsigned. If
2498 its type is signed, its value must be nonnegative. */
2499
2500 static widest_int
2501 derive_constant_upper_bound_ops (tree type, tree op0,
2502 enum tree_code code, tree op1)
2503 {
2504 tree subtype, maxt;
2505 widest_int bnd, max, mmax, cst;
2506 gimple stmt;
2507
2508 if (INTEGRAL_TYPE_P (type))
2509 maxt = TYPE_MAX_VALUE (type);
2510 else
2511 maxt = upper_bound_in_type (type, type);
2512
2513 max = wi::to_widest (maxt);
2514
2515 switch (code)
2516 {
2517 case INTEGER_CST:
2518 return wi::to_widest (op0);
2519
2520 CASE_CONVERT:
2521 subtype = TREE_TYPE (op0);
2522 if (!TYPE_UNSIGNED (subtype)
2523 /* If TYPE is also signed, the fact that VAL is nonnegative implies
2524 that OP0 is nonnegative. */
2525 && TYPE_UNSIGNED (type)
2526 && !tree_expr_nonnegative_p (op0))
2527 {
2528 /* If we cannot prove that the casted expression is nonnegative,
2529 we cannot establish more useful upper bound than the precision
2530 of the type gives us. */
2531 return max;
2532 }
2533
2534 /* We now know that op0 is an nonnegative value. Try deriving an upper
2535 bound for it. */
2536 bnd = derive_constant_upper_bound (op0);
2537
2538 /* If the bound does not fit in TYPE, max. value of TYPE could be
2539 attained. */
2540 if (wi::ltu_p (max, bnd))
2541 return max;
2542
2543 return bnd;
2544
2545 case PLUS_EXPR:
2546 case POINTER_PLUS_EXPR:
2547 case MINUS_EXPR:
2548 if (TREE_CODE (op1) != INTEGER_CST
2549 || !tree_expr_nonnegative_p (op0))
2550 return max;
2551
2552 /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
2553 choose the most logical way how to treat this constant regardless
2554 of the signedness of the type. */
2555 cst = wi::sext (wi::to_widest (op1), TYPE_PRECISION (type));
2556 if (code != MINUS_EXPR)
2557 cst = -cst;
2558
2559 bnd = derive_constant_upper_bound (op0);
2560
2561 if (wi::neg_p (cst))
2562 {
2563 cst = -cst;
2564 /* Avoid CST == 0x80000... */
2565 if (wi::neg_p (cst))
2566 return max;;
2567
2568 /* OP0 + CST. We need to check that
2569 BND <= MAX (type) - CST. */
2570
2571 mmax -= cst;
2572 if (wi::ltu_p (bnd, max))
2573 return max;
2574
2575 return bnd + cst;
2576 }
2577 else
2578 {
2579 /* OP0 - CST, where CST >= 0.
2580
2581 If TYPE is signed, we have already verified that OP0 >= 0, and we
2582 know that the result is nonnegative. This implies that
2583 VAL <= BND - CST.
2584
2585 If TYPE is unsigned, we must additionally know that OP0 >= CST,
2586 otherwise the operation underflows.
2587 */
2588
2589 /* This should only happen if the type is unsigned; however, for
2590 buggy programs that use overflowing signed arithmetics even with
2591 -fno-wrapv, this condition may also be true for signed values. */
2592 if (wi::ltu_p (bnd, cst))
2593 return max;
2594
2595 if (TYPE_UNSIGNED (type))
2596 {
2597 tree tem = fold_binary (GE_EXPR, boolean_type_node, op0,
2598 wide_int_to_tree (type, cst));
2599 if (!tem || integer_nonzerop (tem))
2600 return max;
2601 }
2602
2603 bnd -= cst;
2604 }
2605
2606 return bnd;
2607
2608 case FLOOR_DIV_EXPR:
2609 case EXACT_DIV_EXPR:
2610 if (TREE_CODE (op1) != INTEGER_CST
2611 || tree_int_cst_sign_bit (op1))
2612 return max;
2613
2614 bnd = derive_constant_upper_bound (op0);
2615 return wi::udiv_floor (bnd, wi::to_widest (op1));
2616
2617 case BIT_AND_EXPR:
2618 if (TREE_CODE (op1) != INTEGER_CST
2619 || tree_int_cst_sign_bit (op1))
2620 return max;
2621 return wi::to_widest (op1);
2622
2623 case SSA_NAME:
2624 stmt = SSA_NAME_DEF_STMT (op0);
2625 if (gimple_code (stmt) != GIMPLE_ASSIGN
2626 || gimple_assign_lhs (stmt) != op0)
2627 return max;
2628 return derive_constant_upper_bound_assign (stmt);
2629
2630 default:
2631 return max;
2632 }
2633 }
2634
2635 /* Emit a -Waggressive-loop-optimizations warning if needed. */
2636
2637 static void
2638 do_warn_aggressive_loop_optimizations (struct loop *loop,
2639 widest_int i_bound, gimple stmt)
2640 {
2641 /* Don't warn if the loop doesn't have known constant bound. */
2642 if (!loop->nb_iterations
2643 || TREE_CODE (loop->nb_iterations) != INTEGER_CST
2644 || !warn_aggressive_loop_optimizations
2645 /* To avoid warning multiple times for the same loop,
2646 only start warning when we preserve loops. */
2647 || (cfun->curr_properties & PROP_loops) == 0
2648 /* Only warn once per loop. */
2649 || loop->warned_aggressive_loop_optimizations
2650 /* Only warn if undefined behavior gives us lower estimate than the
2651 known constant bound. */
2652 || wi::cmpu (i_bound, wi::to_widest (loop->nb_iterations)) >= 0
2653 /* And undefined behavior happens unconditionally. */
2654 || !dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (stmt)))
2655 return;
2656
2657 edge e = single_exit (loop);
2658 if (e == NULL)
2659 return;
2660
2661 gimple estmt = last_stmt (e->src);
2662 if (warning_at (gimple_location (stmt), OPT_Waggressive_loop_optimizations,
2663 "iteration %E invokes undefined behavior",
2664 wide_int_to_tree (TREE_TYPE (loop->nb_iterations),
2665 i_bound)))
2666 inform (gimple_location (estmt), "containing loop");
2667 loop->warned_aggressive_loop_optimizations = true;
2668 }
2669
2670 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
2671 is true if the loop is exited immediately after STMT, and this exit
2672 is taken at last when the STMT is executed BOUND + 1 times.
2673 REALISTIC is true if BOUND is expected to be close to the real number
2674 of iterations. UPPER is true if we are sure the loop iterates at most
2675 BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
2676
2677 static void
2678 record_estimate (struct loop *loop, tree bound, const widest_int &i_bound,
2679 gimple at_stmt, bool is_exit, bool realistic, bool upper)
2680 {
2681 widest_int delta;
2682
2683 if (dump_file && (dump_flags & TDF_DETAILS))
2684 {
2685 fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
2686 print_gimple_stmt (dump_file, at_stmt, 0, TDF_SLIM);
2687 fprintf (dump_file, " is %sexecuted at most ",
2688 upper ? "" : "probably ");
2689 print_generic_expr (dump_file, bound, TDF_SLIM);
2690 fprintf (dump_file, " (bounded by ");
2691 print_decu (i_bound, dump_file);
2692 fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
2693 }
2694
2695 /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
2696 real number of iterations. */
2697 if (TREE_CODE (bound) != INTEGER_CST)
2698 realistic = false;
2699 else
2700 gcc_checking_assert (i_bound == wi::to_widest (bound));
2701 if (!upper && !realistic)
2702 return;
2703
2704 /* If we have a guaranteed upper bound, record it in the appropriate
2705 list, unless this is an !is_exit bound (i.e. undefined behavior in
2706 at_stmt) in a loop with known constant number of iterations. */
2707 if (upper
2708 && (is_exit
2709 || loop->nb_iterations == NULL_TREE
2710 || TREE_CODE (loop->nb_iterations) != INTEGER_CST))
2711 {
2712 struct nb_iter_bound *elt = ggc_alloc<nb_iter_bound> ();
2713
2714 elt->bound = i_bound;
2715 elt->stmt = at_stmt;
2716 elt->is_exit = is_exit;
2717 elt->next = loop->bounds;
2718 loop->bounds = elt;
2719 }
2720
2721 /* If statement is executed on every path to the loop latch, we can directly
2722 infer the upper bound on the # of iterations of the loop. */
2723 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (at_stmt)))
2724 return;
2725
2726 /* Update the number of iteration estimates according to the bound.
2727 If at_stmt is an exit then the loop latch is executed at most BOUND times,
2728 otherwise it can be executed BOUND + 1 times. We will lower the estimate
2729 later if such statement must be executed on last iteration */
2730 if (is_exit)
2731 delta = 0;
2732 else
2733 delta = 1;
2734 widest_int new_i_bound = i_bound + delta;
2735
2736 /* If an overflow occurred, ignore the result. */
2737 if (wi::ltu_p (new_i_bound, delta))
2738 return;
2739
2740 if (upper && !is_exit)
2741 do_warn_aggressive_loop_optimizations (loop, new_i_bound, at_stmt);
2742 record_niter_bound (loop, new_i_bound, realistic, upper);
2743 }
2744
2745 /* Record the estimate on number of iterations of LOOP based on the fact that
2746 the induction variable BASE + STEP * i evaluated in STMT does not wrap and
2747 its values belong to the range <LOW, HIGH>. REALISTIC is true if the
2748 estimated number of iterations is expected to be close to the real one.
2749 UPPER is true if we are sure the induction variable does not wrap. */
2750
2751 static void
2752 record_nonwrapping_iv (struct loop *loop, tree base, tree step, gimple stmt,
2753 tree low, tree high, bool realistic, bool upper)
2754 {
2755 tree niter_bound, extreme, delta;
2756 tree type = TREE_TYPE (base), unsigned_type;
2757
2758 if (TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
2759 return;
2760
2761 if (dump_file && (dump_flags & TDF_DETAILS))
2762 {
2763 fprintf (dump_file, "Induction variable (");
2764 print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
2765 fprintf (dump_file, ") ");
2766 print_generic_expr (dump_file, base, TDF_SLIM);
2767 fprintf (dump_file, " + ");
2768 print_generic_expr (dump_file, step, TDF_SLIM);
2769 fprintf (dump_file, " * iteration does not wrap in statement ");
2770 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2771 fprintf (dump_file, " in loop %d.\n", loop->num);
2772 }
2773
2774 unsigned_type = unsigned_type_for (type);
2775 base = fold_convert (unsigned_type, base);
2776 step = fold_convert (unsigned_type, step);
2777
2778 if (tree_int_cst_sign_bit (step))
2779 {
2780 extreme = fold_convert (unsigned_type, low);
2781 if (TREE_CODE (base) != INTEGER_CST)
2782 base = fold_convert (unsigned_type, high);
2783 delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
2784 step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
2785 }
2786 else
2787 {
2788 extreme = fold_convert (unsigned_type, high);
2789 if (TREE_CODE (base) != INTEGER_CST)
2790 base = fold_convert (unsigned_type, low);
2791 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
2792 }
2793
2794 /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
2795 would get out of the range. */
2796 niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
2797 widest_int max = derive_constant_upper_bound (niter_bound);
2798 record_estimate (loop, niter_bound, max, stmt, false, realistic, upper);
2799 }
2800
2801 /* Determine information about number of iterations a LOOP from the index
2802 IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
2803 guaranteed to be executed in every iteration of LOOP. Callback for
2804 for_each_index. */
2805
2806 struct ilb_data
2807 {
2808 struct loop *loop;
2809 gimple stmt;
2810 };
2811
2812 static bool
2813 idx_infer_loop_bounds (tree base, tree *idx, void *dta)
2814 {
2815 struct ilb_data *data = (struct ilb_data *) dta;
2816 tree ev, init, step;
2817 tree low, high, type, next;
2818 bool sign, upper = true, at_end = false;
2819 struct loop *loop = data->loop;
2820 bool reliable = true;
2821
2822 if (TREE_CODE (base) != ARRAY_REF)
2823 return true;
2824
2825 /* For arrays at the end of the structure, we are not guaranteed that they
2826 do not really extend over their declared size. However, for arrays of
2827 size greater than one, this is unlikely to be intended. */
2828 if (array_at_struct_end_p (base))
2829 {
2830 at_end = true;
2831 upper = false;
2832 }
2833
2834 struct loop *dloop = loop_containing_stmt (data->stmt);
2835 if (!dloop)
2836 return true;
2837
2838 ev = analyze_scalar_evolution (dloop, *idx);
2839 ev = instantiate_parameters (loop, ev);
2840 init = initial_condition (ev);
2841 step = evolution_part_in_loop_num (ev, loop->num);
2842
2843 if (!init
2844 || !step
2845 || TREE_CODE (step) != INTEGER_CST
2846 || integer_zerop (step)
2847 || tree_contains_chrecs (init, NULL)
2848 || chrec_contains_symbols_defined_in_loop (init, loop->num))
2849 return true;
2850
2851 low = array_ref_low_bound (base);
2852 high = array_ref_up_bound (base);
2853
2854 /* The case of nonconstant bounds could be handled, but it would be
2855 complicated. */
2856 if (TREE_CODE (low) != INTEGER_CST
2857 || !high
2858 || TREE_CODE (high) != INTEGER_CST)
2859 return true;
2860 sign = tree_int_cst_sign_bit (step);
2861 type = TREE_TYPE (step);
2862
2863 /* The array of length 1 at the end of a structure most likely extends
2864 beyond its bounds. */
2865 if (at_end
2866 && operand_equal_p (low, high, 0))
2867 return true;
2868
2869 /* In case the relevant bound of the array does not fit in type, or
2870 it does, but bound + step (in type) still belongs into the range of the
2871 array, the index may wrap and still stay within the range of the array
2872 (consider e.g. if the array is indexed by the full range of
2873 unsigned char).
2874
2875 To make things simpler, we require both bounds to fit into type, although
2876 there are cases where this would not be strictly necessary. */
2877 if (!int_fits_type_p (high, type)
2878 || !int_fits_type_p (low, type))
2879 return true;
2880 low = fold_convert (type, low);
2881 high = fold_convert (type, high);
2882
2883 if (sign)
2884 next = fold_binary (PLUS_EXPR, type, low, step);
2885 else
2886 next = fold_binary (PLUS_EXPR, type, high, step);
2887
2888 if (tree_int_cst_compare (low, next) <= 0
2889 && tree_int_cst_compare (next, high) <= 0)
2890 return true;
2891
2892 /* If access is not executed on every iteration, we must ensure that overlow may
2893 not make the access valid later. */
2894 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (data->stmt))
2895 && scev_probably_wraps_p (initial_condition_in_loop_num (ev, loop->num),
2896 step, data->stmt, loop, true))
2897 reliable = false;
2898
2899 record_nonwrapping_iv (loop, init, step, data->stmt, low, high, reliable, upper);
2900 return true;
2901 }
2902
2903 /* Determine information about number of iterations a LOOP from the bounds
2904 of arrays in the data reference REF accessed in STMT. RELIABLE is true if
2905 STMT is guaranteed to be executed in every iteration of LOOP.*/
2906
2907 static void
2908 infer_loop_bounds_from_ref (struct loop *loop, gimple stmt, tree ref)
2909 {
2910 struct ilb_data data;
2911
2912 data.loop = loop;
2913 data.stmt = stmt;
2914 for_each_index (&ref, idx_infer_loop_bounds, &data);
2915 }
2916
2917 /* Determine information about number of iterations of a LOOP from the way
2918 arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
2919 executed in every iteration of LOOP. */
2920
2921 static void
2922 infer_loop_bounds_from_array (struct loop *loop, gimple stmt)
2923 {
2924 if (is_gimple_assign (stmt))
2925 {
2926 tree op0 = gimple_assign_lhs (stmt);
2927 tree op1 = gimple_assign_rhs1 (stmt);
2928
2929 /* For each memory access, analyze its access function
2930 and record a bound on the loop iteration domain. */
2931 if (REFERENCE_CLASS_P (op0))
2932 infer_loop_bounds_from_ref (loop, stmt, op0);
2933
2934 if (REFERENCE_CLASS_P (op1))
2935 infer_loop_bounds_from_ref (loop, stmt, op1);
2936 }
2937 else if (is_gimple_call (stmt))
2938 {
2939 tree arg, lhs;
2940 unsigned i, n = gimple_call_num_args (stmt);
2941
2942 lhs = gimple_call_lhs (stmt);
2943 if (lhs && REFERENCE_CLASS_P (lhs))
2944 infer_loop_bounds_from_ref (loop, stmt, lhs);
2945
2946 for (i = 0; i < n; i++)
2947 {
2948 arg = gimple_call_arg (stmt, i);
2949 if (REFERENCE_CLASS_P (arg))
2950 infer_loop_bounds_from_ref (loop, stmt, arg);
2951 }
2952 }
2953 }
2954
2955 /* Determine information about number of iterations of a LOOP from the fact
2956 that pointer arithmetics in STMT does not overflow. */
2957
2958 static void
2959 infer_loop_bounds_from_pointer_arith (struct loop *loop, gimple stmt)
2960 {
2961 tree def, base, step, scev, type, low, high;
2962 tree var, ptr;
2963
2964 if (!is_gimple_assign (stmt)
2965 || gimple_assign_rhs_code (stmt) != POINTER_PLUS_EXPR)
2966 return;
2967
2968 def = gimple_assign_lhs (stmt);
2969 if (TREE_CODE (def) != SSA_NAME)
2970 return;
2971
2972 type = TREE_TYPE (def);
2973 if (!nowrap_type_p (type))
2974 return;
2975
2976 ptr = gimple_assign_rhs1 (stmt);
2977 if (!expr_invariant_in_loop_p (loop, ptr))
2978 return;
2979
2980 var = gimple_assign_rhs2 (stmt);
2981 if (TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (var)))
2982 return;
2983
2984 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
2985 if (chrec_contains_undetermined (scev))
2986 return;
2987
2988 base = initial_condition_in_loop_num (scev, loop->num);
2989 step = evolution_part_in_loop_num (scev, loop->num);
2990
2991 if (!base || !step
2992 || TREE_CODE (step) != INTEGER_CST
2993 || tree_contains_chrecs (base, NULL)
2994 || chrec_contains_symbols_defined_in_loop (base, loop->num))
2995 return;
2996
2997 low = lower_bound_in_type (type, type);
2998 high = upper_bound_in_type (type, type);
2999
3000 /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
3001 produce a NULL pointer. The contrary would mean NULL points to an object,
3002 while NULL is supposed to compare unequal with the address of all objects.
3003 Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
3004 NULL pointer since that would mean wrapping, which we assume here not to
3005 happen. So, we can exclude NULL from the valid range of pointer
3006 arithmetic. */
3007 if (flag_delete_null_pointer_checks && int_cst_value (low) == 0)
3008 low = build_int_cstu (TREE_TYPE (low), TYPE_ALIGN_UNIT (TREE_TYPE (type)));
3009
3010 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
3011 }
3012
3013 /* Determine information about number of iterations of a LOOP from the fact
3014 that signed arithmetics in STMT does not overflow. */
3015
3016 static void
3017 infer_loop_bounds_from_signedness (struct loop *loop, gimple stmt)
3018 {
3019 tree def, base, step, scev, type, low, high;
3020
3021 if (gimple_code (stmt) != GIMPLE_ASSIGN)
3022 return;
3023
3024 def = gimple_assign_lhs (stmt);
3025
3026 if (TREE_CODE (def) != SSA_NAME)
3027 return;
3028
3029 type = TREE_TYPE (def);
3030 if (!INTEGRAL_TYPE_P (type)
3031 || !TYPE_OVERFLOW_UNDEFINED (type))
3032 return;
3033
3034 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
3035 if (chrec_contains_undetermined (scev))
3036 return;
3037
3038 base = initial_condition_in_loop_num (scev, loop->num);
3039 step = evolution_part_in_loop_num (scev, loop->num);
3040
3041 if (!base || !step
3042 || TREE_CODE (step) != INTEGER_CST
3043 || tree_contains_chrecs (base, NULL)
3044 || chrec_contains_symbols_defined_in_loop (base, loop->num))
3045 return;
3046
3047 low = lower_bound_in_type (type, type);
3048 high = upper_bound_in_type (type, type);
3049
3050 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
3051 }
3052
3053 /* The following analyzers are extracting informations on the bounds
3054 of LOOP from the following undefined behaviors:
3055
3056 - data references should not access elements over the statically
3057 allocated size,
3058
3059 - signed variables should not overflow when flag_wrapv is not set.
3060 */
3061
3062 static void
3063 infer_loop_bounds_from_undefined (struct loop *loop)
3064 {
3065 unsigned i;
3066 basic_block *bbs;
3067 gimple_stmt_iterator bsi;
3068 basic_block bb;
3069 bool reliable;
3070
3071 bbs = get_loop_body (loop);
3072
3073 for (i = 0; i < loop->num_nodes; i++)
3074 {
3075 bb = bbs[i];
3076
3077 /* If BB is not executed in each iteration of the loop, we cannot
3078 use the operations in it to infer reliable upper bound on the
3079 # of iterations of the loop. However, we can use it as a guess.
3080 Reliable guesses come only from array bounds. */
3081 reliable = dominated_by_p (CDI_DOMINATORS, loop->latch, bb);
3082
3083 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
3084 {
3085 gimple stmt = gsi_stmt (bsi);
3086
3087 infer_loop_bounds_from_array (loop, stmt);
3088
3089 if (reliable)
3090 {
3091 infer_loop_bounds_from_signedness (loop, stmt);
3092 infer_loop_bounds_from_pointer_arith (loop, stmt);
3093 }
3094 }
3095
3096 }
3097
3098 free (bbs);
3099 }
3100
3101 /* Compare wide ints, callback for qsort. */
3102
3103 static int
3104 wide_int_cmp (const void *p1, const void *p2)
3105 {
3106 const widest_int *d1 = (const widest_int *) p1;
3107 const widest_int *d2 = (const widest_int *) p2;
3108 return wi::cmpu (*d1, *d2);
3109 }
3110
3111 /* Return index of BOUND in BOUNDS array sorted in increasing order.
3112 Lookup by binary search. */
3113
3114 static int
3115 bound_index (vec<widest_int> bounds, const widest_int &bound)
3116 {
3117 unsigned int end = bounds.length ();
3118 unsigned int begin = 0;
3119
3120 /* Find a matching index by means of a binary search. */
3121 while (begin != end)
3122 {
3123 unsigned int middle = (begin + end) / 2;
3124 widest_int index = bounds[middle];
3125
3126 if (index == bound)
3127 return middle;
3128 else if (wi::ltu_p (index, bound))
3129 begin = middle + 1;
3130 else
3131 end = middle;
3132 }
3133 gcc_unreachable ();
3134 }
3135
3136 /* We recorded loop bounds only for statements dominating loop latch (and thus
3137 executed each loop iteration). If there are any bounds on statements not
3138 dominating the loop latch we can improve the estimate by walking the loop
3139 body and seeing if every path from loop header to loop latch contains
3140 some bounded statement. */
3141
3142 static void
3143 discover_iteration_bound_by_body_walk (struct loop *loop)
3144 {
3145 struct nb_iter_bound *elt;
3146 vec<widest_int> bounds = vNULL;
3147 vec<vec<basic_block> > queues = vNULL;
3148 vec<basic_block> queue = vNULL;
3149 ptrdiff_t queue_index;
3150 ptrdiff_t latch_index = 0;
3151
3152 /* Discover what bounds may interest us. */
3153 for (elt = loop->bounds; elt; elt = elt->next)
3154 {
3155 widest_int bound = elt->bound;
3156
3157 /* Exit terminates loop at given iteration, while non-exits produce undefined
3158 effect on the next iteration. */
3159 if (!elt->is_exit)
3160 {
3161 bound += 1;
3162 /* If an overflow occurred, ignore the result. */
3163 if (bound == 0)
3164 continue;
3165 }
3166
3167 if (!loop->any_upper_bound
3168 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3169 bounds.safe_push (bound);
3170 }
3171
3172 /* Exit early if there is nothing to do. */
3173 if (!bounds.exists ())
3174 return;
3175
3176 if (dump_file && (dump_flags & TDF_DETAILS))
3177 fprintf (dump_file, " Trying to walk loop body to reduce the bound.\n");
3178
3179 /* Sort the bounds in decreasing order. */
3180 bounds.qsort (wide_int_cmp);
3181
3182 /* For every basic block record the lowest bound that is guaranteed to
3183 terminate the loop. */
3184
3185 hash_map<basic_block, ptrdiff_t> bb_bounds;
3186 for (elt = loop->bounds; elt; elt = elt->next)
3187 {
3188 widest_int bound = elt->bound;
3189 if (!elt->is_exit)
3190 {
3191 bound += 1;
3192 /* If an overflow occurred, ignore the result. */
3193 if (bound == 0)
3194 continue;
3195 }
3196
3197 if (!loop->any_upper_bound
3198 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3199 {
3200 ptrdiff_t index = bound_index (bounds, bound);
3201 ptrdiff_t *entry = bb_bounds.get (gimple_bb (elt->stmt));
3202 if (!entry)
3203 bb_bounds.put (gimple_bb (elt->stmt), index);
3204 else if ((ptrdiff_t)*entry > index)
3205 *entry = index;
3206 }
3207 }
3208
3209 hash_map<basic_block, ptrdiff_t> block_priority;
3210
3211 /* Perform shortest path discovery loop->header ... loop->latch.
3212
3213 The "distance" is given by the smallest loop bound of basic block
3214 present in the path and we look for path with largest smallest bound
3215 on it.
3216
3217 To avoid the need for fibonacci heap on double ints we simply compress
3218 double ints into indexes to BOUNDS array and then represent the queue
3219 as arrays of queues for every index.
3220 Index of BOUNDS.length() means that the execution of given BB has
3221 no bounds determined.
3222
3223 VISITED is a pointer map translating basic block into smallest index
3224 it was inserted into the priority queue with. */
3225 latch_index = -1;
3226
3227 /* Start walk in loop header with index set to infinite bound. */
3228 queue_index = bounds.length ();
3229 queues.safe_grow_cleared (queue_index + 1);
3230 queue.safe_push (loop->header);
3231 queues[queue_index] = queue;
3232 block_priority.put (loop->header, queue_index);
3233
3234 for (; queue_index >= 0; queue_index--)
3235 {
3236 if (latch_index < queue_index)
3237 {
3238 while (queues[queue_index].length ())
3239 {
3240 basic_block bb;
3241 ptrdiff_t bound_index = queue_index;
3242 edge e;
3243 edge_iterator ei;
3244
3245 queue = queues[queue_index];
3246 bb = queue.pop ();
3247
3248 /* OK, we later inserted the BB with lower priority, skip it. */
3249 if (*block_priority.get (bb) > queue_index)
3250 continue;
3251
3252 /* See if we can improve the bound. */
3253 ptrdiff_t *entry = bb_bounds.get (bb);
3254 if (entry && *entry < bound_index)
3255 bound_index = *entry;
3256
3257 /* Insert succesors into the queue, watch for latch edge
3258 and record greatest index we saw. */
3259 FOR_EACH_EDGE (e, ei, bb->succs)
3260 {
3261 bool insert = false;
3262
3263 if (loop_exit_edge_p (loop, e))
3264 continue;
3265
3266 if (e == loop_latch_edge (loop)
3267 && latch_index < bound_index)
3268 latch_index = bound_index;
3269 else if (!(entry = block_priority.get (e->dest)))
3270 {
3271 insert = true;
3272 block_priority.put (e->dest, bound_index);
3273 }
3274 else if (*entry < bound_index)
3275 {
3276 insert = true;
3277 *entry = bound_index;
3278 }
3279
3280 if (insert)
3281 queues[bound_index].safe_push (e->dest);
3282 }
3283 }
3284 }
3285 queues[queue_index].release ();
3286 }
3287
3288 gcc_assert (latch_index >= 0);
3289 if ((unsigned)latch_index < bounds.length ())
3290 {
3291 if (dump_file && (dump_flags & TDF_DETAILS))
3292 {
3293 fprintf (dump_file, "Found better loop bound ");
3294 print_decu (bounds[latch_index], dump_file);
3295 fprintf (dump_file, "\n");
3296 }
3297 record_niter_bound (loop, bounds[latch_index], false, true);
3298 }
3299
3300 queues.release ();
3301 bounds.release ();
3302 }
3303
3304 /* See if every path cross the loop goes through a statement that is known
3305 to not execute at the last iteration. In that case we can decrese iteration
3306 count by 1. */
3307
3308 static void
3309 maybe_lower_iteration_bound (struct loop *loop)
3310 {
3311 hash_set<gimple> *not_executed_last_iteration = NULL;
3312 struct nb_iter_bound *elt;
3313 bool found_exit = false;
3314 vec<basic_block> queue = vNULL;
3315 vec<gimple> problem_stmts = vNULL;
3316 bitmap visited;
3317
3318 /* Collect all statements with interesting (i.e. lower than
3319 nb_iterations_upper_bound) bound on them.
3320
3321 TODO: Due to the way record_estimate choose estimates to store, the bounds
3322 will be always nb_iterations_upper_bound-1. We can change this to record
3323 also statements not dominating the loop latch and update the walk bellow
3324 to the shortest path algorthm. */
3325 for (elt = loop->bounds; elt; elt = elt->next)
3326 {
3327 if (!elt->is_exit
3328 && wi::ltu_p (elt->bound, loop->nb_iterations_upper_bound))
3329 {
3330 if (!not_executed_last_iteration)
3331 not_executed_last_iteration = new hash_set<gimple>;
3332 not_executed_last_iteration->add (elt->stmt);
3333 }
3334 }
3335 if (!not_executed_last_iteration)
3336 return;
3337
3338 /* Start DFS walk in the loop header and see if we can reach the
3339 loop latch or any of the exits (including statements with side
3340 effects that may terminate the loop otherwise) without visiting
3341 any of the statements known to have undefined effect on the last
3342 iteration. */
3343 queue.safe_push (loop->header);
3344 visited = BITMAP_ALLOC (NULL);
3345 bitmap_set_bit (visited, loop->header->index);
3346 found_exit = false;
3347
3348 do
3349 {
3350 basic_block bb = queue.pop ();
3351 gimple_stmt_iterator gsi;
3352 bool stmt_found = false;
3353
3354 /* Loop for possible exits and statements bounding the execution. */
3355 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3356 {
3357 gimple stmt = gsi_stmt (gsi);
3358 if (not_executed_last_iteration->contains (stmt))
3359 {
3360 stmt_found = true;
3361 problem_stmts.safe_push (stmt);
3362 break;
3363 }
3364 if (gimple_has_side_effects (stmt))
3365 {
3366 found_exit = true;
3367 break;
3368 }
3369 }
3370 if (found_exit)
3371 break;
3372
3373 /* If no bounding statement is found, continue the walk. */
3374 if (!stmt_found)
3375 {
3376 edge e;
3377 edge_iterator ei;
3378
3379 FOR_EACH_EDGE (e, ei, bb->succs)
3380 {
3381 if (loop_exit_edge_p (loop, e)
3382 || e == loop_latch_edge (loop))
3383 {
3384 found_exit = true;
3385 break;
3386 }
3387 if (bitmap_set_bit (visited, e->dest->index))
3388 queue.safe_push (e->dest);
3389 }
3390 }
3391 }
3392 while (queue.length () && !found_exit);
3393
3394 /* If every path through the loop reach bounding statement before exit,
3395 then we know the last iteration of the loop will have undefined effect
3396 and we can decrease number of iterations. */
3397
3398 if (!found_exit)
3399 {
3400 if (dump_file && (dump_flags & TDF_DETAILS))
3401 fprintf (dump_file, "Reducing loop iteration estimate by 1; "
3402 "undefined statement must be executed at the last iteration.\n");
3403 record_niter_bound (loop, loop->nb_iterations_upper_bound - 1,
3404 false, true);
3405
3406 if (warn_aggressive_loop_optimizations)
3407 {
3408 bool exit_warned = false;
3409 for (elt = loop->bounds; elt; elt = elt->next)
3410 {
3411 if (elt->is_exit
3412 && wi::gtu_p (elt->bound, loop->nb_iterations_upper_bound))
3413 {
3414 basic_block bb = gimple_bb (elt->stmt);
3415 edge exit_edge = EDGE_SUCC (bb, 0);
3416 struct tree_niter_desc niter;
3417
3418 if (!loop_exit_edge_p (loop, exit_edge))
3419 exit_edge = EDGE_SUCC (bb, 1);
3420
3421 if(number_of_iterations_exit (loop, exit_edge,
3422 &niter, false, false)
3423 && integer_onep (niter.assumptions)
3424 && integer_zerop (niter.may_be_zero)
3425 && niter.niter
3426 && TREE_CODE (niter.niter) == INTEGER_CST
3427 && wi::ltu_p (loop->nb_iterations_upper_bound,
3428 wi::to_widest (niter.niter)))
3429 {
3430 if (warning_at (gimple_location (elt->stmt),
3431 OPT_Waggressive_loop_optimizations,
3432 "loop exit may only be reached after undefined behavior"))
3433 exit_warned = true;
3434 }
3435 }
3436 }
3437
3438 if (exit_warned && !problem_stmts.is_empty ())
3439 {
3440 gimple stmt;
3441 int index;
3442 FOR_EACH_VEC_ELT (problem_stmts, index, stmt)
3443 inform (gimple_location (stmt),
3444 "possible undefined statement is here");
3445 }
3446 }
3447 }
3448
3449 BITMAP_FREE (visited);
3450 queue.release ();
3451 problem_stmts.release ();
3452 delete not_executed_last_iteration;
3453 }
3454
3455 /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
3456 is true also use estimates derived from undefined behavior. */
3457
3458 static void
3459 estimate_numbers_of_iterations_loop (struct loop *loop)
3460 {
3461 vec<edge> exits;
3462 tree niter, type;
3463 unsigned i;
3464 struct tree_niter_desc niter_desc;
3465 edge ex;
3466 widest_int bound;
3467 edge likely_exit;
3468
3469 /* Give up if we already have tried to compute an estimation. */
3470 if (loop->estimate_state != EST_NOT_COMPUTED)
3471 return;
3472
3473 loop->estimate_state = EST_AVAILABLE;
3474 /* Force estimate compuation but leave any existing upper bound in place. */
3475 loop->any_estimate = false;
3476
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);
3481
3482 exits = get_loop_exit_edges (loop);
3483 likely_exit = single_likely_exit (loop);
3484 FOR_EACH_VEC_ELT (exits, i, ex)
3485 {
3486 if (!number_of_iterations_exit (loop, ex, &niter_desc, false, false))
3487 continue;
3488
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),
3494 niter);
3495 record_estimate (loop, niter, niter_desc.max,
3496 last_stmt (ex->src),
3497 true, ex == likely_exit, true);
3498 }
3499 exits.release ();
3500
3501 if (flag_aggressive_loop_optimizations)
3502 infer_loop_bounds_from_undefined (loop);
3503
3504 discover_iteration_bound_by_body_walk (loop);
3505
3506 maybe_lower_iteration_bound (loop);
3507
3508 /* If we have a measured profile, use it to estimate the number of
3509 iterations. */
3510 if (loop->header->count != 0)
3511 {
3512 gcov_type nit = expected_loop_iterations_unbounded (loop) + 1;
3513 bound = gcov_type_to_wide_int (nit);
3514 record_niter_bound (loop, bound, true, false);
3515 }
3516
3517 /* If we know the exact number of iterations of this loop, try to
3518 not break code with undefined behavior by not recording smaller
3519 maximum number of iterations. */
3520 if (loop->nb_iterations
3521 && TREE_CODE (loop->nb_iterations) == INTEGER_CST)
3522 {
3523 loop->any_upper_bound = true;
3524 loop->nb_iterations_upper_bound = wi::to_widest (loop->nb_iterations);
3525 }
3526 }
3527
3528 /* Sets NIT to the estimated number of executions of the latch of the
3529 LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
3530 large as the number of iterations. If we have no reliable estimate,
3531 the function returns false, otherwise returns true. */
3532
3533 bool
3534 estimated_loop_iterations (struct loop *loop, widest_int *nit)
3535 {
3536 /* When SCEV information is available, try to update loop iterations
3537 estimate. Otherwise just return whatever we recorded earlier. */
3538 if (scev_initialized_p ())
3539 estimate_numbers_of_iterations_loop (loop);
3540
3541 return (get_estimated_loop_iterations (loop, nit));
3542 }
3543
3544 /* Similar to estimated_loop_iterations, but returns the estimate only
3545 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3546 on the number of iterations of LOOP could not be derived, returns -1. */
3547
3548 HOST_WIDE_INT
3549 estimated_loop_iterations_int (struct loop *loop)
3550 {
3551 widest_int nit;
3552 HOST_WIDE_INT hwi_nit;
3553
3554 if (!estimated_loop_iterations (loop, &nit))
3555 return -1;
3556
3557 if (!wi::fits_shwi_p (nit))
3558 return -1;
3559 hwi_nit = nit.to_shwi ();
3560
3561 return hwi_nit < 0 ? -1 : hwi_nit;
3562 }
3563
3564
3565 /* Sets NIT to an upper bound for the maximum number of executions of the
3566 latch of the LOOP. If we have no reliable estimate, the function returns
3567 false, otherwise returns true. */
3568
3569 bool
3570 max_loop_iterations (struct loop *loop, widest_int *nit)
3571 {
3572 /* When SCEV information is available, try to update loop iterations
3573 estimate. Otherwise just return whatever we recorded earlier. */
3574 if (scev_initialized_p ())
3575 estimate_numbers_of_iterations_loop (loop);
3576
3577 return get_max_loop_iterations (loop, nit);
3578 }
3579
3580 /* Similar to max_loop_iterations, but returns the estimate only
3581 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3582 on the number of iterations of LOOP could not be derived, returns -1. */
3583
3584 HOST_WIDE_INT
3585 max_loop_iterations_int (struct loop *loop)
3586 {
3587 widest_int nit;
3588 HOST_WIDE_INT hwi_nit;
3589
3590 if (!max_loop_iterations (loop, &nit))
3591 return -1;
3592
3593 if (!wi::fits_shwi_p (nit))
3594 return -1;
3595 hwi_nit = nit.to_shwi ();
3596
3597 return hwi_nit < 0 ? -1 : hwi_nit;
3598 }
3599
3600 /* Returns an estimate for the number of executions of statements
3601 in the LOOP. For statements before the loop exit, this exceeds
3602 the number of execution of the latch by one. */
3603
3604 HOST_WIDE_INT
3605 estimated_stmt_executions_int (struct loop *loop)
3606 {
3607 HOST_WIDE_INT nit = estimated_loop_iterations_int (loop);
3608 HOST_WIDE_INT snit;
3609
3610 if (nit == -1)
3611 return -1;
3612
3613 snit = (HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) nit + 1);
3614
3615 /* If the computation overflows, return -1. */
3616 return snit < 0 ? -1 : snit;
3617 }
3618
3619 /* Sets NIT to the estimated maximum number of executions of the latch of the
3620 LOOP, plus one. If we have no reliable estimate, the function returns
3621 false, otherwise returns true. */
3622
3623 bool
3624 max_stmt_executions (struct loop *loop, widest_int *nit)
3625 {
3626 widest_int nit_minus_one;
3627
3628 if (!max_loop_iterations (loop, nit))
3629 return false;
3630
3631 nit_minus_one = *nit;
3632
3633 *nit += 1;
3634
3635 return wi::gtu_p (*nit, nit_minus_one);
3636 }
3637
3638 /* Sets NIT to the estimated number of executions of the latch of the
3639 LOOP, plus one. If we have no reliable estimate, the function returns
3640 false, otherwise returns true. */
3641
3642 bool
3643 estimated_stmt_executions (struct loop *loop, widest_int *nit)
3644 {
3645 widest_int nit_minus_one;
3646
3647 if (!estimated_loop_iterations (loop, nit))
3648 return false;
3649
3650 nit_minus_one = *nit;
3651
3652 *nit += 1;
3653
3654 return wi::gtu_p (*nit, nit_minus_one);
3655 }
3656
3657 /* Records estimates on numbers of iterations of loops. */
3658
3659 void
3660 estimate_numbers_of_iterations (void)
3661 {
3662 struct loop *loop;
3663
3664 /* We don't want to issue signed overflow warnings while getting
3665 loop iteration estimates. */
3666 fold_defer_overflow_warnings ();
3667
3668 FOR_EACH_LOOP (loop, 0)
3669 {
3670 estimate_numbers_of_iterations_loop (loop);
3671 }
3672
3673 fold_undefer_and_ignore_overflow_warnings ();
3674 }
3675
3676 /* Returns true if statement S1 dominates statement S2. */
3677
3678 bool
3679 stmt_dominates_stmt_p (gimple s1, gimple s2)
3680 {
3681 basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
3682
3683 if (!bb1
3684 || s1 == s2)
3685 return true;
3686
3687 if (bb1 == bb2)
3688 {
3689 gimple_stmt_iterator bsi;
3690
3691 if (gimple_code (s2) == GIMPLE_PHI)
3692 return false;
3693
3694 if (gimple_code (s1) == GIMPLE_PHI)
3695 return true;
3696
3697 for (bsi = gsi_start_bb (bb1); gsi_stmt (bsi) != s2; gsi_next (&bsi))
3698 if (gsi_stmt (bsi) == s1)
3699 return true;
3700
3701 return false;
3702 }
3703
3704 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
3705 }
3706
3707 /* Returns true when we can prove that the number of executions of
3708 STMT in the loop is at most NITER, according to the bound on
3709 the number of executions of the statement NITER_BOUND->stmt recorded in
3710 NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
3711
3712 ??? This code can become quite a CPU hog - we can have many bounds,
3713 and large basic block forcing stmt_dominates_stmt_p to be queried
3714 many times on a large basic blocks, so the whole thing is O(n^2)
3715 for scev_probably_wraps_p invocation (that can be done n times).
3716
3717 It would make more sense (and give better answers) to remember BB
3718 bounds computed by discover_iteration_bound_by_body_walk. */
3719
3720 static bool
3721 n_of_executions_at_most (gimple stmt,
3722 struct nb_iter_bound *niter_bound,
3723 tree niter)
3724 {
3725 widest_int bound = niter_bound->bound;
3726 tree nit_type = TREE_TYPE (niter), e;
3727 enum tree_code cmp;
3728
3729 gcc_assert (TYPE_UNSIGNED (nit_type));
3730
3731 /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
3732 the number of iterations is small. */
3733 if (!wi::fits_to_tree_p (bound, nit_type))
3734 return false;
3735
3736 /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
3737 times. This means that:
3738
3739 -- if NITER_BOUND->is_exit is true, then everything after
3740 it at most NITER_BOUND->bound times.
3741
3742 -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
3743 is executed, then NITER_BOUND->stmt is executed as well in the same
3744 iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
3745
3746 If we can determine that NITER_BOUND->stmt is always executed
3747 after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
3748 We conclude that if both statements belong to the same
3749 basic block and STMT is before NITER_BOUND->stmt and there are no
3750 statements with side effects in between. */
3751
3752 if (niter_bound->is_exit)
3753 {
3754 if (stmt == niter_bound->stmt
3755 || !stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3756 return false;
3757 cmp = GE_EXPR;
3758 }
3759 else
3760 {
3761 if (!stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3762 {
3763 gimple_stmt_iterator bsi;
3764 if (gimple_bb (stmt) != gimple_bb (niter_bound->stmt)
3765 || gimple_code (stmt) == GIMPLE_PHI
3766 || gimple_code (niter_bound->stmt) == GIMPLE_PHI)
3767 return false;
3768
3769 /* By stmt_dominates_stmt_p we already know that STMT appears
3770 before NITER_BOUND->STMT. Still need to test that the loop
3771 can not be terinated by a side effect in between. */
3772 for (bsi = gsi_for_stmt (stmt); gsi_stmt (bsi) != niter_bound->stmt;
3773 gsi_next (&bsi))
3774 if (gimple_has_side_effects (gsi_stmt (bsi)))
3775 return false;
3776 bound += 1;
3777 if (bound == 0
3778 || !wi::fits_to_tree_p (bound, nit_type))
3779 return false;
3780 }
3781 cmp = GT_EXPR;
3782 }
3783
3784 e = fold_binary (cmp, boolean_type_node,
3785 niter, wide_int_to_tree (nit_type, bound));
3786 return e && integer_nonzerop (e);
3787 }
3788
3789 /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
3790
3791 bool
3792 nowrap_type_p (tree type)
3793 {
3794 if (INTEGRAL_TYPE_P (type)
3795 && TYPE_OVERFLOW_UNDEFINED (type))
3796 return true;
3797
3798 if (POINTER_TYPE_P (type))
3799 return true;
3800
3801 return false;
3802 }
3803
3804 /* Return false only when the induction variable BASE + STEP * I is
3805 known to not overflow: i.e. when the number of iterations is small
3806 enough with respect to the step and initial condition in order to
3807 keep the evolution confined in TYPEs bounds. Return true when the
3808 iv is known to overflow or when the property is not computable.
3809
3810 USE_OVERFLOW_SEMANTICS is true if this function should assume that
3811 the rules for overflow of the given language apply (e.g., that signed
3812 arithmetics in C does not overflow). */
3813
3814 bool
3815 scev_probably_wraps_p (tree base, tree step,
3816 gimple at_stmt, struct loop *loop,
3817 bool use_overflow_semantics)
3818 {
3819 tree delta, step_abs;
3820 tree unsigned_type, valid_niter;
3821 tree type = TREE_TYPE (step);
3822 tree e;
3823 widest_int niter;
3824 struct nb_iter_bound *bound;
3825
3826 /* FIXME: We really need something like
3827 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
3828
3829 We used to test for the following situation that frequently appears
3830 during address arithmetics:
3831
3832 D.1621_13 = (long unsigned intD.4) D.1620_12;
3833 D.1622_14 = D.1621_13 * 8;
3834 D.1623_15 = (doubleD.29 *) D.1622_14;
3835
3836 And derived that the sequence corresponding to D_14
3837 can be proved to not wrap because it is used for computing a
3838 memory access; however, this is not really the case -- for example,
3839 if D_12 = (unsigned char) [254,+,1], then D_14 has values
3840 2032, 2040, 0, 8, ..., but the code is still legal. */
3841
3842 if (chrec_contains_undetermined (base)
3843 || chrec_contains_undetermined (step))
3844 return true;
3845
3846 if (integer_zerop (step))
3847 return false;
3848
3849 /* If we can use the fact that signed and pointer arithmetics does not
3850 wrap, we are done. */
3851 if (use_overflow_semantics && nowrap_type_p (TREE_TYPE (base)))
3852 return false;
3853
3854 /* To be able to use estimates on number of iterations of the loop,
3855 we must have an upper bound on the absolute value of the step. */
3856 if (TREE_CODE (step) != INTEGER_CST)
3857 return true;
3858
3859 /* Don't issue signed overflow warnings. */
3860 fold_defer_overflow_warnings ();
3861
3862 /* Otherwise, compute the number of iterations before we reach the
3863 bound of the type, and verify that the loop is exited before this
3864 occurs. */
3865 unsigned_type = unsigned_type_for (type);
3866 base = fold_convert (unsigned_type, base);
3867
3868 if (tree_int_cst_sign_bit (step))
3869 {
3870 tree extreme = fold_convert (unsigned_type,
3871 lower_bound_in_type (type, type));
3872 delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
3873 step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
3874 fold_convert (unsigned_type, step));
3875 }
3876 else
3877 {
3878 tree extreme = fold_convert (unsigned_type,
3879 upper_bound_in_type (type, type));
3880 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
3881 step_abs = fold_convert (unsigned_type, step);
3882 }
3883
3884 valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
3885
3886 estimate_numbers_of_iterations_loop (loop);
3887
3888 if (max_loop_iterations (loop, &niter)
3889 && wi::fits_to_tree_p (niter, TREE_TYPE (valid_niter))
3890 && (e = fold_binary (GT_EXPR, boolean_type_node, valid_niter,
3891 wide_int_to_tree (TREE_TYPE (valid_niter),
3892 niter))) != NULL
3893 && integer_nonzerop (e))
3894 {
3895 fold_undefer_and_ignore_overflow_warnings ();
3896 return false;
3897 }
3898 if (at_stmt)
3899 for (bound = loop->bounds; bound; bound = bound->next)
3900 {
3901 if (n_of_executions_at_most (at_stmt, bound, valid_niter))
3902 {
3903 fold_undefer_and_ignore_overflow_warnings ();
3904 return false;
3905 }
3906 }
3907
3908 fold_undefer_and_ignore_overflow_warnings ();
3909
3910 /* At this point we still don't have a proof that the iv does not
3911 overflow: give up. */
3912 return true;
3913 }
3914
3915 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
3916
3917 void
3918 free_numbers_of_iterations_estimates_loop (struct loop *loop)
3919 {
3920 struct nb_iter_bound *bound, *next;
3921
3922 loop->nb_iterations = NULL;
3923 loop->estimate_state = EST_NOT_COMPUTED;
3924 for (bound = loop->bounds; bound; bound = next)
3925 {
3926 next = bound->next;
3927 ggc_free (bound);
3928 }
3929
3930 loop->bounds = NULL;
3931 }
3932
3933 /* Frees the information on upper bounds on numbers of iterations of loops. */
3934
3935 void
3936 free_numbers_of_iterations_estimates (void)
3937 {
3938 struct loop *loop;
3939
3940 FOR_EACH_LOOP (loop, 0)
3941 {
3942 free_numbers_of_iterations_estimates_loop (loop);
3943 }
3944 }
3945
3946 /* Substitute value VAL for ssa name NAME inside expressions held
3947 at LOOP. */
3948
3949 void
3950 substitute_in_loop_info (struct loop *loop, tree name, tree val)
3951 {
3952 loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);
3953 }