OSDN Git Service

* tree-vrp.c (execute_vrp): Do not pass loops structure through
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-niter.c
1 /* Functions to determine/estimate number of iterations of a loop.
2    Copyright (C) 2004, 2005 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 2, 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 COPYING.  If not, write to the Free
18 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "hard-reg-set.h"
29 #include "basic-block.h"
30 #include "output.h"
31 #include "diagnostic.h"
32 #include "intl.h"
33 #include "tree-flow.h"
34 #include "tree-dump.h"
35 #include "cfgloop.h"
36 #include "tree-pass.h"
37 #include "ggc.h"
38 #include "tree-chrec.h"
39 #include "tree-scalar-evolution.h"
40 #include "tree-data-ref.h"
41 #include "params.h"
42 #include "flags.h"
43 #include "toplev.h"
44 #include "tree-inline.h"
45
46 #define SWAP(X, Y) do { void *tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
47
48
49 /*
50
51    Analysis of number of iterations of an affine exit test.
52
53 */
54
55 /* Returns true if ARG is either NULL_TREE or constant zero.  Unlike
56    integer_zerop, it does not care about overflow flags.  */
57
58 bool
59 zero_p (tree arg)
60 {
61   if (!arg)
62     return true;
63
64   if (TREE_CODE (arg) != INTEGER_CST)
65     return false;
66
67   return (TREE_INT_CST_LOW (arg) == 0 && TREE_INT_CST_HIGH (arg) == 0);
68 }
69
70 /* Returns true if ARG a nonzero constant.  Unlike integer_nonzerop, it does
71    not care about overflow flags.  */
72
73 static bool
74 nonzero_p (tree arg)
75 {
76   if (!arg)
77     return false;
78
79   if (TREE_CODE (arg) != INTEGER_CST)
80     return false;
81
82   return (TREE_INT_CST_LOW (arg) != 0 || TREE_INT_CST_HIGH (arg) != 0);
83 }
84
85 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1.  */
86
87 static tree
88 inverse (tree x, tree mask)
89 {
90   tree type = TREE_TYPE (x);
91   tree rslt;
92   unsigned ctr = tree_floor_log2 (mask);
93
94   if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
95     {
96       unsigned HOST_WIDE_INT ix;
97       unsigned HOST_WIDE_INT imask;
98       unsigned HOST_WIDE_INT irslt = 1;
99
100       gcc_assert (cst_and_fits_in_hwi (x));
101       gcc_assert (cst_and_fits_in_hwi (mask));
102
103       ix = int_cst_value (x);
104       imask = int_cst_value (mask);
105
106       for (; ctr; ctr--)
107         {
108           irslt *= ix;
109           ix *= ix;
110         }
111       irslt &= imask;
112
113       rslt = build_int_cst_type (type, irslt);
114     }
115   else
116     {
117       rslt = build_int_cst (type, 1);
118       for (; ctr; ctr--)
119         {
120           rslt = int_const_binop (MULT_EXPR, rslt, x, 0);
121           x = int_const_binop (MULT_EXPR, x, x, 0);
122         }
123       rslt = int_const_binop (BIT_AND_EXPR, rslt, mask, 0);
124     }
125
126   return rslt;
127 }
128
129 /* Determines number of iterations of loop whose ending condition
130    is IV <> FINAL.  TYPE is the type of the iv.  The number of
131    iterations is stored to NITER.  NEVER_INFINITE is true if
132    we know that the exit must be taken eventually, i.e., that the IV
133    ever reaches the value FINAL (we derived this earlier, and possibly set
134    NITER->assumptions to make sure this is the case).  */
135
136 static bool
137 number_of_iterations_ne (tree type, affine_iv *iv, tree final,
138                          struct tree_niter_desc *niter, bool never_infinite)
139 {
140   tree niter_type = unsigned_type_for (type);
141   tree s, c, d, bits, assumption, tmp, bound;
142
143   niter->control = *iv;
144   niter->bound = final;
145   niter->cmp = NE_EXPR;
146
147   /* Rearrange the terms so that we get inequality s * i <> c, with s
148      positive.  Also cast everything to the unsigned type.  */
149   if (tree_int_cst_sign_bit (iv->step))
150     {
151       s = fold_convert (niter_type,
152                         fold_build1 (NEGATE_EXPR, type, iv->step));
153       c = fold_build2 (MINUS_EXPR, niter_type,
154                        fold_convert (niter_type, iv->base),
155                        fold_convert (niter_type, final));
156     }
157   else
158     {
159       s = fold_convert (niter_type, iv->step);
160       c = fold_build2 (MINUS_EXPR, niter_type,
161                        fold_convert (niter_type, final),
162                        fold_convert (niter_type, iv->base));
163     }
164
165   /* First the trivial cases -- when the step is 1.  */
166   if (integer_onep (s))
167     {
168       niter->niter = c;
169       return true;
170     }
171
172   /* Let nsd (step, size of mode) = d.  If d does not divide c, the loop
173      is infinite.  Otherwise, the number of iterations is
174      (inverse(s/d) * (c/d)) mod (size of mode/d).  */
175   bits = num_ending_zeros (s);
176   bound = build_low_bits_mask (niter_type,
177                                (TYPE_PRECISION (niter_type)
178                                 - tree_low_cst (bits, 1)));
179
180   d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
181                                build_int_cst (niter_type, 1), bits);
182   s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
183
184   if (!never_infinite)
185     {
186       /* If we cannot assume that the loop is not infinite, record the
187          assumptions for divisibility of c.  */
188       assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
189       assumption = fold_build2 (EQ_EXPR, boolean_type_node,
190                                 assumption, build_int_cst (niter_type, 0));
191       if (!nonzero_p (assumption))
192         niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
193                                           niter->assumptions, assumption);
194     }
195       
196   c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
197   tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
198   niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
199   return true;
200 }
201
202 /* Checks whether we can determine the final value of the control variable
203    of the loop with ending condition IV0 < IV1 (computed in TYPE).
204    DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
205    of the step.  The assumptions necessary to ensure that the computation
206    of the final value does not overflow are recorded in NITER.  If we
207    find the final value, we adjust DELTA and return TRUE.  Otherwise
208    we return false.  */
209
210 static bool
211 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
212                                struct tree_niter_desc *niter,
213                                tree *delta, tree step)
214 {
215   tree niter_type = TREE_TYPE (step);
216   tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
217   tree tmod;
218   tree assumption = boolean_true_node, bound, noloop;
219
220   if (TREE_CODE (mod) != INTEGER_CST)
221     return false;
222   if (nonzero_p (mod))
223     mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
224   tmod = fold_convert (type, mod);
225
226   if (nonzero_p (iv0->step))
227     {
228       /* The final value of the iv is iv1->base + MOD, assuming that this
229          computation does not overflow, and that
230          iv0->base <= iv1->base + MOD.  */
231       if (!iv1->no_overflow && !zero_p (mod))
232         {
233           bound = fold_build2 (MINUS_EXPR, type,
234                                TYPE_MAX_VALUE (type), tmod);
235           assumption = fold_build2 (LE_EXPR, boolean_type_node,
236                                     iv1->base, bound);
237           if (zero_p (assumption))
238             return false;
239         }
240       noloop = fold_build2 (GT_EXPR, boolean_type_node,
241                             iv0->base,
242                             fold_build2 (PLUS_EXPR, type,
243                                          iv1->base, tmod));
244     }
245   else
246     {
247       /* The final value of the iv is iv0->base - MOD, assuming that this
248          computation does not overflow, and that
249          iv0->base - MOD <= iv1->base. */
250       if (!iv0->no_overflow && !zero_p (mod))
251         {
252           bound = fold_build2 (PLUS_EXPR, type,
253                                TYPE_MIN_VALUE (type), tmod);
254           assumption = fold_build2 (GE_EXPR, boolean_type_node,
255                                     iv0->base, bound);
256           if (zero_p (assumption))
257             return false;
258         }
259       noloop = fold_build2 (GT_EXPR, boolean_type_node,
260                             fold_build2 (MINUS_EXPR, type,
261                                          iv0->base, tmod),
262                             iv1->base);
263     }
264
265   if (!nonzero_p (assumption))
266     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
267                                       niter->assumptions,
268                                       assumption);
269   if (!zero_p (noloop))
270     niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
271                                       niter->may_be_zero,
272                                       noloop);
273   *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
274   return true;
275 }
276
277 /* Add assertions to NITER that ensure that the control variable of the loop
278    with ending condition IV0 < IV1 does not overflow.  Types of IV0 and IV1
279    are TYPE.  Returns false if we can prove that there is an overflow, true
280    otherwise.  STEP is the absolute value of the step.  */
281
282 static bool
283 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
284                        struct tree_niter_desc *niter, tree step)
285 {
286   tree bound, d, assumption, diff;
287   tree niter_type = TREE_TYPE (step);
288
289   if (nonzero_p (iv0->step))
290     {
291       /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
292       if (iv0->no_overflow)
293         return true;
294
295       /* If iv0->base is a constant, we can determine the last value before
296          overflow precisely; otherwise we conservatively assume
297          MAX - STEP + 1.  */
298
299       if (TREE_CODE (iv0->base) == INTEGER_CST)
300         {
301           d = fold_build2 (MINUS_EXPR, niter_type,
302                            fold_convert (niter_type, TYPE_MAX_VALUE (type)),
303                            fold_convert (niter_type, iv0->base));
304           diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
305         }
306       else
307         diff = fold_build2 (MINUS_EXPR, niter_type, step,
308                             build_int_cst (niter_type, 1));
309       bound = fold_build2 (MINUS_EXPR, type,
310                            TYPE_MAX_VALUE (type), fold_convert (type, diff));
311       assumption = fold_build2 (LE_EXPR, boolean_type_node,
312                                 iv1->base, bound);
313     }
314   else
315     {
316       /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
317       if (iv1->no_overflow)
318         return true;
319
320       if (TREE_CODE (iv1->base) == INTEGER_CST)
321         {
322           d = fold_build2 (MINUS_EXPR, niter_type,
323                            fold_convert (niter_type, iv1->base),
324                            fold_convert (niter_type, TYPE_MIN_VALUE (type)));
325           diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
326         }
327       else
328         diff = fold_build2 (MINUS_EXPR, niter_type, step,
329                             build_int_cst (niter_type, 1));
330       bound = fold_build2 (PLUS_EXPR, type,
331                            TYPE_MIN_VALUE (type), fold_convert (type, diff));
332       assumption = fold_build2 (GE_EXPR, boolean_type_node,
333                                 iv0->base, bound);
334     }
335
336   if (zero_p (assumption))
337     return false;
338   if (!nonzero_p (assumption))
339     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
340                                       niter->assumptions, assumption);
341     
342   iv0->no_overflow = true;
343   iv1->no_overflow = true;
344   return true;
345 }
346
347 /* Add an assumption to NITER that a loop whose ending condition
348    is IV0 < IV1 rolls.  TYPE is the type of the control iv.  */
349
350 static void
351 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
352                       struct tree_niter_desc *niter)
353 {
354   tree assumption = boolean_true_node, bound, diff;
355   tree mbz, mbzl, mbzr;
356
357   if (nonzero_p (iv0->step))
358     {
359       diff = fold_build2 (MINUS_EXPR, type,
360                           iv0->step, build_int_cst (type, 1));
361
362       /* We need to know that iv0->base >= MIN + iv0->step - 1.  Since
363          0 address never belongs to any object, we can assume this for
364          pointers.  */
365       if (!POINTER_TYPE_P (type))
366         {
367           bound = fold_build2 (PLUS_EXPR, type,
368                                TYPE_MIN_VALUE (type), diff);
369           assumption = fold_build2 (GE_EXPR, boolean_type_node,
370                                     iv0->base, bound);
371         }
372
373       /* And then we can compute iv0->base - diff, and compare it with
374          iv1->base.  */      
375       mbzl = fold_build2 (MINUS_EXPR, type, iv0->base, diff);
376       mbzr = iv1->base;
377     }
378   else
379     {
380       diff = fold_build2 (PLUS_EXPR, type,
381                           iv1->step, build_int_cst (type, 1));
382
383       if (!POINTER_TYPE_P (type))
384         {
385           bound = fold_build2 (PLUS_EXPR, type,
386                                TYPE_MAX_VALUE (type), diff);
387           assumption = fold_build2 (LE_EXPR, boolean_type_node,
388                                     iv1->base, bound);
389         }
390
391       mbzl = iv0->base;
392       mbzr = fold_build2 (MINUS_EXPR, type, iv1->base, diff);
393     }
394
395   mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
396
397   if (!nonzero_p (assumption))
398     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
399                                       niter->assumptions, assumption);
400   if (!zero_p (mbz))
401     niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
402                                       niter->may_be_zero, mbz);
403 }
404
405 /* Determines number of iterations of loop whose ending condition
406    is IV0 < IV1.  TYPE is the type of the iv.  The number of
407    iterations is stored to NITER.  */
408
409 static bool
410 number_of_iterations_lt (tree type, affine_iv *iv0, affine_iv *iv1,
411                          struct tree_niter_desc *niter,
412                          bool never_infinite ATTRIBUTE_UNUSED)
413 {
414   tree niter_type = unsigned_type_for (type);
415   tree delta, step, s;
416
417   if (nonzero_p (iv0->step))
418     {
419       niter->control = *iv0;
420       niter->cmp = LT_EXPR;
421       niter->bound = iv1->base;
422     }
423   else
424     {
425       niter->control = *iv1;
426       niter->cmp = GT_EXPR;
427       niter->bound = iv0->base;
428     }
429
430   delta = fold_build2 (MINUS_EXPR, niter_type,
431                        fold_convert (niter_type, iv1->base),
432                        fold_convert (niter_type, iv0->base));
433
434   /* First handle the special case that the step is +-1.  */
435   if ((iv0->step && integer_onep (iv0->step)
436        && zero_p (iv1->step))
437       || (iv1->step && integer_all_onesp (iv1->step)
438           && zero_p (iv0->step)))
439     {
440       /* for (i = iv0->base; i < iv1->base; i++)
441
442          or
443
444          for (i = iv1->base; i > iv0->base; i--).
445              
446          In both cases # of iterations is iv1->base - iv0->base, assuming that
447          iv1->base >= iv0->base.  */
448       niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
449                                         iv1->base, iv0->base);
450       niter->niter = delta;
451       return true;
452     }
453
454   if (nonzero_p (iv0->step))
455     step = fold_convert (niter_type, iv0->step);
456   else
457     step = fold_convert (niter_type,
458                          fold_build1 (NEGATE_EXPR, type, iv1->step));
459
460   /* If we can determine the final value of the control iv exactly, we can
461      transform the condition to != comparison.  In particular, this will be
462      the case if DELTA is constant.  */
463   if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step))
464     {
465       affine_iv zps;
466
467       zps.base = build_int_cst (niter_type, 0);
468       zps.step = step;
469       /* number_of_iterations_lt_to_ne will add assumptions that ensure that
470          zps does not overflow.  */
471       zps.no_overflow = true;
472
473       return number_of_iterations_ne (type, &zps, delta, niter, true);
474     }
475
476   /* Make sure that the control iv does not overflow.  */
477   if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
478     return false;
479
480   /* We determine the number of iterations as (delta + step - 1) / step.  For
481      this to work, we must know that iv1->base >= iv0->base - step + 1,
482      otherwise the loop does not roll.  */
483   assert_loop_rolls_lt (type, iv0, iv1, niter);
484
485   s = fold_build2 (MINUS_EXPR, niter_type,
486                    step, build_int_cst (niter_type, 1));
487   delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
488   niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
489   return true;
490 }
491
492 /* Determines number of iterations of loop whose ending condition
493    is IV0 <= IV1.  TYPE is the type of the iv.  The number of
494    iterations is stored to NITER.  NEVER_INFINITE is true if
495    we know that this condition must eventually become false (we derived this
496    earlier, and possibly set NITER->assumptions to make sure this
497    is the case).  */
498
499 static bool
500 number_of_iterations_le (tree type, affine_iv *iv0, affine_iv *iv1,
501                          struct tree_niter_desc *niter, bool never_infinite)
502 {
503   tree assumption;
504
505   /* Say that IV0 is the control variable.  Then IV0 <= IV1 iff
506      IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
507      value of the type.  This we must know anyway, since if it is
508      equal to this value, the loop rolls forever.  */
509
510   if (!never_infinite)
511     {
512       if (nonzero_p (iv0->step))
513         assumption = fold_build2 (NE_EXPR, boolean_type_node,
514                                   iv1->base, TYPE_MAX_VALUE (type));
515       else
516         assumption = fold_build2 (NE_EXPR, boolean_type_node,
517                                   iv0->base, TYPE_MIN_VALUE (type));
518
519       if (zero_p (assumption))
520         return false;
521       if (!nonzero_p (assumption))
522         niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
523                                           niter->assumptions, assumption);
524     }
525
526   if (nonzero_p (iv0->step))
527     iv1->base = fold_build2 (PLUS_EXPR, type,
528                              iv1->base, build_int_cst (type, 1));
529   else
530     iv0->base = fold_build2 (MINUS_EXPR, type,
531                              iv0->base, build_int_cst (type, 1));
532   return number_of_iterations_lt (type, iv0, iv1, niter, never_infinite);
533 }
534
535 /* Determine the number of iterations according to condition (for staying
536    inside loop) which compares two induction variables using comparison
537    operator CODE.  The induction variable on left side of the comparison
538    is IV0, the right-hand side is IV1.  Both induction variables must have
539    type TYPE, which must be an integer or pointer type.  The steps of the
540    ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
541
542    ONLY_EXIT is true if we are sure this is the only way the loop could be
543    exited (including possibly non-returning function calls, exceptions, etc.)
544    -- in this case we can use the information whether the control induction
545    variables can overflow or not in a more efficient way.
546    
547    The results (number of iterations and assumptions as described in
548    comments at struct tree_niter_desc in tree-flow.h) are stored to NITER.
549    Returns false if it fails to determine number of iterations, true if it
550    was determined (possibly with some assumptions).  */
551
552 static bool
553 number_of_iterations_cond (tree type, affine_iv *iv0, enum tree_code code,
554                            affine_iv *iv1, struct tree_niter_desc *niter,
555                            bool only_exit)
556 {
557   bool never_infinite;
558
559   /* The meaning of these assumptions is this:
560      if !assumptions
561        then the rest of information does not have to be valid
562      if may_be_zero then the loop does not roll, even if
563        niter != 0.  */
564   niter->assumptions = boolean_true_node;
565   niter->may_be_zero = boolean_false_node;
566   niter->niter = NULL_TREE;
567   niter->additional_info = boolean_true_node;
568
569   niter->bound = NULL_TREE;
570   niter->cmp = ERROR_MARK;
571
572   /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
573      the control variable is on lhs.  */
574   if (code == GE_EXPR || code == GT_EXPR
575       || (code == NE_EXPR && zero_p (iv0->step)))
576     {
577       SWAP (iv0, iv1);
578       code = swap_tree_comparison (code);
579     }
580
581   if (!only_exit)
582     {
583       /* If this is not the only possible exit from the loop, the information
584          that the induction variables cannot overflow as derived from
585          signedness analysis cannot be relied upon.  We use them e.g. in the
586          following way:  given loop for (i = 0; i <= n; i++), if i is
587          signed, it cannot overflow, thus this loop is equivalent to
588          for (i = 0; i < n + 1; i++);  however, if n == MAX, but the loop
589          is exited in some other way before i overflows, this transformation
590          is incorrect (the new loop exits immediately).  */
591       iv0->no_overflow = false;
592       iv1->no_overflow = false;
593     }
594
595   if (POINTER_TYPE_P (type))
596     {
597       /* Comparison of pointers is undefined unless both iv0 and iv1 point
598          to the same object.  If they do, the control variable cannot wrap
599          (as wrap around the bounds of memory will never return a pointer
600          that would be guaranteed to point to the same object, even if we
601          avoid undefined behavior by casting to size_t and back).  The
602          restrictions on pointer arithmetics and comparisons of pointers
603          ensure that using the no-overflow assumptions is correct in this
604          case even if ONLY_EXIT is false.  */
605       iv0->no_overflow = true;
606       iv1->no_overflow = true;
607     }
608
609   /* If the control induction variable does not overflow, the loop obviously
610      cannot be infinite.  */
611   if (!zero_p (iv0->step) && iv0->no_overflow)
612     never_infinite = true;
613   else if (!zero_p (iv1->step) && iv1->no_overflow)
614     never_infinite = true;
615   else
616     never_infinite = false;
617
618   /* We can handle the case when neither of the sides of the comparison is
619      invariant, provided that the test is NE_EXPR.  This rarely occurs in
620      practice, but it is simple enough to manage.  */
621   if (!zero_p (iv0->step) && !zero_p (iv1->step))
622     {
623       if (code != NE_EXPR)
624         return false;
625
626       iv0->step = fold_binary_to_constant (MINUS_EXPR, type,
627                                            iv0->step, iv1->step);
628       iv0->no_overflow = false;
629       iv1->step = NULL_TREE;
630       iv1->no_overflow = true;
631     }
632
633   /* If the result of the comparison is a constant,  the loop is weird.  More
634      precise handling would be possible, but the situation is not common enough
635      to waste time on it.  */
636   if (zero_p (iv0->step) && zero_p (iv1->step))
637     return false;
638
639   /* Ignore loops of while (i-- < 10) type.  */
640   if (code != NE_EXPR)
641     {
642       if (iv0->step && tree_int_cst_sign_bit (iv0->step))
643         return false;
644
645       if (!zero_p (iv1->step) && !tree_int_cst_sign_bit (iv1->step))
646         return false;
647     }
648
649   /* If the loop exits immediately, there is nothing to do.  */
650   if (zero_p (fold_build2 (code, boolean_type_node, iv0->base, iv1->base)))
651     {
652       niter->niter = build_int_cst (unsigned_type_for (type), 0);
653       return true;
654     }
655
656   /* OK, now we know we have a senseful loop.  Handle several cases, depending
657      on what comparison operator is used.  */
658   switch (code)
659     {
660     case NE_EXPR:
661       gcc_assert (zero_p (iv1->step));
662       return number_of_iterations_ne (type, iv0, iv1->base, niter, never_infinite);
663     case LT_EXPR:
664       return number_of_iterations_lt (type, iv0, iv1, niter, never_infinite);
665     case LE_EXPR:
666       return number_of_iterations_le (type, iv0, iv1, niter, never_infinite);
667     default:
668       gcc_unreachable ();
669     }
670 }
671
672 /* Substitute NEW for OLD in EXPR and fold the result.  */
673
674 static tree
675 simplify_replace_tree (tree expr, tree old, tree new)
676 {
677   unsigned i, n;
678   tree ret = NULL_TREE, e, se;
679
680   if (!expr)
681     return NULL_TREE;
682
683   if (expr == old
684       || operand_equal_p (expr, old, 0))
685     return unshare_expr (new);
686
687   if (!EXPR_P (expr))
688     return expr;
689
690   n = TREE_CODE_LENGTH (TREE_CODE (expr));
691   for (i = 0; i < n; i++)
692     {
693       e = TREE_OPERAND (expr, i);
694       se = simplify_replace_tree (e, old, new);
695       if (e == se)
696         continue;
697
698       if (!ret)
699         ret = copy_node (expr);
700
701       TREE_OPERAND (ret, i) = se;
702     }
703
704   return (ret ? fold (ret) : expr);
705 }
706
707 /* Expand definitions of ssa names in EXPR as long as they are simple
708    enough, and return the new expression.  */
709
710 tree
711 expand_simple_operations (tree expr)
712 {
713   unsigned i, n;
714   tree ret = NULL_TREE, e, ee, stmt;
715   enum tree_code code;
716
717   if (expr == NULL_TREE)
718     return expr;
719
720   if (is_gimple_min_invariant (expr))
721     return expr;
722
723   code = TREE_CODE (expr);
724   if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
725     {
726       n = TREE_CODE_LENGTH (code);
727       for (i = 0; i < n; i++)
728         {
729           e = TREE_OPERAND (expr, i);
730           ee = expand_simple_operations (e);
731           if (e == ee)
732             continue;
733
734           if (!ret)
735             ret = copy_node (expr);
736
737           TREE_OPERAND (ret, i) = ee;
738         }
739
740       return (ret ? fold (ret) : expr);
741     }
742
743   if (TREE_CODE (expr) != SSA_NAME)
744     return expr;
745
746   stmt = SSA_NAME_DEF_STMT (expr);
747   if (TREE_CODE (stmt) != MODIFY_EXPR)
748     return expr;
749
750   e = TREE_OPERAND (stmt, 1);
751   if (/* Casts are simple.  */
752       TREE_CODE (e) != NOP_EXPR
753       && TREE_CODE (e) != CONVERT_EXPR
754       /* Copies are simple.  */
755       && TREE_CODE (e) != SSA_NAME
756       /* Assignments of invariants are simple.  */
757       && !is_gimple_min_invariant (e)
758       /* And increments and decrements by a constant are simple.  */
759       && !((TREE_CODE (e) == PLUS_EXPR
760             || TREE_CODE (e) == MINUS_EXPR)
761            && is_gimple_min_invariant (TREE_OPERAND (e, 1))))
762     return expr;
763
764   return expand_simple_operations (e);
765 }
766
767 /* Tries to simplify EXPR using the condition COND.  Returns the simplified
768    expression (or EXPR unchanged, if no simplification was possible).  */
769
770 static tree
771 tree_simplify_using_condition_1 (tree cond, tree expr)
772 {
773   bool changed;
774   tree e, te, e0, e1, e2, notcond;
775   enum tree_code code = TREE_CODE (expr);
776
777   if (code == INTEGER_CST)
778     return expr;
779
780   if (code == TRUTH_OR_EXPR
781       || code == TRUTH_AND_EXPR
782       || code == COND_EXPR)
783     {
784       changed = false;
785
786       e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
787       if (TREE_OPERAND (expr, 0) != e0)
788         changed = true;
789
790       e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
791       if (TREE_OPERAND (expr, 1) != e1)
792         changed = true;
793
794       if (code == COND_EXPR)
795         {
796           e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
797           if (TREE_OPERAND (expr, 2) != e2)
798             changed = true;
799         }
800       else
801         e2 = NULL_TREE;
802
803       if (changed)
804         {
805           if (code == COND_EXPR)
806             expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
807           else
808             expr = fold_build2 (code, boolean_type_node, e0, e1);
809         }
810
811       return expr;
812     }
813
814   /* In case COND is equality, we may be able to simplify EXPR by copy/constant
815      propagation, and vice versa.  Fold does not handle this, since it is
816      considered too expensive.  */
817   if (TREE_CODE (cond) == EQ_EXPR)
818     {
819       e0 = TREE_OPERAND (cond, 0);
820       e1 = TREE_OPERAND (cond, 1);
821
822       /* We know that e0 == e1.  Check whether we cannot simplify expr
823          using this fact.  */
824       e = simplify_replace_tree (expr, e0, e1);
825       if (zero_p (e) || nonzero_p (e))
826         return e;
827
828       e = simplify_replace_tree (expr, e1, e0);
829       if (zero_p (e) || nonzero_p (e))
830         return e;
831     }
832   if (TREE_CODE (expr) == EQ_EXPR)
833     {
834       e0 = TREE_OPERAND (expr, 0);
835       e1 = TREE_OPERAND (expr, 1);
836
837       /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true.  */
838       e = simplify_replace_tree (cond, e0, e1);
839       if (zero_p (e))
840         return e;
841       e = simplify_replace_tree (cond, e1, e0);
842       if (zero_p (e))
843         return e;
844     }
845   if (TREE_CODE (expr) == NE_EXPR)
846     {
847       e0 = TREE_OPERAND (expr, 0);
848       e1 = TREE_OPERAND (expr, 1);
849
850       /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true.  */
851       e = simplify_replace_tree (cond, e0, e1);
852       if (zero_p (e))
853         return boolean_true_node;
854       e = simplify_replace_tree (cond, e1, e0);
855       if (zero_p (e))
856         return boolean_true_node;
857     }
858
859   te = expand_simple_operations (expr);
860
861   /* Check whether COND ==> EXPR.  */
862   notcond = invert_truthvalue (cond);
863   e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, te);
864   if (nonzero_p (e))
865     return e;
866
867   /* Check whether COND ==> not EXPR.  */
868   e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, te);
869   if (e && zero_p (e))
870     return e;
871
872   return expr;
873 }
874
875 /* Tries to simplify EXPR using the condition COND.  Returns the simplified
876    expression (or EXPR unchanged, if no simplification was possible).
877    Wrapper around tree_simplify_using_condition_1 that ensures that chains
878    of simple operations in definitions of ssa names in COND are expanded,
879    so that things like casts or incrementing the value of the bound before
880    the loop do not cause us to fail.  */
881
882 static tree
883 tree_simplify_using_condition (tree cond, tree expr)
884 {
885   cond = expand_simple_operations (cond);
886
887   return tree_simplify_using_condition_1 (cond, expr);
888 }
889
890 /* The maximum number of dominator BBs we search for conditions
891    of loop header copies we use for simplifying a conditional
892    expression.  */
893 #define MAX_DOMINATORS_TO_WALK 8
894
895 /* Tries to simplify EXPR using the conditions on entry to LOOP.
896    Record the conditions used for simplification to CONDS_USED.
897    Returns the simplified expression (or EXPR unchanged, if no
898    simplification was possible).*/
899
900 static tree
901 simplify_using_initial_conditions (struct loop *loop, tree expr,
902                                    tree *conds_used)
903 {
904   edge e;
905   basic_block bb;
906   tree exp, cond;
907   int cnt = 0;
908
909   if (TREE_CODE (expr) == INTEGER_CST)
910     return expr;
911
912   /* Limit walking the dominators to avoid quadraticness in
913      the number of BBs times the number of loops in degenerate
914      cases.  */
915   for (bb = loop->header;
916        bb != ENTRY_BLOCK_PTR && cnt < MAX_DOMINATORS_TO_WALK;
917        bb = get_immediate_dominator (CDI_DOMINATORS, bb))
918     {
919       if (!single_pred_p (bb))
920         continue;
921       e = single_pred_edge (bb);
922
923       if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
924         continue;
925
926       cond = COND_EXPR_COND (last_stmt (e->src));
927       if (e->flags & EDGE_FALSE_VALUE)
928         cond = invert_truthvalue (cond);
929       exp = tree_simplify_using_condition (cond, expr);
930
931       if (exp != expr)
932         *conds_used = fold_build2 (TRUTH_AND_EXPR,
933                                    boolean_type_node,
934                                    *conds_used,
935                                    cond);
936
937       expr = exp;
938       ++cnt;
939     }
940
941   return expr;
942 }
943
944 /* Tries to simplify EXPR using the evolutions of the loop invariants
945    in the superloops of LOOP.  Returns the simplified expression
946    (or EXPR unchanged, if no simplification was possible).  */
947
948 static tree
949 simplify_using_outer_evolutions (struct loop *loop, tree expr)
950 {
951   enum tree_code code = TREE_CODE (expr);
952   bool changed;
953   tree e, e0, e1, e2;
954
955   if (is_gimple_min_invariant (expr))
956     return expr;
957
958   if (code == TRUTH_OR_EXPR
959       || code == TRUTH_AND_EXPR
960       || code == COND_EXPR)
961     {
962       changed = false;
963
964       e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
965       if (TREE_OPERAND (expr, 0) != e0)
966         changed = true;
967
968       e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
969       if (TREE_OPERAND (expr, 1) != e1)
970         changed = true;
971
972       if (code == COND_EXPR)
973         {
974           e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
975           if (TREE_OPERAND (expr, 2) != e2)
976             changed = true;
977         }
978       else
979         e2 = NULL_TREE;
980
981       if (changed)
982         {
983           if (code == COND_EXPR)
984             expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
985           else
986             expr = fold_build2 (code, boolean_type_node, e0, e1);
987         }
988
989       return expr;
990     }
991
992   e = instantiate_parameters (loop, expr);
993   if (is_gimple_min_invariant (e))
994     return e;
995
996   return expr;
997 }
998
999 /* Returns true if EXIT is the only possible exit from LOOP.  */
1000
1001 static bool
1002 loop_only_exit_p (struct loop *loop, edge exit)
1003 {
1004   basic_block *body;
1005   block_stmt_iterator bsi;
1006   unsigned i;
1007   tree call;
1008
1009   if (exit != single_exit (loop))
1010     return false;
1011
1012   body = get_loop_body (loop);
1013   for (i = 0; i < loop->num_nodes; i++)
1014     {
1015       for (bsi = bsi_start (body[0]); !bsi_end_p (bsi); bsi_next (&bsi))
1016         {
1017           call = get_call_expr_in (bsi_stmt (bsi));
1018           if (call && TREE_SIDE_EFFECTS (call))
1019             {
1020               free (body);
1021               return false;
1022             }
1023         }
1024     }
1025
1026   free (body);
1027   return true;
1028 }
1029
1030 /* Stores description of number of iterations of LOOP derived from
1031    EXIT (an exit edge of the LOOP) in NITER.  Returns true if some
1032    useful information could be derived (and fields of NITER has
1033    meaning described in comments at struct tree_niter_desc
1034    declaration), false otherwise.  If WARN is true and
1035    -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
1036    potentially unsafe assumptions.  */
1037
1038 bool
1039 number_of_iterations_exit (struct loop *loop, edge exit,
1040                            struct tree_niter_desc *niter,
1041                            bool warn)
1042 {
1043   tree stmt, cond, type;
1044   tree op0, op1;
1045   enum tree_code code;
1046   affine_iv iv0, iv1;
1047
1048   if (!dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src))
1049     return false;
1050
1051   niter->assumptions = boolean_false_node;
1052   stmt = last_stmt (exit->src);
1053   if (!stmt || TREE_CODE (stmt) != COND_EXPR)
1054     return false;
1055
1056   /* We want the condition for staying inside loop.  */
1057   cond = COND_EXPR_COND (stmt);
1058   if (exit->flags & EDGE_TRUE_VALUE)
1059     cond = invert_truthvalue (cond);
1060
1061   code = TREE_CODE (cond);
1062   switch (code)
1063     {
1064     case GT_EXPR:
1065     case GE_EXPR:
1066     case NE_EXPR:
1067     case LT_EXPR:
1068     case LE_EXPR:
1069       break;
1070
1071     default:
1072       return false;
1073     }
1074   
1075   op0 = TREE_OPERAND (cond, 0);
1076   op1 = TREE_OPERAND (cond, 1);
1077   type = TREE_TYPE (op0);
1078
1079   if (TREE_CODE (type) != INTEGER_TYPE
1080       && !POINTER_TYPE_P (type))
1081     return false;
1082      
1083   if (!simple_iv (loop, stmt, op0, &iv0, false))
1084     return false;
1085   if (!simple_iv (loop, stmt, op1, &iv1, false))
1086     return false;
1087
1088   iv0.base = expand_simple_operations (iv0.base);
1089   iv1.base = expand_simple_operations (iv1.base);
1090   if (!number_of_iterations_cond (type, &iv0, code, &iv1, niter,
1091                                   loop_only_exit_p (loop, exit)))
1092     return false;
1093
1094   if (optimize >= 3)
1095     {
1096       niter->assumptions = simplify_using_outer_evolutions (loop,
1097                                                             niter->assumptions);
1098       niter->may_be_zero = simplify_using_outer_evolutions (loop,
1099                                                             niter->may_be_zero);
1100       niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
1101     }
1102
1103   niter->additional_info = boolean_true_node;
1104   niter->assumptions
1105           = simplify_using_initial_conditions (loop,
1106                                                niter->assumptions,
1107                                                &niter->additional_info);
1108   niter->may_be_zero
1109           = simplify_using_initial_conditions (loop,
1110                                                niter->may_be_zero,
1111                                                &niter->additional_info);
1112
1113   if (integer_onep (niter->assumptions))
1114     return true;
1115
1116   /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
1117      But if we can prove that there is overflow or some other source of weird
1118      behavior, ignore the loop even with -funsafe-loop-optimizations.  */
1119   if (integer_zerop (niter->assumptions))
1120     return false;
1121
1122   if (flag_unsafe_loop_optimizations)
1123     niter->assumptions = boolean_true_node;
1124
1125   if (warn)
1126     {
1127       const char *wording;
1128       location_t loc = EXPR_LOCATION (stmt);
1129   
1130       /* We can provide a more specific warning if one of the operator is
1131          constant and the other advances by +1 or -1.  */
1132       if (!zero_p (iv1.step)
1133           ? (zero_p (iv0.step)
1134              && (integer_onep (iv1.step) || integer_all_onesp (iv1.step)))
1135           : (iv0.step
1136              && (integer_onep (iv0.step) || integer_all_onesp (iv0.step))))
1137         wording =
1138           flag_unsafe_loop_optimizations
1139           ? N_("assuming that the loop is not infinite")
1140           : N_("cannot optimize possibly infinite loops");
1141       else
1142         wording = 
1143           flag_unsafe_loop_optimizations
1144           ? N_("assuming that the loop counter does not overflow")
1145           : N_("cannot optimize loop, the loop counter may overflow");
1146
1147       if (LOCATION_LINE (loc) > 0)
1148         warning (OPT_Wunsafe_loop_optimizations, "%H%s", &loc, gettext (wording));
1149       else
1150         warning (OPT_Wunsafe_loop_optimizations, "%s", gettext (wording));
1151     }
1152
1153   return flag_unsafe_loop_optimizations;
1154 }
1155
1156 /* Try to determine the number of iterations of LOOP.  If we succeed,
1157    expression giving number of iterations is returned and *EXIT is
1158    set to the edge from that the information is obtained.  Otherwise
1159    chrec_dont_know is returned.  */
1160
1161 tree
1162 find_loop_niter (struct loop *loop, edge *exit)
1163 {
1164   unsigned i;
1165   VEC (edge, heap) *exits = get_loop_exit_edges (loop);
1166   edge ex;
1167   tree niter = NULL_TREE, aniter;
1168   struct tree_niter_desc desc;
1169
1170   *exit = NULL;
1171   for (i = 0; VEC_iterate (edge, exits, i, ex); i++)
1172     {
1173       if (!just_once_each_iteration_p (loop, ex->src))
1174         continue;
1175
1176       if (!number_of_iterations_exit (loop, ex, &desc, false))
1177         continue;
1178
1179       if (nonzero_p (desc.may_be_zero))
1180         {
1181           /* We exit in the first iteration through this exit.
1182              We won't find anything better.  */
1183           niter = build_int_cst (unsigned_type_node, 0);
1184           *exit = ex;
1185           break;
1186         }
1187
1188       if (!zero_p (desc.may_be_zero))
1189         continue;
1190
1191       aniter = desc.niter;
1192
1193       if (!niter)
1194         {
1195           /* Nothing recorded yet.  */
1196           niter = aniter;
1197           *exit = ex;
1198           continue;
1199         }
1200
1201       /* Prefer constants, the lower the better.  */
1202       if (TREE_CODE (aniter) != INTEGER_CST)
1203         continue;
1204
1205       if (TREE_CODE (niter) != INTEGER_CST)
1206         {
1207           niter = aniter;
1208           *exit = ex;
1209           continue;
1210         }
1211
1212       if (tree_int_cst_lt (aniter, niter))
1213         {
1214           niter = aniter;
1215           *exit = ex;
1216           continue;
1217         }
1218     }
1219   VEC_free (edge, heap, exits);
1220
1221   return niter ? niter : chrec_dont_know;
1222 }
1223
1224 /*
1225
1226    Analysis of a number of iterations of a loop by a brute-force evaluation.
1227
1228 */
1229
1230 /* Bound on the number of iterations we try to evaluate.  */
1231
1232 #define MAX_ITERATIONS_TO_TRACK \
1233   ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
1234
1235 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
1236    result by a chain of operations such that all but exactly one of their
1237    operands are constants.  */
1238
1239 static tree
1240 chain_of_csts_start (struct loop *loop, tree x)
1241 {
1242   tree stmt = SSA_NAME_DEF_STMT (x);
1243   tree use;
1244   basic_block bb = bb_for_stmt (stmt);
1245
1246   if (!bb
1247       || !flow_bb_inside_loop_p (loop, bb))
1248     return NULL_TREE;
1249   
1250   if (TREE_CODE (stmt) == PHI_NODE)
1251     {
1252       if (bb == loop->header)
1253         return stmt;
1254
1255       return NULL_TREE;
1256     }
1257
1258   if (TREE_CODE (stmt) != MODIFY_EXPR)
1259     return NULL_TREE;
1260
1261   if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
1262     return NULL_TREE;
1263   if (SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF) == NULL_DEF_OPERAND_P)
1264     return NULL_TREE;
1265
1266   use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1267   if (use == NULL_USE_OPERAND_P)
1268     return NULL_TREE;
1269
1270   return chain_of_csts_start (loop, use);
1271 }
1272
1273 /* Determines whether the expression X is derived from a result of a phi node
1274    in header of LOOP such that
1275
1276    * the derivation of X consists only from operations with constants
1277    * the initial value of the phi node is constant
1278    * the value of the phi node in the next iteration can be derived from the
1279      value in the current iteration by a chain of operations with constants.
1280    
1281    If such phi node exists, it is returned.  If X is a constant, X is returned
1282    unchanged.  Otherwise NULL_TREE is returned.  */
1283
1284 static tree
1285 get_base_for (struct loop *loop, tree x)
1286 {
1287   tree phi, init, next;
1288
1289   if (is_gimple_min_invariant (x))
1290     return x;
1291
1292   phi = chain_of_csts_start (loop, x);
1293   if (!phi)
1294     return NULL_TREE;
1295
1296   init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1297   next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1298
1299   if (TREE_CODE (next) != SSA_NAME)
1300     return NULL_TREE;
1301
1302   if (!is_gimple_min_invariant (init))
1303     return NULL_TREE;
1304
1305   if (chain_of_csts_start (loop, next) != phi)
1306     return NULL_TREE;
1307
1308   return phi;
1309 }
1310
1311 /* Given an expression X, then 
1312  
1313    * if X is NULL_TREE, we return the constant BASE.
1314    * otherwise X is a SSA name, whose value in the considered loop is derived
1315      by a chain of operations with constant from a result of a phi node in
1316      the header of the loop.  Then we return value of X when the value of the
1317      result of this phi node is given by the constant BASE.  */
1318
1319 static tree
1320 get_val_for (tree x, tree base)
1321 {
1322   tree stmt, nx, val;
1323   use_operand_p op;
1324   ssa_op_iter iter;
1325
1326   gcc_assert (is_gimple_min_invariant (base));
1327
1328   if (!x)
1329     return base;
1330
1331   stmt = SSA_NAME_DEF_STMT (x);
1332   if (TREE_CODE (stmt) == PHI_NODE)
1333     return base;
1334
1335   FOR_EACH_SSA_USE_OPERAND (op, stmt, iter, SSA_OP_USE)
1336     {
1337       nx = USE_FROM_PTR (op);
1338       val = get_val_for (nx, base);
1339       SET_USE (op, val);
1340       val = fold (TREE_OPERAND (stmt, 1));
1341       SET_USE (op, nx);
1342       /* only iterate loop once.  */
1343       return val;
1344     }
1345
1346   /* Should never reach here.  */
1347   gcc_unreachable();
1348 }
1349
1350 /* Tries to count the number of iterations of LOOP till it exits by EXIT
1351    by brute force -- i.e. by determining the value of the operands of the
1352    condition at EXIT in first few iterations of the loop (assuming that
1353    these values are constant) and determining the first one in that the
1354    condition is not satisfied.  Returns the constant giving the number
1355    of the iterations of LOOP if successful, chrec_dont_know otherwise.  */
1356
1357 tree
1358 loop_niter_by_eval (struct loop *loop, edge exit)
1359 {
1360   tree cond, cnd, acnd;
1361   tree op[2], val[2], next[2], aval[2], phi[2];
1362   unsigned i, j;
1363   enum tree_code cmp;
1364
1365   cond = last_stmt (exit->src);
1366   if (!cond || TREE_CODE (cond) != COND_EXPR)
1367     return chrec_dont_know;
1368
1369   cnd = COND_EXPR_COND (cond);
1370   if (exit->flags & EDGE_TRUE_VALUE)
1371     cnd = invert_truthvalue (cnd);
1372
1373   cmp = TREE_CODE (cnd);
1374   switch (cmp)
1375     {
1376     case EQ_EXPR:
1377     case NE_EXPR:
1378     case GT_EXPR:
1379     case GE_EXPR:
1380     case LT_EXPR:
1381     case LE_EXPR:
1382       for (j = 0; j < 2; j++)
1383         op[j] = TREE_OPERAND (cnd, j);
1384       break;
1385
1386     default:
1387       return chrec_dont_know;
1388     }
1389
1390   for (j = 0; j < 2; j++)
1391     {
1392       phi[j] = get_base_for (loop, op[j]);
1393       if (!phi[j])
1394         return chrec_dont_know;
1395     }
1396
1397   for (j = 0; j < 2; j++)
1398     {
1399       if (TREE_CODE (phi[j]) == PHI_NODE)
1400         {
1401           val[j] = PHI_ARG_DEF_FROM_EDGE (phi[j], loop_preheader_edge (loop));
1402           next[j] = PHI_ARG_DEF_FROM_EDGE (phi[j], loop_latch_edge (loop));
1403         }
1404       else
1405         {
1406           val[j] = phi[j];
1407           next[j] = NULL_TREE;
1408           op[j] = NULL_TREE;
1409         }
1410     }
1411
1412   for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
1413     {
1414       for (j = 0; j < 2; j++)
1415         aval[j] = get_val_for (op[j], val[j]);
1416
1417       acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
1418       if (acnd && zero_p (acnd))
1419         {
1420           if (dump_file && (dump_flags & TDF_DETAILS))
1421             fprintf (dump_file,
1422                      "Proved that loop %d iterates %d times using brute force.\n",
1423                      loop->num, i);
1424           return build_int_cst (unsigned_type_node, i);
1425         }
1426
1427       for (j = 0; j < 2; j++)
1428         {
1429           val[j] = get_val_for (next[j], val[j]);
1430           if (!is_gimple_min_invariant (val[j]))
1431             return chrec_dont_know;
1432         }
1433     }
1434
1435   return chrec_dont_know;
1436 }
1437
1438 /* Finds the exit of the LOOP by that the loop exits after a constant
1439    number of iterations and stores the exit edge to *EXIT.  The constant
1440    giving the number of iterations of LOOP is returned.  The number of
1441    iterations is determined using loop_niter_by_eval (i.e. by brute force
1442    evaluation).  If we are unable to find the exit for that loop_niter_by_eval
1443    determines the number of iterations, chrec_dont_know is returned.  */
1444
1445 tree
1446 find_loop_niter_by_eval (struct loop *loop, edge *exit)
1447 {
1448   unsigned i;
1449   VEC (edge, heap) *exits = get_loop_exit_edges (loop);
1450   edge ex;
1451   tree niter = NULL_TREE, aniter;
1452
1453   *exit = NULL;
1454   for (i = 0; VEC_iterate (edge, exits, i, ex); i++)
1455     {
1456       if (!just_once_each_iteration_p (loop, ex->src))
1457         continue;
1458
1459       aniter = loop_niter_by_eval (loop, ex);
1460       if (chrec_contains_undetermined (aniter))
1461         continue;
1462
1463       if (niter
1464           && !tree_int_cst_lt (aniter, niter))
1465         continue;
1466
1467       niter = aniter;
1468       *exit = ex;
1469     }
1470   VEC_free (edge, heap, exits);
1471
1472   return niter ? niter : chrec_dont_know;
1473 }
1474
1475 /*
1476
1477    Analysis of upper bounds on number of iterations of a loop.
1478
1479 */
1480
1481 /* Returns true if we can prove that COND ==> VAL >= 0.  */
1482
1483 static bool
1484 implies_nonnegative_p (tree cond, tree val)
1485 {
1486   tree type = TREE_TYPE (val);
1487   tree compare;
1488
1489   if (tree_expr_nonnegative_p (val))
1490     return true;
1491
1492   if (nonzero_p (cond))
1493     return false;
1494
1495   compare = fold_build2 (GE_EXPR,
1496                          boolean_type_node, val, build_int_cst (type, 0));
1497   compare = tree_simplify_using_condition_1 (cond, compare);
1498
1499   return nonzero_p (compare);
1500 }
1501
1502 /* Returns true if we can prove that COND ==> A >= B.  */
1503
1504 static bool
1505 implies_ge_p (tree cond, tree a, tree b)
1506 {
1507   tree compare = fold_build2 (GE_EXPR, boolean_type_node, a, b);
1508
1509   if (nonzero_p (compare))
1510     return true;
1511
1512   if (nonzero_p (cond))
1513     return false;
1514
1515   compare = tree_simplify_using_condition_1 (cond, compare);
1516
1517   return nonzero_p (compare);
1518 }
1519
1520 /* Returns a constant upper bound on the value of expression VAL.  VAL
1521    is considered to be unsigned.  If its type is signed, its value must
1522    be nonnegative.
1523    
1524    The condition ADDITIONAL must be satisfied (for example, if VAL is
1525    "(unsigned) n" and ADDITIONAL is "n > 0", then we can derive that
1526    VAL is at most (unsigned) MAX_INT).  */
1527  
1528 static double_int
1529 derive_constant_upper_bound (tree val, tree additional)
1530 {
1531   tree type = TREE_TYPE (val);
1532   tree op0, op1, subtype, maxt;
1533   double_int bnd, max, mmax, cst;
1534   tree stmt;
1535
1536   if (INTEGRAL_TYPE_P (type))
1537     maxt = TYPE_MAX_VALUE (type);
1538   else
1539     maxt = upper_bound_in_type (type, type);
1540
1541   max = tree_to_double_int (maxt);
1542
1543   switch (TREE_CODE (val))
1544     {
1545     case INTEGER_CST:
1546       return tree_to_double_int (val);
1547
1548     case NOP_EXPR:
1549     case CONVERT_EXPR:
1550       op0 = TREE_OPERAND (val, 0);
1551       subtype = TREE_TYPE (op0);
1552       if (!TYPE_UNSIGNED (subtype)
1553           /* If TYPE is also signed, the fact that VAL is nonnegative implies
1554              that OP0 is nonnegative.  */
1555           && TYPE_UNSIGNED (type)
1556           && !implies_nonnegative_p (additional, op0))
1557         {
1558           /* If we cannot prove that the casted expression is nonnegative,
1559              we cannot establish more useful upper bound than the precision
1560              of the type gives us.  */
1561           return max;
1562         }
1563
1564       /* We now know that op0 is an nonnegative value.  Try deriving an upper
1565          bound for it.  */
1566       bnd = derive_constant_upper_bound (op0, additional);
1567
1568       /* If the bound does not fit in TYPE, max. value of TYPE could be
1569          attained.  */
1570       if (double_int_ucmp (max, bnd) < 0)
1571         return max;
1572
1573       return bnd;
1574
1575     case PLUS_EXPR:
1576     case MINUS_EXPR:
1577       op0 = TREE_OPERAND (val, 0);
1578       op1 = TREE_OPERAND (val, 1);
1579
1580       if (TREE_CODE (op1) != INTEGER_CST
1581           || !implies_nonnegative_p (additional, op0))
1582         return max;
1583
1584       /* Canonicalize to OP0 - CST.  Consider CST to be signed, in order to
1585          choose the most logical way how to treat this constant regardless
1586          of the signedness of the type.  */
1587       cst = tree_to_double_int (op1);
1588       cst = double_int_sext (cst, TYPE_PRECISION (type));
1589       if (TREE_CODE (val) == PLUS_EXPR)
1590         cst = double_int_neg (cst);
1591
1592       bnd = derive_constant_upper_bound (op0, additional);
1593
1594       if (double_int_negative_p (cst))
1595         {
1596           cst = double_int_neg (cst);
1597           /* Avoid CST == 0x80000...  */
1598           if (double_int_negative_p (cst))
1599             return max;;
1600
1601           /* OP0 + CST.  We need to check that
1602              BND <= MAX (type) - CST.  */
1603
1604           mmax = double_int_add (max, double_int_neg (cst));
1605           if (double_int_ucmp (bnd, mmax) > 0)
1606             return max;
1607
1608           return double_int_add (bnd, cst);
1609         }
1610       else
1611         {
1612           /* OP0 - CST, where CST >= 0.
1613
1614              If TYPE is signed, we have already verified that OP0 >= 0, and we
1615              know that the result is nonnegative.  This implies that
1616              VAL <= BND - CST.
1617
1618              If TYPE is unsigned, we must additionally know that OP0 >= CST,
1619              otherwise the operation underflows.
1620            */
1621
1622           /* This should only happen if the type is unsigned; however, for
1623              programs that use overflowing signed arithmetics even with
1624              -fno-wrapv, this condition may also be true for signed values.  */
1625           if (double_int_ucmp (bnd, cst) < 0)
1626             return max;
1627
1628           if (TYPE_UNSIGNED (type)
1629               && !implies_ge_p (additional,
1630                                 op0, double_int_to_tree (type, cst)))
1631             return max;
1632
1633           bnd = double_int_add (bnd, double_int_neg (cst));
1634         }
1635
1636       return bnd;
1637
1638     case FLOOR_DIV_EXPR:
1639     case EXACT_DIV_EXPR:
1640       op0 = TREE_OPERAND (val, 0);
1641       op1 = TREE_OPERAND (val, 1);
1642       if (TREE_CODE (op1) != INTEGER_CST
1643           || tree_int_cst_sign_bit (op1))
1644         return max;
1645
1646       bnd = derive_constant_upper_bound (op0, additional);
1647       return double_int_udiv (bnd, tree_to_double_int (op1), FLOOR_DIV_EXPR);
1648
1649     case BIT_AND_EXPR:
1650       op1 = TREE_OPERAND (val, 1);
1651       if (TREE_CODE (op1) != INTEGER_CST
1652           || tree_int_cst_sign_bit (op1))
1653         return max;
1654       return tree_to_double_int (op1);
1655
1656     case SSA_NAME:
1657       stmt = SSA_NAME_DEF_STMT (val);
1658       if (TREE_CODE (stmt) != MODIFY_EXPR
1659           || TREE_OPERAND (stmt, 0) != val)
1660         return max;
1661       return derive_constant_upper_bound (TREE_OPERAND (stmt, 1), additional);
1662
1663     default: 
1664       return max;
1665     }
1666 }
1667
1668 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP.  The
1669    additional condition ADDITIONAL is recorded with the bound.  IS_EXIT
1670    is true if the loop is exited immediately after STMT, and this exit
1671    is taken at last when the STMT is executed BOUND + 1 times.
1672    REALISTIC is true if the estimate comes from a reliable source
1673    (number of iterations analysis, or size of data accessed in the loop).  */
1674
1675 static void
1676 record_estimate (struct loop *loop, tree bound, tree additional, tree at_stmt,
1677                  bool is_exit, bool realistic)
1678 {
1679   struct nb_iter_bound *elt = xmalloc (sizeof (struct nb_iter_bound));
1680   double_int i_bound = derive_constant_upper_bound (bound, additional);
1681
1682   if (dump_file && (dump_flags & TDF_DETAILS))
1683     {
1684       fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
1685       print_generic_expr (dump_file, at_stmt, TDF_SLIM);
1686       fprintf (dump_file, " is executed at most ");
1687       print_generic_expr (dump_file, bound, TDF_SLIM);
1688       fprintf (dump_file, " (bounded by ");
1689       dump_double_int (dump_file, i_bound, true);
1690       fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
1691     }
1692
1693   elt->bound = i_bound;
1694   elt->stmt = at_stmt;
1695   elt->is_exit = is_exit;
1696   elt->realistic = realistic && TREE_CODE (bound) == INTEGER_CST;
1697   elt->next = loop->bounds;
1698   loop->bounds = elt;
1699 }
1700
1701 /* Record the estimate on number of iterations of LOOP based on the fact that
1702    the induction variable BASE + STEP * i evaluated in STMT does not wrap and
1703    its values belong to the range <LOW, HIGH>.  DATA_SIZE_BOUNDS_P is true if
1704    LOW and HIGH are derived from the size of data.  */
1705
1706 static void
1707 record_nonwrapping_iv (struct loop *loop, tree base, tree step, tree stmt,
1708                        tree low, tree high, bool data_size_bounds_p)
1709 {
1710   tree niter_bound, extreme, delta;
1711   tree type = TREE_TYPE (base), unsigned_type;
1712
1713   if (TREE_CODE (step) != INTEGER_CST || zero_p (step))
1714     return;
1715
1716   if (dump_file && (dump_flags & TDF_DETAILS))
1717     {
1718       fprintf (dump_file, "Induction variable (");
1719       print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
1720       fprintf (dump_file, ") ");
1721       print_generic_expr (dump_file, base, TDF_SLIM);
1722       fprintf (dump_file, " + ");
1723       print_generic_expr (dump_file, step, TDF_SLIM);
1724       fprintf (dump_file, " * iteration does not wrap in statement ");
1725       print_generic_expr (dump_file, stmt, TDF_SLIM);
1726       fprintf (dump_file, " in loop %d.\n", loop->num);
1727     }
1728
1729   unsigned_type = unsigned_type_for (type);
1730   base = fold_convert (unsigned_type, base);
1731   step = fold_convert (unsigned_type, step);
1732
1733   if (tree_int_cst_sign_bit (step))
1734     {
1735       extreme = fold_convert (unsigned_type, low);
1736       if (TREE_CODE (base) != INTEGER_CST)
1737         base = fold_convert (unsigned_type, high);
1738       delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
1739       step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
1740     }
1741   else
1742     {
1743       extreme = fold_convert (unsigned_type, high);
1744       if (TREE_CODE (base) != INTEGER_CST)
1745         base = fold_convert (unsigned_type, low);
1746       delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
1747     }
1748
1749   /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
1750      would get out of the range.  */
1751   niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
1752   record_estimate (loop, niter_bound, boolean_true_node, stmt,
1753                    false, data_size_bounds_p);
1754 }
1755
1756 /* Initialize LOOP->ESTIMATED_NB_ITERATIONS with the lowest safe
1757    approximation of the number of iterations for LOOP.  */
1758
1759 static void
1760 compute_estimated_nb_iterations (struct loop *loop)
1761 {
1762   struct nb_iter_bound *bound;
1763  
1764   gcc_assert (loop->estimate_state == EST_NOT_AVAILABLE);
1765
1766   for (bound = loop->bounds; bound; bound = bound->next)
1767     {
1768       if (!bound->realistic)
1769         continue;
1770
1771       /* Update only when there is no previous estimation, or when the current
1772          estimation is smaller.  */
1773       if (loop->estimate_state == EST_NOT_AVAILABLE
1774           || double_int_ucmp (bound->bound, loop->estimated_nb_iterations) < 0)
1775         {
1776           loop->estimate_state = EST_AVAILABLE;
1777           loop->estimated_nb_iterations = bound->bound;
1778         }
1779     }
1780 }
1781
1782 /* Determine information about number of iterations a LOOP from the index
1783    IDX of a data reference accessed in STMT.  Callback for for_each_index.  */
1784
1785 struct ilb_data
1786 {
1787   struct loop *loop;
1788   tree stmt;
1789 };
1790
1791 static bool
1792 idx_infer_loop_bounds (tree base, tree *idx, void *dta)
1793 {
1794   struct ilb_data *data = dta;
1795   tree ev, init, step;
1796   tree low, high, type, next;
1797   bool sign;
1798   struct loop *loop = data->loop;
1799
1800   if (TREE_CODE (base) != ARRAY_REF)
1801     return true;
1802
1803   ev = instantiate_parameters (loop, analyze_scalar_evolution (loop, *idx));
1804   init = initial_condition (ev);
1805   step = evolution_part_in_loop_num (ev, loop->num);
1806
1807   if (!init
1808       || !step
1809       || TREE_CODE (step) != INTEGER_CST
1810       || zero_p (step)
1811       || tree_contains_chrecs (init, NULL)
1812       || chrec_contains_symbols_defined_in_loop (init, loop->num))
1813     return true;
1814
1815   low = array_ref_low_bound (base);
1816   high = array_ref_up_bound (base);
1817   
1818   /* The case of nonconstant bounds could be handled, but it would be
1819      complicated.  */
1820   if (TREE_CODE (low) != INTEGER_CST
1821       || !high
1822       || TREE_CODE (high) != INTEGER_CST)
1823     return true;
1824   sign = tree_int_cst_sign_bit (step);
1825   type = TREE_TYPE (step);
1826   
1827   /* In case the relevant bound of the array does not fit in type, or
1828      it does, but bound + step (in type) still belongs into the range of the
1829      array, the index may wrap and still stay within the range of the array
1830      (consider e.g. if the array is indexed by the full range of
1831      unsigned char).
1832
1833      To make things simpler, we require both bounds to fit into type, although
1834      there are cases where this would not be strightly necessary.  */
1835   if (!int_fits_type_p (high, type)
1836       || !int_fits_type_p (low, type))
1837     return true;
1838   low = fold_convert (type, low);
1839   high = fold_convert (type, high);
1840
1841   if (sign)
1842     next = fold_binary (PLUS_EXPR, type, low, step);
1843   else
1844     next = fold_binary (PLUS_EXPR, type, high, step);
1845   
1846   if (tree_int_cst_compare (low, next) <= 0
1847       && tree_int_cst_compare (next, high) <= 0)
1848     return true;
1849
1850   record_nonwrapping_iv (loop, init, step, data->stmt, low, high, true);
1851   return true;
1852 }
1853
1854 /* Determine information about number of iterations a LOOP from the bounds
1855    of arrays in the data reference REF accessed in STMT.  */
1856
1857 static void
1858 infer_loop_bounds_from_ref (struct loop *loop, tree stmt, tree ref)
1859 {
1860   struct ilb_data data;
1861
1862   data.loop = loop;
1863   data.stmt = stmt;
1864   for_each_index (&ref, idx_infer_loop_bounds, &data);
1865 }
1866
1867 /* Determine information about number of iterations of a LOOP from the way
1868    arrays are used in STMT.  */
1869
1870 static void
1871 infer_loop_bounds_from_array (struct loop *loop, tree stmt)
1872 {
1873   tree call;
1874
1875   if (TREE_CODE (stmt) == MODIFY_EXPR)
1876     {
1877       tree op0 = TREE_OPERAND (stmt, 0);
1878       tree op1 = TREE_OPERAND (stmt, 1);
1879
1880       /* For each memory access, analyze its access function
1881          and record a bound on the loop iteration domain.  */
1882       if (REFERENCE_CLASS_P (op0))
1883         infer_loop_bounds_from_ref (loop, stmt, op0);
1884
1885       if (REFERENCE_CLASS_P (op1))
1886         infer_loop_bounds_from_ref (loop, stmt, op1);
1887     }
1888   
1889   
1890   call = get_call_expr_in (stmt);
1891   if (call)
1892     {
1893       tree args;
1894
1895       for (args = TREE_OPERAND (call, 1); args; args = TREE_CHAIN (args))
1896         if (REFERENCE_CLASS_P (TREE_VALUE (args)))
1897           infer_loop_bounds_from_ref (loop, stmt, TREE_VALUE (args));
1898     }
1899 }
1900
1901 /* Determine information about number of iterations of a LOOP from the fact
1902    that signed arithmetics in STMT does not overflow.  */
1903
1904 static void
1905 infer_loop_bounds_from_signedness (struct loop *loop, tree stmt)
1906 {
1907   tree def, base, step, scev, type, low, high;
1908
1909   if (flag_wrapv || TREE_CODE (stmt) != MODIFY_EXPR)
1910     return;
1911
1912   def = TREE_OPERAND (stmt, 0);
1913
1914   if (TREE_CODE (def) != SSA_NAME)
1915     return;
1916
1917   type = TREE_TYPE (def);
1918   if (!INTEGRAL_TYPE_P (type)
1919       || TYPE_UNSIGNED (type))
1920     return;
1921
1922   scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
1923   if (chrec_contains_undetermined (scev))
1924     return;
1925
1926   base = initial_condition_in_loop_num (scev, loop->num);
1927   step = evolution_part_in_loop_num (scev, loop->num);
1928
1929   if (!base || !step
1930       || TREE_CODE (step) != INTEGER_CST
1931       || tree_contains_chrecs (base, NULL)
1932       || chrec_contains_symbols_defined_in_loop (base, loop->num))
1933     return;
1934
1935   low = lower_bound_in_type (type, type);
1936   high = upper_bound_in_type (type, type);
1937
1938   record_nonwrapping_iv (loop, base, step, stmt, low, high, false);
1939 }
1940
1941 /* The following analyzers are extracting informations on the bounds
1942    of LOOP from the following undefined behaviors:
1943
1944    - data references should not access elements over the statically
1945      allocated size,
1946
1947    - signed variables should not overflow when flag_wrapv is not set.
1948 */
1949
1950 static void
1951 infer_loop_bounds_from_undefined (struct loop *loop)
1952 {
1953   unsigned i;
1954   basic_block *bbs;
1955   block_stmt_iterator bsi;
1956   basic_block bb;
1957   
1958   bbs = get_loop_body (loop);
1959
1960   for (i = 0; i < loop->num_nodes; i++)
1961     {
1962       bb = bbs[i];
1963
1964       /* If BB is not executed in each iteration of the loop, we cannot
1965          use it to infer any information about # of iterations of the loop.  */
1966       if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
1967         continue;
1968
1969       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1970         {
1971           tree stmt = bsi_stmt (bsi);
1972
1973           infer_loop_bounds_from_array (loop, stmt);
1974           infer_loop_bounds_from_signedness (loop, stmt);
1975         }
1976
1977     }
1978
1979   free (bbs);
1980 }
1981
1982 /* Records estimates on numbers of iterations of LOOP.  */
1983
1984 static void
1985 estimate_numbers_of_iterations_loop (struct loop *loop)
1986 {
1987   VEC (edge, heap) *exits;
1988   tree niter, type;
1989   unsigned i;
1990   struct tree_niter_desc niter_desc;
1991   edge ex;
1992
1993   /* Give up if we already have tried to compute an estimation.  */
1994   if (loop->estimate_state != EST_NOT_COMPUTED)
1995     return;
1996   loop->estimate_state = EST_NOT_AVAILABLE;
1997
1998   exits = get_loop_exit_edges (loop);
1999   for (i = 0; VEC_iterate (edge, exits, i, ex); i++)
2000     {
2001       if (!number_of_iterations_exit (loop, ex, &niter_desc, false))
2002         continue;
2003
2004       niter = niter_desc.niter;
2005       type = TREE_TYPE (niter);
2006       if (TREE_CODE (niter_desc.may_be_zero) != INTEGER_CST)
2007         niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
2008                         build_int_cst (type, 0),
2009                         niter);
2010       record_estimate (loop, niter,
2011                        niter_desc.additional_info,
2012                        last_stmt (ex->src),
2013                        true, true);
2014     }
2015   VEC_free (edge, heap, exits);
2016   
2017   infer_loop_bounds_from_undefined (loop);
2018   compute_estimated_nb_iterations (loop);
2019 }
2020
2021 /* Records estimates on numbers of iterations of loops.  */
2022
2023 void
2024 estimate_numbers_of_iterations (void)
2025 {
2026   unsigned i;
2027   struct loop *loop;
2028
2029   for (i = 1; i < current_loops->num; i++)
2030     {
2031       loop = current_loops->parray[i];
2032       if (loop)
2033         estimate_numbers_of_iterations_loop (loop);
2034     }
2035 }
2036
2037 /* Returns true if statement S1 dominates statement S2.  */
2038
2039 static bool
2040 stmt_dominates_stmt_p (tree s1, tree s2)
2041 {
2042   basic_block bb1 = bb_for_stmt (s1), bb2 = bb_for_stmt (s2);
2043
2044   if (!bb1
2045       || s1 == s2)
2046     return true;
2047
2048   if (bb1 == bb2)
2049     {
2050       block_stmt_iterator bsi;
2051
2052       for (bsi = bsi_start (bb1); bsi_stmt (bsi) != s2; bsi_next (&bsi))
2053         if (bsi_stmt (bsi) == s1)
2054           return true;
2055
2056       return false;
2057     }
2058
2059   return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
2060 }
2061
2062 /* Returns true when we can prove that the number of executions of
2063    STMT in the loop is at most NITER, according to the bound on
2064    the number of executions of the statement NITER_BOUND->stmt recorded in
2065    NITER_BOUND.  If STMT is NULL, we must prove this bound for all
2066    statements in the loop.  */
2067
2068 static bool
2069 n_of_executions_at_most (tree stmt,
2070                          struct nb_iter_bound *niter_bound, 
2071                          tree niter)
2072 {
2073   double_int bound = niter_bound->bound;
2074   tree nit_type = TREE_TYPE (niter);
2075   enum tree_code cmp;
2076
2077   gcc_assert (TYPE_UNSIGNED (nit_type));
2078
2079   /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
2080      the number of iterations is small.  */
2081   if (!double_int_fits_to_tree_p (nit_type, bound))
2082     return false;
2083
2084   /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
2085      times.  This means that:
2086      
2087      -- if NITER_BOUND->is_exit is true, then everything before
2088         NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
2089         times, and everyting after it at most NITER_BOUND->bound times.
2090
2091      -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
2092         is executed, then NITER_BOUND->stmt is executed as well in the same
2093         iteration (we conclude that if both statements belong to the same
2094         basic block, or if STMT is after NITER_BOUND->stmt), then STMT
2095         is executed at most NITER_BOUND->bound + 1 times.  Otherwise STMT is
2096         executed at most NITER_BOUND->bound + 2 times.  */
2097
2098   if (niter_bound->is_exit)
2099     {
2100       if (stmt
2101           && stmt != niter_bound->stmt
2102           && stmt_dominates_stmt_p (niter_bound->stmt, stmt))
2103         cmp = GE_EXPR;
2104       else
2105         cmp = GT_EXPR;
2106     }
2107   else
2108     {
2109       if (!stmt
2110           || (bb_for_stmt (stmt) != bb_for_stmt (niter_bound->stmt)
2111               && !stmt_dominates_stmt_p (niter_bound->stmt, stmt)))
2112         {
2113           bound = double_int_add (bound, double_int_one);
2114           if (double_int_zero_p (bound)
2115               || !double_int_fits_to_tree_p (nit_type, bound))
2116             return false;
2117         }
2118       cmp = GT_EXPR;
2119     }
2120
2121   return nonzero_p (fold_binary (cmp, boolean_type_node,
2122                                  niter,
2123                                  double_int_to_tree (nit_type, bound)));
2124 }
2125
2126 /* Returns true if the arithmetics in TYPE can be assumed not to wrap.  */
2127
2128 bool
2129 nowrap_type_p (tree type)
2130 {
2131   if (!flag_wrapv
2132       && INTEGRAL_TYPE_P (type)
2133       && !TYPE_UNSIGNED (type))
2134     return true;
2135
2136   if (POINTER_TYPE_P (type))
2137     return true;
2138
2139   return false;
2140 }
2141
2142 /* Return false only when the induction variable BASE + STEP * I is
2143    known to not overflow: i.e. when the number of iterations is small
2144    enough with respect to the step and initial condition in order to
2145    keep the evolution confined in TYPEs bounds.  Return true when the
2146    iv is known to overflow or when the property is not computable.
2147  
2148    USE_OVERFLOW_SEMANTICS is true if this function should assume that
2149    the rules for overflow of the given language apply (e.g., that signed
2150    arithmetics in C does not overflow).  */
2151
2152 bool
2153 scev_probably_wraps_p (tree base, tree step, 
2154                        tree at_stmt, struct loop *loop,
2155                        bool use_overflow_semantics)
2156 {
2157   struct nb_iter_bound *bound;
2158   tree delta, step_abs;
2159   tree unsigned_type, valid_niter;
2160   tree type = TREE_TYPE (step);
2161
2162   /* FIXME: We really need something like
2163      http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
2164
2165      We used to test for the following situation that frequently appears
2166      during address arithmetics:
2167          
2168        D.1621_13 = (long unsigned intD.4) D.1620_12;
2169        D.1622_14 = D.1621_13 * 8;
2170        D.1623_15 = (doubleD.29 *) D.1622_14;
2171
2172      And derived that the sequence corresponding to D_14
2173      can be proved to not wrap because it is used for computing a
2174      memory access; however, this is not really the case -- for example,
2175      if D_12 = (unsigned char) [254,+,1], then D_14 has values
2176      2032, 2040, 0, 8, ..., but the code is still legal.  */
2177
2178   if (chrec_contains_undetermined (base)
2179       || chrec_contains_undetermined (step)
2180       || TREE_CODE (step) != INTEGER_CST)
2181     return true;
2182
2183   if (zero_p (step))
2184     return false;
2185
2186   /* If we can use the fact that signed and pointer arithmetics does not
2187      wrap, we are done.  */
2188   if (use_overflow_semantics && nowrap_type_p (type))
2189     return false;
2190
2191   /* Otherwise, compute the number of iterations before we reach the
2192      bound of the type, and verify that the loop is exited before this
2193      occurs.  */
2194   unsigned_type = unsigned_type_for (type);
2195   base = fold_convert (unsigned_type, base);
2196
2197   if (tree_int_cst_sign_bit (step))
2198     {
2199       tree extreme = fold_convert (unsigned_type,
2200                                    lower_bound_in_type (type, type));
2201       delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
2202       step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
2203                               fold_convert (unsigned_type, step));
2204     }
2205   else
2206     {
2207       tree extreme = fold_convert (unsigned_type,
2208                                    upper_bound_in_type (type, type));
2209       delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
2210       step_abs = fold_convert (unsigned_type, step);
2211     }
2212
2213   valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
2214
2215   estimate_numbers_of_iterations_loop (loop);
2216   for (bound = loop->bounds; bound; bound = bound->next)
2217     if (n_of_executions_at_most (at_stmt, bound, valid_niter))
2218       return false;
2219
2220   /* At this point we still don't have a proof that the iv does not
2221      overflow: give up.  */
2222   return true;
2223 }
2224
2225 /* Frees the information on upper bounds on numbers of iterations of LOOP.  */
2226
2227 void
2228 free_numbers_of_iterations_estimates_loop (struct loop *loop)
2229 {
2230   struct nb_iter_bound *bound, *next;
2231
2232   loop->nb_iterations = NULL;
2233   loop->estimate_state = EST_NOT_COMPUTED;
2234   for (bound = loop->bounds; bound; bound = next)
2235     {
2236       next = bound->next;
2237       free (bound);
2238     }
2239
2240   loop->bounds = NULL;
2241 }
2242
2243 /* Frees the information on upper bounds on numbers of iterations of loops.  */
2244
2245 void
2246 free_numbers_of_iterations_estimates (void)
2247 {
2248   unsigned i;
2249   struct loop *loop;
2250
2251   for (i = 1; i < current_loops->num; i++)
2252     {
2253       loop = current_loops->parray[i];
2254       if (loop)
2255         free_numbers_of_iterations_estimates_loop (loop);
2256     }
2257 }
2258
2259 /* Substitute value VAL for ssa name NAME inside expressions held
2260    at LOOP.  */
2261
2262 void
2263 substitute_in_loop_info (struct loop *loop, tree name, tree val)
2264 {
2265   loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);
2266 }