OSDN Git Service

b165418b36765f97c1489972f72968a0e9fbe081
[pf3gnuchains/gcc-fork.git] / gcc / tree-vrp.c
1 /* Support routines for Value Range Propagation (VRP).
2    Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "ggc.h"
27 #include "flags.h"
28 #include "tree.h"
29 #include "basic-block.h"
30 #include "tree-flow.h"
31 #include "tree-pass.h"
32 #include "tree-dump.h"
33 #include "timevar.h"
34 #include "diagnostic.h"
35 #include "toplev.h"
36 #include "intl.h"
37 #include "cfgloop.h"
38 #include "tree-scalar-evolution.h"
39 #include "tree-ssa-propagate.h"
40 #include "tree-chrec.h"
41
42 /* Set of SSA names found during the dominator traversal of a
43    sub-graph in find_assert_locations.  */
44 static sbitmap found_in_subgraph;
45
46 /* Local functions.  */
47 static int compare_values (tree val1, tree val2);
48 static int compare_values_warnv (tree val1, tree val2, bool *);
49 static void vrp_meet (value_range_t *, value_range_t *);
50 static tree vrp_evaluate_conditional_warnv (tree, bool, bool *);
51
52 /* Location information for ASSERT_EXPRs.  Each instance of this
53    structure describes an ASSERT_EXPR for an SSA name.  Since a single
54    SSA name may have more than one assertion associated with it, these
55    locations are kept in a linked list attached to the corresponding
56    SSA name.  */
57 struct assert_locus_d
58 {
59   /* Basic block where the assertion would be inserted.  */
60   basic_block bb;
61
62   /* Some assertions need to be inserted on an edge (e.g., assertions
63      generated by COND_EXPRs).  In those cases, BB will be NULL.  */
64   edge e;
65
66   /* Pointer to the statement that generated this assertion.  */
67   block_stmt_iterator si;
68
69   /* Predicate code for the ASSERT_EXPR.  Must be COMPARISON_CLASS_P.  */
70   enum tree_code comp_code;
71
72   /* Value being compared against.  */
73   tree val;
74
75   /* Next node in the linked list.  */
76   struct assert_locus_d *next;
77 };
78
79 typedef struct assert_locus_d *assert_locus_t;
80
81 /* If bit I is present, it means that SSA name N_i has a list of
82    assertions that should be inserted in the IL.  */
83 static bitmap need_assert_for;
84
85 /* Array of locations lists where to insert assertions.  ASSERTS_FOR[I]
86    holds a list of ASSERT_LOCUS_T nodes that describe where
87    ASSERT_EXPRs for SSA name N_I should be inserted.  */
88 static assert_locus_t *asserts_for;
89
90 /* Set of blocks visited in find_assert_locations.  Used to avoid
91    visiting the same block more than once.  */
92 static sbitmap blocks_visited;
93
94 /* Value range array.  After propagation, VR_VALUE[I] holds the range
95    of values that SSA name N_I may take.  */
96 static value_range_t **vr_value;
97
98 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
99    number of executable edges we saw the last time we visited the
100    node.  */
101 static int *vr_phi_edge_counts;
102
103
104 /* Return whether TYPE should use an overflow infinity distinct from
105    TYPE_{MIN,MAX}_VALUE.  We use an overflow infinity value to
106    represent a signed overflow during VRP computations.  An infinity
107    is distinct from a half-range, which will go from some number to
108    TYPE_{MIN,MAX}_VALUE.  */
109
110 static inline bool
111 needs_overflow_infinity (tree type)
112 {
113   return INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type);
114 }
115
116 /* Return whether TYPE can support our overflow infinity
117    representation: we use the TREE_OVERFLOW flag, which only exists
118    for constants.  If TYPE doesn't support this, we don't optimize
119    cases which would require signed overflow--we drop them to
120    VARYING.  */
121
122 static inline bool
123 supports_overflow_infinity (tree type)
124 {
125 #ifdef ENABLE_CHECKING
126   gcc_assert (needs_overflow_infinity (type));
127 #endif
128   return (TYPE_MIN_VALUE (type) != NULL_TREE
129           && CONSTANT_CLASS_P (TYPE_MIN_VALUE (type))
130           && TYPE_MAX_VALUE (type) != NULL_TREE
131           && CONSTANT_CLASS_P (TYPE_MAX_VALUE (type)));
132 }
133
134 /* VAL is the maximum or minimum value of a type.  Return a
135    corresponding overflow infinity.  */
136
137 static inline tree
138 make_overflow_infinity (tree val)
139 {
140 #ifdef ENABLE_CHECKING
141   gcc_assert (val != NULL_TREE && CONSTANT_CLASS_P (val));
142 #endif
143   val = copy_node (val);
144   TREE_OVERFLOW (val) = 1;
145   return val;
146 }
147
148 /* Return a negative overflow infinity for TYPE.  */
149
150 static inline tree
151 negative_overflow_infinity (tree type)
152 {
153 #ifdef ENABLE_CHECKING
154   gcc_assert (supports_overflow_infinity (type));
155 #endif
156   return make_overflow_infinity (TYPE_MIN_VALUE (type));
157 }
158
159 /* Return a positive overflow infinity for TYPE.  */
160
161 static inline tree
162 positive_overflow_infinity (tree type)
163 {
164 #ifdef ENABLE_CHECKING
165   gcc_assert (supports_overflow_infinity (type));
166 #endif
167   return make_overflow_infinity (TYPE_MAX_VALUE (type));
168 }
169
170 /* Return whether VAL is a negative overflow infinity.  */
171
172 static inline bool
173 is_negative_overflow_infinity (tree val)
174 {
175   return (needs_overflow_infinity (TREE_TYPE (val))
176           && CONSTANT_CLASS_P (val)
177           && TREE_OVERFLOW (val)
178           && operand_equal_p (val, TYPE_MIN_VALUE (TREE_TYPE (val)), 0));
179 }
180
181 /* Return whether VAL is a positive overflow infinity.  */
182
183 static inline bool
184 is_positive_overflow_infinity (tree val)
185 {
186   return (needs_overflow_infinity (TREE_TYPE (val))
187           && CONSTANT_CLASS_P (val)
188           && TREE_OVERFLOW (val)
189           && operand_equal_p (val, TYPE_MAX_VALUE (TREE_TYPE (val)), 0));
190 }
191
192 /* Return whether VAL is a positive or negative overflow infinity.  */
193
194 static inline bool
195 is_overflow_infinity (tree val)
196 {
197   return (needs_overflow_infinity (TREE_TYPE (val))
198           && CONSTANT_CLASS_P (val)
199           && TREE_OVERFLOW (val)
200           && (operand_equal_p (val, TYPE_MAX_VALUE (TREE_TYPE (val)), 0)
201               || operand_equal_p (val, TYPE_MIN_VALUE (TREE_TYPE (val)), 0)));
202 }
203
204
205 /* Return true if ARG is marked with the nonnull attribute in the
206    current function signature.  */
207
208 static bool
209 nonnull_arg_p (tree arg)
210 {
211   tree t, attrs, fntype;
212   unsigned HOST_WIDE_INT arg_num;
213
214   gcc_assert (TREE_CODE (arg) == PARM_DECL && POINTER_TYPE_P (TREE_TYPE (arg)));
215
216   /* The static chain decl is always non null.  */
217   if (arg == cfun->static_chain_decl)
218     return true;
219
220   fntype = TREE_TYPE (current_function_decl);
221   attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (fntype));
222
223   /* If "nonnull" wasn't specified, we know nothing about the argument.  */
224   if (attrs == NULL_TREE)
225     return false;
226
227   /* If "nonnull" applies to all the arguments, then ARG is non-null.  */
228   if (TREE_VALUE (attrs) == NULL_TREE)
229     return true;
230
231   /* Get the position number for ARG in the function signature.  */
232   for (arg_num = 1, t = DECL_ARGUMENTS (current_function_decl);
233        t;
234        t = TREE_CHAIN (t), arg_num++)
235     {
236       if (t == arg)
237         break;
238     }
239
240   gcc_assert (t == arg);
241
242   /* Now see if ARG_NUM is mentioned in the nonnull list.  */
243   for (t = TREE_VALUE (attrs); t; t = TREE_CHAIN (t))
244     {
245       if (compare_tree_int (TREE_VALUE (t), arg_num) == 0)
246         return true;
247     }
248
249   return false;
250 }
251
252
253 /* Set value range VR to {T, MIN, MAX, EQUIV}.  */
254
255 static void
256 set_value_range (value_range_t *vr, enum value_range_type t, tree min,
257                  tree max, bitmap equiv)
258 {
259 #if defined ENABLE_CHECKING
260   /* Check the validity of the range.  */
261   if (t == VR_RANGE || t == VR_ANTI_RANGE)
262     {
263       int cmp;
264
265       gcc_assert (min && max);
266
267       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
268         gcc_assert ((min != TYPE_MIN_VALUE (TREE_TYPE (min))
269                      && !is_negative_overflow_infinity (min))
270                     || (max != TYPE_MAX_VALUE (TREE_TYPE (max))
271                         && !is_positive_overflow_infinity (max)));
272
273       cmp = compare_values (min, max);
274       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
275
276       if (needs_overflow_infinity (TREE_TYPE (min)))
277         gcc_assert (!is_overflow_infinity (min)
278                     || !is_overflow_infinity (max));
279     }
280
281   if (t == VR_UNDEFINED || t == VR_VARYING)
282     gcc_assert (min == NULL_TREE && max == NULL_TREE);
283
284   if (t == VR_UNDEFINED || t == VR_VARYING)
285     gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
286 #endif
287
288   vr->type = t;
289   vr->min = min;
290   vr->max = max;
291
292   /* Since updating the equivalence set involves deep copying the
293      bitmaps, only do it if absolutely necessary.  */
294   if (vr->equiv == NULL
295       && equiv != NULL)
296     vr->equiv = BITMAP_ALLOC (NULL);
297
298   if (equiv != vr->equiv)
299     {
300       if (equiv && !bitmap_empty_p (equiv))
301         bitmap_copy (vr->equiv, equiv);
302       else
303         bitmap_clear (vr->equiv);
304     }
305 }
306
307
308 /* Copy value range FROM into value range TO.  */
309
310 static inline void
311 copy_value_range (value_range_t *to, value_range_t *from)
312 {
313   set_value_range (to, from->type, from->min, from->max, from->equiv);
314 }
315
316
317 /* Set value range VR to VR_VARYING.  */
318
319 static inline void
320 set_value_range_to_varying (value_range_t *vr)
321 {
322   vr->type = VR_VARYING;
323   vr->min = vr->max = NULL_TREE;
324   if (vr->equiv)
325     bitmap_clear (vr->equiv);
326 }
327
328 /* Set value range VR to a single value.  This function is only called
329    with values we get from statements, and exists to clear the
330    TREE_OVERFLOW flag so that we don't think we have an overflow
331    infinity when we shouldn't.  */
332
333 static inline void
334 set_value_range_to_value (value_range_t *vr, tree val)
335 {
336   gcc_assert (is_gimple_min_invariant (val));
337   if (is_overflow_infinity (val))
338     {
339       val = copy_node (val);
340       TREE_OVERFLOW (val) = 0;
341     }
342   set_value_range (vr, VR_RANGE, val, val, NULL);
343 }
344
345 /* Set value range VR to a non-negative range of type TYPE.
346    OVERFLOW_INFINITY indicates whether to use a overflow infinity
347    rather than TYPE_MAX_VALUE; this should be true if we determine
348    that the range is nonnegative based on the assumption that signed
349    overflow does not occur.  */
350
351 static inline void
352 set_value_range_to_nonnegative (value_range_t *vr, tree type,
353                                 bool overflow_infinity)
354 {
355   tree zero;
356
357   if (overflow_infinity && !supports_overflow_infinity (type))
358     {
359       set_value_range_to_varying (vr);
360       return;
361     }
362
363   zero = build_int_cst (type, 0);
364   set_value_range (vr, VR_RANGE, zero,
365                    (overflow_infinity
366                     ? positive_overflow_infinity (type)
367                     : TYPE_MAX_VALUE (type)),
368                    vr->equiv);
369 }
370
371 /* Set value range VR to a non-NULL range of type TYPE.  */
372
373 static inline void
374 set_value_range_to_nonnull (value_range_t *vr, tree type)
375 {
376   tree zero = build_int_cst (type, 0);
377   set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
378 }
379
380
381 /* Set value range VR to a NULL range of type TYPE.  */
382
383 static inline void
384 set_value_range_to_null (value_range_t *vr, tree type)
385 {
386   tree zero = build_int_cst (type, 0);
387   set_value_range (vr, VR_RANGE, zero, zero, vr->equiv);
388 }
389
390
391 /* Set value range VR to a range of a truthvalue of type TYPE.  */
392
393 static inline void
394 set_value_range_to_truthvalue (value_range_t *vr, tree type)
395 {
396   if (TYPE_PRECISION (type) == 1)
397     set_value_range_to_varying (vr);
398   else
399     set_value_range (vr, VR_RANGE,
400                      build_int_cst (type, 0), build_int_cst (type, 1),
401                      vr->equiv);
402 }
403
404
405 /* Set value range VR to VR_UNDEFINED.  */
406
407 static inline void
408 set_value_range_to_undefined (value_range_t *vr)
409 {
410   vr->type = VR_UNDEFINED;
411   vr->min = vr->max = NULL_TREE;
412   if (vr->equiv)
413     bitmap_clear (vr->equiv);
414 }
415
416
417 /* Return value range information for VAR.  
418
419    If we have no values ranges recorded (ie, VRP is not running), then
420    return NULL.  Otherwise create an empty range if none existed for VAR.  */
421
422 static value_range_t *
423 get_value_range (tree var)
424 {
425   value_range_t *vr;
426   tree sym;
427   unsigned ver = SSA_NAME_VERSION (var);
428
429   /* If we have no recorded ranges, then return NULL.  */
430   if (! vr_value)
431     return NULL;
432
433   vr = vr_value[ver];
434   if (vr)
435     return vr;
436
437   /* Create a default value range.  */
438   vr_value[ver] = vr = XCNEW (value_range_t);
439
440   /* Defer allocating the equivalence set.  */
441   vr->equiv = NULL;
442
443   /* If VAR is a default definition, the variable can take any value
444      in VAR's type.  */
445   sym = SSA_NAME_VAR (var);
446   if (SSA_NAME_IS_DEFAULT_DEF (var))
447     {
448       /* Try to use the "nonnull" attribute to create ~[0, 0]
449          anti-ranges for pointers.  Note that this is only valid with
450          default definitions of PARM_DECLs.  */
451       if (TREE_CODE (sym) == PARM_DECL
452           && POINTER_TYPE_P (TREE_TYPE (sym))
453           && nonnull_arg_p (sym))
454         set_value_range_to_nonnull (vr, TREE_TYPE (sym));
455       else
456         set_value_range_to_varying (vr);
457     }
458
459   return vr;
460 }
461
462 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes.  */
463
464 static inline bool
465 vrp_operand_equal_p (tree val1, tree val2)
466 {
467   if (val1 == val2)
468     return true;
469   if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
470     return false;
471   if (is_overflow_infinity (val1))
472     return is_overflow_infinity (val2);
473   return true;
474 }
475
476 /* Return true, if the bitmaps B1 and B2 are equal.  */
477
478 static inline bool
479 vrp_bitmap_equal_p (bitmap b1, bitmap b2)
480 {
481   return (b1 == b2
482           || (b1 && b2
483               && bitmap_equal_p (b1, b2)));
484 }
485
486 /* Update the value range and equivalence set for variable VAR to
487    NEW_VR.  Return true if NEW_VR is different from VAR's previous
488    value.
489
490    NOTE: This function assumes that NEW_VR is a temporary value range
491    object created for the sole purpose of updating VAR's range.  The
492    storage used by the equivalence set from NEW_VR will be freed by
493    this function.  Do not call update_value_range when NEW_VR
494    is the range object associated with another SSA name.  */
495
496 static inline bool
497 update_value_range (tree var, value_range_t *new_vr)
498 {
499   value_range_t *old_vr;
500   bool is_new;
501
502   /* Update the value range, if necessary.  */
503   old_vr = get_value_range (var);
504   is_new = old_vr->type != new_vr->type
505            || !vrp_operand_equal_p (old_vr->min, new_vr->min)
506            || !vrp_operand_equal_p (old_vr->max, new_vr->max)
507            || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
508
509   if (is_new)
510     set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
511                      new_vr->equiv);
512
513   BITMAP_FREE (new_vr->equiv);
514
515   return is_new;
516 }
517
518
519 /* Add VAR and VAR's equivalence set to EQUIV.  This is the central
520    point where equivalence processing can be turned on/off.  */
521
522 static void
523 add_equivalence (bitmap *equiv, tree var)
524 {
525   unsigned ver = SSA_NAME_VERSION (var);
526   value_range_t *vr = vr_value[ver];
527
528   if (*equiv == NULL)
529     *equiv = BITMAP_ALLOC (NULL);
530   bitmap_set_bit (*equiv, ver);
531   if (vr && vr->equiv)
532     bitmap_ior_into (*equiv, vr->equiv);
533 }
534
535
536 /* Return true if VR is ~[0, 0].  */
537
538 static inline bool
539 range_is_nonnull (value_range_t *vr)
540 {
541   return vr->type == VR_ANTI_RANGE
542          && integer_zerop (vr->min)
543          && integer_zerop (vr->max);
544 }
545
546
547 /* Return true if VR is [0, 0].  */
548
549 static inline bool
550 range_is_null (value_range_t *vr)
551 {
552   return vr->type == VR_RANGE
553          && integer_zerop (vr->min)
554          && integer_zerop (vr->max);
555 }
556
557
558 /* Return true if value range VR involves at least one symbol.  */
559
560 static inline bool
561 symbolic_range_p (value_range_t *vr)
562 {
563   return (!is_gimple_min_invariant (vr->min)
564           || !is_gimple_min_invariant (vr->max));
565 }
566
567 /* Return true if value range VR uses a overflow infinity.  */
568
569 static inline bool
570 overflow_infinity_range_p (value_range_t *vr)
571 {
572   return (vr->type == VR_RANGE
573           && (is_overflow_infinity (vr->min)
574               || is_overflow_infinity (vr->max)));
575 }
576
577 /* Return false if we can not make a valid comparison based on VR;
578    this will be the case if it uses an overflow infinity and overflow
579    is not undefined (i.e., -fno-strict-overflow is in effect).
580    Otherwise return true, and set *STRICT_OVERFLOW_P to true if VR
581    uses an overflow infinity.  */
582
583 static bool
584 usable_range_p (value_range_t *vr, bool *strict_overflow_p)
585 {
586   gcc_assert (vr->type == VR_RANGE);
587   if (is_overflow_infinity (vr->min))
588     {
589       *strict_overflow_p = true;
590       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->min)))
591         return false;
592     }
593   if (is_overflow_infinity (vr->max))
594     {
595       *strict_overflow_p = true;
596       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->max)))
597         return false;
598     }
599   return true;
600 }
601
602
603 /* Like tree_expr_nonnegative_warnv_p, but this function uses value
604    ranges obtained so far.  */
605
606 static bool
607 vrp_expr_computes_nonnegative (tree expr, bool *strict_overflow_p)
608 {
609   return tree_expr_nonnegative_warnv_p (expr, strict_overflow_p);
610 }
611
612 /* Like tree_expr_nonzero_warnv_p, but this function uses value ranges
613    obtained so far.  */
614
615 static bool
616 vrp_expr_computes_nonzero (tree expr, bool *strict_overflow_p)
617 {
618   if (tree_expr_nonzero_warnv_p (expr, strict_overflow_p))
619     return true;
620
621   /* If we have an expression of the form &X->a, then the expression
622      is nonnull if X is nonnull.  */
623   if (TREE_CODE (expr) == ADDR_EXPR)
624     {
625       tree base = get_base_address (TREE_OPERAND (expr, 0));
626
627       if (base != NULL_TREE
628           && TREE_CODE (base) == INDIRECT_REF
629           && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
630         {
631           value_range_t *vr = get_value_range (TREE_OPERAND (base, 0));
632           if (range_is_nonnull (vr))
633             return true;
634         }
635     }
636
637   return false;
638 }
639
640 /* Returns true if EXPR is a valid value (as expected by compare_values) --
641    a gimple invariant, or SSA_NAME +- CST.  */
642
643 static bool
644 valid_value_p (tree expr)
645 {
646   if (TREE_CODE (expr) == SSA_NAME)
647     return true;
648
649   if (TREE_CODE (expr) == PLUS_EXPR
650       || TREE_CODE (expr) == MINUS_EXPR)
651     return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
652             && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
653   
654   return is_gimple_min_invariant (expr);
655 }
656
657 /* Return 
658    1 if VAL < VAL2
659    0 if !(VAL < VAL2)
660    -2 if those are incomparable.  */
661 static inline int
662 operand_less_p (tree val, tree val2)
663 {
664   /* LT is folded faster than GE and others.  Inline the common case.  */
665   if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
666     {
667       if (TYPE_UNSIGNED (TREE_TYPE (val)))
668         return INT_CST_LT_UNSIGNED (val, val2);
669       else
670         {
671           if (INT_CST_LT (val, val2))
672             return 1;
673         }
674     }
675   else
676     {
677       tree tcmp;
678
679       fold_defer_overflow_warnings ();
680
681       tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
682
683       fold_undefer_and_ignore_overflow_warnings ();
684
685       if (!tcmp)
686         return -2;
687
688       if (!integer_zerop (tcmp))
689         return 1;
690     }
691
692   /* val >= val2, not considering overflow infinity.  */
693   if (is_negative_overflow_infinity (val))
694     return is_negative_overflow_infinity (val2) ? 0 : 1;
695   else if (is_positive_overflow_infinity (val2))
696     return is_positive_overflow_infinity (val) ? 0 : 1;
697
698   return 0;
699 }
700
701 /* Compare two values VAL1 and VAL2.  Return
702    
703         -2 if VAL1 and VAL2 cannot be compared at compile-time,
704         -1 if VAL1 < VAL2,
705          0 if VAL1 == VAL2,
706         +1 if VAL1 > VAL2, and
707         +2 if VAL1 != VAL2
708
709    This is similar to tree_int_cst_compare but supports pointer values
710    and values that cannot be compared at compile time.
711
712    If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
713    true if the return value is only valid if we assume that signed
714    overflow is undefined.  */
715
716 static int
717 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
718 {
719   if (val1 == val2)
720     return 0;
721
722   /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
723      both integers.  */
724   gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
725               == POINTER_TYPE_P (TREE_TYPE (val2)));
726
727   if ((TREE_CODE (val1) == SSA_NAME
728        || TREE_CODE (val1) == PLUS_EXPR
729        || TREE_CODE (val1) == MINUS_EXPR)
730       && (TREE_CODE (val2) == SSA_NAME
731           || TREE_CODE (val2) == PLUS_EXPR
732           || TREE_CODE (val2) == MINUS_EXPR))
733     {
734       tree n1, c1, n2, c2;
735       enum tree_code code1, code2;
736   
737       /* If VAL1 and VAL2 are of the form 'NAME [+-] CST' or 'NAME',
738          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
739          same name, return -2.  */
740       if (TREE_CODE (val1) == SSA_NAME)
741         {
742           code1 = SSA_NAME;
743           n1 = val1;
744           c1 = NULL_TREE;
745         }
746       else
747         {
748           code1 = TREE_CODE (val1);
749           n1 = TREE_OPERAND (val1, 0);
750           c1 = TREE_OPERAND (val1, 1);
751           if (tree_int_cst_sgn (c1) == -1)
752             {
753               if (is_negative_overflow_infinity (c1))
754                 return -2;
755               c1 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c1), c1);
756               if (!c1)
757                 return -2;
758               code1 = code1 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
759             }
760         }
761
762       if (TREE_CODE (val2) == SSA_NAME)
763         {
764           code2 = SSA_NAME;
765           n2 = val2;
766           c2 = NULL_TREE;
767         }
768       else
769         {
770           code2 = TREE_CODE (val2);
771           n2 = TREE_OPERAND (val2, 0);
772           c2 = TREE_OPERAND (val2, 1);
773           if (tree_int_cst_sgn (c2) == -1)
774             {
775               if (is_negative_overflow_infinity (c2))
776                 return -2;
777               c2 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c2), c2);
778               if (!c2)
779                 return -2;
780               code2 = code2 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
781             }
782         }
783
784       /* Both values must use the same name.  */
785       if (n1 != n2)
786         return -2;
787
788       if (code1 == SSA_NAME
789           && code2 == SSA_NAME)
790         /* NAME == NAME  */
791         return 0;
792
793       /* If overflow is defined we cannot simplify more.  */
794       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
795         return -2;
796
797       if (strict_overflow_p != NULL)
798         *strict_overflow_p = true;
799
800       if (code1 == SSA_NAME)
801         {
802           if (code2 == PLUS_EXPR)
803             /* NAME < NAME + CST  */
804             return -1;
805           else if (code2 == MINUS_EXPR)
806             /* NAME > NAME - CST  */
807             return 1;
808         }
809       else if (code1 == PLUS_EXPR)
810         {
811           if (code2 == SSA_NAME)
812             /* NAME + CST > NAME  */
813             return 1;
814           else if (code2 == PLUS_EXPR)
815             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
816             return compare_values_warnv (c1, c2, strict_overflow_p);
817           else if (code2 == MINUS_EXPR)
818             /* NAME + CST1 > NAME - CST2  */
819             return 1;
820         }
821       else if (code1 == MINUS_EXPR)
822         {
823           if (code2 == SSA_NAME)
824             /* NAME - CST < NAME  */
825             return -1;
826           else if (code2 == PLUS_EXPR)
827             /* NAME - CST1 < NAME + CST2  */
828             return -1;
829           else if (code2 == MINUS_EXPR)
830             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
831                C1 and C2 are swapped in the call to compare_values.  */
832             return compare_values_warnv (c2, c1, strict_overflow_p);
833         }
834
835       gcc_unreachable ();
836     }
837
838   /* We cannot compare non-constants.  */
839   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
840     return -2;
841
842   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
843     {
844       /* We cannot compare overflowed values, except for overflow
845          infinities.  */
846       if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
847         {
848           if (strict_overflow_p != NULL)
849             *strict_overflow_p = true;
850           if (is_negative_overflow_infinity (val1))
851             return is_negative_overflow_infinity (val2) ? 0 : -1;
852           else if (is_negative_overflow_infinity (val2))
853             return 1;
854           else if (is_positive_overflow_infinity (val1))
855             return is_positive_overflow_infinity (val2) ? 0 : 1;
856           else if (is_positive_overflow_infinity (val2))
857             return -1;
858           return -2;
859         }
860
861       return tree_int_cst_compare (val1, val2);
862     }
863   else
864     {
865       tree t;
866
867       /* First see if VAL1 and VAL2 are not the same.  */
868       if (val1 == val2 || operand_equal_p (val1, val2, 0))
869         return 0;
870       
871       /* If VAL1 is a lower address than VAL2, return -1.  */
872       if (operand_less_p (val1, val2) == 1)
873         return -1;
874
875       /* If VAL1 is a higher address than VAL2, return +1.  */
876       if (operand_less_p (val2, val1) == 1)
877         return 1;
878
879       /* If VAL1 is different than VAL2, return +2.
880          For integer constants we either have already returned -1 or 1
881          or they are equivalent.  We still might succeed in proving
882          something about non-trivial operands.  */
883       if (TREE_CODE (val1) != INTEGER_CST
884           || TREE_CODE (val2) != INTEGER_CST)
885         {
886           t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
887           if (t && tree_expr_nonzero_p (t))
888             return 2;
889         }
890
891       return -2;
892     }
893 }
894
895 /* Compare values like compare_values_warnv, but treat comparisons of
896    nonconstants which rely on undefined overflow as incomparable.  */
897
898 static int
899 compare_values (tree val1, tree val2)
900 {
901   bool sop;
902   int ret;
903
904   sop = false;
905   ret = compare_values_warnv (val1, val2, &sop);
906   if (sop
907       && (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2)))
908     ret = -2;
909   return ret;
910 }
911
912
913 /* Return 1 if VAL is inside value range VR (VR->MIN <= VAL <= VR->MAX),
914           0 if VAL is not inside VR,
915          -2 if we cannot tell either way.
916
917    FIXME, the current semantics of this functions are a bit quirky
918           when taken in the context of VRP.  In here we do not care
919           about VR's type.  If VR is the anti-range ~[3, 5] the call
920           value_inside_range (4, VR) will return 1.
921
922           This is counter-intuitive in a strict sense, but the callers
923           currently expect this.  They are calling the function
924           merely to determine whether VR->MIN <= VAL <= VR->MAX.  The
925           callers are applying the VR_RANGE/VR_ANTI_RANGE semantics
926           themselves.
927
928           This also applies to value_ranges_intersect_p and
929           range_includes_zero_p.  The semantics of VR_RANGE and
930           VR_ANTI_RANGE should be encoded here, but that also means
931           adapting the users of these functions to the new semantics.  
932
933    Benchmark compile/20001226-1.c compilation time after changing this
934    function.  */
935
936 static inline int
937 value_inside_range (tree val, value_range_t * vr)
938 {
939   int cmp1, cmp2;
940
941   cmp1 = operand_less_p (val, vr->min);
942   if (cmp1 == -2)
943     return -2;
944   if (cmp1 == 1)
945     return 0;
946
947   cmp2 = operand_less_p (vr->max, val);
948   if (cmp2 == -2)
949     return -2;
950
951   return !cmp2;
952 }
953
954
955 /* Return true if value ranges VR0 and VR1 have a non-empty
956    intersection.  
957    
958    Benchmark compile/20001226-1.c compilation time after changing this
959    function.
960    */
961
962 static inline bool
963 value_ranges_intersect_p (value_range_t *vr0, value_range_t *vr1)
964 {
965   /* The value ranges do not intersect if the maximum of the first range is
966      less than the minimum of the second range or vice versa.
967      When those relations are unknown, we can't do any better.  */
968   if (operand_less_p (vr0->max, vr1->min) != 0)
969     return false;
970   if (operand_less_p (vr1->max, vr0->min) != 0)
971     return false;
972   return true;
973 }
974
975
976 /* Return true if VR includes the value zero, false otherwise.  FIXME,
977    currently this will return false for an anti-range like ~[-4, 3].
978    This will be wrong when the semantics of value_inside_range are
979    modified (currently the users of this function expect these
980    semantics).  */
981
982 static inline bool
983 range_includes_zero_p (value_range_t *vr)
984 {
985   tree zero;
986
987   gcc_assert (vr->type != VR_UNDEFINED
988               && vr->type != VR_VARYING
989               && !symbolic_range_p (vr));
990
991   zero = build_int_cst (TREE_TYPE (vr->min), 0);
992   return (value_inside_range (zero, vr) == 1);
993 }
994
995 /* Return true if T, an SSA_NAME, is known to be nonnegative.  Return
996    false otherwise or if no value range information is available.  */
997
998 bool
999 ssa_name_nonnegative_p (tree t)
1000 {
1001   value_range_t *vr = get_value_range (t);
1002
1003   if (!vr)
1004     return false;
1005
1006   /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1007      which would return a useful value should be encoded as a VR_RANGE.  */
1008   if (vr->type == VR_RANGE)
1009     {
1010       int result = compare_values (vr->min, integer_zero_node);
1011
1012       return (result == 0 || result == 1);
1013     }
1014   return false;
1015 }
1016
1017 /* Return true if T, an SSA_NAME, is known to be nonzero.  Return
1018    false otherwise or if no value range information is available.  */
1019
1020 bool
1021 ssa_name_nonzero_p (tree t)
1022 {
1023   value_range_t *vr = get_value_range (t);
1024
1025   if (!vr)
1026     return false;
1027
1028   /* A VR_RANGE which does not include zero is a nonzero value.  */
1029   if (vr->type == VR_RANGE && !symbolic_range_p (vr))
1030     return ! range_includes_zero_p (vr);
1031
1032   /* A VR_ANTI_RANGE which does include zero is a nonzero value.  */
1033   if (vr->type == VR_ANTI_RANGE && !symbolic_range_p (vr))
1034     return range_includes_zero_p (vr);
1035
1036   return false;
1037 }
1038
1039
1040 /* Extract value range information from an ASSERT_EXPR EXPR and store
1041    it in *VR_P.  */
1042
1043 static void
1044 extract_range_from_assert (value_range_t *vr_p, tree expr)
1045 {
1046   tree var, cond, limit, min, max, type;
1047   value_range_t *var_vr, *limit_vr;
1048   enum tree_code cond_code;
1049
1050   var = ASSERT_EXPR_VAR (expr);
1051   cond = ASSERT_EXPR_COND (expr);
1052
1053   gcc_assert (COMPARISON_CLASS_P (cond));
1054
1055   /* Find VAR in the ASSERT_EXPR conditional.  */
1056   if (var == TREE_OPERAND (cond, 0))
1057     {
1058       /* If the predicate is of the form VAR COMP LIMIT, then we just
1059          take LIMIT from the RHS and use the same comparison code.  */
1060       limit = TREE_OPERAND (cond, 1);
1061       cond_code = TREE_CODE (cond);
1062     }
1063   else
1064     {
1065       /* If the predicate is of the form LIMIT COMP VAR, then we need
1066          to flip around the comparison code to create the proper range
1067          for VAR.  */
1068       limit = TREE_OPERAND (cond, 0);
1069       cond_code = swap_tree_comparison (TREE_CODE (cond));
1070     }
1071
1072   type = TREE_TYPE (limit);
1073   gcc_assert (limit != var);
1074
1075   /* For pointer arithmetic, we only keep track of pointer equality
1076      and inequality.  */
1077   if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1078     {
1079       set_value_range_to_varying (vr_p);
1080       return;
1081     }
1082
1083   /* If LIMIT is another SSA name and LIMIT has a range of its own,
1084      try to use LIMIT's range to avoid creating symbolic ranges
1085      unnecessarily. */
1086   limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1087
1088   /* LIMIT's range is only interesting if it has any useful information.  */
1089   if (limit_vr
1090       && (limit_vr->type == VR_UNDEFINED
1091           || limit_vr->type == VR_VARYING
1092           || symbolic_range_p (limit_vr)))
1093     limit_vr = NULL;
1094
1095   /* Initially, the new range has the same set of equivalences of
1096      VAR's range.  This will be revised before returning the final
1097      value.  Since assertions may be chained via mutually exclusive
1098      predicates, we will need to trim the set of equivalences before
1099      we are done.  */
1100   gcc_assert (vr_p->equiv == NULL);
1101   add_equivalence (&vr_p->equiv, var);
1102
1103   /* Extract a new range based on the asserted comparison for VAR and
1104      LIMIT's value range.  Notice that if LIMIT has an anti-range, we
1105      will only use it for equality comparisons (EQ_EXPR).  For any
1106      other kind of assertion, we cannot derive a range from LIMIT's
1107      anti-range that can be used to describe the new range.  For
1108      instance, ASSERT_EXPR <x_2, x_2 <= b_4>.  If b_4 is ~[2, 10],
1109      then b_4 takes on the ranges [-INF, 1] and [11, +INF].  There is
1110      no single range for x_2 that could describe LE_EXPR, so we might
1111      as well build the range [b_4, +INF] for it.  */
1112   if (cond_code == EQ_EXPR)
1113     {
1114       enum value_range_type range_type;
1115
1116       if (limit_vr)
1117         {
1118           range_type = limit_vr->type;
1119           min = limit_vr->min;
1120           max = limit_vr->max;
1121         }
1122       else
1123         {
1124           range_type = VR_RANGE;
1125           min = limit;
1126           max = limit;
1127         }
1128
1129       set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1130
1131       /* When asserting the equality VAR == LIMIT and LIMIT is another
1132          SSA name, the new range will also inherit the equivalence set
1133          from LIMIT.  */
1134       if (TREE_CODE (limit) == SSA_NAME)
1135         add_equivalence (&vr_p->equiv, limit);
1136     }
1137   else if (cond_code == NE_EXPR)
1138     {
1139       /* As described above, when LIMIT's range is an anti-range and
1140          this assertion is an inequality (NE_EXPR), then we cannot
1141          derive anything from the anti-range.  For instance, if
1142          LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1143          not imply that VAR's range is [0, 0].  So, in the case of
1144          anti-ranges, we just assert the inequality using LIMIT and
1145          not its anti-range.
1146
1147          If LIMIT_VR is a range, we can only use it to build a new
1148          anti-range if LIMIT_VR is a single-valued range.  For
1149          instance, if LIMIT_VR is [0, 1], the predicate
1150          VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1151          Rather, it means that for value 0 VAR should be ~[0, 0]
1152          and for value 1, VAR should be ~[1, 1].  We cannot
1153          represent these ranges.
1154
1155          The only situation in which we can build a valid
1156          anti-range is when LIMIT_VR is a single-valued range
1157          (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX).  In that case, 
1158          build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX].  */
1159       if (limit_vr
1160           && limit_vr->type == VR_RANGE
1161           && compare_values (limit_vr->min, limit_vr->max) == 0)
1162         {
1163           min = limit_vr->min;
1164           max = limit_vr->max;
1165         }
1166       else
1167         {
1168           /* In any other case, we cannot use LIMIT's range to build a
1169              valid anti-range.  */
1170           min = max = limit;
1171         }
1172
1173       /* If MIN and MAX cover the whole range for their type, then
1174          just use the original LIMIT.  */
1175       if (INTEGRAL_TYPE_P (type)
1176           && (min == TYPE_MIN_VALUE (type)
1177               || is_negative_overflow_infinity (min))
1178           && (max == TYPE_MAX_VALUE (type)
1179               || is_positive_overflow_infinity (max)))
1180         min = max = limit;
1181
1182       set_value_range (vr_p, VR_ANTI_RANGE, min, max, vr_p->equiv);
1183     }
1184   else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1185     {
1186       min = TYPE_MIN_VALUE (type);
1187
1188       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1189         max = limit;
1190       else
1191         {
1192           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1193              range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1194              LT_EXPR.  */
1195           max = limit_vr->max;
1196         }
1197
1198       /* If the maximum value forces us to be out of bounds, simply punt.
1199          It would be pointless to try and do anything more since this
1200          all should be optimized away above us.  */
1201       if ((cond_code == LT_EXPR
1202            && compare_values (max, min) == 0)
1203           || is_overflow_infinity (max))
1204         set_value_range_to_varying (vr_p);
1205       else
1206         {
1207           /* For LT_EXPR, we create the range [MIN, MAX - 1].  */
1208           if (cond_code == LT_EXPR)
1209             {
1210               tree one = build_int_cst (type, 1);
1211               max = fold_build2 (MINUS_EXPR, type, max, one);
1212             }
1213
1214           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1215         }
1216     }
1217   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1218     {
1219       max = TYPE_MAX_VALUE (type);
1220
1221       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1222         min = limit;
1223       else
1224         {
1225           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1226              range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1227              GT_EXPR.  */
1228           min = limit_vr->min;
1229         }
1230
1231       /* If the minimum value forces us to be out of bounds, simply punt.
1232          It would be pointless to try and do anything more since this
1233          all should be optimized away above us.  */
1234       if ((cond_code == GT_EXPR
1235            && compare_values (min, max) == 0)
1236           || is_overflow_infinity (min))
1237         set_value_range_to_varying (vr_p);
1238       else
1239         {
1240           /* For GT_EXPR, we create the range [MIN + 1, MAX].  */
1241           if (cond_code == GT_EXPR)
1242             {
1243               tree one = build_int_cst (type, 1);
1244               min = fold_build2 (PLUS_EXPR, type, min, one);
1245             }
1246
1247           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1248         }
1249     }
1250   else
1251     gcc_unreachable ();
1252
1253   /* If VAR already had a known range, it may happen that the new
1254      range we have computed and VAR's range are not compatible.  For
1255      instance,
1256
1257         if (p_5 == NULL)
1258           p_6 = ASSERT_EXPR <p_5, p_5 == NULL>;
1259           x_7 = p_6->fld;
1260           p_8 = ASSERT_EXPR <p_6, p_6 != NULL>;
1261
1262      While the above comes from a faulty program, it will cause an ICE
1263      later because p_8 and p_6 will have incompatible ranges and at
1264      the same time will be considered equivalent.  A similar situation
1265      would arise from
1266
1267         if (i_5 > 10)
1268           i_6 = ASSERT_EXPR <i_5, i_5 > 10>;
1269           if (i_5 < 5)
1270             i_7 = ASSERT_EXPR <i_6, i_6 < 5>;
1271
1272      Again i_6 and i_7 will have incompatible ranges.  It would be
1273      pointless to try and do anything with i_7's range because
1274      anything dominated by 'if (i_5 < 5)' will be optimized away.
1275      Note, due to the wa in which simulation proceeds, the statement
1276      i_7 = ASSERT_EXPR <...> we would never be visited because the
1277      conditional 'if (i_5 < 5)' always evaluates to false.  However,
1278      this extra check does not hurt and may protect against future
1279      changes to VRP that may get into a situation similar to the
1280      NULL pointer dereference example.
1281
1282      Note that these compatibility tests are only needed when dealing
1283      with ranges or a mix of range and anti-range.  If VAR_VR and VR_P
1284      are both anti-ranges, they will always be compatible, because two
1285      anti-ranges will always have a non-empty intersection.  */
1286
1287   var_vr = get_value_range (var);
1288
1289   /* We may need to make adjustments when VR_P and VAR_VR are numeric
1290      ranges or anti-ranges.  */
1291   if (vr_p->type == VR_VARYING
1292       || vr_p->type == VR_UNDEFINED
1293       || var_vr->type == VR_VARYING
1294       || var_vr->type == VR_UNDEFINED
1295       || symbolic_range_p (vr_p)
1296       || symbolic_range_p (var_vr))
1297     return;
1298
1299   if (var_vr->type == VR_RANGE && vr_p->type == VR_RANGE)
1300     {
1301       /* If the two ranges have a non-empty intersection, we can
1302          refine the resulting range.  Since the assert expression
1303          creates an equivalency and at the same time it asserts a
1304          predicate, we can take the intersection of the two ranges to
1305          get better precision.  */
1306       if (value_ranges_intersect_p (var_vr, vr_p))
1307         {
1308           /* Use the larger of the two minimums.  */
1309           if (compare_values (vr_p->min, var_vr->min) == -1)
1310             min = var_vr->min;
1311           else
1312             min = vr_p->min;
1313
1314           /* Use the smaller of the two maximums.  */
1315           if (compare_values (vr_p->max, var_vr->max) == 1)
1316             max = var_vr->max;
1317           else
1318             max = vr_p->max;
1319
1320           set_value_range (vr_p, vr_p->type, min, max, vr_p->equiv);
1321         }
1322       else
1323         {
1324           /* The two ranges do not intersect, set the new range to
1325              VARYING, because we will not be able to do anything
1326              meaningful with it.  */
1327           set_value_range_to_varying (vr_p);
1328         }
1329     }
1330   else if ((var_vr->type == VR_RANGE && vr_p->type == VR_ANTI_RANGE)
1331            || (var_vr->type == VR_ANTI_RANGE && vr_p->type == VR_RANGE))
1332     {
1333       /* A range and an anti-range will cancel each other only if
1334          their ends are the same.  For instance, in the example above,
1335          p_8's range ~[0, 0] and p_6's range [0, 0] are incompatible,
1336          so VR_P should be set to VR_VARYING.  */
1337       if (compare_values (var_vr->min, vr_p->min) == 0
1338           && compare_values (var_vr->max, vr_p->max) == 0)
1339         set_value_range_to_varying (vr_p);
1340       else
1341         {
1342           tree min, max, anti_min, anti_max, real_min, real_max;
1343           int cmp;
1344
1345           /* We want to compute the logical AND of the two ranges;
1346              there are three cases to consider.
1347
1348
1349              1. The VR_ANTI_RANGE range is completely within the 
1350                 VR_RANGE and the endpoints of the ranges are
1351                 different.  In that case the resulting range
1352                 should be whichever range is more precise.
1353                 Typically that will be the VR_RANGE.
1354
1355              2. The VR_ANTI_RANGE is completely disjoint from
1356                 the VR_RANGE.  In this case the resulting range
1357                 should be the VR_RANGE.
1358
1359              3. There is some overlap between the VR_ANTI_RANGE
1360                 and the VR_RANGE.
1361
1362                 3a. If the high limit of the VR_ANTI_RANGE resides
1363                     within the VR_RANGE, then the result is a new
1364                     VR_RANGE starting at the high limit of the
1365                     the VR_ANTI_RANGE + 1 and extending to the
1366                     high limit of the original VR_RANGE.
1367
1368                 3b. If the low limit of the VR_ANTI_RANGE resides
1369                     within the VR_RANGE, then the result is a new
1370                     VR_RANGE starting at the low limit of the original
1371                     VR_RANGE and extending to the low limit of the
1372                     VR_ANTI_RANGE - 1.  */
1373           if (vr_p->type == VR_ANTI_RANGE)
1374             {
1375               anti_min = vr_p->min;
1376               anti_max = vr_p->max;
1377               real_min = var_vr->min;
1378               real_max = var_vr->max;
1379             }
1380           else
1381             {
1382               anti_min = var_vr->min;
1383               anti_max = var_vr->max;
1384               real_min = vr_p->min;
1385               real_max = vr_p->max;
1386             }
1387
1388
1389           /* Case 1, VR_ANTI_RANGE completely within VR_RANGE,
1390              not including any endpoints.  */
1391           if (compare_values (anti_max, real_max) == -1
1392               && compare_values (anti_min, real_min) == 1)
1393             {
1394               set_value_range (vr_p, VR_RANGE, real_min,
1395                                real_max, vr_p->equiv);
1396             }
1397           /* Case 2, VR_ANTI_RANGE completely disjoint from
1398              VR_RANGE.  */
1399           else if (compare_values (anti_min, real_max) == 1
1400                    || compare_values (anti_max, real_min) == -1)
1401             {
1402               set_value_range (vr_p, VR_RANGE, real_min,
1403                                real_max, vr_p->equiv);
1404             }
1405           /* Case 3a, the anti-range extends into the low
1406              part of the real range.  Thus creating a new
1407              low for the real range.  */
1408           else if (((cmp = compare_values (anti_max, real_min)) == 1
1409                     || cmp == 0)
1410                    && compare_values (anti_max, real_max) == -1)
1411             {
1412               gcc_assert (!is_positive_overflow_infinity (anti_max));
1413               if (needs_overflow_infinity (TREE_TYPE (anti_max))
1414                   && anti_max == TYPE_MAX_VALUE (TREE_TYPE (anti_max)))
1415                 {
1416                   if (!supports_overflow_infinity (TREE_TYPE (var_vr->min)))
1417                     {
1418                       set_value_range_to_varying (vr_p);
1419                       return;
1420                     }
1421                   min = positive_overflow_infinity (TREE_TYPE (var_vr->min));
1422                 }
1423               else
1424                 min = fold_build2 (PLUS_EXPR, TREE_TYPE (var_vr->min),
1425                                    anti_max,
1426                                    build_int_cst (TREE_TYPE (var_vr->min), 1));
1427               max = real_max;
1428               set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1429             }
1430           /* Case 3b, the anti-range extends into the high
1431              part of the real range.  Thus creating a new
1432              higher for the real range.  */
1433           else if (compare_values (anti_min, real_min) == 1
1434                    && ((cmp = compare_values (anti_min, real_max)) == -1
1435                        || cmp == 0))
1436             {
1437               gcc_assert (!is_negative_overflow_infinity (anti_min));
1438               if (needs_overflow_infinity (TREE_TYPE (anti_min))
1439                   && anti_min == TYPE_MIN_VALUE (TREE_TYPE (anti_min)))
1440                 {
1441                   if (!supports_overflow_infinity (TREE_TYPE (var_vr->min)))
1442                     {
1443                       set_value_range_to_varying (vr_p);
1444                       return;
1445                     }
1446                   max = negative_overflow_infinity (TREE_TYPE (var_vr->min));
1447                 }
1448               else
1449                 max = fold_build2 (MINUS_EXPR, TREE_TYPE (var_vr->min),
1450                                    anti_min,
1451                                    build_int_cst (TREE_TYPE (var_vr->min), 1));
1452               min = real_min;
1453               set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1454             }
1455         }
1456     }
1457 }
1458
1459
1460 /* Extract range information from SSA name VAR and store it in VR.  If
1461    VAR has an interesting range, use it.  Otherwise, create the
1462    range [VAR, VAR] and return it.  This is useful in situations where
1463    we may have conditionals testing values of VARYING names.  For
1464    instance,
1465
1466         x_3 = y_5;
1467         if (x_3 > y_5)
1468           ...
1469
1470     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1471     always false.  */
1472
1473 static void
1474 extract_range_from_ssa_name (value_range_t *vr, tree var)
1475 {
1476   value_range_t *var_vr = get_value_range (var);
1477
1478   if (var_vr->type != VR_UNDEFINED && var_vr->type != VR_VARYING)
1479     copy_value_range (vr, var_vr);
1480   else
1481     set_value_range (vr, VR_RANGE, var, var, NULL);
1482
1483   add_equivalence (&vr->equiv, var);
1484 }
1485
1486
1487 /* Wrapper around int_const_binop.  If the operation overflows and we
1488    are not using wrapping arithmetic, then adjust the result to be
1489    -INF or +INF depending on CODE, VAL1 and VAL2.  This can return
1490    NULL_TREE if we need to use an overflow infinity representation but
1491    the type does not support it.  */
1492
1493 static tree
1494 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
1495 {
1496   tree res;
1497
1498   res = int_const_binop (code, val1, val2, 0);
1499
1500   /* If we are not using wrapping arithmetic, operate symbolically
1501      on -INF and +INF.  */
1502   if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (val1)))
1503     {
1504       int checkz = compare_values (res, val1);
1505       bool overflow = false;
1506
1507       /* Ensure that res = val1 [+*] val2 >= val1
1508          or that res = val1 - val2 <= val1.  */
1509       if ((code == PLUS_EXPR
1510            && !(checkz == 1 || checkz == 0))
1511           || (code == MINUS_EXPR
1512               && !(checkz == 0 || checkz == -1)))
1513         {
1514           overflow = true;
1515         }
1516       /* Checking for multiplication overflow is done by dividing the
1517          output of the multiplication by the first input of the
1518          multiplication.  If the result of that division operation is
1519          not equal to the second input of the multiplication, then the
1520          multiplication overflowed.  */
1521       else if (code == MULT_EXPR && !integer_zerop (val1))
1522         {
1523           tree tmp = int_const_binop (TRUNC_DIV_EXPR,
1524                                       res,
1525                                       val1, 0);
1526           int check = compare_values (tmp, val2);
1527
1528           if (check != 0)
1529             overflow = true;
1530         }
1531
1532       if (overflow)
1533         {
1534           res = copy_node (res);
1535           TREE_OVERFLOW (res) = 1;
1536         }
1537
1538     }
1539   else if ((TREE_OVERFLOW (res)
1540             && !TREE_OVERFLOW (val1)
1541             && !TREE_OVERFLOW (val2))
1542            || is_overflow_infinity (val1)
1543            || is_overflow_infinity (val2))
1544     {
1545       /* If the operation overflowed but neither VAL1 nor VAL2 are
1546          overflown, return -INF or +INF depending on the operation
1547          and the combination of signs of the operands.  */
1548       int sgn1 = tree_int_cst_sgn (val1);
1549       int sgn2 = tree_int_cst_sgn (val2);
1550
1551       if (needs_overflow_infinity (TREE_TYPE (res))
1552           && !supports_overflow_infinity (TREE_TYPE (res)))
1553         return NULL_TREE;
1554
1555       /* We have to punt on adding infinities of different signs,
1556          since we can't tell what the sign of the result should be.
1557          Likewise for subtracting infinities of the same sign.  */
1558       if (((code == PLUS_EXPR && sgn1 != sgn2)
1559            || (code == MINUS_EXPR && sgn1 == sgn2))
1560           && is_overflow_infinity (val1)
1561           && is_overflow_infinity (val2))
1562         return NULL_TREE;
1563
1564       /* Don't try to handle division or shifting of infinities.  */
1565       if ((code == TRUNC_DIV_EXPR
1566            || code == FLOOR_DIV_EXPR
1567            || code == CEIL_DIV_EXPR
1568            || code == EXACT_DIV_EXPR
1569            || code == ROUND_DIV_EXPR
1570            || code == RSHIFT_EXPR)
1571           && (is_overflow_infinity (val1)
1572               || is_overflow_infinity (val2)))
1573         return NULL_TREE;
1574
1575       /* Notice that we only need to handle the restricted set of
1576          operations handled by extract_range_from_binary_expr.
1577          Among them, only multiplication, addition and subtraction
1578          can yield overflow without overflown operands because we
1579          are working with integral types only... except in the
1580          case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1581          for division too.  */
1582
1583       /* For multiplication, the sign of the overflow is given
1584          by the comparison of the signs of the operands.  */
1585       if ((code == MULT_EXPR && sgn1 == sgn2)
1586           /* For addition, the operands must be of the same sign
1587              to yield an overflow.  Its sign is therefore that
1588              of one of the operands, for example the first.  For
1589              infinite operands X + -INF is negative, not positive.  */
1590           || (code == PLUS_EXPR
1591               && (sgn1 >= 0
1592                   ? !is_negative_overflow_infinity (val2)
1593                   : is_positive_overflow_infinity (val2)))
1594           /* For subtraction, non-infinite operands must be of
1595              different signs to yield an overflow.  Its sign is
1596              therefore that of the first operand or the opposite of
1597              that of the second operand.  A first operand of 0 counts
1598              as positive here, for the corner case 0 - (-INF), which
1599              overflows, but must yield +INF.  For infinite operands 0
1600              - INF is negative, not positive.  */
1601           || (code == MINUS_EXPR
1602               && (sgn1 >= 0
1603                   ? !is_positive_overflow_infinity (val2)
1604                   : is_negative_overflow_infinity (val2)))
1605           /* We only get in here with positive shift count, so the
1606              overflow direction is the same as the sign of val1.
1607              Actually rshift does not overflow at all, but we only
1608              handle the case of shifting overflowed -INF and +INF.  */
1609           || (code == RSHIFT_EXPR
1610               && sgn1 >= 0)
1611           /* For division, the only case is -INF / -1 = +INF.  */
1612           || code == TRUNC_DIV_EXPR
1613           || code == FLOOR_DIV_EXPR
1614           || code == CEIL_DIV_EXPR
1615           || code == EXACT_DIV_EXPR
1616           || code == ROUND_DIV_EXPR)
1617         return (needs_overflow_infinity (TREE_TYPE (res))
1618                 ? positive_overflow_infinity (TREE_TYPE (res))
1619                 : TYPE_MAX_VALUE (TREE_TYPE (res)));
1620       else
1621         return (needs_overflow_infinity (TREE_TYPE (res))
1622                 ? negative_overflow_infinity (TREE_TYPE (res))
1623                 : TYPE_MIN_VALUE (TREE_TYPE (res)));
1624     }
1625
1626   return res;
1627 }
1628
1629
1630 /* Extract range information from a binary expression EXPR based on
1631    the ranges of each of its operands and the expression code.  */
1632
1633 static void
1634 extract_range_from_binary_expr (value_range_t *vr, tree expr)
1635 {
1636   enum tree_code code = TREE_CODE (expr);
1637   enum value_range_type type;
1638   tree op0, op1, min, max;
1639   int cmp;
1640   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
1641   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
1642
1643   /* Not all binary expressions can be applied to ranges in a
1644      meaningful way.  Handle only arithmetic operations.  */
1645   if (code != PLUS_EXPR
1646       && code != MINUS_EXPR
1647       && code != MULT_EXPR
1648       && code != TRUNC_DIV_EXPR
1649       && code != FLOOR_DIV_EXPR
1650       && code != CEIL_DIV_EXPR
1651       && code != EXACT_DIV_EXPR
1652       && code != ROUND_DIV_EXPR
1653       && code != RSHIFT_EXPR
1654       && code != MIN_EXPR
1655       && code != MAX_EXPR
1656       && code != BIT_AND_EXPR
1657       && code != TRUTH_ANDIF_EXPR
1658       && code != TRUTH_ORIF_EXPR
1659       && code != TRUTH_AND_EXPR
1660       && code != TRUTH_OR_EXPR)
1661     {
1662       set_value_range_to_varying (vr);
1663       return;
1664     }
1665
1666   /* Get value ranges for each operand.  For constant operands, create
1667      a new value range with the operand to simplify processing.  */
1668   op0 = TREE_OPERAND (expr, 0);
1669   if (TREE_CODE (op0) == SSA_NAME)
1670     vr0 = *(get_value_range (op0));
1671   else if (is_gimple_min_invariant (op0))
1672     set_value_range_to_value (&vr0, op0);
1673   else
1674     set_value_range_to_varying (&vr0);
1675
1676   op1 = TREE_OPERAND (expr, 1);
1677   if (TREE_CODE (op1) == SSA_NAME)
1678     vr1 = *(get_value_range (op1));
1679   else if (is_gimple_min_invariant (op1))
1680     set_value_range_to_value (&vr1, op1);
1681   else
1682     set_value_range_to_varying (&vr1);
1683
1684   /* If either range is UNDEFINED, so is the result.  */
1685   if (vr0.type == VR_UNDEFINED || vr1.type == VR_UNDEFINED)
1686     {
1687       set_value_range_to_undefined (vr);
1688       return;
1689     }
1690
1691   /* The type of the resulting value range defaults to VR0.TYPE.  */
1692   type = vr0.type;
1693
1694   /* Refuse to operate on VARYING ranges, ranges of different kinds
1695      and symbolic ranges.  As an exception, we allow BIT_AND_EXPR
1696      because we may be able to derive a useful range even if one of
1697      the operands is VR_VARYING or symbolic range.  TODO, we may be
1698      able to derive anti-ranges in some cases.  */
1699   if (code != BIT_AND_EXPR
1700       && code != TRUTH_AND_EXPR
1701       && code != TRUTH_OR_EXPR
1702       && (vr0.type == VR_VARYING
1703           || vr1.type == VR_VARYING
1704           || vr0.type != vr1.type
1705           || symbolic_range_p (&vr0)
1706           || symbolic_range_p (&vr1)))
1707     {
1708       set_value_range_to_varying (vr);
1709       return;
1710     }
1711
1712   /* Now evaluate the expression to determine the new range.  */
1713   if (POINTER_TYPE_P (TREE_TYPE (expr))
1714       || POINTER_TYPE_P (TREE_TYPE (op0))
1715       || POINTER_TYPE_P (TREE_TYPE (op1)))
1716     {
1717       /* For pointer types, we are really only interested in asserting
1718          whether the expression evaluates to non-NULL.  FIXME, we used
1719          to gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR), but
1720          ivopts is generating expressions with pointer multiplication
1721          in them.  */
1722       if (code == PLUS_EXPR)
1723         {
1724           if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
1725             set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1726           else if (range_is_null (&vr0) && range_is_null (&vr1))
1727             set_value_range_to_null (vr, TREE_TYPE (expr));
1728           else
1729             set_value_range_to_varying (vr);
1730         }
1731       else
1732         {
1733           /* Subtracting from a pointer, may yield 0, so just drop the
1734              resulting range to varying.  */
1735           set_value_range_to_varying (vr);
1736         }
1737
1738       return;
1739     }
1740
1741   /* For integer ranges, apply the operation to each end of the
1742      range and see what we end up with.  */
1743   if (code == TRUTH_ANDIF_EXPR
1744       || code == TRUTH_ORIF_EXPR
1745       || code == TRUTH_AND_EXPR
1746       || code == TRUTH_OR_EXPR)
1747     {
1748       /* If one of the operands is zero, we know that the whole
1749          expression evaluates zero.  */
1750       if (code == TRUTH_AND_EXPR
1751           && ((vr0.type == VR_RANGE
1752                && integer_zerop (vr0.min)
1753                && integer_zerop (vr0.max))
1754               || (vr1.type == VR_RANGE
1755                   && integer_zerop (vr1.min)
1756                   && integer_zerop (vr1.max))))
1757         {
1758           type = VR_RANGE;
1759           min = max = build_int_cst (TREE_TYPE (expr), 0);
1760         }
1761       /* If one of the operands is one, we know that the whole
1762          expression evaluates one.  */
1763       else if (code == TRUTH_OR_EXPR
1764                && ((vr0.type == VR_RANGE
1765                     && integer_onep (vr0.min)
1766                     && integer_onep (vr0.max))
1767                    || (vr1.type == VR_RANGE
1768                        && integer_onep (vr1.min)
1769                        && integer_onep (vr1.max))))
1770         {
1771           type = VR_RANGE;
1772           min = max = build_int_cst (TREE_TYPE (expr), 1);
1773         }
1774       else if (vr0.type != VR_VARYING
1775                && vr1.type != VR_VARYING
1776                && vr0.type == vr1.type
1777                && !symbolic_range_p (&vr0)
1778                && !overflow_infinity_range_p (&vr0)
1779                && !symbolic_range_p (&vr1)
1780                && !overflow_infinity_range_p (&vr1))
1781         {
1782           /* Boolean expressions cannot be folded with int_const_binop.  */
1783           min = fold_binary (code, TREE_TYPE (expr), vr0.min, vr1.min);
1784           max = fold_binary (code, TREE_TYPE (expr), vr0.max, vr1.max);
1785         }
1786       else
1787         {
1788           /* The result of a TRUTH_*_EXPR is always true or false.  */
1789           set_value_range_to_truthvalue (vr, TREE_TYPE (expr));
1790           return;
1791         }
1792     }
1793   else if (code == PLUS_EXPR
1794            || code == MIN_EXPR
1795            || code == MAX_EXPR)
1796     {
1797       /* If we have a PLUS_EXPR with two VR_ANTI_RANGEs, drop to
1798          VR_VARYING.  It would take more effort to compute a precise
1799          range for such a case.  For example, if we have op0 == 1 and
1800          op1 == -1 with their ranges both being ~[0,0], we would have
1801          op0 + op1 == 0, so we cannot claim that the sum is in ~[0,0].
1802          Note that we are guaranteed to have vr0.type == vr1.type at
1803          this point.  */
1804       if (code == PLUS_EXPR && vr0.type == VR_ANTI_RANGE)
1805         {
1806           set_value_range_to_varying (vr);
1807           return;
1808         }
1809
1810       /* For operations that make the resulting range directly
1811          proportional to the original ranges, apply the operation to
1812          the same end of each range.  */
1813       min = vrp_int_const_binop (code, vr0.min, vr1.min);
1814       max = vrp_int_const_binop (code, vr0.max, vr1.max);
1815     }
1816   else if (code == MULT_EXPR
1817            || code == TRUNC_DIV_EXPR
1818            || code == FLOOR_DIV_EXPR
1819            || code == CEIL_DIV_EXPR
1820            || code == EXACT_DIV_EXPR
1821            || code == ROUND_DIV_EXPR
1822            || code == RSHIFT_EXPR)
1823     {
1824       tree val[4];
1825       size_t i;
1826       bool sop;
1827
1828       /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
1829          drop to VR_VARYING.  It would take more effort to compute a
1830          precise range for such a case.  For example, if we have
1831          op0 == 65536 and op1 == 65536 with their ranges both being
1832          ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
1833          we cannot claim that the product is in ~[0,0].  Note that we
1834          are guaranteed to have vr0.type == vr1.type at this
1835          point.  */
1836       if (code == MULT_EXPR
1837           && vr0.type == VR_ANTI_RANGE
1838           && !TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
1839         {
1840           set_value_range_to_varying (vr);
1841           return;
1842         }
1843
1844       /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
1845          then drop to VR_VARYING.  Outside of this range we get undefined
1846          behavior from the shift operation.  We cannot even trust
1847          SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
1848          shifts, and the operation at the tree level may be widened.  */
1849       if (code == RSHIFT_EXPR)
1850         {
1851           if (vr1.type == VR_ANTI_RANGE
1852               || !vrp_expr_computes_nonnegative (op1, &sop)
1853               || (operand_less_p
1854                   (build_int_cst (TREE_TYPE (vr1.max),
1855                                   TYPE_PRECISION (TREE_TYPE (expr)) - 1),
1856                    vr1.max) != 0))
1857             {
1858               set_value_range_to_varying (vr);
1859               return;
1860             }
1861         }
1862
1863       /* Multiplications and divisions are a bit tricky to handle,
1864          depending on the mix of signs we have in the two ranges, we
1865          need to operate on different values to get the minimum and
1866          maximum values for the new range.  One approach is to figure
1867          out all the variations of range combinations and do the
1868          operations.
1869
1870          However, this involves several calls to compare_values and it
1871          is pretty convoluted.  It's simpler to do the 4 operations
1872          (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1873          MAX1) and then figure the smallest and largest values to form
1874          the new range.  */
1875
1876       /* Divisions by zero result in a VARYING value.  */
1877       else if (code != MULT_EXPR
1878                && (vr0.type == VR_ANTI_RANGE || range_includes_zero_p (&vr1)))
1879         {
1880           set_value_range_to_varying (vr);
1881           return;
1882         }
1883
1884       /* Compute the 4 cross operations.  */
1885       sop = false;
1886       val[0] = vrp_int_const_binop (code, vr0.min, vr1.min);
1887       if (val[0] == NULL_TREE)
1888         sop = true;
1889
1890       if (vr1.max == vr1.min)
1891         val[1] = NULL_TREE;
1892       else
1893         {
1894           val[1] = vrp_int_const_binop (code, vr0.min, vr1.max);
1895           if (val[1] == NULL_TREE)
1896             sop = true;
1897         }
1898
1899       if (vr0.max == vr0.min)
1900         val[2] = NULL_TREE;
1901       else
1902         {
1903           val[2] = vrp_int_const_binop (code, vr0.max, vr1.min);
1904           if (val[2] == NULL_TREE)
1905             sop = true;
1906         }
1907
1908       if (vr0.min == vr0.max || vr1.min == vr1.max)
1909         val[3] = NULL_TREE;
1910       else
1911         {
1912           val[3] = vrp_int_const_binop (code, vr0.max, vr1.max);
1913           if (val[3] == NULL_TREE)
1914             sop = true;
1915         }
1916
1917       if (sop)
1918         {
1919           set_value_range_to_varying (vr);
1920           return;
1921         }
1922
1923       /* Set MIN to the minimum of VAL[i] and MAX to the maximum
1924          of VAL[i].  */
1925       min = val[0];
1926       max = val[0];
1927       for (i = 1; i < 4; i++)
1928         {
1929           if (!is_gimple_min_invariant (min)
1930               || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
1931               || !is_gimple_min_invariant (max)
1932               || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
1933             break;
1934
1935           if (val[i])
1936             {
1937               if (!is_gimple_min_invariant (val[i])
1938                   || (TREE_OVERFLOW (val[i])
1939                       && !is_overflow_infinity (val[i])))
1940                 {
1941                   /* If we found an overflowed value, set MIN and MAX
1942                      to it so that we set the resulting range to
1943                      VARYING.  */
1944                   min = max = val[i];
1945                   break;
1946                 }
1947
1948               if (compare_values (val[i], min) == -1)
1949                 min = val[i];
1950
1951               if (compare_values (val[i], max) == 1)
1952                 max = val[i];
1953             }
1954         }
1955     }
1956   else if (code == MINUS_EXPR)
1957     {
1958       /* If we have a MINUS_EXPR with two VR_ANTI_RANGEs, drop to
1959          VR_VARYING.  It would take more effort to compute a precise
1960          range for such a case.  For example, if we have op0 == 1 and
1961          op1 == 1 with their ranges both being ~[0,0], we would have
1962          op0 - op1 == 0, so we cannot claim that the difference is in
1963          ~[0,0].  Note that we are guaranteed to have
1964          vr0.type == vr1.type at this point.  */
1965       if (vr0.type == VR_ANTI_RANGE)
1966         {
1967           set_value_range_to_varying (vr);
1968           return;
1969         }
1970
1971       /* For MINUS_EXPR, apply the operation to the opposite ends of
1972          each range.  */
1973       min = vrp_int_const_binop (code, vr0.min, vr1.max);
1974       max = vrp_int_const_binop (code, vr0.max, vr1.min);
1975     }
1976   else if (code == BIT_AND_EXPR)
1977     {
1978       if (vr0.type == VR_RANGE
1979           && vr0.min == vr0.max
1980           && TREE_CODE (vr0.max) == INTEGER_CST
1981           && !TREE_OVERFLOW (vr0.max)
1982           && tree_int_cst_sgn (vr0.max) >= 0)
1983         {
1984           min = build_int_cst (TREE_TYPE (expr), 0);
1985           max = vr0.max;
1986         }
1987       else if (vr1.type == VR_RANGE
1988                && vr1.min == vr1.max
1989                && TREE_CODE (vr1.max) == INTEGER_CST
1990                && !TREE_OVERFLOW (vr1.max)
1991                && tree_int_cst_sgn (vr1.max) >= 0)
1992         {
1993           type = VR_RANGE;
1994           min = build_int_cst (TREE_TYPE (expr), 0);
1995           max = vr1.max;
1996         }
1997       else
1998         {
1999           set_value_range_to_varying (vr);
2000           return;
2001         }
2002     }
2003   else
2004     gcc_unreachable ();
2005
2006   /* If either MIN or MAX overflowed, then set the resulting range to
2007      VARYING.  But we do accept an overflow infinity
2008      representation.  */
2009   if (min == NULL_TREE
2010       || !is_gimple_min_invariant (min)
2011       || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2012       || max == NULL_TREE
2013       || !is_gimple_min_invariant (max)
2014       || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2015     {
2016       set_value_range_to_varying (vr);
2017       return;
2018     }
2019
2020   /* We punt if:
2021      1) [-INF, +INF]
2022      2) [-INF, +-INF(OVF)]
2023      3) [+-INF(OVF), +INF]
2024      4) [+-INF(OVF), +-INF(OVF)]
2025      We learn nothing when we have INF and INF(OVF) on both sides.
2026      Note that we do accept [-INF, -INF] and [+INF, +INF] without
2027      overflow.  */
2028   if ((min == TYPE_MIN_VALUE (TREE_TYPE (min))
2029        || is_overflow_infinity (min))
2030       && (max == TYPE_MAX_VALUE (TREE_TYPE (max))
2031           || is_overflow_infinity (max)))
2032     {
2033       set_value_range_to_varying (vr);
2034       return;
2035     }
2036
2037   cmp = compare_values (min, max);
2038   if (cmp == -2 || cmp == 1)
2039     {
2040       /* If the new range has its limits swapped around (MIN > MAX),
2041          then the operation caused one of them to wrap around, mark
2042          the new range VARYING.  */
2043       set_value_range_to_varying (vr);
2044     }
2045   else
2046     set_value_range (vr, type, min, max, NULL);
2047 }
2048
2049
2050 /* Extract range information from a unary expression EXPR based on
2051    the range of its operand and the expression code.  */
2052
2053 static void
2054 extract_range_from_unary_expr (value_range_t *vr, tree expr)
2055 {
2056   enum tree_code code = TREE_CODE (expr);
2057   tree min, max, op0;
2058   int cmp;
2059   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2060
2061   /* Refuse to operate on certain unary expressions for which we
2062      cannot easily determine a resulting range.  */
2063   if (code == FIX_TRUNC_EXPR
2064       || code == FLOAT_EXPR
2065       || code == BIT_NOT_EXPR
2066       || code == NON_LVALUE_EXPR
2067       || code == CONJ_EXPR)
2068     {
2069       set_value_range_to_varying (vr);
2070       return;
2071     }
2072
2073   /* Get value ranges for the operand.  For constant operands, create
2074      a new value range with the operand to simplify processing.  */
2075   op0 = TREE_OPERAND (expr, 0);
2076   if (TREE_CODE (op0) == SSA_NAME)
2077     vr0 = *(get_value_range (op0));
2078   else if (is_gimple_min_invariant (op0))
2079     set_value_range_to_value (&vr0, op0);
2080   else
2081     set_value_range_to_varying (&vr0);
2082
2083   /* If VR0 is UNDEFINED, so is the result.  */
2084   if (vr0.type == VR_UNDEFINED)
2085     {
2086       set_value_range_to_undefined (vr);
2087       return;
2088     }
2089
2090   /* Refuse to operate on symbolic ranges, or if neither operand is
2091      a pointer or integral type.  */
2092   if ((!INTEGRAL_TYPE_P (TREE_TYPE (op0))
2093        && !POINTER_TYPE_P (TREE_TYPE (op0)))
2094       || (vr0.type != VR_VARYING
2095           && symbolic_range_p (&vr0)))
2096     {
2097       set_value_range_to_varying (vr);
2098       return;
2099     }
2100
2101   /* If the expression involves pointers, we are only interested in
2102      determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
2103   if (POINTER_TYPE_P (TREE_TYPE (expr)) || POINTER_TYPE_P (TREE_TYPE (op0)))
2104     {
2105       bool sop;
2106
2107       sop = false;
2108       if (range_is_nonnull (&vr0)
2109           || (tree_expr_nonzero_warnv_p (expr, &sop)
2110               && !sop))
2111         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
2112       else if (range_is_null (&vr0))
2113         set_value_range_to_null (vr, TREE_TYPE (expr));
2114       else
2115         set_value_range_to_varying (vr);
2116
2117       return;
2118     }
2119
2120   /* Handle unary expressions on integer ranges.  */
2121   if (code == NOP_EXPR || code == CONVERT_EXPR)
2122     {
2123       tree inner_type = TREE_TYPE (op0);
2124       tree outer_type = TREE_TYPE (expr);
2125
2126       /* If VR0 represents a simple range, then try to convert
2127          the min and max values for the range to the same type
2128          as OUTER_TYPE.  If the results compare equal to VR0's
2129          min and max values and the new min is still less than
2130          or equal to the new max, then we can safely use the newly
2131          computed range for EXPR.  This allows us to compute
2132          accurate ranges through many casts.  */
2133       if ((vr0.type == VR_RANGE
2134            && !overflow_infinity_range_p (&vr0))
2135           || (vr0.type == VR_VARYING
2136               && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)))
2137         {
2138           tree new_min, new_max, orig_min, orig_max;
2139
2140           /* Convert the input operand min/max to OUTER_TYPE.   If
2141              the input has no range information, then use the min/max
2142              for the input's type.  */
2143           if (vr0.type == VR_RANGE)
2144             {
2145               orig_min = vr0.min;
2146               orig_max = vr0.max;
2147             }
2148           else
2149             {
2150               orig_min = TYPE_MIN_VALUE (inner_type);
2151               orig_max = TYPE_MAX_VALUE (inner_type);
2152             }
2153
2154           new_min = fold_convert (outer_type, orig_min);
2155           new_max = fold_convert (outer_type, orig_max);
2156
2157           /* Verify the new min/max values are gimple values and
2158              that they compare equal to the original input's
2159              min/max values.  */
2160           if (is_gimple_val (new_min)
2161               && is_gimple_val (new_max)
2162               && tree_int_cst_equal (new_min, orig_min)
2163               && tree_int_cst_equal (new_max, orig_max)
2164               && (cmp = compare_values (new_min, new_max)) <= 0
2165               && cmp >= -1)
2166             {
2167               set_value_range (vr, VR_RANGE, new_min, new_max, vr->equiv);
2168               return;
2169             }
2170         }
2171
2172       /* When converting types of different sizes, set the result to
2173          VARYING.  Things like sign extensions and precision loss may
2174          change the range.  For instance, if x_3 is of type 'long long
2175          int' and 'y_5 = (unsigned short) x_3', if x_3 is ~[0, 0], it
2176          is impossible to know at compile time whether y_5 will be
2177          ~[0, 0].  */
2178       if (TYPE_SIZE (inner_type) != TYPE_SIZE (outer_type)
2179           || TYPE_PRECISION (inner_type) != TYPE_PRECISION (outer_type))
2180         {
2181           set_value_range_to_varying (vr);
2182           return;
2183         }
2184     }
2185
2186   /* Conversion of a VR_VARYING value to a wider type can result
2187      in a usable range.  So wait until after we've handled conversions
2188      before dropping the result to VR_VARYING if we had a source
2189      operand that is VR_VARYING.  */
2190   if (vr0.type == VR_VARYING)
2191     {
2192       set_value_range_to_varying (vr);
2193       return;
2194     }
2195
2196   /* Apply the operation to each end of the range and see what we end
2197      up with.  */
2198   if (code == NEGATE_EXPR
2199       && !TYPE_UNSIGNED (TREE_TYPE (expr)))
2200     {
2201       /* NEGATE_EXPR flips the range around.  We need to treat
2202          TYPE_MIN_VALUE specially.  */
2203       if (is_positive_overflow_infinity (vr0.max))
2204         min = negative_overflow_infinity (TREE_TYPE (expr));
2205       else if (is_negative_overflow_infinity (vr0.max))
2206         min = positive_overflow_infinity (TREE_TYPE (expr));
2207       else if (vr0.max != TYPE_MIN_VALUE (TREE_TYPE (expr)))
2208         min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
2209       else if (needs_overflow_infinity (TREE_TYPE (expr)))
2210         {
2211           if (supports_overflow_infinity (TREE_TYPE (expr))
2212               && !is_overflow_infinity (vr0.min)
2213               && vr0.min != TYPE_MIN_VALUE (TREE_TYPE (expr)))
2214             min = positive_overflow_infinity (TREE_TYPE (expr));
2215           else
2216             {
2217               set_value_range_to_varying (vr);
2218               return;
2219             }
2220         }
2221       else
2222         min = TYPE_MIN_VALUE (TREE_TYPE (expr));
2223
2224       if (is_positive_overflow_infinity (vr0.min))
2225         max = negative_overflow_infinity (TREE_TYPE (expr));
2226       else if (is_negative_overflow_infinity (vr0.min))
2227         max = positive_overflow_infinity (TREE_TYPE (expr));
2228       else if (vr0.min != TYPE_MIN_VALUE (TREE_TYPE (expr)))
2229         max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
2230       else if (needs_overflow_infinity (TREE_TYPE (expr)))
2231         {
2232           if (supports_overflow_infinity (TREE_TYPE (expr)))
2233             max = positive_overflow_infinity (TREE_TYPE (expr));
2234           else
2235             {
2236               set_value_range_to_varying (vr);
2237               return;
2238             }
2239         }
2240       else
2241         max = TYPE_MIN_VALUE (TREE_TYPE (expr));
2242     }
2243   else if (code == NEGATE_EXPR
2244            && TYPE_UNSIGNED (TREE_TYPE (expr)))
2245     {
2246       if (!range_includes_zero_p (&vr0))
2247         {
2248           max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
2249           min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
2250         }
2251       else
2252         {
2253           if (range_is_null (&vr0))
2254             set_value_range_to_null (vr, TREE_TYPE (expr));
2255           else
2256             set_value_range_to_varying (vr);
2257           return;
2258         }
2259     }
2260   else if (code == ABS_EXPR
2261            && !TYPE_UNSIGNED (TREE_TYPE (expr)))
2262     {
2263       /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
2264          useful range.  */
2265       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (expr))
2266           && ((vr0.type == VR_RANGE
2267                && vr0.min == TYPE_MIN_VALUE (TREE_TYPE (expr)))
2268               || (vr0.type == VR_ANTI_RANGE
2269                   && vr0.min != TYPE_MIN_VALUE (TREE_TYPE (expr))
2270                   && !range_includes_zero_p (&vr0))))
2271         {
2272           set_value_range_to_varying (vr);
2273           return;
2274         }
2275         
2276       /* ABS_EXPR may flip the range around, if the original range
2277          included negative values.  */
2278       if (is_overflow_infinity (vr0.min))
2279         min = positive_overflow_infinity (TREE_TYPE (expr));
2280       else if (vr0.min != TYPE_MIN_VALUE (TREE_TYPE (expr)))
2281         min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
2282       else if (!needs_overflow_infinity (TREE_TYPE (expr)))
2283         min = TYPE_MAX_VALUE (TREE_TYPE (expr));
2284       else if (supports_overflow_infinity (TREE_TYPE (expr)))
2285         min = positive_overflow_infinity (TREE_TYPE (expr));
2286       else
2287         {
2288           set_value_range_to_varying (vr);
2289           return;
2290         }
2291
2292       if (is_overflow_infinity (vr0.max))
2293         max = positive_overflow_infinity (TREE_TYPE (expr));
2294       else if (vr0.max != TYPE_MIN_VALUE (TREE_TYPE (expr)))
2295         max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
2296       else if (!needs_overflow_infinity (TREE_TYPE (expr)))
2297         max = TYPE_MAX_VALUE (TREE_TYPE (expr));
2298       else if (supports_overflow_infinity (TREE_TYPE (expr)))
2299         max = positive_overflow_infinity (TREE_TYPE (expr));
2300       else
2301         {
2302           set_value_range_to_varying (vr);
2303           return;
2304         }
2305
2306       cmp = compare_values (min, max);
2307
2308       /* If a VR_ANTI_RANGEs contains zero, then we have
2309          ~[-INF, min(MIN, MAX)].  */
2310       if (vr0.type == VR_ANTI_RANGE)
2311         { 
2312           if (range_includes_zero_p (&vr0))
2313             {
2314               /* Take the lower of the two values.  */
2315               if (cmp != 1)
2316                 max = min;
2317
2318               /* Create ~[-INF, min (abs(MIN), abs(MAX))]
2319                  or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
2320                  flag_wrapv is set and the original anti-range doesn't include
2321                  TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE.  */
2322               if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr)))
2323                 {
2324                   tree type_min_value = TYPE_MIN_VALUE (TREE_TYPE (expr));
2325
2326                   min = (vr0.min != type_min_value
2327                          ? int_const_binop (PLUS_EXPR, type_min_value,
2328                                             integer_one_node, 0)
2329                          : type_min_value);
2330                 }
2331               else
2332                 {
2333                   if (overflow_infinity_range_p (&vr0))
2334                     min = negative_overflow_infinity (TREE_TYPE (expr));
2335                   else
2336                     min = TYPE_MIN_VALUE (TREE_TYPE (expr));
2337                 }
2338             }
2339           else
2340             {
2341               /* All else has failed, so create the range [0, INF], even for
2342                  flag_wrapv since TYPE_MIN_VALUE is in the original
2343                  anti-range.  */
2344               vr0.type = VR_RANGE;
2345               min = build_int_cst (TREE_TYPE (expr), 0);
2346               if (needs_overflow_infinity (TREE_TYPE (expr)))
2347                 {
2348                   if (supports_overflow_infinity (TREE_TYPE (expr)))
2349                     max = positive_overflow_infinity (TREE_TYPE (expr));
2350                   else
2351                     {
2352                       set_value_range_to_varying (vr);
2353                       return;
2354                     }
2355                 }
2356               else
2357                 max = TYPE_MAX_VALUE (TREE_TYPE (expr));
2358             }
2359         }
2360
2361       /* If the range contains zero then we know that the minimum value in the
2362          range will be zero.  */
2363       else if (range_includes_zero_p (&vr0))
2364         {
2365           if (cmp == 1)
2366             max = min;
2367           min = build_int_cst (TREE_TYPE (expr), 0);
2368         }
2369       else
2370         {
2371           /* If the range was reversed, swap MIN and MAX.  */
2372           if (cmp == 1)
2373             {
2374               tree t = min;
2375               min = max;
2376               max = t;
2377             }
2378         }
2379     }
2380   else
2381     {
2382       /* Otherwise, operate on each end of the range.  */
2383       min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
2384       max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
2385
2386       if (needs_overflow_infinity (TREE_TYPE (expr)))
2387         {
2388           gcc_assert (code != NEGATE_EXPR && code != ABS_EXPR);
2389
2390           /* If both sides have overflowed, we don't know
2391              anything.  */
2392           if ((is_overflow_infinity (vr0.min)
2393                || TREE_OVERFLOW (min))
2394               && (is_overflow_infinity (vr0.max)
2395                   || TREE_OVERFLOW (max)))
2396             {
2397               set_value_range_to_varying (vr);
2398               return;
2399             }
2400
2401           if (is_overflow_infinity (vr0.min))
2402             min = vr0.min;
2403           else if (TREE_OVERFLOW (min))
2404             {
2405               if (supports_overflow_infinity (TREE_TYPE (expr)))
2406                 min = (tree_int_cst_sgn (min) >= 0
2407                        ? positive_overflow_infinity (TREE_TYPE (min))
2408                        : negative_overflow_infinity (TREE_TYPE (min)));
2409               else
2410                 {
2411                   set_value_range_to_varying (vr);
2412                   return;
2413                 }
2414             }
2415
2416           if (is_overflow_infinity (vr0.max))
2417             max = vr0.max;
2418           else if (TREE_OVERFLOW (max))
2419             {
2420               if (supports_overflow_infinity (TREE_TYPE (expr)))
2421                 max = (tree_int_cst_sgn (max) >= 0
2422                        ? positive_overflow_infinity (TREE_TYPE (max))
2423                        : negative_overflow_infinity (TREE_TYPE (max)));
2424               else
2425                 {
2426                   set_value_range_to_varying (vr);
2427                   return;
2428                 }
2429             }
2430         }
2431     }
2432
2433   cmp = compare_values (min, max);
2434   if (cmp == -2 || cmp == 1)
2435     {
2436       /* If the new range has its limits swapped around (MIN > MAX),
2437          then the operation caused one of them to wrap around, mark
2438          the new range VARYING.  */
2439       set_value_range_to_varying (vr);
2440     }
2441   else
2442     set_value_range (vr, vr0.type, min, max, NULL);
2443 }
2444
2445
2446 /* Extract range information from a conditional expression EXPR based on
2447    the ranges of each of its operands and the expression code.  */
2448
2449 static void
2450 extract_range_from_cond_expr (value_range_t *vr, tree expr)
2451 {
2452   tree op0, op1;
2453   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2454   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2455
2456   /* Get value ranges for each operand.  For constant operands, create
2457      a new value range with the operand to simplify processing.  */
2458   op0 = COND_EXPR_THEN (expr);
2459   if (TREE_CODE (op0) == SSA_NAME)
2460     vr0 = *(get_value_range (op0));
2461   else if (is_gimple_min_invariant (op0))
2462     set_value_range_to_value (&vr0, op0);
2463   else
2464     set_value_range_to_varying (&vr0);
2465
2466   op1 = COND_EXPR_ELSE (expr);
2467   if (TREE_CODE (op1) == SSA_NAME)
2468     vr1 = *(get_value_range (op1));
2469   else if (is_gimple_min_invariant (op1))
2470     set_value_range_to_value (&vr1, op1);
2471   else
2472     set_value_range_to_varying (&vr1);
2473
2474   /* The resulting value range is the union of the operand ranges */
2475   vrp_meet (&vr0, &vr1);
2476   copy_value_range (vr, &vr0);
2477 }
2478
2479
2480 /* Extract range information from a comparison expression EXPR based
2481    on the range of its operand and the expression code.  */
2482
2483 static void
2484 extract_range_from_comparison (value_range_t *vr, tree expr)
2485 {
2486   bool sop = false;
2487   tree val = vrp_evaluate_conditional_warnv (expr, false, &sop);
2488
2489   /* A disadvantage of using a special infinity as an overflow
2490      representation is that we lose the ability to record overflow
2491      when we don't have an infinity.  So we have to ignore a result
2492      which relies on overflow.  */
2493
2494   if (val && !is_overflow_infinity (val) && !sop)
2495     {
2496       /* Since this expression was found on the RHS of an assignment,
2497          its type may be different from _Bool.  Convert VAL to EXPR's
2498          type.  */
2499       val = fold_convert (TREE_TYPE (expr), val);
2500       set_value_range (vr, VR_RANGE, val, val, vr->equiv);
2501     }
2502   else
2503     /* The result of a comparison is always true or false.  */
2504     set_value_range_to_truthvalue (vr, TREE_TYPE (expr));
2505 }
2506
2507
2508 /* Try to compute a useful range out of expression EXPR and store it
2509    in *VR.  */
2510
2511 static void
2512 extract_range_from_expr (value_range_t *vr, tree expr)
2513 {
2514   enum tree_code code = TREE_CODE (expr);
2515
2516   if (code == ASSERT_EXPR)
2517     extract_range_from_assert (vr, expr);
2518   else if (code == SSA_NAME)
2519     extract_range_from_ssa_name (vr, expr);
2520   else if (TREE_CODE_CLASS (code) == tcc_binary
2521            || code == TRUTH_ANDIF_EXPR
2522            || code == TRUTH_ORIF_EXPR
2523            || code == TRUTH_AND_EXPR
2524            || code == TRUTH_OR_EXPR
2525            || code == TRUTH_XOR_EXPR)
2526     extract_range_from_binary_expr (vr, expr);
2527   else if (TREE_CODE_CLASS (code) == tcc_unary)
2528     extract_range_from_unary_expr (vr, expr);
2529   else if (code == COND_EXPR)
2530     extract_range_from_cond_expr (vr, expr);
2531   else if (TREE_CODE_CLASS (code) == tcc_comparison)
2532     extract_range_from_comparison (vr, expr);
2533   else if (is_gimple_min_invariant (expr))
2534     set_value_range_to_value (vr, expr);
2535   else
2536     set_value_range_to_varying (vr);
2537
2538   /* If we got a varying range from the tests above, try a final
2539      time to derive a nonnegative or nonzero range.  This time
2540      relying primarily on generic routines in fold in conjunction
2541      with range data.  */
2542   if (vr->type == VR_VARYING)
2543     {
2544       bool sop = false;
2545
2546       if (INTEGRAL_TYPE_P (TREE_TYPE (expr))
2547           && vrp_expr_computes_nonnegative (expr, &sop))
2548         set_value_range_to_nonnegative (vr, TREE_TYPE (expr),
2549                                         sop || is_overflow_infinity (expr));
2550       else if (vrp_expr_computes_nonzero (expr, &sop)
2551                && !sop)
2552         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
2553     }
2554 }
2555
2556 /* Given a range VR, a LOOP and a variable VAR, determine whether it
2557    would be profitable to adjust VR using scalar evolution information
2558    for VAR.  If so, update VR with the new limits.  */
2559
2560 static void
2561 adjust_range_with_scev (value_range_t *vr, struct loop *loop, tree stmt,
2562                         tree var)
2563 {
2564   tree init, step, chrec, tmin, tmax, min, max, type;
2565   enum ev_direction dir;
2566
2567   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
2568      better opportunities than a regular range, but I'm not sure.  */
2569   if (vr->type == VR_ANTI_RANGE)
2570     return;
2571
2572   chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
2573   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
2574     return;
2575
2576   init = initial_condition_in_loop_num (chrec, loop->num);
2577   step = evolution_part_in_loop_num (chrec, loop->num);
2578
2579   /* If STEP is symbolic, we can't know whether INIT will be the
2580      minimum or maximum value in the range.  Also, unless INIT is
2581      a simple expression, compare_values and possibly other functions
2582      in tree-vrp won't be able to handle it.  */
2583   if (step == NULL_TREE
2584       || !is_gimple_min_invariant (step)
2585       || !valid_value_p (init))
2586     return;
2587
2588   dir = scev_direction (chrec);
2589   if (/* Do not adjust ranges if we do not know whether the iv increases
2590          or decreases,  ... */
2591       dir == EV_DIR_UNKNOWN
2592       /* ... or if it may wrap.  */
2593       || scev_probably_wraps_p (init, step, stmt, get_chrec_loop (chrec),
2594                                 true))
2595     return;
2596
2597   /* We use TYPE_MIN_VALUE and TYPE_MAX_VALUE here instead of
2598      negative_overflow_infinity and positive_overflow_infinity,
2599      because we have concluded that the loop probably does not
2600      wrap.  */
2601
2602   type = TREE_TYPE (var);
2603   if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
2604     tmin = lower_bound_in_type (type, type);
2605   else
2606     tmin = TYPE_MIN_VALUE (type);
2607   if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
2608     tmax = upper_bound_in_type (type, type);
2609   else
2610     tmax = TYPE_MAX_VALUE (type);
2611
2612   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
2613     {
2614       min = tmin;
2615       max = tmax;
2616
2617       /* For VARYING or UNDEFINED ranges, just about anything we get
2618          from scalar evolutions should be better.  */
2619
2620       if (dir == EV_DIR_DECREASES)
2621         max = init;
2622       else
2623         min = init;
2624
2625       /* If we would create an invalid range, then just assume we
2626          know absolutely nothing.  This may be over-conservative,
2627          but it's clearly safe, and should happen only in unreachable
2628          parts of code, or for invalid programs.  */
2629       if (compare_values (min, max) == 1)
2630         return;
2631
2632       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
2633     }
2634   else if (vr->type == VR_RANGE)
2635     {
2636       min = vr->min;
2637       max = vr->max;
2638
2639       if (dir == EV_DIR_DECREASES)
2640         {
2641           /* INIT is the maximum value.  If INIT is lower than VR->MAX
2642              but no smaller than VR->MIN, set VR->MAX to INIT.  */
2643           if (compare_values (init, max) == -1)
2644             {
2645               max = init;
2646
2647               /* If we just created an invalid range with the minimum
2648                  greater than the maximum, we fail conservatively.
2649                  This should happen only in unreachable
2650                  parts of code, or for invalid programs.  */
2651               if (compare_values (min, max) == 1)
2652                 return;
2653             }
2654         }
2655       else
2656         {
2657           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
2658           if (compare_values (init, min) == 1)
2659             {
2660               min = init;
2661
2662               /* Again, avoid creating invalid range by failing.  */
2663               if (compare_values (min, max) == 1)
2664                 return;
2665             }
2666         }
2667
2668       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
2669     }
2670 }
2671
2672
2673 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
2674    
2675    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
2676      all the values in the ranges.
2677
2678    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
2679
2680    - Return NULL_TREE if it is not always possible to determine the
2681      value of the comparison.
2682
2683    Also set *STRICT_OVERFLOW_P to indicate whether a range with an
2684    overflow infinity was used in the test.  */
2685
2686
2687 static tree
2688 compare_ranges (enum tree_code comp, value_range_t *vr0, value_range_t *vr1,
2689                 bool *strict_overflow_p)
2690 {
2691   /* VARYING or UNDEFINED ranges cannot be compared.  */
2692   if (vr0->type == VR_VARYING
2693       || vr0->type == VR_UNDEFINED
2694       || vr1->type == VR_VARYING
2695       || vr1->type == VR_UNDEFINED)
2696     return NULL_TREE;
2697
2698   /* Anti-ranges need to be handled separately.  */
2699   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
2700     {
2701       /* If both are anti-ranges, then we cannot compute any
2702          comparison.  */
2703       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
2704         return NULL_TREE;
2705
2706       /* These comparisons are never statically computable.  */
2707       if (comp == GT_EXPR
2708           || comp == GE_EXPR
2709           || comp == LT_EXPR
2710           || comp == LE_EXPR)
2711         return NULL_TREE;
2712
2713       /* Equality can be computed only between a range and an
2714          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
2715       if (vr0->type == VR_RANGE)
2716         {
2717           /* To simplify processing, make VR0 the anti-range.  */
2718           value_range_t *tmp = vr0;
2719           vr0 = vr1;
2720           vr1 = tmp;
2721         }
2722
2723       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
2724
2725       if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
2726           && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
2727         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
2728
2729       return NULL_TREE;
2730     }
2731
2732   if (!usable_range_p (vr0, strict_overflow_p)
2733       || !usable_range_p (vr1, strict_overflow_p))
2734     return NULL_TREE;
2735
2736   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
2737      operands around and change the comparison code.  */
2738   if (comp == GT_EXPR || comp == GE_EXPR)
2739     {
2740       value_range_t *tmp;
2741       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
2742       tmp = vr0;
2743       vr0 = vr1;
2744       vr1 = tmp;
2745     }
2746
2747   if (comp == EQ_EXPR)
2748     {
2749       /* Equality may only be computed if both ranges represent
2750          exactly one value.  */
2751       if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
2752           && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
2753         {
2754           int cmp_min = compare_values_warnv (vr0->min, vr1->min,
2755                                               strict_overflow_p);
2756           int cmp_max = compare_values_warnv (vr0->max, vr1->max,
2757                                               strict_overflow_p);
2758           if (cmp_min == 0 && cmp_max == 0)
2759             return boolean_true_node;
2760           else if (cmp_min != -2 && cmp_max != -2)
2761             return boolean_false_node;
2762         }
2763       /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1.  */
2764       else if (compare_values_warnv (vr0->min, vr1->max,
2765                                      strict_overflow_p) == 1
2766                || compare_values_warnv (vr1->min, vr0->max,
2767                                         strict_overflow_p) == 1)
2768         return boolean_false_node;
2769
2770       return NULL_TREE;
2771     }
2772   else if (comp == NE_EXPR)
2773     {
2774       int cmp1, cmp2;
2775
2776       /* If VR0 is completely to the left or completely to the right
2777          of VR1, they are always different.  Notice that we need to
2778          make sure that both comparisons yield similar results to
2779          avoid comparing values that cannot be compared at
2780          compile-time.  */
2781       cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
2782       cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
2783       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
2784         return boolean_true_node;
2785
2786       /* If VR0 and VR1 represent a single value and are identical,
2787          return false.  */
2788       else if (compare_values_warnv (vr0->min, vr0->max,
2789                                      strict_overflow_p) == 0
2790                && compare_values_warnv (vr1->min, vr1->max,
2791                                         strict_overflow_p) == 0
2792                && compare_values_warnv (vr0->min, vr1->min,
2793                                         strict_overflow_p) == 0
2794                && compare_values_warnv (vr0->max, vr1->max,
2795                                         strict_overflow_p) == 0)
2796         return boolean_false_node;
2797
2798       /* Otherwise, they may or may not be different.  */
2799       else
2800         return NULL_TREE;
2801     }
2802   else if (comp == LT_EXPR || comp == LE_EXPR)
2803     {
2804       int tst;
2805
2806       /* If VR0 is to the left of VR1, return true.  */
2807       tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
2808       if ((comp == LT_EXPR && tst == -1)
2809           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
2810         {
2811           if (overflow_infinity_range_p (vr0)
2812               || overflow_infinity_range_p (vr1))
2813             *strict_overflow_p = true;
2814           return boolean_true_node;
2815         }
2816
2817       /* If VR0 is to the right of VR1, return false.  */
2818       tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
2819       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
2820           || (comp == LE_EXPR && tst == 1))
2821         {
2822           if (overflow_infinity_range_p (vr0)
2823               || overflow_infinity_range_p (vr1))
2824             *strict_overflow_p = true;
2825           return boolean_false_node;
2826         }
2827
2828       /* Otherwise, we don't know.  */
2829       return NULL_TREE;
2830     }
2831     
2832   gcc_unreachable ();
2833 }
2834
2835
2836 /* Given a value range VR, a value VAL and a comparison code COMP, return
2837    BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
2838    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
2839    always returns false.  Return NULL_TREE if it is not always
2840    possible to determine the value of the comparison.  Also set
2841    *STRICT_OVERFLOW_P to indicate whether a range with an overflow
2842    infinity was used in the test.  */
2843
2844 static tree
2845 compare_range_with_value (enum tree_code comp, value_range_t *vr, tree val,
2846                           bool *strict_overflow_p)
2847 {
2848   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
2849     return NULL_TREE;
2850
2851   /* Anti-ranges need to be handled separately.  */
2852   if (vr->type == VR_ANTI_RANGE)
2853     {
2854       /* For anti-ranges, the only predicates that we can compute at
2855          compile time are equality and inequality.  */
2856       if (comp == GT_EXPR
2857           || comp == GE_EXPR
2858           || comp == LT_EXPR
2859           || comp == LE_EXPR)
2860         return NULL_TREE;
2861
2862       /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2.  */
2863       if (value_inside_range (val, vr) == 1)
2864         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
2865
2866       return NULL_TREE;
2867     }
2868
2869   if (!usable_range_p (vr, strict_overflow_p))
2870     return NULL_TREE;
2871
2872   if (comp == EQ_EXPR)
2873     {
2874       /* EQ_EXPR may only be computed if VR represents exactly
2875          one value.  */
2876       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
2877         {
2878           int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
2879           if (cmp == 0)
2880             return boolean_true_node;
2881           else if (cmp == -1 || cmp == 1 || cmp == 2)
2882             return boolean_false_node;
2883         }
2884       else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
2885                || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
2886         return boolean_false_node;
2887
2888       return NULL_TREE;
2889     }
2890   else if (comp == NE_EXPR)
2891     {
2892       /* If VAL is not inside VR, then they are always different.  */
2893       if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
2894           || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
2895         return boolean_true_node;
2896
2897       /* If VR represents exactly one value equal to VAL, then return
2898          false.  */
2899       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
2900           && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
2901         return boolean_false_node;
2902
2903       /* Otherwise, they may or may not be different.  */
2904       return NULL_TREE;
2905     }
2906   else if (comp == LT_EXPR || comp == LE_EXPR)
2907     {
2908       int tst;
2909
2910       /* If VR is to the left of VAL, return true.  */
2911       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
2912       if ((comp == LT_EXPR && tst == -1)
2913           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
2914         {
2915           if (overflow_infinity_range_p (vr))
2916             *strict_overflow_p = true;
2917           return boolean_true_node;
2918         }
2919
2920       /* If VR is to the right of VAL, return false.  */
2921       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
2922       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
2923           || (comp == LE_EXPR && tst == 1))
2924         {
2925           if (overflow_infinity_range_p (vr))
2926             *strict_overflow_p = true;
2927           return boolean_false_node;
2928         }
2929
2930       /* Otherwise, we don't know.  */
2931       return NULL_TREE;
2932     }
2933   else if (comp == GT_EXPR || comp == GE_EXPR)
2934     {
2935       int tst;
2936
2937       /* If VR is to the right of VAL, return true.  */
2938       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
2939       if ((comp == GT_EXPR && tst == 1)
2940           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
2941         {
2942           if (overflow_infinity_range_p (vr))
2943             *strict_overflow_p = true;
2944           return boolean_true_node;
2945         }
2946
2947       /* If VR is to the left of VAL, return false.  */
2948       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
2949       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
2950           || (comp == GE_EXPR && tst == -1))
2951         {
2952           if (overflow_infinity_range_p (vr))
2953             *strict_overflow_p = true;
2954           return boolean_false_node;
2955         }
2956
2957       /* Otherwise, we don't know.  */
2958       return NULL_TREE;
2959     }
2960
2961   gcc_unreachable ();
2962 }
2963
2964
2965 /* Debugging dumps.  */
2966
2967 void dump_value_range (FILE *, value_range_t *);
2968 void debug_value_range (value_range_t *);
2969 void dump_all_value_ranges (FILE *);
2970 void debug_all_value_ranges (void);
2971 void dump_vr_equiv (FILE *, bitmap);
2972 void debug_vr_equiv (bitmap);
2973
2974
2975 /* Dump value range VR to FILE.  */
2976
2977 void
2978 dump_value_range (FILE *file, value_range_t *vr)
2979 {
2980   if (vr == NULL)
2981     fprintf (file, "[]");
2982   else if (vr->type == VR_UNDEFINED)
2983     fprintf (file, "UNDEFINED");
2984   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2985     {
2986       tree type = TREE_TYPE (vr->min);
2987
2988       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2989
2990       if (INTEGRAL_TYPE_P (type)
2991           && !TYPE_UNSIGNED (type)
2992           && vr->min == TYPE_MIN_VALUE (type))
2993         fprintf (file, "-INF");
2994       else if (needs_overflow_infinity (type)
2995                && is_negative_overflow_infinity (vr->min))
2996         fprintf (file, "-INF(OVF)");
2997       else
2998         print_generic_expr (file, vr->min, 0);
2999
3000       fprintf (file, ", ");
3001
3002       if (INTEGRAL_TYPE_P (type)
3003           && vr->max == TYPE_MAX_VALUE (type))
3004         fprintf (file, "+INF");
3005       else if (needs_overflow_infinity (type)
3006                && is_positive_overflow_infinity (vr->max))
3007         fprintf (file, "+INF(OVF)");
3008       else
3009         print_generic_expr (file, vr->max, 0);
3010
3011       fprintf (file, "]");
3012
3013       if (vr->equiv)
3014         {
3015           bitmap_iterator bi;
3016           unsigned i, c = 0;
3017
3018           fprintf (file, "  EQUIVALENCES: { ");
3019
3020           EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
3021             {
3022               print_generic_expr (file, ssa_name (i), 0);
3023               fprintf (file, " ");
3024               c++;
3025             }
3026
3027           fprintf (file, "} (%u elements)", c);
3028         }
3029     }
3030   else if (vr->type == VR_VARYING)
3031     fprintf (file, "VARYING");
3032   else
3033     fprintf (file, "INVALID RANGE");
3034 }
3035
3036
3037 /* Dump value range VR to stderr.  */
3038
3039 void
3040 debug_value_range (value_range_t *vr)
3041 {
3042   dump_value_range (stderr, vr);
3043   fprintf (stderr, "\n");
3044 }
3045
3046
3047 /* Dump value ranges of all SSA_NAMEs to FILE.  */
3048
3049 void
3050 dump_all_value_ranges (FILE *file)
3051 {
3052   size_t i;
3053
3054   for (i = 0; i < num_ssa_names; i++)
3055     {
3056       if (vr_value[i])
3057         {
3058           print_generic_expr (file, ssa_name (i), 0);
3059           fprintf (file, ": ");
3060           dump_value_range (file, vr_value[i]);
3061           fprintf (file, "\n");
3062         }
3063     }
3064
3065   fprintf (file, "\n");
3066 }
3067
3068
3069 /* Dump all value ranges to stderr.  */
3070
3071 void
3072 debug_all_value_ranges (void)
3073 {
3074   dump_all_value_ranges (stderr);
3075 }
3076
3077
3078 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
3079    create a new SSA name N and return the assertion assignment
3080    'V = ASSERT_EXPR <V, V OP W>'.  */
3081
3082 static tree
3083 build_assert_expr_for (tree cond, tree v)
3084 {
3085   tree n, assertion;
3086
3087   gcc_assert (TREE_CODE (v) == SSA_NAME);
3088   n = duplicate_ssa_name (v, NULL_TREE);
3089
3090   if (COMPARISON_CLASS_P (cond))
3091     {
3092       tree a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond); 
3093       assertion = build_gimple_modify_stmt (n, a);
3094     }
3095   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
3096     {
3097       /* Given !V, build the assignment N = false.  */
3098       tree op0 = TREE_OPERAND (cond, 0);
3099       gcc_assert (op0 == v);
3100       assertion = build_gimple_modify_stmt (n, boolean_false_node);
3101     }
3102   else if (TREE_CODE (cond) == SSA_NAME)
3103     {
3104       /* Given V, build the assignment N = true.  */
3105       gcc_assert (v == cond);
3106       assertion = build_gimple_modify_stmt (n, boolean_true_node);
3107     }
3108   else
3109     gcc_unreachable ();
3110
3111   SSA_NAME_DEF_STMT (n) = assertion;
3112
3113   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
3114      operand of the ASSERT_EXPR. Register the new name and the old one
3115      in the replacement table so that we can fix the SSA web after
3116      adding all the ASSERT_EXPRs.  */
3117   register_new_name_mapping (n, v);
3118
3119   return assertion;
3120 }
3121
3122
3123 /* Return false if EXPR is a predicate expression involving floating
3124    point values.  */
3125
3126 static inline bool
3127 fp_predicate (tree expr)
3128 {
3129   return (COMPARISON_CLASS_P (expr)
3130           && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0))));
3131 }
3132
3133
3134 /* If the range of values taken by OP can be inferred after STMT executes,
3135    return the comparison code (COMP_CODE_P) and value (VAL_P) that
3136    describes the inferred range.  Return true if a range could be
3137    inferred.  */
3138
3139 static bool
3140 infer_value_range (tree stmt, tree op, enum tree_code *comp_code_p, tree *val_p)
3141 {
3142   *val_p = NULL_TREE;
3143   *comp_code_p = ERROR_MARK;
3144
3145   /* Do not attempt to infer anything in names that flow through
3146      abnormal edges.  */
3147   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
3148     return false;
3149
3150   /* Similarly, don't infer anything from statements that may throw
3151      exceptions.  */
3152   if (tree_could_throw_p (stmt))
3153     return false;
3154
3155   /* If STMT is the last statement of a basic block with no
3156      successors, there is no point inferring anything about any of its
3157      operands.  We would not be able to find a proper insertion point
3158      for the assertion, anyway.  */
3159   if (stmt_ends_bb_p (stmt) && EDGE_COUNT (bb_for_stmt (stmt)->succs) == 0)
3160     return false;
3161
3162   /* We can only assume that a pointer dereference will yield
3163      non-NULL if -fdelete-null-pointer-checks is enabled.  */
3164   if (flag_delete_null_pointer_checks && POINTER_TYPE_P (TREE_TYPE (op)))
3165     {
3166       unsigned num_uses, num_loads, num_stores;
3167
3168       count_uses_and_derefs (op, stmt, &num_uses, &num_loads, &num_stores);
3169       if (num_loads + num_stores > 0)
3170         {
3171           *val_p = build_int_cst (TREE_TYPE (op), 0);
3172           *comp_code_p = NE_EXPR;
3173           return true;
3174         }
3175     }
3176
3177   return false;
3178 }
3179
3180
3181 void dump_asserts_for (FILE *, tree);
3182 void debug_asserts_for (tree);
3183 void dump_all_asserts (FILE *);
3184 void debug_all_asserts (void);
3185
3186 /* Dump all the registered assertions for NAME to FILE.  */
3187
3188 void
3189 dump_asserts_for (FILE *file, tree name)
3190 {
3191   assert_locus_t loc;
3192
3193   fprintf (file, "Assertions to be inserted for ");
3194   print_generic_expr (file, name, 0);
3195   fprintf (file, "\n");
3196
3197   loc = asserts_for[SSA_NAME_VERSION (name)];
3198   while (loc)
3199     {
3200       fprintf (file, "\t");
3201       print_generic_expr (file, bsi_stmt (loc->si), 0);
3202       fprintf (file, "\n\tBB #%d", loc->bb->index);
3203       if (loc->e)
3204         {
3205           fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
3206                    loc->e->dest->index);
3207           dump_edge_info (file, loc->e, 0);
3208         }
3209       fprintf (file, "\n\tPREDICATE: ");
3210       print_generic_expr (file, name, 0);
3211       fprintf (file, " %s ", tree_code_name[(int)loc->comp_code]);
3212       print_generic_expr (file, loc->val, 0);
3213       fprintf (file, "\n\n");
3214       loc = loc->next;
3215     }
3216
3217   fprintf (file, "\n");
3218 }
3219
3220
3221 /* Dump all the registered assertions for NAME to stderr.  */
3222
3223 void
3224 debug_asserts_for (tree name)
3225 {
3226   dump_asserts_for (stderr, name);
3227 }
3228
3229
3230 /* Dump all the registered assertions for all the names to FILE.  */
3231
3232 void
3233 dump_all_asserts (FILE *file)
3234 {
3235   unsigned i;
3236   bitmap_iterator bi;
3237
3238   fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
3239   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
3240     dump_asserts_for (file, ssa_name (i));
3241   fprintf (file, "\n");
3242 }
3243
3244
3245 /* Dump all the registered assertions for all the names to stderr.  */
3246
3247 void
3248 debug_all_asserts (void)
3249 {
3250   dump_all_asserts (stderr);
3251 }
3252
3253
3254 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
3255    'NAME COMP_CODE VAL' at a location that dominates block BB or
3256    E->DEST, then register this location as a possible insertion point
3257    for ASSERT_EXPR <NAME, NAME COMP_CODE VAL>.
3258
3259    BB, E and SI provide the exact insertion point for the new
3260    ASSERT_EXPR.  If BB is NULL, then the ASSERT_EXPR is to be inserted
3261    on edge E.  Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
3262    BB.  If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
3263    must not be NULL.  */
3264
3265 static void
3266 register_new_assert_for (tree name,
3267                          enum tree_code comp_code,
3268                          tree val,
3269                          basic_block bb,
3270                          edge e,
3271                          block_stmt_iterator si)
3272 {
3273   assert_locus_t n, loc, last_loc;
3274   bool found;
3275   basic_block dest_bb;
3276
3277 #if defined ENABLE_CHECKING
3278   gcc_assert (bb == NULL || e == NULL);
3279
3280   if (e == NULL)
3281     gcc_assert (TREE_CODE (bsi_stmt (si)) != COND_EXPR
3282                 && TREE_CODE (bsi_stmt (si)) != SWITCH_EXPR);
3283 #endif
3284
3285   /* The new assertion A will be inserted at BB or E.  We need to
3286      determine if the new location is dominated by a previously
3287      registered location for A.  If we are doing an edge insertion,
3288      assume that A will be inserted at E->DEST.  Note that this is not
3289      necessarily true.
3290      
3291      If E is a critical edge, it will be split.  But even if E is
3292      split, the new block will dominate the same set of blocks that
3293      E->DEST dominates.
3294      
3295      The reverse, however, is not true, blocks dominated by E->DEST
3296      will not be dominated by the new block created to split E.  So,
3297      if the insertion location is on a critical edge, we will not use
3298      the new location to move another assertion previously registered
3299      at a block dominated by E->DEST.  */
3300   dest_bb = (bb) ? bb : e->dest;
3301
3302   /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
3303      VAL at a block dominating DEST_BB, then we don't need to insert a new
3304      one.  Similarly, if the same assertion already exists at a block
3305      dominated by DEST_BB and the new location is not on a critical
3306      edge, then update the existing location for the assertion (i.e.,
3307      move the assertion up in the dominance tree).
3308
3309      Note, this is implemented as a simple linked list because there
3310      should not be more than a handful of assertions registered per
3311      name.  If this becomes a performance problem, a table hashed by
3312      COMP_CODE and VAL could be implemented.  */
3313   loc = asserts_for[SSA_NAME_VERSION (name)];
3314   last_loc = loc;
3315   found = false;
3316   while (loc)
3317     {
3318       if (loc->comp_code == comp_code
3319           && (loc->val == val
3320               || operand_equal_p (loc->val, val, 0)))
3321         {
3322           /* If the assertion NAME COMP_CODE VAL has already been
3323              registered at a basic block that dominates DEST_BB, then
3324              we don't need to insert the same assertion again.  Note
3325              that we don't check strict dominance here to avoid
3326              replicating the same assertion inside the same basic
3327              block more than once (e.g., when a pointer is
3328              dereferenced several times inside a block).
3329
3330              An exception to this rule are edge insertions.  If the
3331              new assertion is to be inserted on edge E, then it will
3332              dominate all the other insertions that we may want to
3333              insert in DEST_BB.  So, if we are doing an edge
3334              insertion, don't do this dominance check.  */
3335           if (e == NULL
3336               && dominated_by_p (CDI_DOMINATORS, dest_bb, loc->bb))
3337             return;
3338
3339           /* Otherwise, if E is not a critical edge and DEST_BB
3340              dominates the existing location for the assertion, move
3341              the assertion up in the dominance tree by updating its
3342              location information.  */
3343           if ((e == NULL || !EDGE_CRITICAL_P (e))
3344               && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
3345             {
3346               loc->bb = dest_bb;
3347               loc->e = e;
3348               loc->si = si;
3349               return;
3350             }
3351         }
3352
3353       /* Update the last node of the list and move to the next one.  */
3354       last_loc = loc;
3355       loc = loc->next;
3356     }
3357
3358   /* If we didn't find an assertion already registered for
3359      NAME COMP_CODE VAL, add a new one at the end of the list of
3360      assertions associated with NAME.  */
3361   n = XNEW (struct assert_locus_d);
3362   n->bb = dest_bb;
3363   n->e = e;
3364   n->si = si;
3365   n->comp_code = comp_code;
3366   n->val = val;
3367   n->next = NULL;
3368
3369   if (last_loc)
3370     last_loc->next = n;
3371   else
3372     asserts_for[SSA_NAME_VERSION (name)] = n;
3373
3374   bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
3375 }
3376
3377 /* COND is a predicate which uses NAME.  Extract a suitable test code
3378    and value and store them into *CODE_P and *VAL_P so the predicate
3379    is normalized to NAME *CODE_P *VAL_P.
3380
3381    If no extraction was possible, return FALSE, otherwise return TRUE.
3382
3383    If INVERT is true, then we invert the result stored into *CODE_P.  */
3384
3385 static bool
3386 extract_code_and_val_from_cond (tree name, tree cond, bool invert,
3387                                 enum tree_code *code_p, tree *val_p)
3388 {
3389   enum tree_code comp_code;
3390   tree val;
3391
3392   /* Predicates may be a single SSA name or NAME OP VAL.  */
3393   if (cond == name)
3394     {
3395       /* If the predicate is a name, it must be NAME, in which
3396          case we create the predicate NAME == true or
3397          NAME == false accordingly.  */
3398       comp_code = EQ_EXPR;
3399       val = invert ? boolean_false_node : boolean_true_node;
3400     }
3401   else
3402     {
3403       /* Otherwise, we have a comparison of the form NAME COMP VAL
3404          or VAL COMP NAME.  */
3405       if (name == TREE_OPERAND (cond, 1))
3406         {
3407           /* If the predicate is of the form VAL COMP NAME, flip
3408              COMP around because we need to register NAME as the
3409              first operand in the predicate.  */
3410           comp_code = swap_tree_comparison (TREE_CODE (cond));
3411           val = TREE_OPERAND (cond, 0);
3412         }
3413       else
3414         {
3415           /* The comparison is of the form NAME COMP VAL, so the
3416              comparison code remains unchanged.  */
3417           comp_code = TREE_CODE (cond);
3418           val = TREE_OPERAND (cond, 1);
3419         }
3420
3421       /* Invert the comparison code as necessary.  */
3422       if (invert)
3423         comp_code = invert_tree_comparison (comp_code, 0);
3424
3425       /* VRP does not handle float types.  */
3426       if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (val)))
3427         return false;
3428
3429       /* Do not register always-false predicates.
3430          FIXME:  this works around a limitation in fold() when dealing with
3431          enumerations.  Given 'enum { N1, N2 } x;', fold will not
3432          fold 'if (x > N2)' to 'if (0)'.  */
3433       if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
3434           && INTEGRAL_TYPE_P (TREE_TYPE (val)))
3435         {
3436           tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
3437           tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
3438
3439           if (comp_code == GT_EXPR
3440               && (!max
3441                   || compare_values (val, max) == 0))
3442             return false;
3443
3444           if (comp_code == LT_EXPR
3445               && (!min
3446                   || compare_values (val, min) == 0))
3447             return false;
3448         }
3449     }
3450   *code_p = comp_code;
3451   *val_p = val;
3452   return true;
3453 }
3454
3455 /* OP is an operand of a truth value expression which is known to have
3456    a particular value.  Register any asserts for OP and for any
3457    operands in OP's defining statement. 
3458
3459    If CODE is EQ_EXPR, then we want to register OP is zero (false),
3460    if CODE is NE_EXPR, then we want to register OP is nonzero (true).   */
3461
3462 static bool
3463 register_edge_assert_for_1 (tree op, enum tree_code code,
3464                             edge e, block_stmt_iterator bsi)
3465 {
3466   bool retval = false;
3467   tree op_def, rhs, val;
3468
3469   /* We only care about SSA_NAMEs.  */
3470   if (TREE_CODE (op) != SSA_NAME)
3471     return false;
3472
3473   /* We know that OP will have a zero or nonzero value.  If OP is used
3474      more than once go ahead and register an assert for OP. 
3475
3476      The FOUND_IN_SUBGRAPH support is not helpful in this situation as
3477      it will always be set for OP (because OP is used in a COND_EXPR in
3478      the subgraph).  */
3479   if (!has_single_use (op))
3480     {
3481       val = build_int_cst (TREE_TYPE (op), 0);
3482       register_new_assert_for (op, code, val, NULL, e, bsi);
3483       retval = true;
3484     }
3485
3486   /* Now look at how OP is set.  If it's set from a comparison,
3487      a truth operation or some bit operations, then we may be able
3488      to register information about the operands of that assignment.  */
3489   op_def = SSA_NAME_DEF_STMT (op);
3490   if (TREE_CODE (op_def) != GIMPLE_MODIFY_STMT)
3491     return retval;
3492
3493   rhs = GIMPLE_STMT_OPERAND (op_def, 1);
3494
3495   if (COMPARISON_CLASS_P (rhs))
3496     {
3497       bool invert = (code == EQ_EXPR ? true : false);
3498       tree op0 = TREE_OPERAND (rhs, 0);
3499       tree op1 = TREE_OPERAND (rhs, 1);
3500
3501       /* Conditionally register an assert for each SSA_NAME in the
3502          comparison.  */
3503       if (TREE_CODE (op0) == SSA_NAME
3504           && !has_single_use (op0)
3505           && extract_code_and_val_from_cond (op0, rhs,
3506                                              invert, &code, &val))
3507         {
3508           register_new_assert_for (op0, code, val, NULL, e, bsi);
3509           retval = true;
3510         }
3511
3512       /* Similarly for the second operand of the comparison.  */
3513       if (TREE_CODE (op1) == SSA_NAME
3514           && !has_single_use (op1)
3515           && extract_code_and_val_from_cond (op1, rhs,
3516                                              invert, &code, &val))
3517         {
3518           register_new_assert_for (op1, code, val, NULL, e, bsi);
3519           retval = true;
3520         }
3521     }
3522   else if ((code == NE_EXPR
3523             && (TREE_CODE (rhs) == TRUTH_AND_EXPR
3524                 || TREE_CODE (rhs) == BIT_AND_EXPR))
3525            || (code == EQ_EXPR
3526                && (TREE_CODE (rhs) == TRUTH_OR_EXPR
3527                    || TREE_CODE (rhs) == BIT_IOR_EXPR)))
3528     {
3529       /* Recurse on each operand.  */
3530       retval |= register_edge_assert_for_1 (TREE_OPERAND (rhs, 0),
3531                                             code, e, bsi);
3532       retval |= register_edge_assert_for_1 (TREE_OPERAND (rhs, 1),
3533                                             code, e, bsi);
3534     }
3535   else if (TREE_CODE (rhs) == TRUTH_NOT_EXPR)
3536     {
3537       /* Recurse, flipping CODE.  */
3538       code = invert_tree_comparison (code, false);
3539       retval |= register_edge_assert_for_1 (TREE_OPERAND (rhs, 0),
3540                                             code, e, bsi);
3541     }
3542   else if (TREE_CODE (rhs) == SSA_NAME)
3543     {
3544       /* Recurse through the copy.  */
3545       retval |= register_edge_assert_for_1 (rhs, code, e, bsi);
3546     }
3547   else if (TREE_CODE (rhs) == NOP_EXPR
3548            || TREE_CODE (rhs) == CONVERT_EXPR
3549            || TREE_CODE (rhs) == NON_LVALUE_EXPR)
3550     { 
3551       /* Recurse through the type conversion.  */
3552       retval |= register_edge_assert_for_1 (TREE_OPERAND (rhs, 0),
3553                                             code, e, bsi);
3554     }
3555
3556   return retval;
3557 }
3558
3559 /* Try to register an edge assertion for SSA name NAME on edge E for
3560    the condition COND contributing to the conditional jump pointed to by SI.
3561    Return true if an assertion for NAME could be registered.  */
3562
3563 static bool
3564 register_edge_assert_for (tree name, edge e, block_stmt_iterator si, tree cond)
3565 {
3566   tree val;
3567   enum tree_code comp_code;
3568   bool retval = false;
3569   bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3570
3571   /* Do not attempt to infer anything in names that flow through
3572      abnormal edges.  */
3573   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3574     return false;
3575
3576   if (!extract_code_and_val_from_cond (name, cond, is_else_edge,
3577                                        &comp_code, &val))
3578     return false;
3579
3580   /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3581      reachable from E.  */
3582   if (TEST_BIT (found_in_subgraph, SSA_NAME_VERSION (name)))
3583     {
3584       register_new_assert_for (name, comp_code, val, NULL, e, si);
3585       retval = true;
3586     }
3587
3588   /* If COND is effectively an equality test of an SSA_NAME against
3589      the value zero or one, then we may be able to assert values
3590      for SSA_NAMEs which flow into COND.  */
3591
3592   /* In the case of NAME == 1 or NAME != 0, for TRUTH_AND_EXPR defining
3593      statement of NAME we can assert both operands of the TRUTH_AND_EXPR
3594      have nonzero value.  */
3595   if (((comp_code == EQ_EXPR && integer_onep (val))
3596        || (comp_code == NE_EXPR && integer_zerop (val))))
3597     {
3598       tree def_stmt = SSA_NAME_DEF_STMT (name);
3599
3600       if (TREE_CODE (def_stmt) == GIMPLE_MODIFY_STMT
3601           && (TREE_CODE (GIMPLE_STMT_OPERAND (def_stmt, 1)) == TRUTH_AND_EXPR
3602               || TREE_CODE (GIMPLE_STMT_OPERAND (def_stmt, 1)) == BIT_AND_EXPR))
3603         {
3604           tree op0 = TREE_OPERAND (GIMPLE_STMT_OPERAND (def_stmt, 1), 0);
3605           tree op1 = TREE_OPERAND (GIMPLE_STMT_OPERAND (def_stmt, 1), 1);
3606           retval |= register_edge_assert_for_1 (op0, NE_EXPR, e, si);
3607           retval |= register_edge_assert_for_1 (op1, NE_EXPR, e, si);
3608         }
3609     }
3610
3611   /* In the case of NAME == 0 or NAME != 1, for TRUTH_OR_EXPR defining
3612      statement of NAME we can assert both operands of the TRUTH_OR_EXPR
3613      have zero value.  */
3614   if (((comp_code == EQ_EXPR && integer_zerop (val))
3615        || (comp_code == NE_EXPR && integer_onep (val))))
3616     {
3617       tree def_stmt = SSA_NAME_DEF_STMT (name);
3618
3619       if (TREE_CODE (def_stmt) == GIMPLE_MODIFY_STMT
3620           && (TREE_CODE (GIMPLE_STMT_OPERAND (def_stmt, 1)) == TRUTH_OR_EXPR
3621               || TREE_CODE (GIMPLE_STMT_OPERAND (def_stmt, 1)) == BIT_IOR_EXPR))
3622         {
3623           tree op0 = TREE_OPERAND (GIMPLE_STMT_OPERAND (def_stmt, 1), 0);
3624           tree op1 = TREE_OPERAND (GIMPLE_STMT_OPERAND (def_stmt, 1), 1);
3625           retval |= register_edge_assert_for_1 (op0, EQ_EXPR, e, si);
3626           retval |= register_edge_assert_for_1 (op1, EQ_EXPR, e, si);
3627         }
3628     }
3629
3630   return retval;
3631 }
3632
3633
3634 static bool find_assert_locations (basic_block bb);
3635
3636 /* Determine whether the outgoing edges of BB should receive an
3637    ASSERT_EXPR for each of the operands of BB's LAST statement.
3638    The last statement of BB must be a COND_EXPR.
3639
3640    If any of the sub-graphs rooted at BB have an interesting use of
3641    the predicate operands, an assert location node is added to the
3642    list of assertions for the corresponding operands.  */
3643
3644 static bool
3645 find_conditional_asserts (basic_block bb, tree last)
3646 {
3647   bool need_assert;
3648   block_stmt_iterator bsi;
3649   tree op;
3650   edge_iterator ei;
3651   edge e;
3652   ssa_op_iter iter;
3653
3654   need_assert = false;
3655   bsi = bsi_for_stmt (last);
3656
3657   /* Look for uses of the operands in each of the sub-graphs
3658      rooted at BB.  We need to check each of the outgoing edges
3659      separately, so that we know what kind of ASSERT_EXPR to
3660      insert.  */
3661   FOR_EACH_EDGE (e, ei, bb->succs)
3662     {
3663       if (e->dest == bb)
3664         continue;
3665
3666       /* Remove the COND_EXPR operands from the FOUND_IN_SUBGRAPH bitmap.
3667          Otherwise, when we finish traversing each of the sub-graphs, we
3668          won't know whether the variables were found in the sub-graphs or
3669          if they had been found in a block upstream from BB. 
3670
3671          This is actually a bad idea is some cases, particularly jump
3672          threading.  Consider a CFG like the following:
3673
3674                     0
3675                    /|
3676                   1 |
3677                    \|
3678                     2
3679                    / \
3680                   3   4
3681
3682          Assume that one or more operands in the conditional at the
3683          end of block 0 are used in a conditional in block 2, but not
3684          anywhere in block 1.  In this case we will not insert any
3685          assert statements in block 1, which may cause us to miss
3686          opportunities to optimize, particularly for jump threading.  */
3687       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3688         RESET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
3689
3690       /* Traverse the strictly dominated sub-graph rooted at E->DEST
3691          to determine if any of the operands in the conditional
3692          predicate are used.  */
3693       if (e->dest != bb)
3694         need_assert |= find_assert_locations (e->dest);
3695
3696       /* Register the necessary assertions for each operand in the
3697          conditional predicate.  */
3698       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3699         need_assert |= register_edge_assert_for (op, e, bsi,
3700                                                  COND_EXPR_COND (last));
3701     }
3702
3703   /* Finally, indicate that we have found the operands in the
3704      conditional.  */
3705   FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3706     SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
3707
3708   return need_assert;
3709 }
3710
3711 /* Compare two case labels sorting first by the destination label uid
3712    and then by the case value.  */
3713
3714 static int
3715 compare_case_labels (const void *p1, const void *p2)
3716 {
3717   tree case1 = *(tree *)p1;
3718   tree case2 = *(tree *)p2;
3719   unsigned int uid1 = DECL_UID (CASE_LABEL (case1));
3720   unsigned int uid2 = DECL_UID (CASE_LABEL (case2));
3721
3722   if (uid1 < uid2)
3723     return -1;
3724   else if (uid1 == uid2)
3725     {
3726       /* Make sure the default label is first in a group.  */
3727       if (!CASE_LOW (case1))
3728         return -1;
3729       else if (!CASE_LOW (case2))
3730         return 1;
3731       else
3732         return tree_int_cst_compare (CASE_LOW (case1), CASE_LOW (case2));
3733     }
3734   else
3735     return 1;
3736 }
3737
3738 /* Determine whether the outgoing edges of BB should receive an
3739    ASSERT_EXPR for each of the operands of BB's LAST statement.
3740    The last statement of BB must be a SWITCH_EXPR.
3741
3742    If any of the sub-graphs rooted at BB have an interesting use of
3743    the predicate operands, an assert location node is added to the
3744    list of assertions for the corresponding operands.  */
3745
3746 static bool
3747 find_switch_asserts (basic_block bb, tree last)
3748 {
3749   bool need_assert;
3750   block_stmt_iterator bsi;
3751   tree op, cond;
3752   edge e;
3753   tree vec = SWITCH_LABELS (last), vec2;
3754   size_t n = TREE_VEC_LENGTH (vec);
3755   unsigned int idx;
3756
3757   need_assert = false;
3758   bsi = bsi_for_stmt (last);
3759   op = TREE_OPERAND (last, 0);
3760   if (TREE_CODE (op) != SSA_NAME)
3761     return false;
3762
3763   /* Build a vector of case labels sorted by destination label.  */
3764   vec2 = make_tree_vec (n);
3765   for (idx = 0; idx < n; ++idx)
3766     TREE_VEC_ELT (vec2, idx) = TREE_VEC_ELT (vec, idx);
3767   qsort (&TREE_VEC_ELT (vec2, 0), n, sizeof (tree), compare_case_labels);
3768
3769   for (idx = 0; idx < n; ++idx)
3770     {
3771       tree min, max;
3772       tree cl = TREE_VEC_ELT (vec2, idx);
3773
3774       min = CASE_LOW (cl);
3775       max = CASE_HIGH (cl);
3776
3777       /* If there are multiple case labels with the same destination
3778          we need to combine them to a single value range for the edge.  */
3779       if (idx + 1 < n
3780           && CASE_LABEL (cl) == CASE_LABEL (TREE_VEC_ELT (vec2, idx + 1)))
3781         {
3782           /* Skip labels until the last of the group.  */
3783           do {
3784             ++idx;
3785           } while (idx < n
3786                    && CASE_LABEL (cl) == CASE_LABEL (TREE_VEC_ELT (vec2, idx)));
3787           --idx;
3788
3789           /* Pick up the maximum of the case label range.  */
3790           if (CASE_HIGH (TREE_VEC_ELT (vec2, idx)))
3791             max = CASE_HIGH (TREE_VEC_ELT (vec2, idx));
3792           else
3793             max = CASE_LOW (TREE_VEC_ELT (vec2, idx));
3794         }
3795
3796       /* Nothing to do if the range includes the default label until we
3797          can register anti-ranges.  */
3798       if (min == NULL_TREE)
3799         continue;
3800
3801       /* Find the edge to register the assert expr on.  */
3802       e = find_edge (bb, label_to_block (CASE_LABEL (cl)));
3803
3804       /* Remove the SWITCH_EXPR operand from the FOUND_IN_SUBGRAPH bitmap.
3805          Otherwise, when we finish traversing each of the sub-graphs, we
3806          won't know whether the variables were found in the sub-graphs or
3807          if they had been found in a block upstream from BB.  */
3808       RESET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
3809
3810       /* Traverse the strictly dominated sub-graph rooted at E->DEST
3811          to determine if any of the operands in the conditional
3812          predicate are used.  */
3813       if (e->dest != bb)
3814         need_assert |= find_assert_locations (e->dest);
3815
3816       /* Register the necessary assertions for the operand in the
3817          SWITCH_EXPR.  */
3818       cond = build2 (max ? GE_EXPR : EQ_EXPR, boolean_type_node,
3819                      op, fold_convert (TREE_TYPE (op), min));
3820       need_assert |= register_edge_assert_for (op, e, bsi, cond);
3821       if (max)
3822         {
3823           cond = build2 (LE_EXPR, boolean_type_node,
3824                          op, fold_convert (TREE_TYPE (op), max));
3825           need_assert |= register_edge_assert_for (op, e, bsi, cond);
3826         }
3827     }
3828
3829   /* Finally, indicate that we have found the operand in the
3830      SWITCH_EXPR.  */
3831   SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
3832
3833   return need_assert;
3834 }
3835
3836
3837 /* Traverse all the statements in block BB looking for statements that
3838    may generate useful assertions for the SSA names in their operand.
3839    If a statement produces a useful assertion A for name N_i, then the
3840    list of assertions already generated for N_i is scanned to
3841    determine if A is actually needed.
3842    
3843    If N_i already had the assertion A at a location dominating the
3844    current location, then nothing needs to be done.  Otherwise, the
3845    new location for A is recorded instead.
3846
3847    1- For every statement S in BB, all the variables used by S are
3848       added to bitmap FOUND_IN_SUBGRAPH.
3849
3850    2- If statement S uses an operand N in a way that exposes a known
3851       value range for N, then if N was not already generated by an
3852       ASSERT_EXPR, create a new assert location for N.  For instance,
3853       if N is a pointer and the statement dereferences it, we can
3854       assume that N is not NULL.
3855
3856    3- COND_EXPRs are a special case of #2.  We can derive range
3857       information from the predicate but need to insert different
3858       ASSERT_EXPRs for each of the sub-graphs rooted at the
3859       conditional block.  If the last statement of BB is a conditional
3860       expression of the form 'X op Y', then
3861
3862       a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3863
3864       b) If the conditional is the only entry point to the sub-graph
3865          corresponding to the THEN_CLAUSE, recurse into it.  On
3866          return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3867          an ASSERT_EXPR is added for the corresponding variable.
3868
3869       c) Repeat step (b) on the ELSE_CLAUSE.
3870
3871       d) Mark X and Y in FOUND_IN_SUBGRAPH.
3872
3873       For instance,
3874
3875             if (a == 9)
3876               b = a;
3877             else
3878               b = c + 1;
3879
3880       In this case, an assertion on the THEN clause is useful to
3881       determine that 'a' is always 9 on that edge.  However, an assertion
3882       on the ELSE clause would be unnecessary.
3883
3884    4- If BB does not end in a conditional expression, then we recurse
3885       into BB's dominator children.
3886    
3887    At the end of the recursive traversal, every SSA name will have a
3888    list of locations where ASSERT_EXPRs should be added.  When a new
3889    location for name N is found, it is registered by calling
3890    register_new_assert_for.  That function keeps track of all the
3891    registered assertions to prevent adding unnecessary assertions.
3892    For instance, if a pointer P_4 is dereferenced more than once in a
3893    dominator tree, only the location dominating all the dereference of
3894    P_4 will receive an ASSERT_EXPR.
3895
3896    If this function returns true, then it means that there are names
3897    for which we need to generate ASSERT_EXPRs.  Those assertions are
3898    inserted by process_assert_insertions.  */
3899
3900 static bool
3901 find_assert_locations (basic_block bb)
3902 {
3903   block_stmt_iterator si;
3904   tree last, phi;
3905   bool need_assert;
3906   basic_block son;
3907
3908   if (TEST_BIT (blocks_visited, bb->index))
3909     return false;
3910
3911   SET_BIT (blocks_visited, bb->index);
3912
3913   need_assert = false;
3914
3915   /* Traverse all PHI nodes in BB marking used operands.  */
3916   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
3917     {
3918       use_operand_p arg_p;
3919       ssa_op_iter i;
3920
3921       FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3922         {
3923           tree arg = USE_FROM_PTR (arg_p);
3924           if (TREE_CODE (arg) == SSA_NAME)
3925             {
3926               gcc_assert (is_gimple_reg (PHI_RESULT (phi)));
3927               SET_BIT (found_in_subgraph, SSA_NAME_VERSION (arg));
3928             }
3929         }
3930     }
3931
3932   /* Traverse all the statements in BB marking used names and looking
3933      for statements that may infer assertions for their used operands.  */
3934   last = NULL_TREE;
3935   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
3936     {
3937       tree stmt, op;
3938       ssa_op_iter i;
3939
3940       stmt = bsi_stmt (si);
3941
3942       /* See if we can derive an assertion for any of STMT's operands.  */
3943       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3944         {
3945           tree value;
3946           enum tree_code comp_code;
3947
3948           /* Mark OP in bitmap FOUND_IN_SUBGRAPH.  If STMT is inside
3949              the sub-graph of a conditional block, when we return from
3950              this recursive walk, our parent will use the
3951              FOUND_IN_SUBGRAPH bitset to determine if one of the
3952              operands it was looking for was present in the sub-graph.  */
3953           SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
3954
3955           /* If OP is used in such a way that we can infer a value
3956              range for it, and we don't find a previous assertion for
3957              it, create a new assertion location node for OP.  */
3958           if (infer_value_range (stmt, op, &comp_code, &value))
3959             {
3960               /* If we are able to infer a nonzero value range for OP,
3961                  then walk backwards through the use-def chain to see if OP
3962                  was set via a typecast.
3963
3964                  If so, then we can also infer a nonzero value range
3965                  for the operand of the NOP_EXPR.  */
3966               if (comp_code == NE_EXPR && integer_zerop (value))
3967                 {
3968                   tree t = op;
3969                   tree def_stmt = SSA_NAME_DEF_STMT (t);
3970         
3971                   while (TREE_CODE (def_stmt) == GIMPLE_MODIFY_STMT
3972                          && TREE_CODE
3973                              (GIMPLE_STMT_OPERAND (def_stmt, 1)) == NOP_EXPR
3974                          && TREE_CODE
3975                              (TREE_OPERAND (GIMPLE_STMT_OPERAND (def_stmt, 1),
3976                                             0)) == SSA_NAME
3977                          && POINTER_TYPE_P
3978                              (TREE_TYPE (TREE_OPERAND
3979                                           (GIMPLE_STMT_OPERAND (def_stmt,
3980                                                                 1), 0))))
3981                     {
3982                       t = TREE_OPERAND (GIMPLE_STMT_OPERAND (def_stmt, 1), 0);
3983                       def_stmt = SSA_NAME_DEF_STMT (t);
3984
3985                       /* Note we want to register the assert for the
3986                          operand of the NOP_EXPR after SI, not after the
3987                          conversion.  */
3988                       if (! has_single_use (t))
3989                         {
3990                           register_new_assert_for (t, comp_code, value,
3991                                                    bb, NULL, si);
3992                           need_assert = true;
3993                         }
3994                     }
3995                 }
3996
3997               /* If OP is used only once, namely in this STMT, don't
3998                  bother creating an ASSERT_EXPR for it.  Such an
3999                  ASSERT_EXPR would do nothing but increase compile time.  */
4000               if (!has_single_use (op))
4001                 {
4002                   register_new_assert_for (op, comp_code, value, bb, NULL, si);
4003                   need_assert = true;
4004                 }
4005             }
4006         }
4007
4008       /* Remember the last statement of the block.  */
4009       last = stmt;
4010     }
4011
4012   /* If BB's last statement is a conditional expression
4013      involving integer operands, recurse into each of the sub-graphs
4014      rooted at BB to determine if we need to add ASSERT_EXPRs.  */
4015   if (last
4016       && TREE_CODE (last) == COND_EXPR
4017       && !fp_predicate (COND_EXPR_COND (last))
4018       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4019     need_assert |= find_conditional_asserts (bb, last);
4020
4021   if (last
4022       && TREE_CODE (last) == SWITCH_EXPR
4023       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4024     need_assert |= find_switch_asserts (bb, last);
4025
4026   /* Recurse into the dominator children of BB.  */
4027   for (son = first_dom_son (CDI_DOMINATORS, bb);
4028        son;
4029        son = next_dom_son (CDI_DOMINATORS, son))
4030     need_assert |= find_assert_locations (son);
4031
4032   return need_assert;
4033 }
4034
4035
4036 /* Create an ASSERT_EXPR for NAME and insert it in the location
4037    indicated by LOC.  Return true if we made any edge insertions.  */
4038
4039 static bool
4040 process_assert_insertions_for (tree name, assert_locus_t loc)
4041 {
4042   /* Build the comparison expression NAME_i COMP_CODE VAL.  */
4043   tree stmt, cond, assert_expr;
4044   edge_iterator ei;
4045   edge e;
4046
4047   cond = build2 (loc->comp_code, boolean_type_node, name, loc->val);
4048   assert_expr = build_assert_expr_for (cond, name);
4049
4050   if (loc->e)
4051     {
4052       /* We have been asked to insert the assertion on an edge.  This
4053          is used only by COND_EXPR and SWITCH_EXPR assertions.  */
4054 #if defined ENABLE_CHECKING
4055       gcc_assert (TREE_CODE (bsi_stmt (loc->si)) == COND_EXPR
4056           || TREE_CODE (bsi_stmt (loc->si)) == SWITCH_EXPR);
4057 #endif
4058
4059       bsi_insert_on_edge (loc->e, assert_expr);
4060       return true;
4061     }
4062
4063   /* Otherwise, we can insert right after LOC->SI iff the
4064      statement must not be the last statement in the block.  */
4065   stmt = bsi_stmt (loc->si);
4066   if (!stmt_ends_bb_p (stmt))
4067     {
4068       bsi_insert_after (&loc->si, assert_expr, BSI_SAME_STMT);
4069       return false;
4070     }
4071
4072   /* If STMT must be the last statement in BB, we can only insert new
4073      assertions on the non-abnormal edge out of BB.  Note that since
4074      STMT is not control flow, there may only be one non-abnormal edge
4075      out of BB.  */
4076   FOR_EACH_EDGE (e, ei, loc->bb->succs)
4077     if (!(e->flags & EDGE_ABNORMAL))
4078       {
4079         bsi_insert_on_edge (e, assert_expr);
4080         return true;
4081       }
4082
4083   gcc_unreachable ();
4084 }
4085
4086
4087 /* Process all the insertions registered for every name N_i registered
4088    in NEED_ASSERT_FOR.  The list of assertions to be inserted are
4089    found in ASSERTS_FOR[i].  */
4090
4091 static void
4092 process_assert_insertions (void)
4093 {
4094   unsigned i;
4095   bitmap_iterator bi;
4096   bool update_edges_p = false;
4097   int num_asserts = 0;
4098
4099   if (dump_file && (dump_flags & TDF_DETAILS))
4100     dump_all_asserts (dump_file);
4101
4102   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4103     {
4104       assert_locus_t loc = asserts_for[i];
4105       gcc_assert (loc);
4106
4107       while (loc)
4108         {
4109           assert_locus_t next = loc->next;
4110           update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4111           free (loc);
4112           loc = next;
4113           num_asserts++;
4114         }
4115     }
4116
4117   if (update_edges_p)
4118     bsi_commit_edge_inserts ();
4119
4120   if (dump_file && (dump_flags & TDF_STATS))
4121     fprintf (dump_file, "\nNumber of ASSERT_EXPR expressions inserted: %d\n\n",
4122              num_asserts);
4123 }
4124
4125
4126 /* Traverse the flowgraph looking for conditional jumps to insert range
4127    expressions.  These range expressions are meant to provide information
4128    to optimizations that need to reason in terms of value ranges.  They
4129    will not be expanded into RTL.  For instance, given:
4130
4131    x = ...
4132    y = ...
4133    if (x < y)
4134      y = x - 2;
4135    else
4136      x = y + 3;
4137
4138    this pass will transform the code into:
4139
4140    x = ...
4141    y = ...
4142    if (x < y)
4143     {
4144       x = ASSERT_EXPR <x, x < y>
4145       y = x - 2
4146     }
4147    else
4148     {
4149       y = ASSERT_EXPR <y, x <= y>
4150       x = y + 3
4151     }
4152
4153    The idea is that once copy and constant propagation have run, other
4154    optimizations will be able to determine what ranges of values can 'x'
4155    take in different paths of the code, simply by checking the reaching
4156    definition of 'x'.  */
4157
4158 static void
4159 insert_range_assertions (void)
4160 {
4161   edge e;
4162   edge_iterator ei;
4163   bool update_ssa_p;
4164   
4165   found_in_subgraph = sbitmap_alloc (num_ssa_names);
4166   sbitmap_zero (found_in_subgraph);
4167
4168   blocks_visited = sbitmap_alloc (last_basic_block);
4169   sbitmap_zero (blocks_visited);
4170
4171   need_assert_for = BITMAP_ALLOC (NULL);
4172   asserts_for = XCNEWVEC (assert_locus_t, num_ssa_names);
4173
4174   calculate_dominance_info (CDI_DOMINATORS);
4175
4176   update_ssa_p = false;
4177   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
4178     if (find_assert_locations (e->dest))
4179       update_ssa_p = true;
4180
4181   if (update_ssa_p)
4182     {
4183       process_assert_insertions ();
4184       update_ssa (TODO_update_ssa_no_phi);
4185     }
4186
4187   if (dump_file && (dump_flags & TDF_DETAILS))
4188     {
4189       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4190       dump_function_to_file (current_function_decl, dump_file, dump_flags);
4191     }
4192
4193   sbitmap_free (found_in_subgraph);
4194   free (asserts_for);
4195   BITMAP_FREE (need_assert_for);
4196 }
4197
4198 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4199    and "struct" hacks. If VRP can determine that the
4200    array subscript is a constant, check if it is outside valid
4201    range. If the array subscript is a RANGE, warn if it is
4202    non-overlapping with valid range.
4203    IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR.  */
4204
4205 static void
4206 check_array_ref (tree ref, location_t* locus, bool ignore_off_by_one)
4207 {
4208   value_range_t* vr = NULL;
4209   tree low_sub, up_sub;
4210   tree low_bound, up_bound = array_ref_up_bound (ref);
4211
4212   low_sub = up_sub = TREE_OPERAND (ref, 1);
4213
4214   if (!up_bound || !locus || TREE_NO_WARNING (ref)
4215       || TREE_CODE (up_bound) != INTEGER_CST
4216       /* Can not check flexible arrays.  */
4217       || (TYPE_SIZE (TREE_TYPE (ref)) == NULL_TREE
4218           && TYPE_DOMAIN (TREE_TYPE (ref)) != NULL_TREE
4219           && TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (ref))) == NULL_TREE)
4220       /* Accesses after the end of arrays of size 0 (gcc
4221          extension) and 1 are likely intentional ("struct
4222          hack").  */
4223       || compare_tree_int (up_bound, 1) <= 0)
4224     return;
4225
4226   low_bound = array_ref_low_bound (ref);
4227
4228   if (TREE_CODE (low_sub) == SSA_NAME)
4229     {
4230       vr = get_value_range (low_sub);
4231       if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4232         {
4233           low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4234           up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4235         }
4236     }
4237
4238   if (vr && vr->type == VR_ANTI_RANGE)
4239     {
4240       if (TREE_CODE (up_sub) == INTEGER_CST
4241           && tree_int_cst_lt (up_bound, up_sub)
4242           && TREE_CODE (low_sub) == INTEGER_CST
4243           && tree_int_cst_lt (low_sub, low_bound))
4244         {
4245           warning (OPT_Warray_bounds,
4246                    "%Harray subscript is outside array bounds", locus);
4247           TREE_NO_WARNING (ref) = 1;
4248         }
4249     }
4250   else if (TREE_CODE (up_sub) == INTEGER_CST
4251            && tree_int_cst_lt (up_bound, up_sub)
4252            && !tree_int_cst_equal (up_bound, up_sub)
4253            && (!ignore_off_by_one
4254                || !tree_int_cst_equal (int_const_binop (PLUS_EXPR,
4255                                                         up_bound,
4256                                                         integer_one_node,
4257                                                         0),
4258                                        up_sub)))
4259     {
4260       warning (OPT_Warray_bounds, "%Harray subscript is above array bounds",
4261                locus);
4262       TREE_NO_WARNING (ref) = 1;
4263     }
4264   else if (TREE_CODE (low_sub) == INTEGER_CST
4265            && tree_int_cst_lt (low_sub, low_bound))
4266     {
4267       warning (OPT_Warray_bounds, "%Harray subscript is below array bounds",
4268                locus);
4269       TREE_NO_WARNING (ref) = 1;
4270     }
4271 }
4272
4273 /* Searches if the expr T, located at LOCATION computes
4274    address of an ARRAY_REF, and call check_array_ref on it.  */
4275
4276 static void
4277 search_for_addr_array(tree t, location_t* location)
4278 {
4279   while (TREE_CODE (t) == SSA_NAME)
4280     {
4281       t = SSA_NAME_DEF_STMT (t);
4282       if (TREE_CODE (t) != GIMPLE_MODIFY_STMT)
4283         return;
4284       t = GIMPLE_STMT_OPERAND (t, 1);
4285     }
4286
4287
4288   /* We are only interested in addresses of ARRAY_REF's.  */
4289   if (TREE_CODE (t) != ADDR_EXPR) 
4290     return;
4291
4292   /* Check each ARRAY_REFs in the reference chain. */
4293   do 
4294     {
4295       if (TREE_CODE (t) == ARRAY_REF)
4296         check_array_ref (t, location, true /*ignore_off_by_one*/);
4297
4298       t = TREE_OPERAND(t,0);
4299     }
4300   while (handled_component_p (t));
4301 }
4302
4303 /* walk_tree() callback that checks if *TP is
4304    an ARRAY_REF inside an ADDR_EXPR (in which an array
4305    subscript one outside the valid range is allowed). Call
4306    check_array_ref for each ARRAY_REF found. The location is 
4307    passed in DATA.  */
4308
4309 static tree
4310 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4311 {
4312   tree t = *tp;
4313   tree stmt = (tree)data;
4314   location_t *location = EXPR_LOCUS (stmt);
4315
4316   *walk_subtree = TRUE;
4317
4318   if (TREE_CODE (t) == ARRAY_REF)
4319     check_array_ref (t, location, false /*ignore_off_by_one*/);
4320
4321   if (TREE_CODE (t) == INDIRECT_REF
4322       || (TREE_CODE (t) == RETURN_EXPR && TREE_OPERAND (t, 0)))
4323     search_for_addr_array (TREE_OPERAND (t, 0), location);
4324   else if (TREE_CODE (t) == CALL_EXPR)
4325     {
4326       tree arg;
4327       call_expr_arg_iterator iter;
4328
4329       FOR_EACH_CALL_EXPR_ARG (arg, iter, t) 
4330         search_for_addr_array (arg, location);
4331     }
4332
4333   if (TREE_CODE (t) == ADDR_EXPR)
4334     *walk_subtree = FALSE;
4335
4336   return NULL_TREE;
4337 }
4338
4339 /* Walk over all statements of all reachable BBs and call check_array_bounds
4340    on them.  */
4341
4342 static void
4343 check_all_array_refs (void)
4344 {
4345   basic_block bb;
4346   block_stmt_iterator si;
4347
4348   FOR_EACH_BB (bb)
4349     {
4350       /* Skip bb's that are clearly unreachable.  */
4351       if (single_pred_p (bb))
4352       {
4353         basic_block pred_bb = EDGE_PRED (bb, 0)->src;
4354         tree ls = NULL_TREE;
4355
4356         if (!bsi_end_p (bsi_last (pred_bb)))
4357           ls = bsi_stmt (bsi_last (pred_bb));
4358
4359         if (ls && TREE_CODE (ls) == COND_EXPR
4360             && ((COND_EXPR_COND (ls) == boolean_false_node
4361                  && (EDGE_PRED (bb, 0)->flags & EDGE_TRUE_VALUE))
4362                 || (COND_EXPR_COND (ls) == boolean_true_node
4363                     && (EDGE_PRED (bb, 0)->flags & EDGE_FALSE_VALUE))))
4364           continue;
4365       }
4366       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
4367         walk_tree (bsi_stmt_ptr (si), check_array_bounds,
4368                    bsi_stmt (si), NULL);
4369     }
4370 }
4371
4372 /* Convert range assertion expressions into the implied copies and
4373    copy propagate away the copies.  Doing the trivial copy propagation
4374    here avoids the need to run the full copy propagation pass after
4375    VRP. 
4376    
4377    FIXME, this will eventually lead to copy propagation removing the
4378    names that had useful range information attached to them.  For
4379    instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4380    then N_i will have the range [3, +INF].
4381    
4382    However, by converting the assertion into the implied copy
4383    operation N_i = N_j, we will then copy-propagate N_j into the uses
4384    of N_i and lose the range information.  We may want to hold on to
4385    ASSERT_EXPRs a little while longer as the ranges could be used in
4386    things like jump threading.
4387    
4388    The problem with keeping ASSERT_EXPRs around is that passes after
4389    VRP need to handle them appropriately. 
4390
4391    Another approach would be to make the range information a first
4392    class property of the SSA_NAME so that it can be queried from
4393    any pass.  This is made somewhat more complex by the need for
4394    multiple ranges to be associated with one SSA_NAME.  */
4395
4396 static void
4397 remove_range_assertions (void)
4398 {
4399   basic_block bb;
4400   block_stmt_iterator si;
4401
4402   /* Note that the BSI iterator bump happens at the bottom of the
4403      loop and no bump is necessary if we're removing the statement
4404      referenced by the current BSI.  */
4405   FOR_EACH_BB (bb)
4406     for (si = bsi_start (bb); !bsi_end_p (si);)
4407       {
4408         tree stmt = bsi_stmt (si);
4409         tree use_stmt;
4410
4411         if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
4412             && TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == ASSERT_EXPR)
4413           {
4414             tree rhs = GIMPLE_STMT_OPERAND (stmt, 1), var;
4415             tree cond = fold (ASSERT_EXPR_COND (rhs));
4416             use_operand_p use_p;
4417             imm_use_iterator iter;
4418
4419             gcc_assert (cond != boolean_false_node);
4420
4421             /* Propagate the RHS into every use of the LHS.  */
4422             var = ASSERT_EXPR_VAR (rhs);
4423             FOR_EACH_IMM_USE_STMT (use_stmt, iter,
4424                                    GIMPLE_STMT_OPERAND (stmt, 0))
4425               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4426                 {
4427                   SET_USE (use_p, var);
4428                   gcc_assert (TREE_CODE (var) == SSA_NAME);
4429                 }
4430
4431             /* And finally, remove the copy, it is not needed.  */
4432             bsi_remove (&si, true);
4433             release_defs (stmt); 
4434           }
4435         else
4436           bsi_next (&si);
4437       }
4438
4439   sbitmap_free (blocks_visited);
4440 }
4441
4442
4443 /* Return true if STMT is interesting for VRP.  */
4444
4445 static bool
4446 stmt_interesting_for_vrp (tree stmt)
4447 {
4448   if (TREE_CODE (stmt) == PHI_NODE
4449       && is_gimple_reg (PHI_RESULT (stmt))
4450       && (INTEGRAL_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))
4451           || POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))))
4452     return true;
4453   else if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
4454     {
4455       tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
4456       tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
4457
4458       /* In general, assignments with virtual operands are not useful
4459          for deriving ranges, with the obvious exception of calls to
4460          builtin functions.  */
4461       if (TREE_CODE (lhs) == SSA_NAME
4462           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4463               || POINTER_TYPE_P (TREE_TYPE (lhs)))
4464           && ((TREE_CODE (rhs) == CALL_EXPR
4465                && TREE_CODE (CALL_EXPR_FN (rhs)) == ADDR_EXPR
4466                && DECL_P (TREE_OPERAND (CALL_EXPR_FN (rhs), 0))
4467                && DECL_IS_BUILTIN (TREE_OPERAND (CALL_EXPR_FN (rhs), 0)))
4468               || ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS)))
4469         return true;
4470     }
4471   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
4472     return true;
4473
4474   return false;
4475 }
4476
4477
4478 /* Initialize local data structures for VRP.  */
4479
4480 static void
4481 vrp_initialize (void)
4482 {
4483   basic_block bb;
4484
4485   vr_value = XCNEWVEC (value_range_t *, num_ssa_names);
4486   vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
4487
4488   FOR_EACH_BB (bb)
4489     {
4490       block_stmt_iterator si;
4491       tree phi;
4492
4493       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
4494         {
4495           if (!stmt_interesting_for_vrp (phi))
4496             {
4497               tree lhs = PHI_RESULT (phi);
4498               set_value_range_to_varying (get_value_range (lhs));
4499               DONT_SIMULATE_AGAIN (phi) = true;
4500             }
4501           else
4502             DONT_SIMULATE_AGAIN (phi) = false;
4503         }
4504
4505       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
4506         {
4507           tree stmt = bsi_stmt (si);
4508
4509           if (!stmt_interesting_for_vrp (stmt))
4510             {
4511               ssa_op_iter i;
4512               tree def;
4513               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
4514                 set_value_range_to_varying (get_value_range (def));
4515               DONT_SIMULATE_AGAIN (stmt) = true;
4516             }
4517           else
4518             {
4519               DONT_SIMULATE_AGAIN (stmt) = false;
4520             }
4521         }
4522     }
4523 }
4524
4525
4526 /* Visit assignment STMT.  If it produces an interesting range, record
4527    the SSA name in *OUTPUT_P.  */
4528
4529 static enum ssa_prop_result
4530 vrp_visit_assignment (tree stmt, tree *output_p)
4531 {
4532   tree lhs, rhs, def;
4533   ssa_op_iter iter;
4534
4535   lhs = GIMPLE_STMT_OPERAND (stmt, 0);
4536   rhs = GIMPLE_STMT_OPERAND (stmt, 1);
4537
4538   /* We only keep track of ranges in integral and pointer types.  */
4539   if (TREE_CODE (lhs) == SSA_NAME
4540       && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4541            /* It is valid to have NULL MIN/MAX values on a type.  See
4542               build_range_type.  */
4543            && TYPE_MIN_VALUE (TREE_TYPE (lhs))
4544            && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
4545           || POINTER_TYPE_P (TREE_TYPE (lhs))))
4546     {
4547       struct loop *l;
4548       value_range_t new_vr = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
4549
4550       extract_range_from_expr (&new_vr, rhs);
4551
4552       /* If STMT is inside a loop, we may be able to know something
4553          else about the range of LHS by examining scalar evolution
4554          information.  */
4555       if (current_loops && (l = loop_containing_stmt (stmt)))
4556         adjust_range_with_scev (&new_vr, l, stmt, lhs);
4557
4558       if (update_value_range (lhs, &new_vr))
4559         {
4560           *output_p = lhs;
4561
4562           if (dump_file && (dump_flags & TDF_DETAILS))
4563             {
4564               fprintf (dump_file, "Found new range for ");
4565               print_generic_expr (dump_file, lhs, 0);
4566               fprintf (dump_file, ": ");
4567               dump_value_range (dump_file, &new_vr);
4568               fprintf (dump_file, "\n\n");
4569             }
4570
4571           if (new_vr.type == VR_VARYING)
4572             return SSA_PROP_VARYING;
4573
4574           return SSA_PROP_INTERESTING;
4575         }
4576
4577       return SSA_PROP_NOT_INTERESTING;
4578     }
4579   
4580   /* Every other statement produces no useful ranges.  */
4581   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
4582     set_value_range_to_varying (get_value_range (def));
4583
4584   return SSA_PROP_VARYING;
4585 }
4586
4587 /* Helper that gets the value range of the SSA_NAME with version I
4588    or a symbolic range contaning the SSA_NAME only if the value range
4589    is varying or undefined.  */
4590
4591 static inline value_range_t
4592 get_vr_for_comparison (int i)
4593 {
4594   value_range_t vr = *(vr_value[i]);
4595
4596   /* If name N_i does not have a valid range, use N_i as its own
4597      range.  This allows us to compare against names that may
4598      have N_i in their ranges.  */
4599   if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
4600     {
4601       vr.type = VR_RANGE;
4602       vr.min = ssa_name (i);
4603       vr.max = ssa_name (i);
4604     }
4605
4606   return vr;
4607 }
4608
4609 /* Compare all the value ranges for names equivalent to VAR with VAL
4610    using comparison code COMP.  Return the same value returned by
4611    compare_range_with_value, including the setting of
4612    *STRICT_OVERFLOW_P.  */
4613
4614 static tree
4615 compare_name_with_value (enum tree_code comp, tree var, tree val,
4616                          bool *strict_overflow_p)
4617 {
4618   bitmap_iterator bi;
4619   unsigned i;
4620   bitmap e;
4621   tree retval, t;
4622   int used_strict_overflow;
4623   bool sop;
4624   value_range_t equiv_vr;
4625
4626   /* Get the set of equivalences for VAR.  */
4627   e = get_value_range (var)->equiv;
4628
4629   /* Start at -1.  Set it to 0 if we do a comparison without relying
4630      on overflow, or 1 if all comparisons rely on overflow.  */
4631   used_strict_overflow = -1;
4632
4633   /* Compare vars' value range with val.  */
4634   equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
4635   sop = false;
4636   retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
4637   if (sop)
4638     used_strict_overflow = 1;
4639
4640   /* If the equiv set is empty we have done all work we need to do.  */
4641   if (e == NULL)
4642     {
4643       if (retval
4644           && used_strict_overflow > 0)
4645         *strict_overflow_p = true;
4646       return retval;
4647     }
4648
4649   EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
4650     {
4651       equiv_vr = get_vr_for_comparison (i);
4652       sop = false;
4653       t = compare_range_with_value (comp, &equiv_vr, val, &sop);
4654       if (t)
4655         {
4656           /* If we get different answers from different members
4657              of the equivalence set this check must be in a dead
4658              code region.  Folding it to a trap representation
4659              would be correct here.  For now just return don't-know.  */
4660           if (retval != NULL
4661               && t != retval)
4662             {
4663               retval = NULL_TREE;
4664               break;
4665             }
4666           retval = t;
4667
4668           if (!sop)
4669             used_strict_overflow = 0;
4670           else if (used_strict_overflow < 0)
4671             used_strict_overflow = 1;
4672         }
4673     }
4674
4675   if (retval
4676       && used_strict_overflow > 0)
4677     *strict_overflow_p = true;
4678
4679   return retval;
4680 }
4681
4682
4683 /* Given a comparison code COMP and names N1 and N2, compare all the
4684    ranges equivalent to N1 against all the ranges equivalent to N2
4685    to determine the value of N1 COMP N2.  Return the same value
4686    returned by compare_ranges.  Set *STRICT_OVERFLOW_P to indicate
4687    whether we relied on an overflow infinity in the comparison.  */
4688
4689
4690 static tree
4691 compare_names (enum tree_code comp, tree n1, tree n2,
4692                bool *strict_overflow_p)
4693 {
4694   tree t, retval;
4695   bitmap e1, e2;
4696   bitmap_iterator bi1, bi2;
4697   unsigned i1, i2;
4698   int used_strict_overflow;
4699   static bitmap_obstack *s_obstack = NULL;
4700   static bitmap s_e1 = NULL, s_e2 = NULL;
4701
4702   /* Compare the ranges of every name equivalent to N1 against the
4703      ranges of every name equivalent to N2.  */
4704   e1 = get_value_range (n1)->equiv;
4705   e2 = get_value_range (n2)->equiv;
4706
4707   /* Use the fake bitmaps if e1 or e2 are not available.  */
4708   if (s_obstack == NULL)
4709     {
4710       s_obstack = XNEW (bitmap_obstack);
4711       bitmap_obstack_initialize (s_obstack);
4712       s_e1 = BITMAP_ALLOC (s_obstack);
4713       s_e2 = BITMAP_ALLOC (s_obstack);
4714     }
4715   if (e1 == NULL)
4716     e1 = s_e1;
4717   if (e2 == NULL)
4718     e2 = s_e2;
4719
4720   /* Add N1 and N2 to their own set of equivalences to avoid
4721      duplicating the body of the loop just to check N1 and N2
4722      ranges.  */
4723   bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
4724   bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
4725
4726   /* If the equivalence sets have a common intersection, then the two
4727      names can be compared without checking their ranges.  */
4728   if (bitmap_intersect_p (e1, e2))
4729     {
4730       bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
4731       bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
4732
4733       return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
4734              ? boolean_true_node
4735              : boolean_false_node;
4736     }
4737
4738   /* Start at -1.  Set it to 0 if we do a comparison without relying
4739      on overflow, or 1 if all comparisons rely on overflow.  */
4740   used_strict_overflow = -1;
4741
4742   /* Otherwise, compare all the equivalent ranges.  First, add N1 and
4743      N2 to their own set of equivalences to avoid duplicating the body
4744      of the loop just to check N1 and N2 ranges.  */
4745   EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
4746     {
4747       value_range_t vr1 = get_vr_for_comparison (i1);
4748
4749       t = retval = NULL_TREE;
4750       EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
4751         {
4752           bool sop;
4753
4754           value_range_t vr2 = get_vr_for_comparison (i2);
4755
4756           t = compare_ranges (comp, &vr1, &vr2, &sop);
4757           if (t)
4758             {
4759               /* If we get different answers from different members
4760                  of the equivalence set this check must be in a dead
4761                  code region.  Folding it to a trap representation
4762                  would be correct here.  For now just return don't-know.  */
4763               if (retval != NULL
4764                   && t != retval)
4765                 {
4766                   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
4767                   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
4768                   return NULL_TREE;
4769                 }
4770               retval = t;
4771
4772               if (!sop)
4773                 used_strict_overflow = 0;
4774               else if (used_strict_overflow < 0)
4775                 used_strict_overflow = 1;
4776             }
4777         }
4778
4779       if (retval)
4780         {
4781           bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
4782           bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
4783           if (used_strict_overflow > 0)
4784             *strict_overflow_p = true;
4785           return retval;
4786         }
4787     }
4788
4789   /* None of the equivalent ranges are useful in computing this
4790      comparison.  */
4791   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
4792   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
4793   return NULL_TREE;
4794 }
4795
4796
4797 /* Given a conditional predicate COND, try to determine if COND yields
4798    true or false based on the value ranges of its operands.  Return
4799    BOOLEAN_TRUE_NODE if the conditional always evaluates to true,
4800    BOOLEAN_FALSE_NODE if the conditional always evaluates to false, and,
4801    NULL if the conditional cannot be evaluated at compile time.
4802
4803    If USE_EQUIV_P is true, the ranges of all the names equivalent with
4804    the operands in COND are used when trying to compute its value.
4805    This is only used during final substitution.  During propagation,
4806    we only check the range of each variable and not its equivalents.
4807
4808    Set *STRICT_OVERFLOW_P to indicate whether we relied on an overflow
4809    infinity to produce the result.  */
4810
4811 static tree
4812 vrp_evaluate_conditional_warnv (tree cond, bool use_equiv_p,
4813                                 bool *strict_overflow_p)
4814 {
4815   gcc_assert (TREE_CODE (cond) == SSA_NAME
4816               || TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
4817
4818   if (TREE_CODE (cond) == SSA_NAME)
4819     {
4820       value_range_t *vr;
4821       tree retval;
4822
4823       if (use_equiv_p)
4824         retval = compare_name_with_value (NE_EXPR, cond, boolean_false_node,
4825                                           strict_overflow_p);
4826       else
4827         {
4828           value_range_t *vr = get_value_range (cond);
4829           retval = compare_range_with_value (NE_EXPR, vr, boolean_false_node,
4830                                              strict_overflow_p);
4831         }
4832
4833       /* If COND has a known boolean range, return it.  */
4834       if (retval)
4835         return retval;
4836
4837       /* Otherwise, if COND has a symbolic range of exactly one value,
4838          return it.  */
4839       vr = get_value_range (cond);
4840       if (vr->type == VR_RANGE && vr->min == vr->max)
4841         return vr->min;
4842     }
4843   else
4844     {
4845       tree op0 = TREE_OPERAND (cond, 0);
4846       tree op1 = TREE_OPERAND (cond, 1);
4847
4848       /* We only deal with integral and pointer types.  */
4849       if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
4850           && !POINTER_TYPE_P (TREE_TYPE (op0)))
4851         return NULL_TREE;
4852
4853       if (use_equiv_p)
4854         {
4855           if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME)
4856             return compare_names (TREE_CODE (cond), op0, op1,
4857                                   strict_overflow_p);
4858           else if (TREE_CODE (op0) == SSA_NAME)
4859             return compare_name_with_value (TREE_CODE (cond), op0, op1,
4860                                             strict_overflow_p);
4861           else if (TREE_CODE (op1) == SSA_NAME)
4862             return (compare_name_with_value
4863                     (swap_tree_comparison (TREE_CODE (cond)), op1, op0,
4864                      strict_overflow_p));
4865         }
4866       else
4867         {
4868           value_range_t *vr0, *vr1;
4869
4870           vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
4871           vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
4872
4873           if (vr0 && vr1)
4874             return compare_ranges (TREE_CODE (cond), vr0, vr1,
4875                                    strict_overflow_p);
4876           else if (vr0 && vr1 == NULL)
4877             return compare_range_with_value (TREE_CODE (cond), vr0, op1,
4878                                              strict_overflow_p);
4879           else if (vr0 == NULL && vr1)
4880             return (compare_range_with_value
4881                     (swap_tree_comparison (TREE_CODE (cond)), vr1, op0,
4882                      strict_overflow_p));
4883         }
4884     }
4885
4886   /* Anything else cannot be computed statically.  */
4887   return NULL_TREE;
4888 }
4889
4890 /* Given COND within STMT, try to simplify it based on value range
4891    information.  Return NULL if the conditional can not be evaluated.
4892    The ranges of all the names equivalent with the operands in COND
4893    will be used when trying to compute the value.  If the result is
4894    based on undefined signed overflow, issue a warning if
4895    appropriate.  */
4896
4897 tree
4898 vrp_evaluate_conditional (tree cond, tree stmt)
4899 {
4900   bool sop;
4901   tree ret;
4902
4903   sop = false;
4904   ret = vrp_evaluate_conditional_warnv (cond, true, &sop);
4905
4906   if (ret && sop)
4907     {
4908       enum warn_strict_overflow_code wc;
4909       const char* warnmsg;
4910
4911       if (is_gimple_min_invariant (ret))
4912         {
4913           wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
4914           warnmsg = G_("assuming signed overflow does not occur when "
4915                        "simplifying conditional to constant");
4916         }
4917       else
4918         {
4919           wc = WARN_STRICT_OVERFLOW_COMPARISON;
4920           warnmsg = G_("assuming signed overflow does not occur when "
4921                        "simplifying conditional");
4922         }
4923
4924       if (issue_strict_overflow_warning (wc))
4925         {
4926           location_t locus;
4927
4928           if (!EXPR_HAS_LOCATION (stmt))
4929             locus = input_location;
4930           else
4931             locus = EXPR_LOCATION (stmt);
4932           warning (OPT_Wstrict_overflow, "%H%s", &locus, warnmsg);
4933         }
4934     }
4935
4936   return ret;
4937 }
4938
4939
4940 /* Visit conditional statement STMT.  If we can determine which edge
4941    will be taken out of STMT's basic block, record it in
4942    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
4943    SSA_PROP_VARYING.  */
4944
4945 static enum ssa_prop_result
4946 vrp_visit_cond_stmt (tree stmt, edge *taken_edge_p)
4947 {
4948   tree cond, val;
4949   bool sop;
4950
4951   *taken_edge_p = NULL;
4952
4953   /* FIXME.  Handle SWITCH_EXPRs.  */
4954   if (TREE_CODE (stmt) == SWITCH_EXPR)
4955     return SSA_PROP_VARYING;
4956
4957   cond = COND_EXPR_COND (stmt);
4958
4959   if (dump_file && (dump_flags & TDF_DETAILS))
4960     {
4961       tree use;
4962       ssa_op_iter i;
4963
4964       fprintf (dump_file, "\nVisiting conditional with predicate: ");
4965       print_generic_expr (dump_file, cond, 0);
4966       fprintf (dump_file, "\nWith known ranges\n");
4967       
4968       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
4969         {
4970           fprintf (dump_file, "\t");
4971           print_generic_expr (dump_file, use, 0);
4972           fprintf (dump_file, ": ");
4973           dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
4974         }
4975
4976       fprintf (dump_file, "\n");
4977     }
4978
4979   /* Compute the value of the predicate COND by checking the known
4980      ranges of each of its operands.
4981      
4982      Note that we cannot evaluate all the equivalent ranges here
4983      because those ranges may not yet be final and with the current
4984      propagation strategy, we cannot determine when the value ranges
4985      of the names in the equivalence set have changed.
4986
4987      For instance, given the following code fragment
4988
4989         i_5 = PHI <8, i_13>
4990         ...
4991         i_14 = ASSERT_EXPR <i_5, i_5 != 0>
4992         if (i_14 == 1)
4993           ...
4994
4995      Assume that on the first visit to i_14, i_5 has the temporary
4996      range [8, 8] because the second argument to the PHI function is
4997      not yet executable.  We derive the range ~[0, 0] for i_14 and the
4998      equivalence set { i_5 }.  So, when we visit 'if (i_14 == 1)' for
4999      the first time, since i_14 is equivalent to the range [8, 8], we
5000      determine that the predicate is always false.
5001
5002      On the next round of propagation, i_13 is determined to be
5003      VARYING, which causes i_5 to drop down to VARYING.  So, another
5004      visit to i_14 is scheduled.  In this second visit, we compute the
5005      exact same range and equivalence set for i_14, namely ~[0, 0] and
5006      { i_5 }.  But we did not have the previous range for i_5
5007      registered, so vrp_visit_assignment thinks that the range for
5008      i_14 has not changed.  Therefore, the predicate 'if (i_14 == 1)'
5009      is not visited again, which stops propagation from visiting
5010      statements in the THEN clause of that if().
5011
5012      To properly fix this we would need to keep the previous range
5013      value for the names in the equivalence set.  This way we would've
5014      discovered that from one visit to the other i_5 changed from
5015      range [8, 8] to VR_VARYING.
5016
5017      However, fixing this apparent limitation may not be worth the
5018      additional checking.  Testing on several code bases (GCC, DLV,
5019      MICO, TRAMP3D and SPEC2000) showed that doing this results in
5020      4 more predicates folded in SPEC.  */
5021   sop = false;
5022   val = vrp_evaluate_conditional_warnv (cond, false, &sop);
5023   if (val)
5024     {
5025       if (!sop)
5026         *taken_edge_p = find_taken_edge (bb_for_stmt (stmt), val);
5027       else
5028         {
5029           if (dump_file && (dump_flags & TDF_DETAILS))
5030             fprintf (dump_file,
5031                      "\nIgnoring predicate evaluation because "
5032                      "it assumes that signed overflow is undefined");
5033           val = NULL_TREE;
5034         }
5035     }
5036
5037   if (dump_file && (dump_flags & TDF_DETAILS))
5038     {
5039       fprintf (dump_file, "\nPredicate evaluates to: ");
5040       if (val == NULL_TREE)
5041         fprintf (dump_file, "DON'T KNOW\n");
5042       else
5043         print_generic_stmt (dump_file, val, 0);
5044     }
5045
5046   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5047 }
5048
5049
5050 /* Evaluate statement STMT.  If the statement produces a useful range,
5051    return SSA_PROP_INTERESTING and record the SSA name with the
5052    interesting range into *OUTPUT_P.
5053
5054    If STMT is a conditional branch and we can determine its truth
5055    value, the taken edge is recorded in *TAKEN_EDGE_P.
5056
5057    If STMT produces a varying value, return SSA_PROP_VARYING.  */
5058
5059 static enum ssa_prop_result
5060 vrp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
5061 {
5062   tree def;
5063   ssa_op_iter iter;
5064   stmt_ann_t ann;
5065
5066   if (dump_file && (dump_flags & TDF_DETAILS))
5067     {
5068       fprintf (dump_file, "\nVisiting statement:\n");
5069       print_generic_stmt (dump_file, stmt, dump_flags);
5070       fprintf (dump_file, "\n");
5071     }
5072
5073   ann = stmt_ann (stmt);
5074   if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
5075     {
5076       tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
5077
5078       /* In general, assignments with virtual operands are not useful
5079          for deriving ranges, with the obvious exception of calls to
5080          builtin functions.  */
5081       if ((TREE_CODE (rhs) == CALL_EXPR
5082            && TREE_CODE (CALL_EXPR_FN (rhs)) == ADDR_EXPR
5083            && DECL_P (TREE_OPERAND (CALL_EXPR_FN (rhs), 0))
5084            && DECL_IS_BUILTIN (TREE_OPERAND (CALL_EXPR_FN (rhs), 0)))
5085           || ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
5086         return vrp_visit_assignment (stmt, output_p);
5087     }
5088   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
5089     return vrp_visit_cond_stmt (stmt, taken_edge_p);
5090
5091   /* All other statements produce nothing of interest for VRP, so mark
5092      their outputs varying and prevent further simulation.  */
5093   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
5094     set_value_range_to_varying (get_value_range (def));
5095
5096   return SSA_PROP_VARYING;
5097 }
5098
5099
5100 /* Meet operation for value ranges.  Given two value ranges VR0 and
5101    VR1, store in VR0 a range that contains both VR0 and VR1.  This
5102    may not be the smallest possible such range.  */
5103
5104 static void
5105 vrp_meet (value_range_t *vr0, value_range_t *vr1)
5106 {
5107   if (vr0->type == VR_UNDEFINED)
5108     {
5109       copy_value_range (vr0, vr1);
5110       return;
5111     }
5112
5113   if (vr1->type == VR_UNDEFINED)
5114     {
5115       /* Nothing to do.  VR0 already has the resulting range.  */
5116       return;
5117     }
5118
5119   if (vr0->type == VR_VARYING)
5120     {
5121       /* Nothing to do.  VR0 already has the resulting range.  */
5122       return;
5123     }
5124
5125   if (vr1->type == VR_VARYING)
5126     {
5127       set_value_range_to_varying (vr0);
5128       return;
5129     }
5130
5131   if (vr0->type == VR_RANGE && vr1->type == VR_RANGE)
5132     {
5133       int cmp;
5134       tree min, max;
5135
5136       /* Compute the convex hull of the ranges.  The lower limit of
5137          the new range is the minimum of the two ranges.  If they
5138          cannot be compared, then give up.  */
5139       cmp = compare_values (vr0->min, vr1->min);
5140       if (cmp == 0 || cmp == 1)
5141         min = vr1->min;
5142       else if (cmp == -1)
5143         min = vr0->min;
5144       else
5145         goto give_up;
5146
5147       /* Similarly, the upper limit of the new range is the maximum
5148          of the two ranges.  If they cannot be compared, then
5149          give up.  */
5150       cmp = compare_values (vr0->max, vr1->max);
5151       if (cmp == 0 || cmp == -1)
5152         max = vr1->max;
5153       else if (cmp == 1)
5154         max = vr0->max;
5155       else
5156         goto give_up;
5157
5158       /* Check for useless ranges.  */
5159       if (INTEGRAL_TYPE_P (TREE_TYPE (min))
5160           && ((min == TYPE_MIN_VALUE (TREE_TYPE (min))
5161                || is_overflow_infinity (min))
5162               && (max == TYPE_MAX_VALUE (TREE_TYPE (max))
5163                   || is_overflow_infinity (max))))
5164         goto give_up;
5165
5166       /* The resulting set of equivalences is the intersection of
5167          the two sets.  */
5168       if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5169         bitmap_and_into (vr0->equiv, vr1->equiv);
5170       else if (vr0->equiv && !vr1->equiv)
5171         bitmap_clear (vr0->equiv);
5172
5173       set_value_range (vr0, vr0->type, min, max, vr0->equiv);
5174     }
5175   else if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
5176     {
5177       /* Two anti-ranges meet only if their complements intersect.
5178          Only handle the case of identical ranges.  */
5179       if (compare_values (vr0->min, vr1->min) == 0
5180           && compare_values (vr0->max, vr1->max) == 0
5181           && compare_values (vr0->min, vr0->max) == 0)
5182         {
5183           /* The resulting set of equivalences is the intersection of
5184              the two sets.  */
5185           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5186             bitmap_and_into (vr0->equiv, vr1->equiv);
5187           else if (vr0->equiv && !vr1->equiv)
5188             bitmap_clear (vr0->equiv);
5189         }
5190       else
5191         goto give_up;
5192     }
5193   else if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
5194     {
5195       /* For a numeric range [VAL1, VAL2] and an anti-range ~[VAL3, VAL4],
5196          only handle the case where the ranges have an empty intersection.
5197          The result of the meet operation is the anti-range.  */
5198       if (!symbolic_range_p (vr0)
5199           && !symbolic_range_p (vr1)
5200           && !value_ranges_intersect_p (vr0, vr1))
5201         {
5202           /* Copy most of VR1 into VR0.  Don't copy VR1's equivalence
5203              set.  We need to compute the intersection of the two
5204              equivalence sets.  */
5205           if (vr1->type == VR_ANTI_RANGE)
5206             set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr0->equiv);
5207
5208           /* The resulting set of equivalences is the intersection of
5209              the two sets.  */
5210           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5211             bitmap_and_into (vr0->equiv, vr1->equiv);
5212           else if (vr0->equiv && !vr1->equiv)
5213             bitmap_clear (vr0->equiv);
5214         }
5215       else
5216         goto give_up;
5217     }
5218   else
5219     gcc_unreachable ();
5220
5221   return;
5222
5223 give_up:
5224   /* Failed to find an efficient meet.  Before giving up and setting
5225      the result to VARYING, see if we can at least derive a useful
5226      anti-range.  FIXME, all this nonsense about distinguishing
5227      anti-ranges from ranges is necessary because of the odd
5228      semantics of range_includes_zero_p and friends.  */
5229   if (!symbolic_range_p (vr0)
5230       && ((vr0->type == VR_RANGE && !range_includes_zero_p (vr0))
5231           || (vr0->type == VR_ANTI_RANGE && range_includes_zero_p (vr0)))
5232       && !symbolic_range_p (vr1)
5233       && ((vr1->type == VR_RANGE && !range_includes_zero_p (vr1))
5234           || (vr1->type == VR_ANTI_RANGE && range_includes_zero_p (vr1))))
5235     {
5236       set_value_range_to_nonnull (vr0, TREE_TYPE (vr0->min));
5237
5238       /* Since this meet operation did not result from the meeting of
5239          two equivalent names, VR0 cannot have any equivalences.  */
5240       if (vr0->equiv)
5241         bitmap_clear (vr0->equiv);
5242     }
5243   else
5244     set_value_range_to_varying (vr0);
5245 }
5246
5247
5248 /* Visit all arguments for PHI node PHI that flow through executable
5249    edges.  If a valid value range can be derived from all the incoming
5250    value ranges, set a new range for the LHS of PHI.  */
5251
5252 static enum ssa_prop_result
5253 vrp_visit_phi_node (tree phi)
5254 {
5255   int i;
5256   tree lhs = PHI_RESULT (phi);
5257   value_range_t *lhs_vr = get_value_range (lhs);
5258   value_range_t vr_result = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
5259   int edges, old_edges;
5260
5261   copy_value_range (&vr_result, lhs_vr);
5262
5263   if (dump_file && (dump_flags & TDF_DETAILS))
5264     {
5265       fprintf (dump_file, "\nVisiting PHI node: ");
5266       print_generic_expr (dump_file, phi, dump_flags);
5267     }
5268
5269   edges = 0;
5270   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
5271     {
5272       edge e = PHI_ARG_EDGE (phi, i);
5273
5274       if (dump_file && (dump_flags & TDF_DETAILS))
5275         {
5276           fprintf (dump_file,
5277               "\n    Argument #%d (%d -> %d %sexecutable)\n",
5278               i, e->src->index, e->dest->index,
5279               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
5280         }
5281
5282       if (e->flags & EDGE_EXECUTABLE)
5283         {
5284           tree arg = PHI_ARG_DEF (phi, i);
5285           value_range_t vr_arg;
5286
5287           ++edges;
5288
5289           if (TREE_CODE (arg) == SSA_NAME)
5290             {
5291               vr_arg = *(get_value_range (arg));
5292             }
5293           else
5294             {
5295               if (is_overflow_infinity (arg))
5296                 {
5297                   arg = copy_node (arg);
5298                   TREE_OVERFLOW (arg) = 0;
5299                 }
5300
5301               vr_arg.type = VR_RANGE;
5302               vr_arg.min = arg;
5303               vr_arg.max = arg;
5304               vr_arg.equiv = NULL;
5305             }
5306
5307           if (dump_file && (dump_flags & TDF_DETAILS))
5308             {
5309               fprintf (dump_file, "\t");
5310               print_generic_expr (dump_file, arg, dump_flags);
5311               fprintf (dump_file, "\n\tValue: ");
5312               dump_value_range (dump_file, &vr_arg);
5313               fprintf (dump_file, "\n");
5314             }
5315
5316           vrp_meet (&vr_result, &vr_arg);
5317
5318           if (vr_result.type == VR_VARYING)
5319             break;
5320         }
5321     }
5322
5323   if (vr_result.type == VR_VARYING)
5324     goto varying;
5325
5326   old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
5327   vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
5328
5329   /* To prevent infinite iterations in the algorithm, derive ranges
5330      when the new value is slightly bigger or smaller than the
5331      previous one.  We don't do this if we have seen a new executable
5332      edge; this helps us avoid an overflow infinity for conditionals
5333      which are not in a loop.  */
5334   if (lhs_vr->type == VR_RANGE && vr_result.type == VR_RANGE
5335       && edges <= old_edges)
5336     {
5337       if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
5338         {
5339           int cmp_min = compare_values (lhs_vr->min, vr_result.min);
5340           int cmp_max = compare_values (lhs_vr->max, vr_result.max);
5341
5342           /* If the new minimum is smaller or larger than the previous
5343              one, go all the way to -INF.  In the first case, to avoid
5344              iterating millions of times to reach -INF, and in the
5345              other case to avoid infinite bouncing between different
5346              minimums.  */
5347           if (cmp_min > 0 || cmp_min < 0)
5348             {
5349               /* If we will end up with a (-INF, +INF) range, set it
5350                  to VARYING.  */
5351               if (is_positive_overflow_infinity (vr_result.max)
5352                   || (vr_result.max
5353                       == TYPE_MAX_VALUE (TREE_TYPE (vr_result.max))))
5354                 goto varying;
5355
5356               if (!needs_overflow_infinity (TREE_TYPE (vr_result.min)))
5357                 vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
5358               else if (supports_overflow_infinity (TREE_TYPE (vr_result.min)))
5359                 vr_result.min =
5360                   negative_overflow_infinity (TREE_TYPE (vr_result.min));
5361               else
5362                 goto varying;
5363             }
5364
5365           /* Similarly, if the new maximum is smaller or larger than
5366              the previous one, go all the way to +INF.  */
5367           if (cmp_max < 0 || cmp_max > 0)
5368             {
5369               /* If we will end up with a (-INF, +INF) range, set it
5370                  to VARYING.  */
5371               if (is_negative_overflow_infinity (vr_result.min)
5372                   || (vr_result.min
5373                       == TYPE_MIN_VALUE (TREE_TYPE (vr_result.min))))
5374                 goto varying;
5375
5376               if (!needs_overflow_infinity (TREE_TYPE (vr_result.max)))
5377                 vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
5378               else if (supports_overflow_infinity (TREE_TYPE (vr_result.max)))
5379                 vr_result.max =
5380                   positive_overflow_infinity (TREE_TYPE (vr_result.max));
5381               else
5382                 goto varying;
5383             }
5384         }
5385     }
5386
5387   /* If the new range is different than the previous value, keep
5388      iterating.  */
5389   if (update_value_range (lhs, &vr_result))
5390     return SSA_PROP_INTERESTING;
5391
5392   /* Nothing changed, don't add outgoing edges.  */
5393   return SSA_PROP_NOT_INTERESTING;
5394
5395   /* No match found.  Set the LHS to VARYING.  */
5396 varying:
5397   set_value_range_to_varying (lhs_vr);
5398   return SSA_PROP_VARYING;
5399 }
5400
5401 /* Simplify a division or modulo operator to a right shift or
5402    bitwise and if the first operand is unsigned or is greater
5403    than zero and the second operand is an exact power of two.  */
5404
5405 static void
5406 simplify_div_or_mod_using_ranges (tree stmt, tree rhs, enum tree_code rhs_code)
5407 {
5408   tree val = NULL;
5409   tree op = TREE_OPERAND (rhs, 0);
5410   value_range_t *vr = get_value_range (TREE_OPERAND (rhs, 0));
5411
5412   if (TYPE_UNSIGNED (TREE_TYPE (op)))
5413     {
5414       val = integer_one_node;
5415     }
5416   else
5417     {
5418       bool sop = false;
5419
5420       val = compare_range_with_value (GT_EXPR, vr, integer_zero_node, &sop);
5421
5422       if (val
5423           && sop
5424           && integer_onep (val)
5425           && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
5426         {
5427           location_t locus;
5428
5429           if (!EXPR_HAS_LOCATION (stmt))
5430             locus = input_location;
5431           else
5432             locus = EXPR_LOCATION (stmt);
5433           warning (OPT_Wstrict_overflow,
5434                    ("%Hassuming signed overflow does not occur when "
5435                     "simplifying / or %% to >> or &"),
5436                    &locus);
5437         }
5438     }
5439
5440   if (val && integer_onep (val))
5441     {
5442       tree t;
5443       tree op0 = TREE_OPERAND (rhs, 0);
5444       tree op1 = TREE_OPERAND (rhs, 1);
5445
5446       if (rhs_code == TRUNC_DIV_EXPR)
5447         {
5448           t = build_int_cst (NULL_TREE, tree_log2 (op1));
5449           t = build2 (RSHIFT_EXPR, TREE_TYPE (op0), op0, t);
5450         }
5451       else
5452         {
5453           t = build_int_cst (TREE_TYPE (op1), 1);
5454           t = int_const_binop (MINUS_EXPR, op1, t, 0);
5455           t = fold_convert (TREE_TYPE (op0), t);
5456           t = build2 (BIT_AND_EXPR, TREE_TYPE (op0), op0, t);
5457         }
5458
5459       GIMPLE_STMT_OPERAND (stmt, 1) = t;
5460       update_stmt (stmt);
5461     }
5462 }
5463
5464 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
5465    ABS_EXPR.  If the operand is <= 0, then simplify the
5466    ABS_EXPR into a NEGATE_EXPR.  */
5467
5468 static void
5469 simplify_abs_using_ranges (tree stmt, tree rhs)
5470 {
5471   tree val = NULL;
5472   tree op = TREE_OPERAND (rhs, 0);
5473   tree type = TREE_TYPE (op);
5474   value_range_t *vr = get_value_range (TREE_OPERAND (rhs, 0));
5475
5476   if (TYPE_UNSIGNED (type))
5477     {
5478       val = integer_zero_node;
5479     }
5480   else if (vr)
5481     {
5482       bool sop = false;
5483
5484       val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
5485       if (!val)
5486         {
5487           sop = false;
5488           val = compare_range_with_value (GE_EXPR, vr, integer_zero_node,
5489                                           &sop);
5490
5491           if (val)
5492             {
5493               if (integer_zerop (val))
5494                 val = integer_one_node;
5495               else if (integer_onep (val))
5496                 val = integer_zero_node;
5497             }
5498         }
5499
5500       if (val
5501           && (integer_onep (val) || integer_zerop (val)))
5502         {
5503           tree t;
5504
5505           if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
5506             {
5507               location_t locus;
5508
5509               if (!EXPR_HAS_LOCATION (stmt))
5510                 locus = input_location;
5511               else
5512                 locus = EXPR_LOCATION (stmt);
5513               warning (OPT_Wstrict_overflow,
5514                        ("%Hassuming signed overflow does not occur when "
5515                         "simplifying abs (X) to X or -X"),
5516                        &locus);
5517             }
5518
5519           if (integer_onep (val))
5520             t = build1 (NEGATE_EXPR, TREE_TYPE (op), op);
5521           else
5522             t = op;
5523
5524           GIMPLE_STMT_OPERAND (stmt, 1) = t;
5525           update_stmt (stmt);
5526         }
5527     }
5528 }
5529
5530 /* We are comparing trees OP0 and OP1 using COND_CODE.  OP0 has
5531    a known value range VR.
5532
5533    If there is one and only one value which will satisfy the
5534    conditional, then return that value.  Else return NULL.  */
5535
5536 static tree
5537 test_for_singularity (enum tree_code cond_code, tree op0,
5538                       tree op1, value_range_t *vr)
5539 {
5540   tree min = NULL;
5541   tree max = NULL;
5542
5543   /* Extract minimum/maximum values which satisfy the
5544      the conditional as it was written.  */
5545   if (cond_code == LE_EXPR || cond_code == LT_EXPR)
5546     {
5547       /* This should not be negative infinity; there is no overflow
5548          here.  */
5549       min = TYPE_MIN_VALUE (TREE_TYPE (op0));
5550
5551       max = op1;
5552       if (cond_code == LT_EXPR && !is_overflow_infinity (max))
5553         {
5554           tree one = build_int_cst (TREE_TYPE (op0), 1);
5555           max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
5556         }
5557     }
5558   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
5559     {
5560       /* This should not be positive infinity; there is no overflow
5561          here.  */
5562       max = TYPE_MAX_VALUE (TREE_TYPE (op0));
5563
5564       min = op1;
5565       if (cond_code == GT_EXPR && !is_overflow_infinity (min))
5566         {
5567           tree one = build_int_cst (TREE_TYPE (op0), 1);
5568           min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
5569         }
5570     }
5571
5572   /* Now refine the minimum and maximum values using any
5573      value range information we have for op0.  */
5574   if (min && max)
5575     {
5576       if (compare_values (vr->min, min) == -1)
5577         min = min;
5578       else
5579         min = vr->min;
5580       if (compare_values (vr->max, max) == 1)
5581         max = max;
5582       else
5583         max = vr->max;
5584
5585       /* If the new min/max values have converged to a single value,
5586          then there is only one value which can satisfy the condition,
5587          return that value.  */
5588       if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
5589         return min;
5590     }
5591   return NULL;
5592 }
5593
5594 /* Simplify a conditional using a relational operator to an equality
5595    test if the range information indicates only one value can satisfy
5596    the original conditional.  */
5597
5598 static void
5599 simplify_cond_using_ranges (tree stmt)
5600 {
5601   tree cond = COND_EXPR_COND (stmt);
5602   tree op0 = TREE_OPERAND (cond, 0);
5603   tree op1 = TREE_OPERAND (cond, 1);
5604   enum tree_code cond_code = TREE_CODE (cond);
5605
5606   if (cond_code != NE_EXPR
5607       && cond_code != EQ_EXPR
5608       && TREE_CODE (op0) == SSA_NAME
5609       && INTEGRAL_TYPE_P (TREE_TYPE (op0))
5610       && is_gimple_min_invariant (op1))
5611     {
5612       value_range_t *vr = get_value_range (op0);
5613           
5614       /* If we have range information for OP0, then we might be
5615          able to simplify this conditional. */
5616       if (vr->type == VR_RANGE)
5617         {
5618           tree new = test_for_singularity (cond_code, op0, op1, vr);
5619
5620           if (new)
5621             {
5622               if (dump_file)
5623                 {
5624                   fprintf (dump_file, "Simplified relational ");
5625                   print_generic_expr (dump_file, cond, 0);
5626                   fprintf (dump_file, " into ");
5627                 }
5628
5629               COND_EXPR_COND (stmt)
5630                 = build2 (EQ_EXPR, boolean_type_node, op0, new);
5631               update_stmt (stmt);
5632
5633               if (dump_file)
5634                 {
5635                   print_generic_expr (dump_file, COND_EXPR_COND (stmt), 0);
5636                   fprintf (dump_file, "\n");
5637                 }
5638               return;
5639
5640             }
5641
5642           /* Try again after inverting the condition.  We only deal
5643              with integral types here, so no need to worry about
5644              issues with inverting FP comparisons.  */
5645           cond_code = invert_tree_comparison (cond_code, false);
5646           new = test_for_singularity (cond_code, op0, op1, vr);
5647
5648           if (new)
5649             {
5650               if (dump_file)
5651                 {
5652                   fprintf (dump_file, "Simplified relational ");
5653                   print_generic_expr (dump_file, cond, 0);
5654                   fprintf (dump_file, " into ");
5655                 }
5656
5657               COND_EXPR_COND (stmt)
5658                 = build2 (NE_EXPR, boolean_type_node, op0, new);
5659               update_stmt (stmt);
5660
5661               if (dump_file)
5662                 {
5663                   print_generic_expr (dump_file, COND_EXPR_COND (stmt), 0);
5664                   fprintf (dump_file, "\n");
5665                 }
5666               return;
5667
5668             }
5669         }
5670     }
5671 }
5672
5673 /* Simplify STMT using ranges if possible.  */
5674
5675 void
5676 simplify_stmt_using_ranges (tree stmt)
5677 {
5678   if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
5679     {
5680       tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
5681       enum tree_code rhs_code = TREE_CODE (rhs);
5682
5683       /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
5684          and BIT_AND_EXPR respectively if the first operand is greater
5685          than zero and the second operand is an exact power of two.  */
5686       if ((rhs_code == TRUNC_DIV_EXPR || rhs_code == TRUNC_MOD_EXPR)
5687           && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0)))
5688           && integer_pow2p (TREE_OPERAND (rhs, 1)))
5689         simplify_div_or_mod_using_ranges (stmt, rhs, rhs_code);
5690
5691       /* Transform ABS (X) into X or -X as appropriate.  */
5692       if (rhs_code == ABS_EXPR
5693           && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME
5694           && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0))))
5695         simplify_abs_using_ranges (stmt, rhs);
5696     }
5697   else if (TREE_CODE (stmt) == COND_EXPR
5698            && COMPARISON_CLASS_P (COND_EXPR_COND (stmt)))
5699     {
5700       simplify_cond_using_ranges (stmt);
5701     }
5702 }
5703
5704 /* Stack of dest,src equivalency pairs that need to be restored after
5705    each attempt to thread a block's incoming edge to an outgoing edge. 
5706
5707    A NULL entry is used to mark the end of pairs which need to be
5708    restored.  */
5709 static VEC(tree,heap) *stack;
5710
5711 /* A trivial wrapper so that we can present the generic jump threading
5712    code with a simple API for simplifying statements.  STMT is the
5713    statement we want to simplify, WITHIN_STMT provides the location
5714    for any overflow warnings.  */
5715
5716 static tree
5717 simplify_stmt_for_jump_threading (tree stmt, tree within_stmt)
5718 {
5719   /* We only use VRP information to simplify conditionals.  This is
5720      overly conservative, but it's unclear if doing more would be
5721      worth the compile time cost.  */
5722   if (TREE_CODE (stmt) != COND_EXPR)
5723     return NULL;
5724
5725   return vrp_evaluate_conditional (COND_EXPR_COND (stmt), within_stmt);
5726 }
5727
5728 /* Blocks which have more than one predecessor and more than
5729    one successor present jump threading opportunities.  ie,
5730    when the block is reached from a specific predecessor, we
5731    may be able to determine which of the outgoing edges will
5732    be traversed.  When this optimization applies, we are able
5733    to avoid conditionals at runtime and we may expose secondary
5734    optimization opportunities.
5735
5736    This routine is effectively a driver for the generic jump
5737    threading code.  It basically just presents the generic code
5738    with edges that may be suitable for jump threading.
5739
5740    Unlike DOM, we do not iterate VRP if jump threading was successful.
5741    While iterating may expose new opportunities for VRP, it is expected
5742    those opportunities would be very limited and the compile time cost
5743    to expose those opportunities would be significant. 
5744
5745    As jump threading opportunities are discovered, they are registered
5746    for later realization.  */
5747
5748 static void
5749 identify_jump_threads (void)
5750 {
5751   basic_block bb;
5752   tree dummy;
5753
5754   /* Ugh.  When substituting values earlier in this pass we can
5755      wipe the dominance information.  So rebuild the dominator
5756      information as we need it within the jump threading code.  */
5757   calculate_dominance_info (CDI_DOMINATORS);
5758
5759   /* We do not allow VRP information to be used for jump threading
5760      across a back edge in the CFG.  Otherwise it becomes too
5761      difficult to avoid eliminating loop exit tests.  Of course
5762      EDGE_DFS_BACK is not accurate at this time so we have to
5763      recompute it.  */
5764   mark_dfs_back_edges ();
5765
5766   /* Allocate our unwinder stack to unwind any temporary equivalences
5767      that might be recorded.  */
5768   stack = VEC_alloc (tree, heap, 20);
5769
5770   /* To avoid lots of silly node creation, we create a single
5771      conditional and just modify it in-place when attempting to
5772      thread jumps.  */
5773   dummy = build2 (EQ_EXPR, boolean_type_node, NULL, NULL);
5774   dummy = build3 (COND_EXPR, void_type_node, dummy, NULL, NULL);
5775
5776   /* Walk through all the blocks finding those which present a
5777      potential jump threading opportunity.  We could set this up
5778      as a dominator walker and record data during the walk, but
5779      I doubt it's worth the effort for the classes of jump
5780      threading opportunities we are trying to identify at this
5781      point in compilation.  */
5782   FOR_EACH_BB (bb)
5783     {
5784       tree last, cond;
5785
5786       /* If the generic jump threading code does not find this block
5787          interesting, then there is nothing to do.  */
5788       if (! potentially_threadable_block (bb))
5789         continue;
5790
5791       /* We only care about blocks ending in a COND_EXPR.  While there
5792          may be some value in handling SWITCH_EXPR here, I doubt it's
5793          terribly important.  */
5794       last = bsi_stmt (bsi_last (bb));
5795       if (TREE_CODE (last) != COND_EXPR)
5796         continue;
5797
5798       /* We're basically looking for any kind of conditional with
5799          integral type arguments.  */
5800       cond = COND_EXPR_COND (last);
5801       if ((TREE_CODE (cond) == SSA_NAME
5802            && INTEGRAL_TYPE_P (TREE_TYPE (cond)))
5803           || (COMPARISON_CLASS_P (cond)
5804               && TREE_CODE (TREE_OPERAND (cond, 0)) == SSA_NAME
5805               && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (cond, 0)))
5806               && (TREE_CODE (TREE_OPERAND (cond, 1)) == SSA_NAME
5807                   || is_gimple_min_invariant (TREE_OPERAND (cond, 1)))
5808               && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (cond, 1)))))
5809         {
5810           edge_iterator ei;
5811           edge e;
5812
5813           /* We've got a block with multiple predecessors and multiple
5814              successors which also ends in a suitable conditional.  For
5815              each predecessor, see if we can thread it to a specific
5816              successor.  */
5817           FOR_EACH_EDGE (e, ei, bb->preds)
5818             {
5819               /* Do not thread across back edges or abnormal edges
5820                  in the CFG.  */
5821               if (e->flags & (EDGE_DFS_BACK | EDGE_COMPLEX))
5822                 continue;
5823
5824               thread_across_edge (dummy, e, true,
5825                                   &stack,
5826                                   simplify_stmt_for_jump_threading);
5827             }
5828         }
5829     }
5830
5831   /* We do not actually update the CFG or SSA graphs at this point as
5832      ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
5833      handle ASSERT_EXPRs gracefully.  */
5834 }
5835
5836 /* We identified all the jump threading opportunities earlier, but could
5837    not transform the CFG at that time.  This routine transforms the
5838    CFG and arranges for the dominator tree to be rebuilt if necessary.
5839
5840    Note the SSA graph update will occur during the normal TODO
5841    processing by the pass manager.  */
5842 static void
5843 finalize_jump_threads (void)
5844 {
5845   bool cfg_altered = false;
5846   cfg_altered = thread_through_all_blocks ();
5847
5848   /* If we threaded jumps, then we need to recompute the dominance
5849      information.  */
5850   if (cfg_altered)
5851     free_dominance_info (CDI_DOMINATORS);
5852   VEC_free (tree, heap, stack);
5853 }
5854
5855
5856 /* Traverse all the blocks folding conditionals with known ranges.  */
5857
5858 static void
5859 vrp_finalize (void)
5860 {
5861   size_t i;
5862   prop_value_t *single_val_range;
5863   bool do_value_subst_p;
5864
5865   if (dump_file)
5866     {
5867       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
5868       dump_all_value_ranges (dump_file);
5869       fprintf (dump_file, "\n");
5870     }
5871
5872   /* We may have ended with ranges that have exactly one value.  Those
5873      values can be substituted as any other copy/const propagated
5874      value using substitute_and_fold.  */
5875   single_val_range = XCNEWVEC (prop_value_t, num_ssa_names);
5876
5877   do_value_subst_p = false;
5878   for (i = 0; i < num_ssa_names; i++)
5879     if (vr_value[i]
5880         && vr_value[i]->type == VR_RANGE
5881         && vr_value[i]->min == vr_value[i]->max)
5882       {
5883         single_val_range[i].value = vr_value[i]->min;
5884         do_value_subst_p = true;
5885       }
5886
5887   if (!do_value_subst_p)
5888     {
5889       /* We found no single-valued ranges, don't waste time trying to
5890          do single value substitution in substitute_and_fold.  */
5891       free (single_val_range);
5892       single_val_range = NULL;
5893     }
5894
5895   substitute_and_fold (single_val_range, true);
5896
5897   if (warn_array_bounds)
5898       check_all_array_refs ();
5899
5900   /* We must identify jump threading opportunities before we release
5901      the datastructures built by VRP.  */
5902   identify_jump_threads ();
5903
5904   /* Free allocated memory.  */
5905   for (i = 0; i < num_ssa_names; i++)
5906     if (vr_value[i])
5907       {
5908         BITMAP_FREE (vr_value[i]->equiv);
5909         free (vr_value[i]);
5910       }
5911
5912   free (single_val_range);
5913   free (vr_value);
5914   free (vr_phi_edge_counts);
5915
5916   /* So that we can distinguish between VRP data being available
5917      and not available.  */
5918   vr_value = NULL;
5919   vr_phi_edge_counts = NULL;
5920 }
5921
5922
5923 /* Main entry point to VRP (Value Range Propagation).  This pass is
5924    loosely based on J. R. C. Patterson, ``Accurate Static Branch
5925    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
5926    Programming Language Design and Implementation, pp. 67-78, 1995.
5927    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
5928
5929    This is essentially an SSA-CCP pass modified to deal with ranges
5930    instead of constants.
5931
5932    While propagating ranges, we may find that two or more SSA name
5933    have equivalent, though distinct ranges.  For instance,
5934
5935      1  x_9 = p_3->a;
5936      2  p_4 = ASSERT_EXPR <p_3, p_3 != 0>
5937      3  if (p_4 == q_2)
5938      4    p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
5939      5  endif
5940      6  if (q_2)
5941         
5942    In the code above, pointer p_5 has range [q_2, q_2], but from the
5943    code we can also determine that p_5 cannot be NULL and, if q_2 had
5944    a non-varying range, p_5's range should also be compatible with it.
5945
5946    These equivalences are created by two expressions: ASSERT_EXPR and
5947    copy operations.  Since p_5 is an assertion on p_4, and p_4 was the
5948    result of another assertion, then we can use the fact that p_5 and
5949    p_4 are equivalent when evaluating p_5's range.
5950
5951    Together with value ranges, we also propagate these equivalences
5952    between names so that we can take advantage of information from
5953    multiple ranges when doing final replacement.  Note that this
5954    equivalency relation is transitive but not symmetric.
5955    
5956    In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
5957    cannot assert that q_2 is equivalent to p_5 because q_2 may be used
5958    in contexts where that assertion does not hold (e.g., in line 6).
5959
5960    TODO, the main difference between this pass and Patterson's is that
5961    we do not propagate edge probabilities.  We only compute whether
5962    edges can be taken or not.  That is, instead of having a spectrum
5963    of jump probabilities between 0 and 1, we only deal with 0, 1 and
5964    DON'T KNOW.  In the future, it may be worthwhile to propagate
5965    probabilities to aid branch prediction.  */
5966
5967 static unsigned int
5968 execute_vrp (void)
5969 {
5970   insert_range_assertions ();
5971
5972   loop_optimizer_init (LOOPS_NORMAL);
5973   if (current_loops)
5974     scev_initialize ();
5975
5976   vrp_initialize ();
5977   ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
5978   vrp_finalize ();
5979
5980   if (current_loops)
5981     {
5982       scev_finalize ();
5983       loop_optimizer_finalize ();
5984     }
5985
5986   /* ASSERT_EXPRs must be removed before finalizing jump threads
5987      as finalizing jump threads calls the CFG cleanup code which
5988      does not properly handle ASSERT_EXPRs.  */
5989   remove_range_assertions ();
5990
5991   /* If we exposed any new variables, go ahead and put them into
5992      SSA form now, before we handle jump threading.  This simplifies
5993      interactions between rewriting of _DECL nodes into SSA form
5994      and rewriting SSA_NAME nodes into SSA form after block
5995      duplication and CFG manipulation.  */
5996   update_ssa (TODO_update_ssa);
5997
5998   finalize_jump_threads ();
5999   return 0;
6000 }
6001
6002 static bool
6003 gate_vrp (void)
6004 {
6005   return flag_tree_vrp != 0;
6006 }
6007
6008 struct tree_opt_pass pass_vrp =
6009 {
6010   "vrp",                                /* name */
6011   gate_vrp,                             /* gate */
6012   execute_vrp,                          /* execute */
6013   NULL,                                 /* sub */
6014   NULL,                                 /* next */
6015   0,                                    /* static_pass_number */
6016   TV_TREE_VRP,                          /* tv_id */
6017   PROP_ssa | PROP_alias,                /* properties_required */
6018   0,                                    /* properties_provided */
6019   0,                                    /* properties_destroyed */
6020   0,                                    /* todo_flags_start */
6021   TODO_cleanup_cfg
6022     | TODO_ggc_collect
6023     | TODO_verify_ssa
6024     | TODO_dump_func
6025     | TODO_update_ssa,                  /* todo_flags_finish */
6026   0                                     /* letter */
6027 };