OSDN Git Service

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