re PR c++/19476 (Missed null checking elimination with new)
[platform/upstream/gcc.git] / gcc / tree-vrp.c
1 /* Support routines for Value Range Propagation (VRP).
2    Copyright (C) 2005-2013 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-ssa.h"
30 #include "tree-pass.h"
31 #include "tree-dump.h"
32 #include "gimple-pretty-print.h"
33 #include "diagnostic-core.h"
34 #include "intl.h"
35 #include "cfgloop.h"
36 #include "tree-scalar-evolution.h"
37 #include "tree-ssa-propagate.h"
38 #include "tree-chrec.h"
39 #include "tree-ssa-threadupdate.h"
40 #include "expr.h"
41 #include "optabs.h"
42
43
44
45 /* Range of values that can be associated with an SSA_NAME after VRP
46    has executed.  */
47 struct value_range_d
48 {
49   /* Lattice value represented by this range.  */
50   enum value_range_type type;
51
52   /* Minimum and maximum values represented by this range.  These
53      values should be interpreted as follows:
54
55         - If TYPE is VR_UNDEFINED or VR_VARYING then MIN and MAX must
56           be NULL.
57
58         - If TYPE == VR_RANGE then MIN holds the minimum value and
59           MAX holds the maximum value of the range [MIN, MAX].
60
61         - If TYPE == ANTI_RANGE the variable is known to NOT
62           take any values in the range [MIN, MAX].  */
63   tree min;
64   tree max;
65
66   /* Set of SSA names whose value ranges are equivalent to this one.
67      This set is only valid when TYPE is VR_RANGE or VR_ANTI_RANGE.  */
68   bitmap equiv;
69 };
70
71 typedef struct value_range_d value_range_t;
72
73 #define VR_INITIALIZER { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL }
74
75 /* Set of SSA names found live during the RPO traversal of the function
76    for still active basic-blocks.  */
77 static sbitmap *live;
78
79 /* Return true if the SSA name NAME is live on the edge E.  */
80
81 static bool
82 live_on_edge (edge e, tree name)
83 {
84   return (live[e->dest->index]
85           && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
86 }
87
88 /* Local functions.  */
89 static int compare_values (tree val1, tree val2);
90 static int compare_values_warnv (tree val1, tree val2, bool *);
91 static void vrp_meet (value_range_t *, value_range_t *);
92 static void vrp_intersect_ranges (value_range_t *, value_range_t *);
93 static tree vrp_evaluate_conditional_warnv_with_ops (enum tree_code,
94                                                      tree, tree, bool, bool *,
95                                                      bool *);
96
97 /* Location information for ASSERT_EXPRs.  Each instance of this
98    structure describes an ASSERT_EXPR for an SSA name.  Since a single
99    SSA name may have more than one assertion associated with it, these
100    locations are kept in a linked list attached to the corresponding
101    SSA name.  */
102 struct assert_locus_d
103 {
104   /* Basic block where the assertion would be inserted.  */
105   basic_block bb;
106
107   /* Some assertions need to be inserted on an edge (e.g., assertions
108      generated by COND_EXPRs).  In those cases, BB will be NULL.  */
109   edge e;
110
111   /* Pointer to the statement that generated this assertion.  */
112   gimple_stmt_iterator si;
113
114   /* Predicate code for the ASSERT_EXPR.  Must be COMPARISON_CLASS_P.  */
115   enum tree_code comp_code;
116
117   /* Value being compared against.  */
118   tree val;
119
120   /* Expression to compare.  */
121   tree expr;
122
123   /* Next node in the linked list.  */
124   struct assert_locus_d *next;
125 };
126
127 typedef struct assert_locus_d *assert_locus_t;
128
129 /* If bit I is present, it means that SSA name N_i has a list of
130    assertions that should be inserted in the IL.  */
131 static bitmap need_assert_for;
132
133 /* Array of locations lists where to insert assertions.  ASSERTS_FOR[I]
134    holds a list of ASSERT_LOCUS_T nodes that describe where
135    ASSERT_EXPRs for SSA name N_I should be inserted.  */
136 static assert_locus_t *asserts_for;
137
138 /* Value range array.  After propagation, VR_VALUE[I] holds the range
139    of values that SSA name N_I may take.  */
140 static unsigned num_vr_values;
141 static value_range_t **vr_value;
142 static bool values_propagated;
143
144 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
145    number of executable edges we saw the last time we visited the
146    node.  */
147 static int *vr_phi_edge_counts;
148
149 typedef struct {
150   gimple stmt;
151   tree vec;
152 } switch_update;
153
154 static vec<edge> to_remove_edges;
155 static vec<switch_update> to_update_switch_stmts;
156
157
158 /* Return the maximum value for TYPE.  */
159
160 static inline tree
161 vrp_val_max (const_tree type)
162 {
163   if (!INTEGRAL_TYPE_P (type))
164     return NULL_TREE;
165
166   return TYPE_MAX_VALUE (type);
167 }
168
169 /* Return the minimum value for TYPE.  */
170
171 static inline tree
172 vrp_val_min (const_tree type)
173 {
174   if (!INTEGRAL_TYPE_P (type))
175     return NULL_TREE;
176
177   return TYPE_MIN_VALUE (type);
178 }
179
180 /* Return whether VAL is equal to the maximum value of its type.  This
181    will be true for a positive overflow infinity.  We can't do a
182    simple equality comparison with TYPE_MAX_VALUE because C typedefs
183    and Ada subtypes can produce types whose TYPE_MAX_VALUE is not ==
184    to the integer constant with the same value in the type.  */
185
186 static inline bool
187 vrp_val_is_max (const_tree val)
188 {
189   tree type_max = vrp_val_max (TREE_TYPE (val));
190   return (val == type_max
191           || (type_max != NULL_TREE
192               && operand_equal_p (val, type_max, 0)));
193 }
194
195 /* Return whether VAL is equal to the minimum value of its type.  This
196    will be true for a negative overflow infinity.  */
197
198 static inline bool
199 vrp_val_is_min (const_tree val)
200 {
201   tree type_min = vrp_val_min (TREE_TYPE (val));
202   return (val == type_min
203           || (type_min != NULL_TREE
204               && operand_equal_p (val, type_min, 0)));
205 }
206
207
208 /* Return whether TYPE should use an overflow infinity distinct from
209    TYPE_{MIN,MAX}_VALUE.  We use an overflow infinity value to
210    represent a signed overflow during VRP computations.  An infinity
211    is distinct from a half-range, which will go from some number to
212    TYPE_{MIN,MAX}_VALUE.  */
213
214 static inline bool
215 needs_overflow_infinity (const_tree type)
216 {
217   return INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type);
218 }
219
220 /* Return whether TYPE can support our overflow infinity
221    representation: we use the TREE_OVERFLOW flag, which only exists
222    for constants.  If TYPE doesn't support this, we don't optimize
223    cases which would require signed overflow--we drop them to
224    VARYING.  */
225
226 static inline bool
227 supports_overflow_infinity (const_tree type)
228 {
229   tree min = vrp_val_min (type), max = vrp_val_max (type);
230 #ifdef ENABLE_CHECKING
231   gcc_assert (needs_overflow_infinity (type));
232 #endif
233   return (min != NULL_TREE
234           && CONSTANT_CLASS_P (min)
235           && max != NULL_TREE
236           && CONSTANT_CLASS_P (max));
237 }
238
239 /* VAL is the maximum or minimum value of a type.  Return a
240    corresponding overflow infinity.  */
241
242 static inline tree
243 make_overflow_infinity (tree val)
244 {
245   gcc_checking_assert (val != NULL_TREE && CONSTANT_CLASS_P (val));
246   val = copy_node (val);
247   TREE_OVERFLOW (val) = 1;
248   return val;
249 }
250
251 /* Return a negative overflow infinity for TYPE.  */
252
253 static inline tree
254 negative_overflow_infinity (tree type)
255 {
256   gcc_checking_assert (supports_overflow_infinity (type));
257   return make_overflow_infinity (vrp_val_min (type));
258 }
259
260 /* Return a positive overflow infinity for TYPE.  */
261
262 static inline tree
263 positive_overflow_infinity (tree type)
264 {
265   gcc_checking_assert (supports_overflow_infinity (type));
266   return make_overflow_infinity (vrp_val_max (type));
267 }
268
269 /* Return whether VAL is a negative overflow infinity.  */
270
271 static inline bool
272 is_negative_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));
278 }
279
280 /* Return whether VAL is a positive overflow infinity.  */
281
282 static inline bool
283 is_positive_overflow_infinity (const_tree val)
284 {
285   return (needs_overflow_infinity (TREE_TYPE (val))
286           && CONSTANT_CLASS_P (val)
287           && TREE_OVERFLOW (val)
288           && vrp_val_is_max (val));
289 }
290
291 /* Return whether VAL is a positive or negative overflow infinity.  */
292
293 static inline bool
294 is_overflow_infinity (const_tree val)
295 {
296   return (needs_overflow_infinity (TREE_TYPE (val))
297           && CONSTANT_CLASS_P (val)
298           && TREE_OVERFLOW (val)
299           && (vrp_val_is_min (val) || vrp_val_is_max (val)));
300 }
301
302 /* Return whether STMT has a constant rhs that is_overflow_infinity. */
303
304 static inline bool
305 stmt_overflow_infinity (gimple stmt)
306 {
307   if (is_gimple_assign (stmt)
308       && get_gimple_rhs_class (gimple_assign_rhs_code (stmt)) ==
309       GIMPLE_SINGLE_RHS)
310     return is_overflow_infinity (gimple_assign_rhs1 (stmt));
311   return false;
312 }
313
314 /* If VAL is now an overflow infinity, return VAL.  Otherwise, return
315    the same value with TREE_OVERFLOW clear.  This can be used to avoid
316    confusing a regular value with an overflow value.  */
317
318 static inline tree
319 avoid_overflow_infinity (tree val)
320 {
321   if (!is_overflow_infinity (val))
322     return val;
323
324   if (vrp_val_is_max (val))
325     return vrp_val_max (TREE_TYPE (val));
326   else
327     {
328       gcc_checking_assert (vrp_val_is_min (val));
329       return vrp_val_min (TREE_TYPE (val));
330     }
331 }
332
333
334 /* Return true if ARG is marked with the nonnull attribute in the
335    current function signature.  */
336
337 static bool
338 nonnull_arg_p (const_tree arg)
339 {
340   tree t, attrs, fntype;
341   unsigned HOST_WIDE_INT arg_num;
342
343   gcc_assert (TREE_CODE (arg) == PARM_DECL && POINTER_TYPE_P (TREE_TYPE (arg)));
344
345   /* The static chain decl is always non null.  */
346   if (arg == cfun->static_chain_decl)
347     return true;
348
349   fntype = TREE_TYPE (current_function_decl);
350   for (attrs = TYPE_ATTRIBUTES (fntype); attrs; attrs = TREE_CHAIN (attrs))
351     {
352       attrs = lookup_attribute ("nonnull", attrs);
353
354       /* If "nonnull" wasn't specified, we know nothing about the argument.  */
355       if (attrs == NULL_TREE)
356         return false;
357
358       /* If "nonnull" applies to all the arguments, then ARG is non-null.  */
359       if (TREE_VALUE (attrs) == NULL_TREE)
360         return true;
361
362       /* Get the position number for ARG in the function signature.  */
363       for (arg_num = 1, t = DECL_ARGUMENTS (current_function_decl);
364            t;
365            t = DECL_CHAIN (t), arg_num++)
366         {
367           if (t == arg)
368             break;
369         }
370
371       gcc_assert (t == arg);
372
373       /* Now see if ARG_NUM is mentioned in the nonnull list.  */
374       for (t = TREE_VALUE (attrs); t; t = TREE_CHAIN (t))
375         {
376           if (compare_tree_int (TREE_VALUE (t), arg_num) == 0)
377             return true;
378         }
379     }
380
381   return false;
382 }
383
384
385 /* Set value range VR to VR_UNDEFINED.  */
386
387 static inline void
388 set_value_range_to_undefined (value_range_t *vr)
389 {
390   vr->type = VR_UNDEFINED;
391   vr->min = vr->max = NULL_TREE;
392   if (vr->equiv)
393     bitmap_clear (vr->equiv);
394 }
395
396
397 /* Set value range VR to VR_VARYING.  */
398
399 static inline void
400 set_value_range_to_varying (value_range_t *vr)
401 {
402   vr->type = VR_VARYING;
403   vr->min = vr->max = NULL_TREE;
404   if (vr->equiv)
405     bitmap_clear (vr->equiv);
406 }
407
408
409 /* Set value range VR to {T, MIN, MAX, EQUIV}.  */
410
411 static void
412 set_value_range (value_range_t *vr, enum value_range_type t, tree min,
413                  tree max, bitmap equiv)
414 {
415 #if defined ENABLE_CHECKING
416   /* Check the validity of the range.  */
417   if (t == VR_RANGE || t == VR_ANTI_RANGE)
418     {
419       int cmp;
420
421       gcc_assert (min && max);
422
423       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
424         gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
425
426       cmp = compare_values (min, max);
427       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
428
429       if (needs_overflow_infinity (TREE_TYPE (min)))
430         gcc_assert (!is_overflow_infinity (min)
431                     || !is_overflow_infinity (max));
432     }
433
434   if (t == VR_UNDEFINED || t == VR_VARYING)
435     gcc_assert (min == NULL_TREE && max == NULL_TREE);
436
437   if (t == VR_UNDEFINED || t == VR_VARYING)
438     gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
439 #endif
440
441   vr->type = t;
442   vr->min = min;
443   vr->max = max;
444
445   /* Since updating the equivalence set involves deep copying the
446      bitmaps, only do it if absolutely necessary.  */
447   if (vr->equiv == NULL
448       && equiv != NULL)
449     vr->equiv = BITMAP_ALLOC (NULL);
450
451   if (equiv != vr->equiv)
452     {
453       if (equiv && !bitmap_empty_p (equiv))
454         bitmap_copy (vr->equiv, equiv);
455       else
456         bitmap_clear (vr->equiv);
457     }
458 }
459
460
461 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
462    This means adjusting T, MIN and MAX representing the case of a
463    wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
464    as anti-rage ~[MAX+1, MIN-1].  Likewise for wrapping anti-ranges.
465    In corner cases where MAX+1 or MIN-1 wraps this will fall back
466    to varying.
467    This routine exists to ease canonicalization in the case where we
468    extract ranges from var + CST op limit.  */
469
470 static void
471 set_and_canonicalize_value_range (value_range_t *vr, enum value_range_type t,
472                                   tree min, tree max, bitmap equiv)
473 {
474   /* Use the canonical setters for VR_UNDEFINED and VR_VARYING.  */
475   if (t == VR_UNDEFINED)
476     {
477       set_value_range_to_undefined (vr);
478       return;
479     }
480   else if (t == VR_VARYING)
481     {
482       set_value_range_to_varying (vr);
483       return;
484     }
485
486   /* Nothing to canonicalize for symbolic ranges.  */
487   if (TREE_CODE (min) != INTEGER_CST
488       || TREE_CODE (max) != INTEGER_CST)
489     {
490       set_value_range (vr, t, min, max, equiv);
491       return;
492     }
493
494   /* Wrong order for min and max, to swap them and the VR type we need
495      to adjust them.  */
496   if (tree_int_cst_lt (max, min))
497     {
498       tree one, tmp;
499
500       /* For one bit precision if max < min, then the swapped
501          range covers all values, so for VR_RANGE it is varying and
502          for VR_ANTI_RANGE empty range, so drop to varying as well.  */
503       if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
504         {
505           set_value_range_to_varying (vr);
506           return;
507         }
508
509       one = build_int_cst (TREE_TYPE (min), 1);
510       tmp = int_const_binop (PLUS_EXPR, max, one);
511       max = int_const_binop (MINUS_EXPR, min, one);
512       min = tmp;
513
514       /* There's one corner case, if we had [C+1, C] before we now have
515          that again.  But this represents an empty value range, so drop
516          to varying in this case.  */
517       if (tree_int_cst_lt (max, min))
518         {
519           set_value_range_to_varying (vr);
520           return;
521         }
522
523       t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
524     }
525
526   /* Anti-ranges that can be represented as ranges should be so.  */
527   if (t == VR_ANTI_RANGE)
528     {
529       bool is_min = vrp_val_is_min (min);
530       bool is_max = vrp_val_is_max (max);
531
532       if (is_min && is_max)
533         {
534           /* We cannot deal with empty ranges, drop to varying.
535              ???  This could be VR_UNDEFINED instead.  */
536           set_value_range_to_varying (vr);
537           return;
538         }
539       else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
540                && (is_min || is_max))
541         {
542           /* Non-empty boolean ranges can always be represented
543              as a singleton range.  */
544           if (is_min)
545             min = max = vrp_val_max (TREE_TYPE (min));
546           else
547             min = max = vrp_val_min (TREE_TYPE (min));
548           t = VR_RANGE;
549         }
550       else if (is_min
551                /* As a special exception preserve non-null ranges.  */
552                && !(TYPE_UNSIGNED (TREE_TYPE (min))
553                     && integer_zerop (max)))
554         {
555           tree one = build_int_cst (TREE_TYPE (max), 1);
556           min = int_const_binop (PLUS_EXPR, max, one);
557           max = vrp_val_max (TREE_TYPE (max));
558           t = VR_RANGE;
559         }
560       else if (is_max)
561         {
562           tree one = build_int_cst (TREE_TYPE (min), 1);
563           max = int_const_binop (MINUS_EXPR, min, one);
564           min = vrp_val_min (TREE_TYPE (min));
565           t = VR_RANGE;
566         }
567     }
568
569   /* Drop [-INF(OVF), +INF(OVF)] to varying.  */
570   if (needs_overflow_infinity (TREE_TYPE (min))
571       && is_overflow_infinity (min)
572       && is_overflow_infinity (max))
573     {
574       set_value_range_to_varying (vr);
575       return;
576     }
577
578   set_value_range (vr, t, min, max, equiv);
579 }
580
581 /* Copy value range FROM into value range TO.  */
582
583 static inline void
584 copy_value_range (value_range_t *to, value_range_t *from)
585 {
586   set_value_range (to, from->type, from->min, from->max, from->equiv);
587 }
588
589 /* Set value range VR to a single value.  This function is only called
590    with values we get from statements, and exists to clear the
591    TREE_OVERFLOW flag so that we don't think we have an overflow
592    infinity when we shouldn't.  */
593
594 static inline void
595 set_value_range_to_value (value_range_t *vr, tree val, bitmap equiv)
596 {
597   gcc_assert (is_gimple_min_invariant (val));
598   val = avoid_overflow_infinity (val);
599   set_value_range (vr, VR_RANGE, val, val, equiv);
600 }
601
602 /* Set value range VR to a non-negative range of type TYPE.
603    OVERFLOW_INFINITY indicates whether to use an overflow infinity
604    rather than TYPE_MAX_VALUE; this should be true if we determine
605    that the range is nonnegative based on the assumption that signed
606    overflow does not occur.  */
607
608 static inline void
609 set_value_range_to_nonnegative (value_range_t *vr, tree type,
610                                 bool overflow_infinity)
611 {
612   tree zero;
613
614   if (overflow_infinity && !supports_overflow_infinity (type))
615     {
616       set_value_range_to_varying (vr);
617       return;
618     }
619
620   zero = build_int_cst (type, 0);
621   set_value_range (vr, VR_RANGE, zero,
622                    (overflow_infinity
623                     ? positive_overflow_infinity (type)
624                     : TYPE_MAX_VALUE (type)),
625                    vr->equiv);
626 }
627
628 /* Set value range VR to a non-NULL range of type TYPE.  */
629
630 static inline void
631 set_value_range_to_nonnull (value_range_t *vr, tree type)
632 {
633   tree zero = build_int_cst (type, 0);
634   set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
635 }
636
637
638 /* Set value range VR to a NULL range of type TYPE.  */
639
640 static inline void
641 set_value_range_to_null (value_range_t *vr, tree type)
642 {
643   set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
644 }
645
646
647 /* Set value range VR to a range of a truthvalue of type TYPE.  */
648
649 static inline void
650 set_value_range_to_truthvalue (value_range_t *vr, tree type)
651 {
652   if (TYPE_PRECISION (type) == 1)
653     set_value_range_to_varying (vr);
654   else
655     set_value_range (vr, VR_RANGE,
656                      build_int_cst (type, 0), build_int_cst (type, 1),
657                      vr->equiv);
658 }
659
660
661 /* If abs (min) < abs (max), set VR to [-max, max], if
662    abs (min) >= abs (max), set VR to [-min, min].  */
663
664 static void
665 abs_extent_range (value_range_t *vr, tree min, tree max)
666 {
667   int cmp;
668
669   gcc_assert (TREE_CODE (min) == INTEGER_CST);
670   gcc_assert (TREE_CODE (max) == INTEGER_CST);
671   gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
672   gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
673   min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
674   max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
675   if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
676     {
677       set_value_range_to_varying (vr);
678       return;
679     }
680   cmp = compare_values (min, max);
681   if (cmp == -1)
682     min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
683   else if (cmp == 0 || cmp == 1)
684     {
685       max = min;
686       min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
687     }
688   else
689     {
690       set_value_range_to_varying (vr);
691       return;
692     }
693   set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
694 }
695
696
697 /* Return value range information for VAR.
698
699    If we have no values ranges recorded (ie, VRP is not running), then
700    return NULL.  Otherwise create an empty range if none existed for VAR.  */
701
702 static value_range_t *
703 get_value_range (const_tree var)
704 {
705   static const struct value_range_d vr_const_varying
706     = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
707   value_range_t *vr;
708   tree sym;
709   unsigned ver = SSA_NAME_VERSION (var);
710
711   /* If we have no recorded ranges, then return NULL.  */
712   if (! vr_value)
713     return NULL;
714
715   /* If we query the range for a new SSA name return an unmodifiable VARYING.
716      We should get here at most from the substitute-and-fold stage which
717      will never try to change values.  */
718   if (ver >= num_vr_values)
719     return CONST_CAST (value_range_t *, &vr_const_varying);
720
721   vr = vr_value[ver];
722   if (vr)
723     return vr;
724
725   /* After propagation finished do not allocate new value-ranges.  */
726   if (values_propagated)
727     return CONST_CAST (value_range_t *, &vr_const_varying);
728
729   /* Create a default value range.  */
730   vr_value[ver] = vr = XCNEW (value_range_t);
731
732   /* Defer allocating the equivalence set.  */
733   vr->equiv = NULL;
734
735   /* If VAR is a default definition of a parameter, the variable can
736      take any value in VAR's type.  */
737   if (SSA_NAME_IS_DEFAULT_DEF (var))
738     {
739       sym = SSA_NAME_VAR (var);
740       if (TREE_CODE (sym) == PARM_DECL)
741         {
742           /* Try to use the "nonnull" attribute to create ~[0, 0]
743              anti-ranges for pointers.  Note that this is only valid with
744              default definitions of PARM_DECLs.  */
745           if (POINTER_TYPE_P (TREE_TYPE (sym))
746               && nonnull_arg_p (sym))
747             set_value_range_to_nonnull (vr, TREE_TYPE (sym));
748           else
749             set_value_range_to_varying (vr);
750         }
751       else if (TREE_CODE (sym) == RESULT_DECL
752                && DECL_BY_REFERENCE (sym))
753         set_value_range_to_nonnull (vr, TREE_TYPE (sym));
754     }
755
756   return vr;
757 }
758
759 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes.  */
760
761 static inline bool
762 vrp_operand_equal_p (const_tree val1, const_tree val2)
763 {
764   if (val1 == val2)
765     return true;
766   if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
767     return false;
768   if (is_overflow_infinity (val1))
769     return is_overflow_infinity (val2);
770   return true;
771 }
772
773 /* Return true, if the bitmaps B1 and B2 are equal.  */
774
775 static inline bool
776 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
777 {
778   return (b1 == b2
779           || ((!b1 || bitmap_empty_p (b1))
780               && (!b2 || bitmap_empty_p (b2)))
781           || (b1 && b2
782               && bitmap_equal_p (b1, b2)));
783 }
784
785 /* Update the value range and equivalence set for variable VAR to
786    NEW_VR.  Return true if NEW_VR is different from VAR's previous
787    value.
788
789    NOTE: This function assumes that NEW_VR is a temporary value range
790    object created for the sole purpose of updating VAR's range.  The
791    storage used by the equivalence set from NEW_VR will be freed by
792    this function.  Do not call update_value_range when NEW_VR
793    is the range object associated with another SSA name.  */
794
795 static inline bool
796 update_value_range (const_tree var, value_range_t *new_vr)
797 {
798   value_range_t *old_vr;
799   bool is_new;
800
801   /* Update the value range, if necessary.  */
802   old_vr = get_value_range (var);
803   is_new = old_vr->type != new_vr->type
804            || !vrp_operand_equal_p (old_vr->min, new_vr->min)
805            || !vrp_operand_equal_p (old_vr->max, new_vr->max)
806            || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
807
808   if (is_new)
809     {
810       /* Do not allow transitions up the lattice.  The following
811          is slightly more awkward than just new_vr->type < old_vr->type
812          because VR_RANGE and VR_ANTI_RANGE need to be considered
813          the same.  We may not have is_new when transitioning to
814          UNDEFINED or from VARYING.  */
815       if (new_vr->type == VR_UNDEFINED
816           || old_vr->type == VR_VARYING)
817         set_value_range_to_varying (old_vr);
818       else
819         set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
820                          new_vr->equiv);
821     }
822
823   BITMAP_FREE (new_vr->equiv);
824
825   return is_new;
826 }
827
828
829 /* Add VAR and VAR's equivalence set to EQUIV.  This is the central
830    point where equivalence processing can be turned on/off.  */
831
832 static void
833 add_equivalence (bitmap *equiv, const_tree var)
834 {
835   unsigned ver = SSA_NAME_VERSION (var);
836   value_range_t *vr = vr_value[ver];
837
838   if (*equiv == NULL)
839     *equiv = BITMAP_ALLOC (NULL);
840   bitmap_set_bit (*equiv, ver);
841   if (vr && vr->equiv)
842     bitmap_ior_into (*equiv, vr->equiv);
843 }
844
845
846 /* Return true if VR is ~[0, 0].  */
847
848 static inline bool
849 range_is_nonnull (value_range_t *vr)
850 {
851   return vr->type == VR_ANTI_RANGE
852          && integer_zerop (vr->min)
853          && integer_zerop (vr->max);
854 }
855
856
857 /* Return true if VR is [0, 0].  */
858
859 static inline bool
860 range_is_null (value_range_t *vr)
861 {
862   return vr->type == VR_RANGE
863          && integer_zerop (vr->min)
864          && integer_zerop (vr->max);
865 }
866
867 /* Return true if max and min of VR are INTEGER_CST.  It's not necessary
868    a singleton.  */
869
870 static inline bool
871 range_int_cst_p (value_range_t *vr)
872 {
873   return (vr->type == VR_RANGE
874           && TREE_CODE (vr->max) == INTEGER_CST
875           && TREE_CODE (vr->min) == INTEGER_CST);
876 }
877
878 /* Return true if VR is a INTEGER_CST singleton.  */
879
880 static inline bool
881 range_int_cst_singleton_p (value_range_t *vr)
882 {
883   return (range_int_cst_p (vr)
884           && !TREE_OVERFLOW (vr->min)
885           && !TREE_OVERFLOW (vr->max)
886           && tree_int_cst_equal (vr->min, vr->max));
887 }
888
889 /* Return true if value range VR involves at least one symbol.  */
890
891 static inline bool
892 symbolic_range_p (value_range_t *vr)
893 {
894   return (!is_gimple_min_invariant (vr->min)
895           || !is_gimple_min_invariant (vr->max));
896 }
897
898 /* Return true if value range VR uses an overflow infinity.  */
899
900 static inline bool
901 overflow_infinity_range_p (value_range_t *vr)
902 {
903   return (vr->type == VR_RANGE
904           && (is_overflow_infinity (vr->min)
905               || is_overflow_infinity (vr->max)));
906 }
907
908 /* Return false if we can not make a valid comparison based on VR;
909    this will be the case if it uses an overflow infinity and overflow
910    is not undefined (i.e., -fno-strict-overflow is in effect).
911    Otherwise return true, and set *STRICT_OVERFLOW_P to true if VR
912    uses an overflow infinity.  */
913
914 static bool
915 usable_range_p (value_range_t *vr, bool *strict_overflow_p)
916 {
917   gcc_assert (vr->type == VR_RANGE);
918   if (is_overflow_infinity (vr->min))
919     {
920       *strict_overflow_p = true;
921       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->min)))
922         return false;
923     }
924   if (is_overflow_infinity (vr->max))
925     {
926       *strict_overflow_p = true;
927       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->max)))
928         return false;
929     }
930   return true;
931 }
932
933
934 /* Return true if the result of assignment STMT is know to be non-negative.
935    If the return value is based on the assumption that signed overflow is
936    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
937    *STRICT_OVERFLOW_P.*/
938
939 static bool
940 gimple_assign_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
941 {
942   enum tree_code code = gimple_assign_rhs_code (stmt);
943   switch (get_gimple_rhs_class (code))
944     {
945     case GIMPLE_UNARY_RHS:
946       return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
947                                              gimple_expr_type (stmt),
948                                              gimple_assign_rhs1 (stmt),
949                                              strict_overflow_p);
950     case GIMPLE_BINARY_RHS:
951       return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
952                                               gimple_expr_type (stmt),
953                                               gimple_assign_rhs1 (stmt),
954                                               gimple_assign_rhs2 (stmt),
955                                               strict_overflow_p);
956     case GIMPLE_TERNARY_RHS:
957       return false;
958     case GIMPLE_SINGLE_RHS:
959       return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
960                                               strict_overflow_p);
961     case GIMPLE_INVALID_RHS:
962       gcc_unreachable ();
963     default:
964       gcc_unreachable ();
965     }
966 }
967
968 /* Return true if return value of call STMT is know to be non-negative.
969    If the return value is based on the assumption that signed overflow is
970    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
971    *STRICT_OVERFLOW_P.*/
972
973 static bool
974 gimple_call_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
975 {
976   tree arg0 = gimple_call_num_args (stmt) > 0 ?
977     gimple_call_arg (stmt, 0) : NULL_TREE;
978   tree arg1 = gimple_call_num_args (stmt) > 1 ?
979     gimple_call_arg (stmt, 1) : NULL_TREE;
980
981   return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
982                                         gimple_call_fndecl (stmt),
983                                         arg0,
984                                         arg1,
985                                         strict_overflow_p);
986 }
987
988 /* Return true if STMT is know to to compute a non-negative value.
989    If the return value is based on the assumption that signed overflow is
990    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
991    *STRICT_OVERFLOW_P.*/
992
993 static bool
994 gimple_stmt_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
995 {
996   switch (gimple_code (stmt))
997     {
998     case GIMPLE_ASSIGN:
999       return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p);
1000     case GIMPLE_CALL:
1001       return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p);
1002     default:
1003       gcc_unreachable ();
1004     }
1005 }
1006
1007 /* Return true if the result of assignment STMT is know to be non-zero.
1008    If the return value is based on the assumption that signed overflow is
1009    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1010    *STRICT_OVERFLOW_P.*/
1011
1012 static bool
1013 gimple_assign_nonzero_warnv_p (gimple stmt, bool *strict_overflow_p)
1014 {
1015   enum tree_code code = gimple_assign_rhs_code (stmt);
1016   switch (get_gimple_rhs_class (code))
1017     {
1018     case GIMPLE_UNARY_RHS:
1019       return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1020                                          gimple_expr_type (stmt),
1021                                          gimple_assign_rhs1 (stmt),
1022                                          strict_overflow_p);
1023     case GIMPLE_BINARY_RHS:
1024       return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1025                                           gimple_expr_type (stmt),
1026                                           gimple_assign_rhs1 (stmt),
1027                                           gimple_assign_rhs2 (stmt),
1028                                           strict_overflow_p);
1029     case GIMPLE_TERNARY_RHS:
1030       return false;
1031     case GIMPLE_SINGLE_RHS:
1032       return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
1033                                           strict_overflow_p);
1034     case GIMPLE_INVALID_RHS:
1035       gcc_unreachable ();
1036     default:
1037       gcc_unreachable ();
1038     }
1039 }
1040
1041 /* Return true if STMT is know to to compute a non-zero value.
1042    If the return value is based on the assumption that signed overflow is
1043    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1044    *STRICT_OVERFLOW_P.*/
1045
1046 static bool
1047 gimple_stmt_nonzero_warnv_p (gimple stmt, bool *strict_overflow_p)
1048 {
1049   switch (gimple_code (stmt))
1050     {
1051     case GIMPLE_ASSIGN:
1052       return gimple_assign_nonzero_warnv_p (stmt, strict_overflow_p);
1053     case GIMPLE_CALL:
1054       {
1055         tree fndecl = gimple_call_fndecl (stmt);
1056         if (!fndecl) return false;
1057         if (flag_delete_null_pointer_checks && !flag_check_new
1058             && DECL_IS_OPERATOR_NEW (fndecl)
1059             && !TREE_NOTHROW (fndecl))
1060           return true;
1061         return gimple_alloca_call_p (stmt);
1062       }
1063     default:
1064       gcc_unreachable ();
1065     }
1066 }
1067
1068 /* Like tree_expr_nonzero_warnv_p, but this function uses value ranges
1069    obtained so far.  */
1070
1071 static bool
1072 vrp_stmt_computes_nonzero (gimple stmt, bool *strict_overflow_p)
1073 {
1074   if (gimple_stmt_nonzero_warnv_p (stmt, strict_overflow_p))
1075     return true;
1076
1077   /* If we have an expression of the form &X->a, then the expression
1078      is nonnull if X is nonnull.  */
1079   if (is_gimple_assign (stmt)
1080       && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
1081     {
1082       tree expr = gimple_assign_rhs1 (stmt);
1083       tree base = get_base_address (TREE_OPERAND (expr, 0));
1084
1085       if (base != NULL_TREE
1086           && TREE_CODE (base) == MEM_REF
1087           && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
1088         {
1089           value_range_t *vr = get_value_range (TREE_OPERAND (base, 0));
1090           if (range_is_nonnull (vr))
1091             return true;
1092         }
1093     }
1094
1095   return false;
1096 }
1097
1098 /* Returns true if EXPR is a valid value (as expected by compare_values) --
1099    a gimple invariant, or SSA_NAME +- CST.  */
1100
1101 static bool
1102 valid_value_p (tree expr)
1103 {
1104   if (TREE_CODE (expr) == SSA_NAME)
1105     return true;
1106
1107   if (TREE_CODE (expr) == PLUS_EXPR
1108       || TREE_CODE (expr) == MINUS_EXPR)
1109     return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1110             && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
1111
1112   return is_gimple_min_invariant (expr);
1113 }
1114
1115 /* Return
1116    1 if VAL < VAL2
1117    0 if !(VAL < VAL2)
1118    -2 if those are incomparable.  */
1119 static inline int
1120 operand_less_p (tree val, tree val2)
1121 {
1122   /* LT is folded faster than GE and others.  Inline the common case.  */
1123   if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
1124     {
1125       if (TYPE_UNSIGNED (TREE_TYPE (val)))
1126         return INT_CST_LT_UNSIGNED (val, val2);
1127       else
1128         {
1129           if (INT_CST_LT (val, val2))
1130             return 1;
1131         }
1132     }
1133   else
1134     {
1135       tree tcmp;
1136
1137       fold_defer_overflow_warnings ();
1138
1139       tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
1140
1141       fold_undefer_and_ignore_overflow_warnings ();
1142
1143       if (!tcmp
1144           || TREE_CODE (tcmp) != INTEGER_CST)
1145         return -2;
1146
1147       if (!integer_zerop (tcmp))
1148         return 1;
1149     }
1150
1151   /* val >= val2, not considering overflow infinity.  */
1152   if (is_negative_overflow_infinity (val))
1153     return is_negative_overflow_infinity (val2) ? 0 : 1;
1154   else if (is_positive_overflow_infinity (val2))
1155     return is_positive_overflow_infinity (val) ? 0 : 1;
1156
1157   return 0;
1158 }
1159
1160 /* Compare two values VAL1 and VAL2.  Return
1161
1162         -2 if VAL1 and VAL2 cannot be compared at compile-time,
1163         -1 if VAL1 < VAL2,
1164          0 if VAL1 == VAL2,
1165         +1 if VAL1 > VAL2, and
1166         +2 if VAL1 != VAL2
1167
1168    This is similar to tree_int_cst_compare but supports pointer values
1169    and values that cannot be compared at compile time.
1170
1171    If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1172    true if the return value is only valid if we assume that signed
1173    overflow is undefined.  */
1174
1175 static int
1176 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1177 {
1178   if (val1 == val2)
1179     return 0;
1180
1181   /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1182      both integers.  */
1183   gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1184               == POINTER_TYPE_P (TREE_TYPE (val2)));
1185   /* Convert the two values into the same type.  This is needed because
1186      sizetype causes sign extension even for unsigned types.  */
1187   val2 = fold_convert (TREE_TYPE (val1), val2);
1188   STRIP_USELESS_TYPE_CONVERSION (val2);
1189
1190   if ((TREE_CODE (val1) == SSA_NAME
1191        || TREE_CODE (val1) == PLUS_EXPR
1192        || TREE_CODE (val1) == MINUS_EXPR)
1193       && (TREE_CODE (val2) == SSA_NAME
1194           || TREE_CODE (val2) == PLUS_EXPR
1195           || TREE_CODE (val2) == MINUS_EXPR))
1196     {
1197       tree n1, c1, n2, c2;
1198       enum tree_code code1, code2;
1199
1200       /* If VAL1 and VAL2 are of the form 'NAME [+-] CST' or 'NAME',
1201          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
1202          same name, return -2.  */
1203       if (TREE_CODE (val1) == SSA_NAME)
1204         {
1205           code1 = SSA_NAME;
1206           n1 = val1;
1207           c1 = NULL_TREE;
1208         }
1209       else
1210         {
1211           code1 = TREE_CODE (val1);
1212           n1 = TREE_OPERAND (val1, 0);
1213           c1 = TREE_OPERAND (val1, 1);
1214           if (tree_int_cst_sgn (c1) == -1)
1215             {
1216               if (is_negative_overflow_infinity (c1))
1217                 return -2;
1218               c1 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c1), c1);
1219               if (!c1)
1220                 return -2;
1221               code1 = code1 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
1222             }
1223         }
1224
1225       if (TREE_CODE (val2) == SSA_NAME)
1226         {
1227           code2 = SSA_NAME;
1228           n2 = val2;
1229           c2 = NULL_TREE;
1230         }
1231       else
1232         {
1233           code2 = TREE_CODE (val2);
1234           n2 = TREE_OPERAND (val2, 0);
1235           c2 = TREE_OPERAND (val2, 1);
1236           if (tree_int_cst_sgn (c2) == -1)
1237             {
1238               if (is_negative_overflow_infinity (c2))
1239                 return -2;
1240               c2 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c2), c2);
1241               if (!c2)
1242                 return -2;
1243               code2 = code2 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
1244             }
1245         }
1246
1247       /* Both values must use the same name.  */
1248       if (n1 != n2)
1249         return -2;
1250
1251       if (code1 == SSA_NAME
1252           && code2 == SSA_NAME)
1253         /* NAME == NAME  */
1254         return 0;
1255
1256       /* If overflow is defined we cannot simplify more.  */
1257       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1258         return -2;
1259
1260       if (strict_overflow_p != NULL
1261           && (code1 == SSA_NAME || !TREE_NO_WARNING (val1))
1262           && (code2 == SSA_NAME || !TREE_NO_WARNING (val2)))
1263         *strict_overflow_p = true;
1264
1265       if (code1 == SSA_NAME)
1266         {
1267           if (code2 == PLUS_EXPR)
1268             /* NAME < NAME + CST  */
1269             return -1;
1270           else if (code2 == MINUS_EXPR)
1271             /* NAME > NAME - CST  */
1272             return 1;
1273         }
1274       else if (code1 == PLUS_EXPR)
1275         {
1276           if (code2 == SSA_NAME)
1277             /* NAME + CST > NAME  */
1278             return 1;
1279           else if (code2 == PLUS_EXPR)
1280             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
1281             return compare_values_warnv (c1, c2, strict_overflow_p);
1282           else if (code2 == MINUS_EXPR)
1283             /* NAME + CST1 > NAME - CST2  */
1284             return 1;
1285         }
1286       else if (code1 == MINUS_EXPR)
1287         {
1288           if (code2 == SSA_NAME)
1289             /* NAME - CST < NAME  */
1290             return -1;
1291           else if (code2 == PLUS_EXPR)
1292             /* NAME - CST1 < NAME + CST2  */
1293             return -1;
1294           else if (code2 == MINUS_EXPR)
1295             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
1296                C1 and C2 are swapped in the call to compare_values.  */
1297             return compare_values_warnv (c2, c1, strict_overflow_p);
1298         }
1299
1300       gcc_unreachable ();
1301     }
1302
1303   /* We cannot compare non-constants.  */
1304   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
1305     return -2;
1306
1307   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1308     {
1309       /* We cannot compare overflowed values, except for overflow
1310          infinities.  */
1311       if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1312         {
1313           if (strict_overflow_p != NULL)
1314             *strict_overflow_p = true;
1315           if (is_negative_overflow_infinity (val1))
1316             return is_negative_overflow_infinity (val2) ? 0 : -1;
1317           else if (is_negative_overflow_infinity (val2))
1318             return 1;
1319           else if (is_positive_overflow_infinity (val1))
1320             return is_positive_overflow_infinity (val2) ? 0 : 1;
1321           else if (is_positive_overflow_infinity (val2))
1322             return -1;
1323           return -2;
1324         }
1325
1326       return tree_int_cst_compare (val1, val2);
1327     }
1328   else
1329     {
1330       tree t;
1331
1332       /* First see if VAL1 and VAL2 are not the same.  */
1333       if (val1 == val2 || operand_equal_p (val1, val2, 0))
1334         return 0;
1335
1336       /* If VAL1 is a lower address than VAL2, return -1.  */
1337       if (operand_less_p (val1, val2) == 1)
1338         return -1;
1339
1340       /* If VAL1 is a higher address than VAL2, return +1.  */
1341       if (operand_less_p (val2, val1) == 1)
1342         return 1;
1343
1344       /* If VAL1 is different than VAL2, return +2.
1345          For integer constants we either have already returned -1 or 1
1346          or they are equivalent.  We still might succeed in proving
1347          something about non-trivial operands.  */
1348       if (TREE_CODE (val1) != INTEGER_CST
1349           || TREE_CODE (val2) != INTEGER_CST)
1350         {
1351           t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1352           if (t && integer_onep (t))
1353             return 2;
1354         }
1355
1356       return -2;
1357     }
1358 }
1359
1360 /* Compare values like compare_values_warnv, but treat comparisons of
1361    nonconstants which rely on undefined overflow as incomparable.  */
1362
1363 static int
1364 compare_values (tree val1, tree val2)
1365 {
1366   bool sop;
1367   int ret;
1368
1369   sop = false;
1370   ret = compare_values_warnv (val1, val2, &sop);
1371   if (sop
1372       && (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2)))
1373     ret = -2;
1374   return ret;
1375 }
1376
1377
1378 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1379           0 if VAL is not inside [MIN, MAX],
1380          -2 if we cannot tell either way.
1381
1382    Benchmark compile/20001226-1.c compilation time after changing this
1383    function.  */
1384
1385 static inline int
1386 value_inside_range (tree val, tree min, tree max)
1387 {
1388   int cmp1, cmp2;
1389
1390   cmp1 = operand_less_p (val, min);
1391   if (cmp1 == -2)
1392     return -2;
1393   if (cmp1 == 1)
1394     return 0;
1395
1396   cmp2 = operand_less_p (max, val);
1397   if (cmp2 == -2)
1398     return -2;
1399
1400   return !cmp2;
1401 }
1402
1403
1404 /* Return true if value ranges VR0 and VR1 have a non-empty
1405    intersection.
1406
1407    Benchmark compile/20001226-1.c compilation time after changing this
1408    function.
1409    */
1410
1411 static inline bool
1412 value_ranges_intersect_p (value_range_t *vr0, value_range_t *vr1)
1413 {
1414   /* The value ranges do not intersect if the maximum of the first range is
1415      less than the minimum of the second range or vice versa.
1416      When those relations are unknown, we can't do any better.  */
1417   if (operand_less_p (vr0->max, vr1->min) != 0)
1418     return false;
1419   if (operand_less_p (vr1->max, vr0->min) != 0)
1420     return false;
1421   return true;
1422 }
1423
1424
1425 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1426    include the value zero, -2 if we cannot tell.  */
1427
1428 static inline int
1429 range_includes_zero_p (tree min, tree max)
1430 {
1431   tree zero = build_int_cst (TREE_TYPE (min), 0);
1432   return value_inside_range (zero, min, max);
1433 }
1434
1435 /* Return true if *VR is know to only contain nonnegative values.  */
1436
1437 static inline bool
1438 value_range_nonnegative_p (value_range_t *vr)
1439 {
1440   /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1441      which would return a useful value should be encoded as a 
1442      VR_RANGE.  */
1443   if (vr->type == VR_RANGE)
1444     {
1445       int result = compare_values (vr->min, integer_zero_node);
1446       return (result == 0 || result == 1);
1447     }
1448
1449   return false;
1450 }
1451
1452 /* Return true if T, an SSA_NAME, is known to be nonnegative.  Return
1453    false otherwise or if no value range information is available.  */
1454
1455 bool
1456 ssa_name_nonnegative_p (const_tree t)
1457 {
1458   value_range_t *vr = get_value_range (t);
1459
1460   if (INTEGRAL_TYPE_P (t)
1461       && TYPE_UNSIGNED (t))
1462     return true;
1463
1464   if (!vr)
1465     return false;
1466
1467   return value_range_nonnegative_p (vr);
1468 }
1469
1470 /* If *VR has a value rante that is a single constant value return that,
1471    otherwise return NULL_TREE.  */
1472
1473 static tree
1474 value_range_constant_singleton (value_range_t *vr)
1475 {
1476   if (vr->type == VR_RANGE
1477       && operand_equal_p (vr->min, vr->max, 0)
1478       && is_gimple_min_invariant (vr->min))
1479     return vr->min;
1480
1481   return NULL_TREE;
1482 }
1483
1484 /* If OP has a value range with a single constant value return that,
1485    otherwise return NULL_TREE.  This returns OP itself if OP is a
1486    constant.  */
1487
1488 static tree
1489 op_with_constant_singleton_value_range (tree op)
1490 {
1491   if (is_gimple_min_invariant (op))
1492     return op;
1493
1494   if (TREE_CODE (op) != SSA_NAME)
1495     return NULL_TREE;
1496
1497   return value_range_constant_singleton (get_value_range (op));
1498 }
1499
1500 /* Return true if op is in a boolean [0, 1] value-range.  */
1501
1502 static bool
1503 op_with_boolean_value_range_p (tree op)
1504 {
1505   value_range_t *vr;
1506
1507   if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1508     return true;
1509
1510   if (integer_zerop (op)
1511       || integer_onep (op))
1512     return true;
1513
1514   if (TREE_CODE (op) != SSA_NAME)
1515     return false;
1516
1517   vr = get_value_range (op);
1518   return (vr->type == VR_RANGE
1519           && integer_zerop (vr->min)
1520           && integer_onep (vr->max));
1521 }
1522
1523 /* Extract value range information from an ASSERT_EXPR EXPR and store
1524    it in *VR_P.  */
1525
1526 static void
1527 extract_range_from_assert (value_range_t *vr_p, tree expr)
1528 {
1529   tree var, cond, limit, min, max, type;
1530   value_range_t *limit_vr;
1531   enum tree_code cond_code;
1532
1533   var = ASSERT_EXPR_VAR (expr);
1534   cond = ASSERT_EXPR_COND (expr);
1535
1536   gcc_assert (COMPARISON_CLASS_P (cond));
1537
1538   /* Find VAR in the ASSERT_EXPR conditional.  */
1539   if (var == TREE_OPERAND (cond, 0)
1540       || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1541       || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1542     {
1543       /* If the predicate is of the form VAR COMP LIMIT, then we just
1544          take LIMIT from the RHS and use the same comparison code.  */
1545       cond_code = TREE_CODE (cond);
1546       limit = TREE_OPERAND (cond, 1);
1547       cond = TREE_OPERAND (cond, 0);
1548     }
1549   else
1550     {
1551       /* If the predicate is of the form LIMIT COMP VAR, then we need
1552          to flip around the comparison code to create the proper range
1553          for VAR.  */
1554       cond_code = swap_tree_comparison (TREE_CODE (cond));
1555       limit = TREE_OPERAND (cond, 0);
1556       cond = TREE_OPERAND (cond, 1);
1557     }
1558
1559   limit = avoid_overflow_infinity (limit);
1560
1561   type = TREE_TYPE (var);
1562   gcc_assert (limit != var);
1563
1564   /* For pointer arithmetic, we only keep track of pointer equality
1565      and inequality.  */
1566   if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1567     {
1568       set_value_range_to_varying (vr_p);
1569       return;
1570     }
1571
1572   /* If LIMIT is another SSA name and LIMIT has a range of its own,
1573      try to use LIMIT's range to avoid creating symbolic ranges
1574      unnecessarily. */
1575   limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1576
1577   /* LIMIT's range is only interesting if it has any useful information.  */
1578   if (limit_vr
1579       && (limit_vr->type == VR_UNDEFINED
1580           || limit_vr->type == VR_VARYING
1581           || symbolic_range_p (limit_vr)))
1582     limit_vr = NULL;
1583
1584   /* Initially, the new range has the same set of equivalences of
1585      VAR's range.  This will be revised before returning the final
1586      value.  Since assertions may be chained via mutually exclusive
1587      predicates, we will need to trim the set of equivalences before
1588      we are done.  */
1589   gcc_assert (vr_p->equiv == NULL);
1590   add_equivalence (&vr_p->equiv, var);
1591
1592   /* Extract a new range based on the asserted comparison for VAR and
1593      LIMIT's value range.  Notice that if LIMIT has an anti-range, we
1594      will only use it for equality comparisons (EQ_EXPR).  For any
1595      other kind of assertion, we cannot derive a range from LIMIT's
1596      anti-range that can be used to describe the new range.  For
1597      instance, ASSERT_EXPR <x_2, x_2 <= b_4>.  If b_4 is ~[2, 10],
1598      then b_4 takes on the ranges [-INF, 1] and [11, +INF].  There is
1599      no single range for x_2 that could describe LE_EXPR, so we might
1600      as well build the range [b_4, +INF] for it.
1601      One special case we handle is extracting a range from a
1602      range test encoded as (unsigned)var + CST <= limit.  */
1603   if (TREE_CODE (cond) == NOP_EXPR
1604       || TREE_CODE (cond) == PLUS_EXPR)
1605     {
1606       if (TREE_CODE (cond) == PLUS_EXPR)
1607         {
1608           min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (cond, 1)),
1609                              TREE_OPERAND (cond, 1));
1610           max = int_const_binop (PLUS_EXPR, limit, min);
1611           cond = TREE_OPERAND (cond, 0);
1612         }
1613       else
1614         {
1615           min = build_int_cst (TREE_TYPE (var), 0);
1616           max = limit;
1617         }
1618
1619       /* Make sure to not set TREE_OVERFLOW on the final type
1620          conversion.  We are willingly interpreting large positive
1621          unsigned values as negative singed values here.  */
1622       min = force_fit_type_double (TREE_TYPE (var), tree_to_double_int (min),
1623                                    0, false);
1624       max = force_fit_type_double (TREE_TYPE (var), tree_to_double_int (max),
1625                                    0, false);
1626
1627       /* We can transform a max, min range to an anti-range or
1628          vice-versa.  Use set_and_canonicalize_value_range which does
1629          this for us.  */
1630       if (cond_code == LE_EXPR)
1631         set_and_canonicalize_value_range (vr_p, VR_RANGE,
1632                                           min, max, vr_p->equiv);
1633       else if (cond_code == GT_EXPR)
1634         set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1635                                           min, max, vr_p->equiv);
1636       else
1637         gcc_unreachable ();
1638     }
1639   else if (cond_code == EQ_EXPR)
1640     {
1641       enum value_range_type range_type;
1642
1643       if (limit_vr)
1644         {
1645           range_type = limit_vr->type;
1646           min = limit_vr->min;
1647           max = limit_vr->max;
1648         }
1649       else
1650         {
1651           range_type = VR_RANGE;
1652           min = limit;
1653           max = limit;
1654         }
1655
1656       set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1657
1658       /* When asserting the equality VAR == LIMIT and LIMIT is another
1659          SSA name, the new range will also inherit the equivalence set
1660          from LIMIT.  */
1661       if (TREE_CODE (limit) == SSA_NAME)
1662         add_equivalence (&vr_p->equiv, limit);
1663     }
1664   else if (cond_code == NE_EXPR)
1665     {
1666       /* As described above, when LIMIT's range is an anti-range and
1667          this assertion is an inequality (NE_EXPR), then we cannot
1668          derive anything from the anti-range.  For instance, if
1669          LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1670          not imply that VAR's range is [0, 0].  So, in the case of
1671          anti-ranges, we just assert the inequality using LIMIT and
1672          not its anti-range.
1673
1674          If LIMIT_VR is a range, we can only use it to build a new
1675          anti-range if LIMIT_VR is a single-valued range.  For
1676          instance, if LIMIT_VR is [0, 1], the predicate
1677          VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1678          Rather, it means that for value 0 VAR should be ~[0, 0]
1679          and for value 1, VAR should be ~[1, 1].  We cannot
1680          represent these ranges.
1681
1682          The only situation in which we can build a valid
1683          anti-range is when LIMIT_VR is a single-valued range
1684          (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX).  In that case,
1685          build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX].  */
1686       if (limit_vr
1687           && limit_vr->type == VR_RANGE
1688           && compare_values (limit_vr->min, limit_vr->max) == 0)
1689         {
1690           min = limit_vr->min;
1691           max = limit_vr->max;
1692         }
1693       else
1694         {
1695           /* In any other case, we cannot use LIMIT's range to build a
1696              valid anti-range.  */
1697           min = max = limit;
1698         }
1699
1700       /* If MIN and MAX cover the whole range for their type, then
1701          just use the original LIMIT.  */
1702       if (INTEGRAL_TYPE_P (type)
1703           && vrp_val_is_min (min)
1704           && vrp_val_is_max (max))
1705         min = max = limit;
1706
1707       set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1708                                         min, max, vr_p->equiv);
1709     }
1710   else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1711     {
1712       min = TYPE_MIN_VALUE (type);
1713
1714       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1715         max = limit;
1716       else
1717         {
1718           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1719              range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1720              LT_EXPR.  */
1721           max = limit_vr->max;
1722         }
1723
1724       /* If the maximum value forces us to be out of bounds, simply punt.
1725          It would be pointless to try and do anything more since this
1726          all should be optimized away above us.  */
1727       if ((cond_code == LT_EXPR
1728            && compare_values (max, min) == 0)
1729           || (CONSTANT_CLASS_P (max) && TREE_OVERFLOW (max)))
1730         set_value_range_to_varying (vr_p);
1731       else
1732         {
1733           /* For LT_EXPR, we create the range [MIN, MAX - 1].  */
1734           if (cond_code == LT_EXPR)
1735             {
1736               if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1737                   && !TYPE_UNSIGNED (TREE_TYPE (max)))
1738                 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1739                                    build_int_cst (TREE_TYPE (max), -1));
1740               else
1741                 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1742                                    build_int_cst (TREE_TYPE (max), 1));
1743               if (EXPR_P (max))
1744                 TREE_NO_WARNING (max) = 1;
1745             }
1746
1747           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1748         }
1749     }
1750   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1751     {
1752       max = TYPE_MAX_VALUE (type);
1753
1754       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1755         min = limit;
1756       else
1757         {
1758           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1759              range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1760              GT_EXPR.  */
1761           min = limit_vr->min;
1762         }
1763
1764       /* If the minimum value forces us to be out of bounds, simply punt.
1765          It would be pointless to try and do anything more since this
1766          all should be optimized away above us.  */
1767       if ((cond_code == GT_EXPR
1768            && compare_values (min, max) == 0)
1769           || (CONSTANT_CLASS_P (min) && TREE_OVERFLOW (min)))
1770         set_value_range_to_varying (vr_p);
1771       else
1772         {
1773           /* For GT_EXPR, we create the range [MIN + 1, MAX].  */
1774           if (cond_code == GT_EXPR)
1775             {
1776               if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1777                   && !TYPE_UNSIGNED (TREE_TYPE (min)))
1778                 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1779                                    build_int_cst (TREE_TYPE (min), -1));
1780               else
1781                 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1782                                    build_int_cst (TREE_TYPE (min), 1));
1783               if (EXPR_P (min))
1784                 TREE_NO_WARNING (min) = 1;
1785             }
1786
1787           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1788         }
1789     }
1790   else
1791     gcc_unreachable ();
1792
1793   /* Finally intersect the new range with what we already know about var.  */
1794   vrp_intersect_ranges (vr_p, get_value_range (var));
1795 }
1796
1797
1798 /* Extract range information from SSA name VAR and store it in VR.  If
1799    VAR has an interesting range, use it.  Otherwise, create the
1800    range [VAR, VAR] and return it.  This is useful in situations where
1801    we may have conditionals testing values of VARYING names.  For
1802    instance,
1803
1804         x_3 = y_5;
1805         if (x_3 > y_5)
1806           ...
1807
1808     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1809     always false.  */
1810
1811 static void
1812 extract_range_from_ssa_name (value_range_t *vr, tree var)
1813 {
1814   value_range_t *var_vr = get_value_range (var);
1815
1816   if (var_vr->type != VR_UNDEFINED && var_vr->type != VR_VARYING)
1817     copy_value_range (vr, var_vr);
1818   else
1819     set_value_range (vr, VR_RANGE, var, var, NULL);
1820
1821   add_equivalence (&vr->equiv, var);
1822 }
1823
1824
1825 /* Wrapper around int_const_binop.  If the operation overflows and we
1826    are not using wrapping arithmetic, then adjust the result to be
1827    -INF or +INF depending on CODE, VAL1 and VAL2.  This can return
1828    NULL_TREE if we need to use an overflow infinity representation but
1829    the type does not support it.  */
1830
1831 static tree
1832 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
1833 {
1834   tree res;
1835
1836   res = int_const_binop (code, val1, val2);
1837
1838   /* If we are using unsigned arithmetic, operate symbolically
1839      on -INF and +INF as int_const_binop only handles signed overflow.  */
1840   if (TYPE_UNSIGNED (TREE_TYPE (val1)))
1841     {
1842       int checkz = compare_values (res, val1);
1843       bool overflow = false;
1844
1845       /* Ensure that res = val1 [+*] val2 >= val1
1846          or that res = val1 - val2 <= val1.  */
1847       if ((code == PLUS_EXPR
1848            && !(checkz == 1 || checkz == 0))
1849           || (code == MINUS_EXPR
1850               && !(checkz == 0 || checkz == -1)))
1851         {
1852           overflow = true;
1853         }
1854       /* Checking for multiplication overflow is done by dividing the
1855          output of the multiplication by the first input of the
1856          multiplication.  If the result of that division operation is
1857          not equal to the second input of the multiplication, then the
1858          multiplication overflowed.  */
1859       else if (code == MULT_EXPR && !integer_zerop (val1))
1860         {
1861           tree tmp = int_const_binop (TRUNC_DIV_EXPR,
1862                                       res,
1863                                       val1);
1864           int check = compare_values (tmp, val2);
1865
1866           if (check != 0)
1867             overflow = true;
1868         }
1869
1870       if (overflow)
1871         {
1872           res = copy_node (res);
1873           TREE_OVERFLOW (res) = 1;
1874         }
1875
1876     }
1877   else if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (val1)))
1878     /* If the singed operation wraps then int_const_binop has done
1879        everything we want.  */
1880     ;
1881   else if ((TREE_OVERFLOW (res)
1882             && !TREE_OVERFLOW (val1)
1883             && !TREE_OVERFLOW (val2))
1884            || is_overflow_infinity (val1)
1885            || is_overflow_infinity (val2))
1886     {
1887       /* If the operation overflowed but neither VAL1 nor VAL2 are
1888          overflown, return -INF or +INF depending on the operation
1889          and the combination of signs of the operands.  */
1890       int sgn1 = tree_int_cst_sgn (val1);
1891       int sgn2 = tree_int_cst_sgn (val2);
1892
1893       if (needs_overflow_infinity (TREE_TYPE (res))
1894           && !supports_overflow_infinity (TREE_TYPE (res)))
1895         return NULL_TREE;
1896
1897       /* We have to punt on adding infinities of different signs,
1898          since we can't tell what the sign of the result should be.
1899          Likewise for subtracting infinities of the same sign.  */
1900       if (((code == PLUS_EXPR && sgn1 != sgn2)
1901            || (code == MINUS_EXPR && sgn1 == sgn2))
1902           && is_overflow_infinity (val1)
1903           && is_overflow_infinity (val2))
1904         return NULL_TREE;
1905
1906       /* Don't try to handle division or shifting of infinities.  */
1907       if ((code == TRUNC_DIV_EXPR
1908            || code == FLOOR_DIV_EXPR
1909            || code == CEIL_DIV_EXPR
1910            || code == EXACT_DIV_EXPR
1911            || code == ROUND_DIV_EXPR
1912            || code == RSHIFT_EXPR)
1913           && (is_overflow_infinity (val1)
1914               || is_overflow_infinity (val2)))
1915         return NULL_TREE;
1916
1917       /* Notice that we only need to handle the restricted set of
1918          operations handled by extract_range_from_binary_expr.
1919          Among them, only multiplication, addition and subtraction
1920          can yield overflow without overflown operands because we
1921          are working with integral types only... except in the
1922          case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1923          for division too.  */
1924
1925       /* For multiplication, the sign of the overflow is given
1926          by the comparison of the signs of the operands.  */
1927       if ((code == MULT_EXPR && sgn1 == sgn2)
1928           /* For addition, the operands must be of the same sign
1929              to yield an overflow.  Its sign is therefore that
1930              of one of the operands, for example the first.  For
1931              infinite operands X + -INF is negative, not positive.  */
1932           || (code == PLUS_EXPR
1933               && (sgn1 >= 0
1934                   ? !is_negative_overflow_infinity (val2)
1935                   : is_positive_overflow_infinity (val2)))
1936           /* For subtraction, non-infinite operands must be of
1937              different signs to yield an overflow.  Its sign is
1938              therefore that of the first operand or the opposite of
1939              that of the second operand.  A first operand of 0 counts
1940              as positive here, for the corner case 0 - (-INF), which
1941              overflows, but must yield +INF.  For infinite operands 0
1942              - INF is negative, not positive.  */
1943           || (code == MINUS_EXPR
1944               && (sgn1 >= 0
1945                   ? !is_positive_overflow_infinity (val2)
1946                   : is_negative_overflow_infinity (val2)))
1947           /* We only get in here with positive shift count, so the
1948              overflow direction is the same as the sign of val1.
1949              Actually rshift does not overflow at all, but we only
1950              handle the case of shifting overflowed -INF and +INF.  */
1951           || (code == RSHIFT_EXPR
1952               && sgn1 >= 0)
1953           /* For division, the only case is -INF / -1 = +INF.  */
1954           || code == TRUNC_DIV_EXPR
1955           || code == FLOOR_DIV_EXPR
1956           || code == CEIL_DIV_EXPR
1957           || code == EXACT_DIV_EXPR
1958           || code == ROUND_DIV_EXPR)
1959         return (needs_overflow_infinity (TREE_TYPE (res))
1960                 ? positive_overflow_infinity (TREE_TYPE (res))
1961                 : TYPE_MAX_VALUE (TREE_TYPE (res)));
1962       else
1963         return (needs_overflow_infinity (TREE_TYPE (res))
1964                 ? negative_overflow_infinity (TREE_TYPE (res))
1965                 : TYPE_MIN_VALUE (TREE_TYPE (res)));
1966     }
1967
1968   return res;
1969 }
1970
1971
1972 /* For range VR compute two double_int bitmasks.  In *MAY_BE_NONZERO
1973    bitmask if some bit is unset, it means for all numbers in the range
1974    the bit is 0, otherwise it might be 0 or 1.  In *MUST_BE_NONZERO
1975    bitmask if some bit is set, it means for all numbers in the range
1976    the bit is 1, otherwise it might be 0 or 1.  */
1977
1978 static bool
1979 zero_nonzero_bits_from_vr (value_range_t *vr,
1980                            double_int *may_be_nonzero,
1981                            double_int *must_be_nonzero)
1982 {
1983   *may_be_nonzero = double_int_minus_one;
1984   *must_be_nonzero = double_int_zero;
1985   if (!range_int_cst_p (vr)
1986       || TREE_OVERFLOW (vr->min)
1987       || TREE_OVERFLOW (vr->max))
1988     return false;
1989
1990   if (range_int_cst_singleton_p (vr))
1991     {
1992       *may_be_nonzero = tree_to_double_int (vr->min);
1993       *must_be_nonzero = *may_be_nonzero;
1994     }
1995   else if (tree_int_cst_sgn (vr->min) >= 0
1996            || tree_int_cst_sgn (vr->max) < 0)
1997     {
1998       double_int dmin = tree_to_double_int (vr->min);
1999       double_int dmax = tree_to_double_int (vr->max);
2000       double_int xor_mask = dmin ^ dmax;
2001       *may_be_nonzero = dmin | dmax;
2002       *must_be_nonzero = dmin & dmax;
2003       if (xor_mask.high != 0)
2004         {
2005           unsigned HOST_WIDE_INT mask
2006               = ((unsigned HOST_WIDE_INT) 1
2007                  << floor_log2 (xor_mask.high)) - 1;
2008           may_be_nonzero->low = ALL_ONES;
2009           may_be_nonzero->high |= mask;
2010           must_be_nonzero->low = 0;
2011           must_be_nonzero->high &= ~mask;
2012         }
2013       else if (xor_mask.low != 0)
2014         {
2015           unsigned HOST_WIDE_INT mask
2016               = ((unsigned HOST_WIDE_INT) 1
2017                  << floor_log2 (xor_mask.low)) - 1;
2018           may_be_nonzero->low |= mask;
2019           must_be_nonzero->low &= ~mask;
2020         }
2021     }
2022
2023   return true;
2024 }
2025
2026 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
2027    so that *VR0 U *VR1 == *AR.  Returns true if that is possible,
2028    false otherwise.  If *AR can be represented with a single range
2029    *VR1 will be VR_UNDEFINED.  */
2030
2031 static bool
2032 ranges_from_anti_range (value_range_t *ar,
2033                         value_range_t *vr0, value_range_t *vr1)
2034 {
2035   tree type = TREE_TYPE (ar->min);
2036
2037   vr0->type = VR_UNDEFINED;
2038   vr1->type = VR_UNDEFINED;
2039
2040   if (ar->type != VR_ANTI_RANGE
2041       || TREE_CODE (ar->min) != INTEGER_CST
2042       || TREE_CODE (ar->max) != INTEGER_CST
2043       || !vrp_val_min (type)
2044       || !vrp_val_max (type))
2045     return false;
2046
2047   if (!vrp_val_is_min (ar->min))
2048     {
2049       vr0->type = VR_RANGE;
2050       vr0->min = vrp_val_min (type);
2051       vr0->max
2052         = double_int_to_tree (type,
2053                               tree_to_double_int (ar->min) - double_int_one);
2054     }
2055   if (!vrp_val_is_max (ar->max))
2056     {
2057       vr1->type = VR_RANGE;
2058       vr1->min
2059         = double_int_to_tree (type,
2060                               tree_to_double_int (ar->max) + double_int_one);
2061       vr1->max = vrp_val_max (type);
2062     }
2063   if (vr0->type == VR_UNDEFINED)
2064     {
2065       *vr0 = *vr1;
2066       vr1->type = VR_UNDEFINED;
2067     }
2068
2069   return vr0->type != VR_UNDEFINED;
2070 }
2071
2072 /* Helper to extract a value-range *VR for a multiplicative operation
2073    *VR0 CODE *VR1.  */
2074
2075 static void
2076 extract_range_from_multiplicative_op_1 (value_range_t *vr,
2077                                         enum tree_code code,
2078                                         value_range_t *vr0, value_range_t *vr1)
2079 {
2080   enum value_range_type type;
2081   tree val[4];
2082   size_t i;
2083   tree min, max;
2084   bool sop;
2085   int cmp;
2086
2087   /* Multiplications, divisions and shifts are a bit tricky to handle,
2088      depending on the mix of signs we have in the two ranges, we
2089      need to operate on different values to get the minimum and
2090      maximum values for the new range.  One approach is to figure
2091      out all the variations of range combinations and do the
2092      operations.
2093
2094      However, this involves several calls to compare_values and it
2095      is pretty convoluted.  It's simpler to do the 4 operations
2096      (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
2097      MAX1) and then figure the smallest and largest values to form
2098      the new range.  */
2099   gcc_assert (code == MULT_EXPR
2100               || code == TRUNC_DIV_EXPR
2101               || code == FLOOR_DIV_EXPR
2102               || code == CEIL_DIV_EXPR
2103               || code == EXACT_DIV_EXPR
2104               || code == ROUND_DIV_EXPR
2105               || code == RSHIFT_EXPR
2106               || code == LSHIFT_EXPR);
2107   gcc_assert ((vr0->type == VR_RANGE
2108                || (code == MULT_EXPR && vr0->type == VR_ANTI_RANGE))
2109               && vr0->type == vr1->type);
2110
2111   type = vr0->type;
2112
2113   /* Compute the 4 cross operations.  */
2114   sop = false;
2115   val[0] = vrp_int_const_binop (code, vr0->min, vr1->min);
2116   if (val[0] == NULL_TREE)
2117     sop = true;
2118
2119   if (vr1->max == vr1->min)
2120     val[1] = NULL_TREE;
2121   else
2122     {
2123       val[1] = vrp_int_const_binop (code, vr0->min, vr1->max);
2124       if (val[1] == NULL_TREE)
2125         sop = true;
2126     }
2127
2128   if (vr0->max == vr0->min)
2129     val[2] = NULL_TREE;
2130   else
2131     {
2132       val[2] = vrp_int_const_binop (code, vr0->max, vr1->min);
2133       if (val[2] == NULL_TREE)
2134         sop = true;
2135     }
2136
2137   if (vr0->min == vr0->max || vr1->min == vr1->max)
2138     val[3] = NULL_TREE;
2139   else
2140     {
2141       val[3] = vrp_int_const_binop (code, vr0->max, vr1->max);
2142       if (val[3] == NULL_TREE)
2143         sop = true;
2144     }
2145
2146   if (sop)
2147     {
2148       set_value_range_to_varying (vr);
2149       return;
2150     }
2151
2152   /* Set MIN to the minimum of VAL[i] and MAX to the maximum
2153      of VAL[i].  */
2154   min = val[0];
2155   max = val[0];
2156   for (i = 1; i < 4; i++)
2157     {
2158       if (!is_gimple_min_invariant (min)
2159           || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2160           || !is_gimple_min_invariant (max)
2161           || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2162         break;
2163
2164       if (val[i])
2165         {
2166           if (!is_gimple_min_invariant (val[i])
2167               || (TREE_OVERFLOW (val[i])
2168                   && !is_overflow_infinity (val[i])))
2169             {
2170               /* If we found an overflowed value, set MIN and MAX
2171                  to it so that we set the resulting range to
2172                  VARYING.  */
2173               min = max = val[i];
2174               break;
2175             }
2176
2177           if (compare_values (val[i], min) == -1)
2178             min = val[i];
2179
2180           if (compare_values (val[i], max) == 1)
2181             max = val[i];
2182         }
2183     }
2184
2185   /* If either MIN or MAX overflowed, then set the resulting range to
2186      VARYING.  But we do accept an overflow infinity
2187      representation.  */
2188   if (min == NULL_TREE
2189       || !is_gimple_min_invariant (min)
2190       || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2191       || max == NULL_TREE
2192       || !is_gimple_min_invariant (max)
2193       || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2194     {
2195       set_value_range_to_varying (vr);
2196       return;
2197     }
2198
2199   /* We punt if:
2200      1) [-INF, +INF]
2201      2) [-INF, +-INF(OVF)]
2202      3) [+-INF(OVF), +INF]
2203      4) [+-INF(OVF), +-INF(OVF)]
2204      We learn nothing when we have INF and INF(OVF) on both sides.
2205      Note that we do accept [-INF, -INF] and [+INF, +INF] without
2206      overflow.  */
2207   if ((vrp_val_is_min (min) || is_overflow_infinity (min))
2208       && (vrp_val_is_max (max) || is_overflow_infinity (max)))
2209     {
2210       set_value_range_to_varying (vr);
2211       return;
2212     }
2213
2214   cmp = compare_values (min, max);
2215   if (cmp == -2 || cmp == 1)
2216     {
2217       /* If the new range has its limits swapped around (MIN > MAX),
2218          then the operation caused one of them to wrap around, mark
2219          the new range VARYING.  */
2220       set_value_range_to_varying (vr);
2221     }
2222   else
2223     set_value_range (vr, type, min, max, NULL);
2224 }
2225
2226 /* Some quadruple precision helpers.  */
2227 static int
2228 quad_int_cmp (double_int l0, double_int h0,
2229               double_int l1, double_int h1, bool uns)
2230 {
2231   int c = h0.cmp (h1, uns);
2232   if (c != 0) return c;
2233   return l0.ucmp (l1);
2234 }
2235
2236 static void
2237 quad_int_pair_sort (double_int *l0, double_int *h0,
2238                     double_int *l1, double_int *h1, bool uns)
2239 {
2240   if (quad_int_cmp (*l0, *h0, *l1, *h1, uns) > 0)
2241     {
2242       double_int tmp;
2243       tmp = *l0; *l0 = *l1; *l1 = tmp;
2244       tmp = *h0; *h0 = *h1; *h1 = tmp;
2245     }
2246 }
2247
2248 /* Extract range information from a binary operation CODE based on
2249    the ranges of each of its operands, *VR0 and *VR1 with resulting
2250    type EXPR_TYPE.  The resulting range is stored in *VR.  */
2251
2252 static void
2253 extract_range_from_binary_expr_1 (value_range_t *vr,
2254                                   enum tree_code code, tree expr_type,
2255                                   value_range_t *vr0_, value_range_t *vr1_)
2256 {
2257   value_range_t vr0 = *vr0_, vr1 = *vr1_;
2258   value_range_t vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2259   enum value_range_type type;
2260   tree min = NULL_TREE, max = NULL_TREE;
2261   int cmp;
2262
2263   if (!INTEGRAL_TYPE_P (expr_type)
2264       && !POINTER_TYPE_P (expr_type))
2265     {
2266       set_value_range_to_varying (vr);
2267       return;
2268     }
2269
2270   /* Not all binary expressions can be applied to ranges in a
2271      meaningful way.  Handle only arithmetic operations.  */
2272   if (code != PLUS_EXPR
2273       && code != MINUS_EXPR
2274       && code != POINTER_PLUS_EXPR
2275       && code != MULT_EXPR
2276       && code != TRUNC_DIV_EXPR
2277       && code != FLOOR_DIV_EXPR
2278       && code != CEIL_DIV_EXPR
2279       && code != EXACT_DIV_EXPR
2280       && code != ROUND_DIV_EXPR
2281       && code != TRUNC_MOD_EXPR
2282       && code != RSHIFT_EXPR
2283       && code != LSHIFT_EXPR
2284       && code != MIN_EXPR
2285       && code != MAX_EXPR
2286       && code != BIT_AND_EXPR
2287       && code != BIT_IOR_EXPR
2288       && code != BIT_XOR_EXPR)
2289     {
2290       set_value_range_to_varying (vr);
2291       return;
2292     }
2293
2294   /* If both ranges are UNDEFINED, so is the result.  */
2295   if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
2296     {
2297       set_value_range_to_undefined (vr);
2298       return;
2299     }
2300   /* If one of the ranges is UNDEFINED drop it to VARYING for the following
2301      code.  At some point we may want to special-case operations that
2302      have UNDEFINED result for all or some value-ranges of the not UNDEFINED
2303      operand.  */
2304   else if (vr0.type == VR_UNDEFINED)
2305     set_value_range_to_varying (&vr0);
2306   else if (vr1.type == VR_UNDEFINED)
2307     set_value_range_to_varying (&vr1);
2308
2309   /* Now canonicalize anti-ranges to ranges when they are not symbolic
2310      and express ~[] op X as ([]' op X) U ([]'' op X).  */
2311   if (vr0.type == VR_ANTI_RANGE
2312       && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2313     {
2314       extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2315       if (vrtem1.type != VR_UNDEFINED)
2316         {
2317           value_range_t vrres = VR_INITIALIZER;
2318           extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2319                                             &vrtem1, vr1_);
2320           vrp_meet (vr, &vrres);
2321         }
2322       return;
2323     }
2324   /* Likewise for X op ~[].  */
2325   if (vr1.type == VR_ANTI_RANGE
2326       && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2327     {
2328       extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2329       if (vrtem1.type != VR_UNDEFINED)
2330         {
2331           value_range_t vrres = VR_INITIALIZER;
2332           extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2333                                             vr0_, &vrtem1);
2334           vrp_meet (vr, &vrres);
2335         }
2336       return;
2337     }
2338
2339   /* The type of the resulting value range defaults to VR0.TYPE.  */
2340   type = vr0.type;
2341
2342   /* Refuse to operate on VARYING ranges, ranges of different kinds
2343      and symbolic ranges.  As an exception, we allow BIT_AND_EXPR
2344      because we may be able to derive a useful range even if one of
2345      the operands is VR_VARYING or symbolic range.  Similarly for
2346      divisions.  TODO, we may be able to derive anti-ranges in
2347      some cases.  */
2348   if (code != BIT_AND_EXPR
2349       && code != BIT_IOR_EXPR
2350       && code != TRUNC_DIV_EXPR
2351       && code != FLOOR_DIV_EXPR
2352       && code != CEIL_DIV_EXPR
2353       && code != EXACT_DIV_EXPR
2354       && code != ROUND_DIV_EXPR
2355       && code != TRUNC_MOD_EXPR
2356       && code != MIN_EXPR
2357       && code != MAX_EXPR
2358       && (vr0.type == VR_VARYING
2359           || vr1.type == VR_VARYING
2360           || vr0.type != vr1.type
2361           || symbolic_range_p (&vr0)
2362           || symbolic_range_p (&vr1)))
2363     {
2364       set_value_range_to_varying (vr);
2365       return;
2366     }
2367
2368   /* Now evaluate the expression to determine the new range.  */
2369   if (POINTER_TYPE_P (expr_type))
2370     {
2371       if (code == MIN_EXPR || code == MAX_EXPR)
2372         {
2373           /* For MIN/MAX expressions with pointers, we only care about
2374              nullness, if both are non null, then the result is nonnull.
2375              If both are null, then the result is null. Otherwise they
2376              are varying.  */
2377           if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2378             set_value_range_to_nonnull (vr, expr_type);
2379           else if (range_is_null (&vr0) && range_is_null (&vr1))
2380             set_value_range_to_null (vr, expr_type);
2381           else
2382             set_value_range_to_varying (vr);
2383         }
2384       else if (code == POINTER_PLUS_EXPR)
2385         {
2386           /* For pointer types, we are really only interested in asserting
2387              whether the expression evaluates to non-NULL.  */
2388           if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2389             set_value_range_to_nonnull (vr, expr_type);
2390           else if (range_is_null (&vr0) && range_is_null (&vr1))
2391             set_value_range_to_null (vr, expr_type);
2392           else
2393             set_value_range_to_varying (vr);
2394         }
2395       else if (code == BIT_AND_EXPR)
2396         {
2397           /* For pointer types, we are really only interested in asserting
2398              whether the expression evaluates to non-NULL.  */
2399           if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2400             set_value_range_to_nonnull (vr, expr_type);
2401           else if (range_is_null (&vr0) || range_is_null (&vr1))
2402             set_value_range_to_null (vr, expr_type);
2403           else
2404             set_value_range_to_varying (vr);
2405         }
2406       else
2407         set_value_range_to_varying (vr);
2408
2409       return;
2410     }
2411
2412   /* For integer ranges, apply the operation to each end of the
2413      range and see what we end up with.  */
2414   if (code == PLUS_EXPR || code == MINUS_EXPR)
2415     {
2416       /* If we have a PLUS_EXPR with two VR_RANGE integer constant
2417          ranges compute the precise range for such case if possible.  */
2418       if (range_int_cst_p (&vr0)
2419           && range_int_cst_p (&vr1)
2420           /* We need as many bits as the possibly unsigned inputs.  */
2421           && TYPE_PRECISION (expr_type) <= HOST_BITS_PER_DOUBLE_INT)
2422         {
2423           double_int min0 = tree_to_double_int (vr0.min);
2424           double_int max0 = tree_to_double_int (vr0.max);
2425           double_int min1 = tree_to_double_int (vr1.min);
2426           double_int max1 = tree_to_double_int (vr1.max);
2427           bool uns = TYPE_UNSIGNED (expr_type);
2428           double_int type_min
2429             = double_int::min_value (TYPE_PRECISION (expr_type), uns);
2430           double_int type_max
2431             = double_int::max_value (TYPE_PRECISION (expr_type), uns);
2432           double_int dmin, dmax;
2433           int min_ovf = 0;
2434           int max_ovf = 0;
2435
2436           if (code == PLUS_EXPR)
2437             {
2438               dmin = min0 + min1;
2439               dmax = max0 + max1;
2440
2441               /* Check for overflow in double_int.  */
2442               if (min1.cmp (double_int_zero, uns) != dmin.cmp (min0, uns))
2443                 min_ovf = min0.cmp (dmin, uns);
2444               if (max1.cmp (double_int_zero, uns) != dmax.cmp (max0, uns))
2445                 max_ovf = max0.cmp (dmax, uns);
2446             }
2447           else /* if (code == MINUS_EXPR) */
2448             {
2449               dmin = min0 - max1;
2450               dmax = max0 - min1;
2451
2452               if (double_int_zero.cmp (max1, uns) != dmin.cmp (min0, uns))
2453                 min_ovf = min0.cmp (max1, uns);
2454               if (double_int_zero.cmp (min1, uns) != dmax.cmp (max0, uns))
2455                 max_ovf = max0.cmp (min1, uns);
2456             }
2457
2458           /* For non-wrapping arithmetic look at possibly smaller
2459              value-ranges of the type.  */
2460           if (!TYPE_OVERFLOW_WRAPS (expr_type))
2461             {
2462               if (vrp_val_min (expr_type))
2463                 type_min = tree_to_double_int (vrp_val_min (expr_type));
2464               if (vrp_val_max (expr_type))
2465                 type_max = tree_to_double_int (vrp_val_max (expr_type));
2466             }
2467
2468           /* Check for type overflow.  */
2469           if (min_ovf == 0)
2470             {
2471               if (dmin.cmp (type_min, uns) == -1)
2472                 min_ovf = -1;
2473               else if (dmin.cmp (type_max, uns) == 1)
2474                 min_ovf = 1;
2475             }
2476           if (max_ovf == 0)
2477             {
2478               if (dmax.cmp (type_min, uns) == -1)
2479                 max_ovf = -1;
2480               else if (dmax.cmp (type_max, uns) == 1)
2481                 max_ovf = 1;
2482             }
2483
2484           if (TYPE_OVERFLOW_WRAPS (expr_type))
2485             {
2486               /* If overflow wraps, truncate the values and adjust the
2487                  range kind and bounds appropriately.  */
2488               double_int tmin
2489                 = dmin.ext (TYPE_PRECISION (expr_type), uns);
2490               double_int tmax
2491                 = dmax.ext (TYPE_PRECISION (expr_type), uns);
2492               if (min_ovf == max_ovf)
2493                 {
2494                   /* No overflow or both overflow or underflow.  The
2495                      range kind stays VR_RANGE.  */
2496                   min = double_int_to_tree (expr_type, tmin);
2497                   max = double_int_to_tree (expr_type, tmax);
2498                 }
2499               else if (min_ovf == -1
2500                        && max_ovf == 1)
2501                 {
2502                   /* Underflow and overflow, drop to VR_VARYING.  */
2503                   set_value_range_to_varying (vr);
2504                   return;
2505                 }
2506               else
2507                 {
2508                   /* Min underflow or max overflow.  The range kind
2509                      changes to VR_ANTI_RANGE.  */
2510                   bool covers = false;
2511                   double_int tem = tmin;
2512                   gcc_assert ((min_ovf == -1 && max_ovf == 0)
2513                               || (max_ovf == 1 && min_ovf == 0));
2514                   type = VR_ANTI_RANGE;
2515                   tmin = tmax + double_int_one;
2516                   if (tmin.cmp (tmax, uns) < 0)
2517                     covers = true;
2518                   tmax = tem + double_int_minus_one;
2519                   if (tmax.cmp (tem, uns) > 0)
2520                     covers = true;
2521                   /* If the anti-range would cover nothing, drop to varying.
2522                      Likewise if the anti-range bounds are outside of the
2523                      types values.  */
2524                   if (covers || tmin.cmp (tmax, uns) > 0)
2525                     {
2526                       set_value_range_to_varying (vr);
2527                       return;
2528                     }
2529                   min = double_int_to_tree (expr_type, tmin);
2530                   max = double_int_to_tree (expr_type, tmax);
2531                 }
2532             }
2533           else
2534             {
2535               /* If overflow does not wrap, saturate to the types min/max
2536                  value.  */
2537               if (min_ovf == -1)
2538                 {
2539                   if (needs_overflow_infinity (expr_type)
2540                       && supports_overflow_infinity (expr_type))
2541                     min = negative_overflow_infinity (expr_type);
2542                   else
2543                     min = double_int_to_tree (expr_type, type_min);
2544                 }
2545               else if (min_ovf == 1)
2546                 {
2547                   if (needs_overflow_infinity (expr_type)
2548                       && supports_overflow_infinity (expr_type))
2549                     min = positive_overflow_infinity (expr_type);
2550                   else
2551                     min = double_int_to_tree (expr_type, type_max);
2552                 }
2553               else
2554                 min = double_int_to_tree (expr_type, dmin);
2555
2556               if (max_ovf == -1)
2557                 {
2558                   if (needs_overflow_infinity (expr_type)
2559                       && supports_overflow_infinity (expr_type))
2560                     max = negative_overflow_infinity (expr_type);
2561                   else
2562                     max = double_int_to_tree (expr_type, type_min);
2563                 }
2564               else if (max_ovf == 1)
2565                 {
2566                   if (needs_overflow_infinity (expr_type)
2567                       && supports_overflow_infinity (expr_type))
2568                     max = positive_overflow_infinity (expr_type);
2569                   else
2570                     max = double_int_to_tree (expr_type, type_max);
2571                 }
2572               else
2573                 max = double_int_to_tree (expr_type, dmax);
2574             }
2575           if (needs_overflow_infinity (expr_type)
2576               && supports_overflow_infinity (expr_type))
2577             {
2578               if (is_negative_overflow_infinity (vr0.min)
2579                   || (code == PLUS_EXPR
2580                       ? is_negative_overflow_infinity (vr1.min)
2581                       : is_positive_overflow_infinity (vr1.max)))
2582                 min = negative_overflow_infinity (expr_type);
2583               if (is_positive_overflow_infinity (vr0.max)
2584                   || (code == PLUS_EXPR
2585                       ? is_positive_overflow_infinity (vr1.max)
2586                       : is_negative_overflow_infinity (vr1.min)))
2587                 max = positive_overflow_infinity (expr_type);
2588             }
2589         }
2590       else
2591         {
2592           /* For other cases, for example if we have a PLUS_EXPR with two
2593              VR_ANTI_RANGEs, drop to VR_VARYING.  It would take more effort
2594              to compute a precise range for such a case.
2595              ???  General even mixed range kind operations can be expressed
2596              by for example transforming ~[3, 5] + [1, 2] to range-only
2597              operations and a union primitive:
2598                [-INF, 2] + [1, 2]  U  [5, +INF] + [1, 2]
2599                    [-INF+1, 4]     U    [6, +INF(OVF)]
2600              though usually the union is not exactly representable with
2601              a single range or anti-range as the above is
2602                  [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2603              but one could use a scheme similar to equivalences for this. */
2604           set_value_range_to_varying (vr);
2605           return;
2606         }
2607     }
2608   else if (code == MIN_EXPR
2609            || code == MAX_EXPR)
2610     {
2611       if (vr0.type == VR_RANGE
2612           && !symbolic_range_p (&vr0))
2613         {
2614           type = VR_RANGE;
2615           if (vr1.type == VR_RANGE
2616               && !symbolic_range_p (&vr1))
2617             {
2618               /* For operations that make the resulting range directly
2619                  proportional to the original ranges, apply the operation to
2620                  the same end of each range.  */
2621               min = vrp_int_const_binop (code, vr0.min, vr1.min);
2622               max = vrp_int_const_binop (code, vr0.max, vr1.max);
2623             }
2624           else if (code == MIN_EXPR)
2625             {
2626               min = vrp_val_min (expr_type);
2627               max = vr0.max;
2628             }
2629           else if (code == MAX_EXPR)
2630             {
2631               min = vr0.min;
2632               max = vrp_val_max (expr_type);
2633             }
2634         }
2635       else if (vr1.type == VR_RANGE
2636                && !symbolic_range_p (&vr1))
2637         {
2638           type = VR_RANGE;
2639           if (code == MIN_EXPR)
2640             {
2641               min = vrp_val_min (expr_type);
2642               max = vr1.max;
2643             }
2644           else if (code == MAX_EXPR)
2645             {
2646               min = vr1.min;
2647               max = vrp_val_max (expr_type);
2648             }
2649         }
2650       else
2651         {
2652           set_value_range_to_varying (vr);
2653           return;
2654         }
2655     }
2656   else if (code == MULT_EXPR)
2657     {
2658       /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2659          drop to varying.  */
2660       if (range_int_cst_p (&vr0)
2661           && range_int_cst_p (&vr1)
2662           && TYPE_OVERFLOW_WRAPS (expr_type))
2663         {
2664           double_int min0, max0, min1, max1, sizem1, size;
2665           double_int prod0l, prod0h, prod1l, prod1h,
2666                      prod2l, prod2h, prod3l, prod3h;
2667           bool uns0, uns1, uns;
2668
2669           sizem1 = double_int::max_value (TYPE_PRECISION (expr_type), true);
2670           size = sizem1 + double_int_one;
2671
2672           min0 = tree_to_double_int (vr0.min);
2673           max0 = tree_to_double_int (vr0.max);
2674           min1 = tree_to_double_int (vr1.min);
2675           max1 = tree_to_double_int (vr1.max);
2676
2677           uns0 = TYPE_UNSIGNED (expr_type);
2678           uns1 = uns0;
2679
2680           /* Canonicalize the intervals.  */
2681           if (TYPE_UNSIGNED (expr_type))
2682             {
2683               double_int min2 = size - min0;
2684               if (!min2.is_zero () && min2.cmp (max0, true) < 0)
2685                 {
2686                   min0 = -min2;
2687                   max0 -= size;
2688                   uns0 = false;
2689                 }
2690
2691               min2 = size - min1;
2692               if (!min2.is_zero () && min2.cmp (max1, true) < 0)
2693                 {
2694                   min1 = -min2;
2695                   max1 -= size;
2696                   uns1 = false;
2697                 }
2698             }
2699           uns = uns0 & uns1;
2700
2701           bool overflow;
2702           prod0l = min0.wide_mul_with_sign (min1, true, &prod0h, &overflow);
2703           if (!uns0 && min0.is_negative ())
2704             prod0h -= min1;
2705           if (!uns1 && min1.is_negative ())
2706             prod0h -= min0;
2707
2708           prod1l = min0.wide_mul_with_sign (max1, true, &prod1h, &overflow);
2709           if (!uns0 && min0.is_negative ())
2710             prod1h -= max1;
2711           if (!uns1 && max1.is_negative ())
2712             prod1h -= min0;
2713
2714           prod2l = max0.wide_mul_with_sign (min1, true, &prod2h, &overflow);
2715           if (!uns0 && max0.is_negative ())
2716             prod2h -= min1;
2717           if (!uns1 && min1.is_negative ())
2718             prod2h -= max0;
2719
2720           prod3l = max0.wide_mul_with_sign (max1, true, &prod3h, &overflow);
2721           if (!uns0 && max0.is_negative ())
2722             prod3h -= max1;
2723           if (!uns1 && max1.is_negative ())
2724             prod3h -= max0;
2725
2726           /* Sort the 4 products.  */
2727           quad_int_pair_sort (&prod0l, &prod0h, &prod3l, &prod3h, uns);
2728           quad_int_pair_sort (&prod1l, &prod1h, &prod2l, &prod2h, uns);
2729           quad_int_pair_sort (&prod0l, &prod0h, &prod1l, &prod1h, uns);
2730           quad_int_pair_sort (&prod2l, &prod2h, &prod3l, &prod3h, uns);
2731
2732           /* Max - min.  */
2733           if (prod0l.is_zero ())
2734             {
2735               prod1l = double_int_zero;
2736               prod1h = -prod0h;
2737             }
2738           else
2739             {
2740               prod1l = -prod0l;
2741               prod1h = ~prod0h;
2742             }
2743           prod2l = prod3l + prod1l;
2744           prod2h = prod3h + prod1h;
2745           if (prod2l.ult (prod3l))
2746             prod2h += double_int_one; /* carry */
2747
2748           if (!prod2h.is_zero ()
2749               || prod2l.cmp (sizem1, true) >= 0)
2750             {
2751               /* the range covers all values.  */
2752               set_value_range_to_varying (vr);
2753               return;
2754             }
2755
2756           /* The following should handle the wrapping and selecting
2757              VR_ANTI_RANGE for us.  */
2758           min = double_int_to_tree (expr_type, prod0l);
2759           max = double_int_to_tree (expr_type, prod3l);
2760           set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2761           return;
2762         }
2763
2764       /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2765          drop to VR_VARYING.  It would take more effort to compute a
2766          precise range for such a case.  For example, if we have
2767          op0 == 65536 and op1 == 65536 with their ranges both being
2768          ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2769          we cannot claim that the product is in ~[0,0].  Note that we
2770          are guaranteed to have vr0.type == vr1.type at this
2771          point.  */
2772       if (vr0.type == VR_ANTI_RANGE
2773           && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2774         {
2775           set_value_range_to_varying (vr);
2776           return;
2777         }
2778
2779       extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2780       return;
2781     }
2782   else if (code == RSHIFT_EXPR
2783            || code == LSHIFT_EXPR)
2784     {
2785       /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2786          then drop to VR_VARYING.  Outside of this range we get undefined
2787          behavior from the shift operation.  We cannot even trust
2788          SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2789          shifts, and the operation at the tree level may be widened.  */
2790       if (range_int_cst_p (&vr1)
2791           && compare_tree_int (vr1.min, 0) >= 0
2792           && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2793         {
2794           if (code == RSHIFT_EXPR)
2795             {
2796               extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2797               return;
2798             }
2799           /* We can map lshifts by constants to MULT_EXPR handling.  */
2800           else if (code == LSHIFT_EXPR
2801                    && range_int_cst_singleton_p (&vr1))
2802             {
2803               bool saved_flag_wrapv;
2804               value_range_t vr1p = VR_INITIALIZER;
2805               vr1p.type = VR_RANGE;
2806               vr1p.min
2807                 = double_int_to_tree (expr_type,
2808                                       double_int_one
2809                                       .llshift (TREE_INT_CST_LOW (vr1.min),
2810                                                 TYPE_PRECISION (expr_type)));
2811               vr1p.max = vr1p.min;
2812               /* We have to use a wrapping multiply though as signed overflow
2813                  on lshifts is implementation defined in C89.  */
2814               saved_flag_wrapv = flag_wrapv;
2815               flag_wrapv = 1;
2816               extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2817                                                 &vr0, &vr1p);
2818               flag_wrapv = saved_flag_wrapv;
2819               return;
2820             }
2821           else if (code == LSHIFT_EXPR
2822                    && range_int_cst_p (&vr0))
2823             {
2824               int prec = TYPE_PRECISION (expr_type);
2825               int overflow_pos = prec;
2826               int bound_shift;
2827               double_int bound, complement, low_bound, high_bound;
2828               bool uns = TYPE_UNSIGNED (expr_type);
2829               bool in_bounds = false;
2830
2831               if (!uns)
2832                 overflow_pos -= 1;
2833
2834               bound_shift = overflow_pos - TREE_INT_CST_LOW (vr1.max);
2835               /* If bound_shift == HOST_BITS_PER_DOUBLE_INT, the llshift can
2836                  overflow.  However, for that to happen, vr1.max needs to be
2837                  zero, which means vr1 is a singleton range of zero, which
2838                  means it should be handled by the previous LSHIFT_EXPR
2839                  if-clause.  */
2840               bound = double_int_one.llshift (bound_shift, prec);
2841               complement = ~(bound - double_int_one);
2842
2843               if (uns)
2844                 {
2845                   low_bound = bound.zext (prec);
2846                   high_bound = complement.zext (prec);
2847                   if (tree_to_double_int (vr0.max).ult (low_bound))
2848                     {
2849                       /* [5, 6] << [1, 2] == [10, 24].  */
2850                       /* We're shifting out only zeroes, the value increases
2851                          monotonically.  */
2852                       in_bounds = true;
2853                     }
2854                   else if (high_bound.ult (tree_to_double_int (vr0.min)))
2855                     {
2856                       /* [0xffffff00, 0xffffffff] << [1, 2]
2857                          == [0xfffffc00, 0xfffffffe].  */
2858                       /* We're shifting out only ones, the value decreases
2859                          monotonically.  */
2860                       in_bounds = true;
2861                     }
2862                 }
2863               else
2864                 {
2865                   /* [-1, 1] << [1, 2] == [-4, 4].  */
2866                   low_bound = complement.sext (prec);
2867                   high_bound = bound;
2868                   if (tree_to_double_int (vr0.max).slt (high_bound)
2869                       && low_bound.slt (tree_to_double_int (vr0.min)))
2870                     {
2871                       /* For non-negative numbers, we're shifting out only
2872                          zeroes, the value increases monotonically.
2873                          For negative numbers, we're shifting out only ones, the
2874                          value decreases monotomically.  */
2875                       in_bounds = true;
2876                     }
2877                 }
2878
2879               if (in_bounds)
2880                 {
2881                   extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2882                   return;
2883                 }
2884             }
2885         }
2886       set_value_range_to_varying (vr);
2887       return;
2888     }
2889   else if (code == TRUNC_DIV_EXPR
2890            || code == FLOOR_DIV_EXPR
2891            || code == CEIL_DIV_EXPR
2892            || code == EXACT_DIV_EXPR
2893            || code == ROUND_DIV_EXPR)
2894     {
2895       if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2896         {
2897           /* For division, if op1 has VR_RANGE but op0 does not, something
2898              can be deduced just from that range.  Say [min, max] / [4, max]
2899              gives [min / 4, max / 4] range.  */
2900           if (vr1.type == VR_RANGE
2901               && !symbolic_range_p (&vr1)
2902               && range_includes_zero_p (vr1.min, vr1.max) == 0)
2903             {
2904               vr0.type = type = VR_RANGE;
2905               vr0.min = vrp_val_min (expr_type);
2906               vr0.max = vrp_val_max (expr_type);
2907             }
2908           else
2909             {
2910               set_value_range_to_varying (vr);
2911               return;
2912             }
2913         }
2914
2915       /* For divisions, if flag_non_call_exceptions is true, we must
2916          not eliminate a division by zero.  */
2917       if (cfun->can_throw_non_call_exceptions
2918           && (vr1.type != VR_RANGE
2919               || range_includes_zero_p (vr1.min, vr1.max) != 0))
2920         {
2921           set_value_range_to_varying (vr);
2922           return;
2923         }
2924
2925       /* For divisions, if op0 is VR_RANGE, we can deduce a range
2926          even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2927          include 0.  */
2928       if (vr0.type == VR_RANGE
2929           && (vr1.type != VR_RANGE
2930               || range_includes_zero_p (vr1.min, vr1.max) != 0))
2931         {
2932           tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2933           int cmp;
2934
2935           min = NULL_TREE;
2936           max = NULL_TREE;
2937           if (TYPE_UNSIGNED (expr_type)
2938               || value_range_nonnegative_p (&vr1))
2939             {
2940               /* For unsigned division or when divisor is known
2941                  to be non-negative, the range has to cover
2942                  all numbers from 0 to max for positive max
2943                  and all numbers from min to 0 for negative min.  */
2944               cmp = compare_values (vr0.max, zero);
2945               if (cmp == -1)
2946                 max = zero;
2947               else if (cmp == 0 || cmp == 1)
2948                 max = vr0.max;
2949               else
2950                 type = VR_VARYING;
2951               cmp = compare_values (vr0.min, zero);
2952               if (cmp == 1)
2953                 min = zero;
2954               else if (cmp == 0 || cmp == -1)
2955                 min = vr0.min;
2956               else
2957                 type = VR_VARYING;
2958             }
2959           else
2960             {
2961               /* Otherwise the range is -max .. max or min .. -min
2962                  depending on which bound is bigger in absolute value,
2963                  as the division can change the sign.  */
2964               abs_extent_range (vr, vr0.min, vr0.max);
2965               return;
2966             }
2967           if (type == VR_VARYING)
2968             {
2969               set_value_range_to_varying (vr);
2970               return;
2971             }
2972         }
2973       else
2974         {
2975           extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2976           return;
2977         }
2978     }
2979   else if (code == TRUNC_MOD_EXPR)
2980     {
2981       if (vr1.type != VR_RANGE
2982           || range_includes_zero_p (vr1.min, vr1.max) != 0
2983           || vrp_val_is_min (vr1.min))
2984         {
2985           set_value_range_to_varying (vr);
2986           return;
2987         }
2988       type = VR_RANGE;
2989       /* Compute MAX <|vr1.min|, |vr1.max|> - 1.  */
2990       max = fold_unary_to_constant (ABS_EXPR, expr_type, vr1.min);
2991       if (tree_int_cst_lt (max, vr1.max))
2992         max = vr1.max;
2993       max = int_const_binop (MINUS_EXPR, max, integer_one_node);
2994       /* If the dividend is non-negative the modulus will be
2995          non-negative as well.  */
2996       if (TYPE_UNSIGNED (expr_type)
2997           || value_range_nonnegative_p (&vr0))
2998         min = build_int_cst (TREE_TYPE (max), 0);
2999       else
3000         min = fold_unary_to_constant (NEGATE_EXPR, expr_type, max);
3001     }
3002   else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
3003     {
3004       bool int_cst_range0, int_cst_range1;
3005       double_int may_be_nonzero0, may_be_nonzero1;
3006       double_int must_be_nonzero0, must_be_nonzero1;
3007
3008       int_cst_range0 = zero_nonzero_bits_from_vr (&vr0, &may_be_nonzero0,
3009                                                   &must_be_nonzero0);
3010       int_cst_range1 = zero_nonzero_bits_from_vr (&vr1, &may_be_nonzero1,
3011                                                   &must_be_nonzero1);
3012
3013       type = VR_RANGE;
3014       if (code == BIT_AND_EXPR)
3015         {
3016           double_int dmax;
3017           min = double_int_to_tree (expr_type,
3018                                     must_be_nonzero0 & must_be_nonzero1);
3019           dmax = may_be_nonzero0 & may_be_nonzero1;
3020           /* If both input ranges contain only negative values we can
3021              truncate the result range maximum to the minimum of the
3022              input range maxima.  */
3023           if (int_cst_range0 && int_cst_range1
3024               && tree_int_cst_sgn (vr0.max) < 0
3025               && tree_int_cst_sgn (vr1.max) < 0)
3026             {
3027               dmax = dmax.min (tree_to_double_int (vr0.max),
3028                                      TYPE_UNSIGNED (expr_type));
3029               dmax = dmax.min (tree_to_double_int (vr1.max),
3030                                      TYPE_UNSIGNED (expr_type));
3031             }
3032           /* If either input range contains only non-negative values
3033              we can truncate the result range maximum to the respective
3034              maximum of the input range.  */
3035           if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
3036             dmax = dmax.min (tree_to_double_int (vr0.max),
3037                                    TYPE_UNSIGNED (expr_type));
3038           if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
3039             dmax = dmax.min (tree_to_double_int (vr1.max),
3040                                    TYPE_UNSIGNED (expr_type));
3041           max = double_int_to_tree (expr_type, dmax);
3042         }
3043       else if (code == BIT_IOR_EXPR)
3044         {
3045           double_int dmin;
3046           max = double_int_to_tree (expr_type,
3047                                     may_be_nonzero0 | may_be_nonzero1);
3048           dmin = must_be_nonzero0 | must_be_nonzero1;
3049           /* If the input ranges contain only positive values we can
3050              truncate the minimum of the result range to the maximum
3051              of the input range minima.  */
3052           if (int_cst_range0 && int_cst_range1
3053               && tree_int_cst_sgn (vr0.min) >= 0
3054               && tree_int_cst_sgn (vr1.min) >= 0)
3055             {
3056               dmin = dmin.max (tree_to_double_int (vr0.min),
3057                                TYPE_UNSIGNED (expr_type));
3058               dmin = dmin.max (tree_to_double_int (vr1.min),
3059                                TYPE_UNSIGNED (expr_type));
3060             }
3061           /* If either input range contains only negative values
3062              we can truncate the minimum of the result range to the
3063              respective minimum range.  */
3064           if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
3065             dmin = dmin.max (tree_to_double_int (vr0.min),
3066                              TYPE_UNSIGNED (expr_type));
3067           if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
3068             dmin = dmin.max (tree_to_double_int (vr1.min),
3069                              TYPE_UNSIGNED (expr_type));
3070           min = double_int_to_tree (expr_type, dmin);
3071         }
3072       else if (code == BIT_XOR_EXPR)
3073         {
3074           double_int result_zero_bits, result_one_bits;
3075           result_zero_bits = (must_be_nonzero0 & must_be_nonzero1)
3076                              | ~(may_be_nonzero0 | may_be_nonzero1);
3077           result_one_bits = must_be_nonzero0.and_not (may_be_nonzero1)
3078                             | must_be_nonzero1.and_not (may_be_nonzero0);
3079           max = double_int_to_tree (expr_type, ~result_zero_bits);
3080           min = double_int_to_tree (expr_type, result_one_bits);
3081           /* If the range has all positive or all negative values the
3082              result is better than VARYING.  */
3083           if (tree_int_cst_sgn (min) < 0
3084               || tree_int_cst_sgn (max) >= 0)
3085             ;
3086           else
3087             max = min = NULL_TREE;
3088         }
3089     }
3090   else
3091     gcc_unreachable ();
3092
3093   /* If either MIN or MAX overflowed, then set the resulting range to
3094      VARYING.  But we do accept an overflow infinity
3095      representation.  */
3096   if (min == NULL_TREE
3097       || !is_gimple_min_invariant (min)
3098       || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
3099       || max == NULL_TREE
3100       || !is_gimple_min_invariant (max)
3101       || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
3102     {
3103       set_value_range_to_varying (vr);
3104       return;
3105     }
3106
3107   /* We punt if:
3108      1) [-INF, +INF]
3109      2) [-INF, +-INF(OVF)]
3110      3) [+-INF(OVF), +INF]
3111      4) [+-INF(OVF), +-INF(OVF)]
3112      We learn nothing when we have INF and INF(OVF) on both sides.
3113      Note that we do accept [-INF, -INF] and [+INF, +INF] without
3114      overflow.  */
3115   if ((vrp_val_is_min (min) || is_overflow_infinity (min))
3116       && (vrp_val_is_max (max) || is_overflow_infinity (max)))
3117     {
3118       set_value_range_to_varying (vr);
3119       return;
3120     }
3121
3122   cmp = compare_values (min, max);
3123   if (cmp == -2 || cmp == 1)
3124     {
3125       /* If the new range has its limits swapped around (MIN > MAX),
3126          then the operation caused one of them to wrap around, mark
3127          the new range VARYING.  */
3128       set_value_range_to_varying (vr);
3129     }
3130   else
3131     set_value_range (vr, type, min, max, NULL);
3132 }
3133
3134 /* Extract range information from a binary expression OP0 CODE OP1 based on
3135    the ranges of each of its operands with resulting type EXPR_TYPE.
3136    The resulting range is stored in *VR.  */
3137
3138 static void
3139 extract_range_from_binary_expr (value_range_t *vr,
3140                                 enum tree_code code,
3141                                 tree expr_type, tree op0, tree op1)
3142 {
3143   value_range_t vr0 = VR_INITIALIZER;
3144   value_range_t vr1 = VR_INITIALIZER;
3145
3146   /* Get value ranges for each operand.  For constant operands, create
3147      a new value range with the operand to simplify processing.  */
3148   if (TREE_CODE (op0) == SSA_NAME)
3149     vr0 = *(get_value_range (op0));
3150   else if (is_gimple_min_invariant (op0))
3151     set_value_range_to_value (&vr0, op0, NULL);
3152   else
3153     set_value_range_to_varying (&vr0);
3154
3155   if (TREE_CODE (op1) == SSA_NAME)
3156     vr1 = *(get_value_range (op1));
3157   else if (is_gimple_min_invariant (op1))
3158     set_value_range_to_value (&vr1, op1, NULL);
3159   else
3160     set_value_range_to_varying (&vr1);
3161
3162   extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3163 }
3164
3165 /* Extract range information from a unary operation CODE based on
3166    the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3167    The The resulting range is stored in *VR.  */
3168
3169 static void
3170 extract_range_from_unary_expr_1 (value_range_t *vr,
3171                                  enum tree_code code, tree type,
3172                                  value_range_t *vr0_, tree op0_type)
3173 {
3174   value_range_t vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3175
3176   /* VRP only operates on integral and pointer types.  */
3177   if (!(INTEGRAL_TYPE_P (op0_type)
3178         || POINTER_TYPE_P (op0_type))
3179       || !(INTEGRAL_TYPE_P (type)
3180            || POINTER_TYPE_P (type)))
3181     {
3182       set_value_range_to_varying (vr);
3183       return;
3184     }
3185
3186   /* If VR0 is UNDEFINED, so is the result.  */
3187   if (vr0.type == VR_UNDEFINED)
3188     {
3189       set_value_range_to_undefined (vr);
3190       return;
3191     }
3192
3193   /* Handle operations that we express in terms of others.  */
3194   if (code == PAREN_EXPR)
3195     {
3196       /* PAREN_EXPR is a simple copy.  */
3197       copy_value_range (vr, &vr0);
3198       return;
3199     }
3200   else if (code == NEGATE_EXPR)
3201     {
3202       /* -X is simply 0 - X, so re-use existing code that also handles
3203          anti-ranges fine.  */
3204       value_range_t zero = VR_INITIALIZER;
3205       set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3206       extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3207       return;
3208     }
3209   else if (code == BIT_NOT_EXPR)
3210     {
3211       /* ~X is simply -1 - X, so re-use existing code that also handles
3212          anti-ranges fine.  */
3213       value_range_t minusone = VR_INITIALIZER;
3214       set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3215       extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3216                                         type, &minusone, &vr0);
3217       return;
3218     }
3219
3220   /* Now canonicalize anti-ranges to ranges when they are not symbolic
3221      and express op ~[]  as (op []') U (op []'').  */
3222   if (vr0.type == VR_ANTI_RANGE
3223       && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3224     {
3225       extract_range_from_unary_expr_1 (vr, code, type, &vrtem0, op0_type);
3226       if (vrtem1.type != VR_UNDEFINED)
3227         {
3228           value_range_t vrres = VR_INITIALIZER;
3229           extract_range_from_unary_expr_1 (&vrres, code, type,
3230                                            &vrtem1, op0_type);
3231           vrp_meet (vr, &vrres);
3232         }
3233       return;
3234     }
3235
3236   if (CONVERT_EXPR_CODE_P (code))
3237     {
3238       tree inner_type = op0_type;
3239       tree outer_type = type;
3240
3241       /* If the expression evaluates to a pointer, we are only interested in
3242          determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
3243       if (POINTER_TYPE_P (type))
3244         {
3245           if (range_is_nonnull (&vr0))
3246             set_value_range_to_nonnull (vr, type);
3247           else if (range_is_null (&vr0))
3248             set_value_range_to_null (vr, type);
3249           else
3250             set_value_range_to_varying (vr);
3251           return;
3252         }
3253
3254       /* If VR0 is varying and we increase the type precision, assume
3255          a full range for the following transformation.  */
3256       if (vr0.type == VR_VARYING
3257           && INTEGRAL_TYPE_P (inner_type)
3258           && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3259         {
3260           vr0.type = VR_RANGE;
3261           vr0.min = TYPE_MIN_VALUE (inner_type);
3262           vr0.max = TYPE_MAX_VALUE (inner_type);
3263         }
3264
3265       /* If VR0 is a constant range or anti-range and the conversion is
3266          not truncating we can convert the min and max values and
3267          canonicalize the resulting range.  Otherwise we can do the
3268          conversion if the size of the range is less than what the
3269          precision of the target type can represent and the range is
3270          not an anti-range.  */
3271       if ((vr0.type == VR_RANGE
3272            || vr0.type == VR_ANTI_RANGE)
3273           && TREE_CODE (vr0.min) == INTEGER_CST
3274           && TREE_CODE (vr0.max) == INTEGER_CST
3275           && (!is_overflow_infinity (vr0.min)
3276               || (vr0.type == VR_RANGE
3277                   && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3278                   && needs_overflow_infinity (outer_type)
3279                   && supports_overflow_infinity (outer_type)))
3280           && (!is_overflow_infinity (vr0.max)
3281               || (vr0.type == VR_RANGE
3282                   && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3283                   && needs_overflow_infinity (outer_type)
3284                   && supports_overflow_infinity (outer_type)))
3285           && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3286               || (vr0.type == VR_RANGE
3287                   && integer_zerop (int_const_binop (RSHIFT_EXPR,
3288                        int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3289                          size_int (TYPE_PRECISION (outer_type)))))))
3290         {
3291           tree new_min, new_max;
3292           if (is_overflow_infinity (vr0.min))
3293             new_min = negative_overflow_infinity (outer_type);
3294           else
3295             new_min = force_fit_type_double (outer_type,
3296                                              tree_to_double_int (vr0.min),
3297                                              0, false);
3298           if (is_overflow_infinity (vr0.max))
3299             new_max = positive_overflow_infinity (outer_type);
3300           else
3301             new_max = force_fit_type_double (outer_type,
3302                                              tree_to_double_int (vr0.max),
3303                                              0, false);
3304           set_and_canonicalize_value_range (vr, vr0.type,
3305                                             new_min, new_max, NULL);
3306           return;
3307         }
3308
3309       set_value_range_to_varying (vr);
3310       return;
3311     }
3312   else if (code == ABS_EXPR)
3313     {
3314       tree min, max;
3315       int cmp;
3316
3317       /* Pass through vr0 in the easy cases.  */
3318       if (TYPE_UNSIGNED (type)
3319           || value_range_nonnegative_p (&vr0))
3320         {
3321           copy_value_range (vr, &vr0);
3322           return;
3323         }
3324
3325       /* For the remaining varying or symbolic ranges we can't do anything
3326          useful.  */
3327       if (vr0.type == VR_VARYING
3328           || symbolic_range_p (&vr0))
3329         {
3330           set_value_range_to_varying (vr);
3331           return;
3332         }
3333
3334       /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3335          useful range.  */
3336       if (!TYPE_OVERFLOW_UNDEFINED (type)
3337           && ((vr0.type == VR_RANGE
3338                && vrp_val_is_min (vr0.min))
3339               || (vr0.type == VR_ANTI_RANGE
3340                   && !vrp_val_is_min (vr0.min))))
3341         {
3342           set_value_range_to_varying (vr);
3343           return;
3344         }
3345
3346       /* ABS_EXPR may flip the range around, if the original range
3347          included negative values.  */
3348       if (is_overflow_infinity (vr0.min))
3349         min = positive_overflow_infinity (type);
3350       else if (!vrp_val_is_min (vr0.min))
3351         min = fold_unary_to_constant (code, type, vr0.min);
3352       else if (!needs_overflow_infinity (type))
3353         min = TYPE_MAX_VALUE (type);
3354       else if (supports_overflow_infinity (type))
3355         min = positive_overflow_infinity (type);
3356       else
3357         {
3358           set_value_range_to_varying (vr);
3359           return;
3360         }
3361
3362       if (is_overflow_infinity (vr0.max))
3363         max = positive_overflow_infinity (type);
3364       else if (!vrp_val_is_min (vr0.max))
3365         max = fold_unary_to_constant (code, type, vr0.max);
3366       else if (!needs_overflow_infinity (type))
3367         max = TYPE_MAX_VALUE (type);
3368       else if (supports_overflow_infinity (type)
3369                /* We shouldn't generate [+INF, +INF] as set_value_range
3370                   doesn't like this and ICEs.  */
3371                && !is_positive_overflow_infinity (min))
3372         max = positive_overflow_infinity (type);
3373       else
3374         {
3375           set_value_range_to_varying (vr);
3376           return;
3377         }
3378
3379       cmp = compare_values (min, max);
3380
3381       /* If a VR_ANTI_RANGEs contains zero, then we have
3382          ~[-INF, min(MIN, MAX)].  */
3383       if (vr0.type == VR_ANTI_RANGE)
3384         {
3385           if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3386             {
3387               /* Take the lower of the two values.  */
3388               if (cmp != 1)
3389                 max = min;
3390
3391               /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3392                  or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3393                  flag_wrapv is set and the original anti-range doesn't include
3394                  TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE.  */
3395               if (TYPE_OVERFLOW_WRAPS (type))
3396                 {
3397                   tree type_min_value = TYPE_MIN_VALUE (type);
3398
3399                   min = (vr0.min != type_min_value
3400                          ? int_const_binop (PLUS_EXPR, type_min_value,
3401                                             integer_one_node)
3402                          : type_min_value);
3403                 }
3404               else
3405                 {
3406                   if (overflow_infinity_range_p (&vr0))
3407                     min = negative_overflow_infinity (type);
3408                   else
3409                     min = TYPE_MIN_VALUE (type);
3410                 }
3411             }
3412           else
3413             {
3414               /* All else has failed, so create the range [0, INF], even for
3415                  flag_wrapv since TYPE_MIN_VALUE is in the original
3416                  anti-range.  */
3417               vr0.type = VR_RANGE;
3418               min = build_int_cst (type, 0);
3419               if (needs_overflow_infinity (type))
3420                 {
3421                   if (supports_overflow_infinity (type))
3422                     max = positive_overflow_infinity (type);
3423                   else
3424                     {
3425                       set_value_range_to_varying (vr);
3426                       return;
3427                     }
3428                 }
3429               else
3430                 max = TYPE_MAX_VALUE (type);
3431             }
3432         }
3433
3434       /* If the range contains zero then we know that the minimum value in the
3435          range will be zero.  */
3436       else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3437         {
3438           if (cmp == 1)
3439             max = min;
3440           min = build_int_cst (type, 0);
3441         }
3442       else
3443         {
3444           /* If the range was reversed, swap MIN and MAX.  */
3445           if (cmp == 1)
3446             {
3447               tree t = min;
3448               min = max;
3449               max = t;
3450             }
3451         }
3452
3453       cmp = compare_values (min, max);
3454       if (cmp == -2 || cmp == 1)
3455         {
3456           /* If the new range has its limits swapped around (MIN > MAX),
3457              then the operation caused one of them to wrap around, mark
3458              the new range VARYING.  */
3459           set_value_range_to_varying (vr);
3460         }
3461       else
3462         set_value_range (vr, vr0.type, min, max, NULL);
3463       return;
3464     }
3465
3466   /* For unhandled operations fall back to varying.  */
3467   set_value_range_to_varying (vr);
3468   return;
3469 }
3470
3471
3472 /* Extract range information from a unary expression CODE OP0 based on
3473    the range of its operand with resulting type TYPE.
3474    The resulting range is stored in *VR.  */
3475
3476 static void
3477 extract_range_from_unary_expr (value_range_t *vr, enum tree_code code,
3478                                tree type, tree op0)
3479 {
3480   value_range_t vr0 = VR_INITIALIZER;
3481
3482   /* Get value ranges for the operand.  For constant operands, create
3483      a new value range with the operand to simplify processing.  */
3484   if (TREE_CODE (op0) == SSA_NAME)
3485     vr0 = *(get_value_range (op0));
3486   else if (is_gimple_min_invariant (op0))
3487     set_value_range_to_value (&vr0, op0, NULL);
3488   else
3489     set_value_range_to_varying (&vr0);
3490
3491   extract_range_from_unary_expr_1 (vr, code, type, &vr0, TREE_TYPE (op0));
3492 }
3493
3494
3495 /* Extract range information from a conditional expression STMT based on
3496    the ranges of each of its operands and the expression code.  */
3497
3498 static void
3499 extract_range_from_cond_expr (value_range_t *vr, gimple stmt)
3500 {
3501   tree op0, op1;
3502   value_range_t vr0 = VR_INITIALIZER;
3503   value_range_t vr1 = VR_INITIALIZER;
3504
3505   /* Get value ranges for each operand.  For constant operands, create
3506      a new value range with the operand to simplify processing.  */
3507   op0 = gimple_assign_rhs2 (stmt);
3508   if (TREE_CODE (op0) == SSA_NAME)
3509     vr0 = *(get_value_range (op0));
3510   else if (is_gimple_min_invariant (op0))
3511     set_value_range_to_value (&vr0, op0, NULL);
3512   else
3513     set_value_range_to_varying (&vr0);
3514
3515   op1 = gimple_assign_rhs3 (stmt);
3516   if (TREE_CODE (op1) == SSA_NAME)
3517     vr1 = *(get_value_range (op1));
3518   else if (is_gimple_min_invariant (op1))
3519     set_value_range_to_value (&vr1, op1, NULL);
3520   else
3521     set_value_range_to_varying (&vr1);
3522
3523   /* The resulting value range is the union of the operand ranges */
3524   copy_value_range (vr, &vr0);
3525   vrp_meet (vr, &vr1);
3526 }
3527
3528
3529 /* Extract range information from a comparison expression EXPR based
3530    on the range of its operand and the expression code.  */
3531
3532 static void
3533 extract_range_from_comparison (value_range_t *vr, enum tree_code code,
3534                                tree type, tree op0, tree op1)
3535 {
3536   bool sop = false;
3537   tree val;
3538
3539   val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3540                                                  NULL);
3541
3542   /* A disadvantage of using a special infinity as an overflow
3543      representation is that we lose the ability to record overflow
3544      when we don't have an infinity.  So we have to ignore a result
3545      which relies on overflow.  */
3546
3547   if (val && !is_overflow_infinity (val) && !sop)
3548     {
3549       /* Since this expression was found on the RHS of an assignment,
3550          its type may be different from _Bool.  Convert VAL to EXPR's
3551          type.  */
3552       val = fold_convert (type, val);
3553       if (is_gimple_min_invariant (val))
3554         set_value_range_to_value (vr, val, vr->equiv);
3555       else
3556         set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3557     }
3558   else
3559     /* The result of a comparison is always true or false.  */
3560     set_value_range_to_truthvalue (vr, type);
3561 }
3562
3563 /* Try to derive a nonnegative or nonzero range out of STMT relying
3564    primarily on generic routines in fold in conjunction with range data.
3565    Store the result in *VR */
3566
3567 static void
3568 extract_range_basic (value_range_t *vr, gimple stmt)
3569 {
3570   bool sop = false;
3571   tree type = gimple_expr_type (stmt);
3572
3573   if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3574     {
3575       tree fndecl = gimple_call_fndecl (stmt), arg;
3576       int mini, maxi, zerov = 0, prec;
3577
3578       switch (DECL_FUNCTION_CODE (fndecl))
3579         {
3580         case BUILT_IN_CONSTANT_P:
3581           /* If the call is __builtin_constant_p and the argument is a
3582              function parameter resolve it to false.  This avoids bogus
3583              array bound warnings.
3584              ???  We could do this as early as inlining is finished.  */
3585           arg = gimple_call_arg (stmt, 0);
3586           if (TREE_CODE (arg) == SSA_NAME
3587               && SSA_NAME_IS_DEFAULT_DEF (arg)
3588               && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL)
3589             {
3590               set_value_range_to_null (vr, type);
3591               return;
3592             }
3593           break;
3594           /* Both __builtin_ffs* and __builtin_popcount return
3595              [0, prec].  */
3596         CASE_INT_FN (BUILT_IN_FFS):
3597         CASE_INT_FN (BUILT_IN_POPCOUNT):
3598           arg = gimple_call_arg (stmt, 0);
3599           prec = TYPE_PRECISION (TREE_TYPE (arg));
3600           mini = 0;
3601           maxi = prec;
3602           if (TREE_CODE (arg) == SSA_NAME)
3603             {
3604               value_range_t *vr0 = get_value_range (arg);
3605               /* If arg is non-zero, then ffs or popcount
3606                  are non-zero.  */
3607               if (((vr0->type == VR_RANGE
3608                     && integer_nonzerop (vr0->min))
3609                    || (vr0->type == VR_ANTI_RANGE
3610                        && integer_zerop (vr0->min)))
3611                   && !TREE_OVERFLOW (vr0->min))
3612                 mini = 1;
3613               /* If some high bits are known to be zero,
3614                  we can decrease the maximum.  */
3615               if (vr0->type == VR_RANGE
3616                   && TREE_CODE (vr0->max) == INTEGER_CST
3617                   && !TREE_OVERFLOW (vr0->max))
3618                 maxi = tree_floor_log2 (vr0->max) + 1;
3619             }
3620           goto bitop_builtin;
3621           /* __builtin_parity* returns [0, 1].  */
3622         CASE_INT_FN (BUILT_IN_PARITY):
3623           mini = 0;
3624           maxi = 1;
3625           goto bitop_builtin;
3626           /* __builtin_c[lt]z* return [0, prec-1], except for
3627              when the argument is 0, but that is undefined behavior.
3628              On many targets where the CLZ RTL or optab value is defined
3629              for 0 the value is prec, so include that in the range
3630              by default.  */
3631         CASE_INT_FN (BUILT_IN_CLZ):
3632           arg = gimple_call_arg (stmt, 0);
3633           prec = TYPE_PRECISION (TREE_TYPE (arg));
3634           mini = 0;
3635           maxi = prec;
3636           if (optab_handler (clz_optab, TYPE_MODE (TREE_TYPE (arg)))
3637               != CODE_FOR_nothing
3638               && CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3639                                             zerov)
3640               /* Handle only the single common value.  */
3641               && zerov != prec)
3642             /* Magic value to give up, unless vr0 proves
3643                arg is non-zero.  */
3644             mini = -2;
3645           if (TREE_CODE (arg) == SSA_NAME)
3646             {
3647               value_range_t *vr0 = get_value_range (arg);
3648               /* From clz of VR_RANGE minimum we can compute
3649                  result maximum.  */
3650               if (vr0->type == VR_RANGE
3651                   && TREE_CODE (vr0->min) == INTEGER_CST
3652                   && !TREE_OVERFLOW (vr0->min))
3653                 {
3654                   maxi = prec - 1 - tree_floor_log2 (vr0->min);
3655                   if (maxi != prec)
3656                     mini = 0;
3657                 }
3658               else if (vr0->type == VR_ANTI_RANGE
3659                        && integer_zerop (vr0->min)
3660                        && !TREE_OVERFLOW (vr0->min))
3661                 {
3662                   maxi = prec - 1;
3663                   mini = 0;
3664                 }
3665               if (mini == -2)
3666                 break;
3667               /* From clz of VR_RANGE maximum we can compute
3668                  result minimum.  */
3669               if (vr0->type == VR_RANGE
3670                   && TREE_CODE (vr0->max) == INTEGER_CST
3671                   && !TREE_OVERFLOW (vr0->max))
3672                 {
3673                   mini = prec - 1 - tree_floor_log2 (vr0->max);
3674                   if (mini == prec)
3675                     break;
3676                 }
3677             }
3678           if (mini == -2)
3679             break;
3680           goto bitop_builtin;
3681           /* __builtin_ctz* return [0, prec-1], except for
3682              when the argument is 0, but that is undefined behavior.
3683              If there is a ctz optab for this mode and
3684              CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3685              otherwise just assume 0 won't be seen.  */
3686         CASE_INT_FN (BUILT_IN_CTZ):
3687           arg = gimple_call_arg (stmt, 0);
3688           prec = TYPE_PRECISION (TREE_TYPE (arg));
3689           mini = 0;
3690           maxi = prec - 1;
3691           if (optab_handler (ctz_optab, TYPE_MODE (TREE_TYPE (arg)))
3692               != CODE_FOR_nothing
3693               && CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3694                                             zerov))
3695             {
3696               /* Handle only the two common values.  */
3697               if (zerov == -1)
3698                 mini = -1;
3699               else if (zerov == prec)
3700                 maxi = prec;
3701               else
3702                 /* Magic value to give up, unless vr0 proves
3703                    arg is non-zero.  */
3704                 mini = -2;
3705             }
3706           if (TREE_CODE (arg) == SSA_NAME)
3707             {
3708               value_range_t *vr0 = get_value_range (arg);
3709               /* If arg is non-zero, then use [0, prec - 1].  */
3710               if (((vr0->type == VR_RANGE
3711                     && integer_nonzerop (vr0->min))
3712                    || (vr0->type == VR_ANTI_RANGE
3713                        && integer_zerop (vr0->min)))
3714                   && !TREE_OVERFLOW (vr0->min))
3715                 {
3716                   mini = 0;
3717                   maxi = prec - 1;
3718                 }
3719               /* If some high bits are known to be zero,
3720                  we can decrease the result maximum.  */
3721               if (vr0->type == VR_RANGE
3722                   && TREE_CODE (vr0->max) == INTEGER_CST
3723                   && !TREE_OVERFLOW (vr0->max))
3724                 {
3725                   maxi = tree_floor_log2 (vr0->max);
3726                   /* For vr0 [0, 0] give up.  */
3727                   if (maxi == -1)
3728                     break;
3729                 }
3730             }
3731           if (mini == -2)
3732             break;
3733           goto bitop_builtin;
3734           /* __builtin_clrsb* returns [0, prec-1].  */
3735         CASE_INT_FN (BUILT_IN_CLRSB):
3736           arg = gimple_call_arg (stmt, 0);
3737           prec = TYPE_PRECISION (TREE_TYPE (arg));
3738           mini = 0;
3739           maxi = prec - 1;
3740           goto bitop_builtin;
3741         bitop_builtin:
3742           set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3743                            build_int_cst (type, maxi), NULL);
3744           return;
3745         default:
3746           break;
3747         }
3748     }
3749   if (INTEGRAL_TYPE_P (type)
3750       && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
3751     set_value_range_to_nonnegative (vr, type,
3752                                     sop || stmt_overflow_infinity (stmt));
3753   else if (vrp_stmt_computes_nonzero (stmt, &sop)
3754            && !sop)
3755     set_value_range_to_nonnull (vr, type);
3756   else
3757     set_value_range_to_varying (vr);
3758 }
3759
3760
3761 /* Try to compute a useful range out of assignment STMT and store it
3762    in *VR.  */
3763
3764 static void
3765 extract_range_from_assignment (value_range_t *vr, gimple stmt)
3766 {
3767   enum tree_code code = gimple_assign_rhs_code (stmt);
3768
3769   if (code == ASSERT_EXPR)
3770     extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
3771   else if (code == SSA_NAME)
3772     extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
3773   else if (TREE_CODE_CLASS (code) == tcc_binary)
3774     extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
3775                                     gimple_expr_type (stmt),
3776                                     gimple_assign_rhs1 (stmt),
3777                                     gimple_assign_rhs2 (stmt));
3778   else if (TREE_CODE_CLASS (code) == tcc_unary)
3779     extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
3780                                    gimple_expr_type (stmt),
3781                                    gimple_assign_rhs1 (stmt));
3782   else if (code == COND_EXPR)
3783     extract_range_from_cond_expr (vr, stmt);
3784   else if (TREE_CODE_CLASS (code) == tcc_comparison)
3785     extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
3786                                    gimple_expr_type (stmt),
3787                                    gimple_assign_rhs1 (stmt),
3788                                    gimple_assign_rhs2 (stmt));
3789   else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
3790            && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3791     set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
3792   else
3793     set_value_range_to_varying (vr);
3794
3795   if (vr->type == VR_VARYING)
3796     extract_range_basic (vr, stmt);
3797 }
3798
3799 /* Given a range VR, a LOOP and a variable VAR, determine whether it
3800    would be profitable to adjust VR using scalar evolution information
3801    for VAR.  If so, update VR with the new limits.  */
3802
3803 static void
3804 adjust_range_with_scev (value_range_t *vr, struct loop *loop,
3805                         gimple stmt, tree var)
3806 {
3807   tree init, step, chrec, tmin, tmax, min, max, type, tem;
3808   enum ev_direction dir;
3809
3810   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
3811      better opportunities than a regular range, but I'm not sure.  */
3812   if (vr->type == VR_ANTI_RANGE)
3813     return;
3814
3815   chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
3816
3817   /* Like in PR19590, scev can return a constant function.  */
3818   if (is_gimple_min_invariant (chrec))
3819     {
3820       set_value_range_to_value (vr, chrec, vr->equiv);
3821       return;
3822     }
3823
3824   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3825     return;
3826
3827   init = initial_condition_in_loop_num (chrec, loop->num);
3828   tem = op_with_constant_singleton_value_range (init);
3829   if (tem)
3830     init = tem;
3831   step = evolution_part_in_loop_num (chrec, loop->num);
3832   tem = op_with_constant_singleton_value_range (step);
3833   if (tem)
3834     step = tem;
3835
3836   /* If STEP is symbolic, we can't know whether INIT will be the
3837      minimum or maximum value in the range.  Also, unless INIT is
3838      a simple expression, compare_values and possibly other functions
3839      in tree-vrp won't be able to handle it.  */
3840   if (step == NULL_TREE
3841       || !is_gimple_min_invariant (step)
3842       || !valid_value_p (init))
3843     return;
3844
3845   dir = scev_direction (chrec);
3846   if (/* Do not adjust ranges if we do not know whether the iv increases
3847          or decreases,  ... */
3848       dir == EV_DIR_UNKNOWN
3849       /* ... or if it may wrap.  */
3850       || scev_probably_wraps_p (init, step, stmt, get_chrec_loop (chrec),
3851                                 true))
3852     return;
3853
3854   /* We use TYPE_MIN_VALUE and TYPE_MAX_VALUE here instead of
3855      negative_overflow_infinity and positive_overflow_infinity,
3856      because we have concluded that the loop probably does not
3857      wrap.  */
3858
3859   type = TREE_TYPE (var);
3860   if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
3861     tmin = lower_bound_in_type (type, type);
3862   else
3863     tmin = TYPE_MIN_VALUE (type);
3864   if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
3865     tmax = upper_bound_in_type (type, type);
3866   else
3867     tmax = TYPE_MAX_VALUE (type);
3868
3869   /* Try to use estimated number of iterations for the loop to constrain the
3870      final value in the evolution.  */
3871   if (TREE_CODE (step) == INTEGER_CST
3872       && is_gimple_val (init)
3873       && (TREE_CODE (init) != SSA_NAME
3874           || get_value_range (init)->type == VR_RANGE))
3875     {
3876       double_int nit;
3877
3878       /* We are only entering here for loop header PHI nodes, so using
3879          the number of latch executions is the correct thing to use.  */
3880       if (max_loop_iterations (loop, &nit))
3881         {
3882           value_range_t maxvr = VR_INITIALIZER;
3883           double_int dtmp;
3884           bool unsigned_p = TYPE_UNSIGNED (TREE_TYPE (step));
3885           bool overflow = false;
3886
3887           dtmp = tree_to_double_int (step)
3888                  .mul_with_sign (nit, unsigned_p, &overflow);
3889           /* If the multiplication overflowed we can't do a meaningful
3890              adjustment.  Likewise if the result doesn't fit in the type
3891              of the induction variable.  For a signed type we have to
3892              check whether the result has the expected signedness which
3893              is that of the step as number of iterations is unsigned.  */
3894           if (!overflow
3895               && double_int_fits_to_tree_p (TREE_TYPE (init), dtmp)
3896               && (unsigned_p
3897                   || ((dtmp.high ^ TREE_INT_CST_HIGH (step)) >= 0)))
3898             {
3899               tem = double_int_to_tree (TREE_TYPE (init), dtmp);
3900               extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
3901                                               TREE_TYPE (init), init, tem);
3902               /* Likewise if the addition did.  */
3903               if (maxvr.type == VR_RANGE)
3904                 {
3905                   tmin = maxvr.min;
3906                   tmax = maxvr.max;
3907                 }
3908             }
3909         }
3910     }
3911
3912   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
3913     {
3914       min = tmin;
3915       max = tmax;
3916
3917       /* For VARYING or UNDEFINED ranges, just about anything we get
3918          from scalar evolutions should be better.  */
3919
3920       if (dir == EV_DIR_DECREASES)
3921         max = init;
3922       else
3923         min = init;
3924
3925       /* If we would create an invalid range, then just assume we
3926          know absolutely nothing.  This may be over-conservative,
3927          but it's clearly safe, and should happen only in unreachable
3928          parts of code, or for invalid programs.  */
3929       if (compare_values (min, max) == 1)
3930         return;
3931
3932       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
3933     }
3934   else if (vr->type == VR_RANGE)
3935     {
3936       min = vr->min;
3937       max = vr->max;
3938
3939       if (dir == EV_DIR_DECREASES)
3940         {
3941           /* INIT is the maximum value.  If INIT is lower than VR->MAX
3942              but no smaller than VR->MIN, set VR->MAX to INIT.  */
3943           if (compare_values (init, max) == -1)
3944             max = init;
3945
3946           /* According to the loop information, the variable does not
3947              overflow.  If we think it does, probably because of an
3948              overflow due to arithmetic on a different INF value,
3949              reset now.  */
3950           if (is_negative_overflow_infinity (min)
3951               || compare_values (min, tmin) == -1)
3952             min = tmin;
3953
3954         }
3955       else
3956         {
3957           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
3958           if (compare_values (init, min) == 1)
3959             min = init;
3960
3961           if (is_positive_overflow_infinity (max)
3962               || compare_values (tmax, max) == -1)
3963             max = tmax;
3964         }
3965
3966       /* If we just created an invalid range with the minimum
3967          greater than the maximum, we fail conservatively.
3968          This should happen only in unreachable
3969          parts of code, or for invalid programs.  */
3970       if (compare_values (min, max) == 1)
3971         return;
3972
3973       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
3974     }
3975 }
3976
3977 /* Return true if VAR may overflow at STMT.  This checks any available
3978    loop information to see if we can determine that VAR does not
3979    overflow.  */
3980
3981 static bool
3982 vrp_var_may_overflow (tree var, gimple stmt)
3983 {
3984   struct loop *l;
3985   tree chrec, init, step;
3986
3987   if (current_loops == NULL)
3988     return true;
3989
3990   l = loop_containing_stmt (stmt);
3991   if (l == NULL
3992       || !loop_outer (l))
3993     return true;
3994
3995   chrec = instantiate_parameters (l, analyze_scalar_evolution (l, var));
3996   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3997     return true;
3998
3999   init = initial_condition_in_loop_num (chrec, l->num);
4000   step = evolution_part_in_loop_num (chrec, l->num);
4001
4002   if (step == NULL_TREE
4003       || !is_gimple_min_invariant (step)
4004       || !valid_value_p (init))
4005     return true;
4006
4007   /* If we get here, we know something useful about VAR based on the
4008      loop information.  If it wraps, it may overflow.  */
4009
4010   if (scev_probably_wraps_p (init, step, stmt, get_chrec_loop (chrec),
4011                              true))
4012     return true;
4013
4014   if (dump_file && (dump_flags & TDF_DETAILS) != 0)
4015     {
4016       print_generic_expr (dump_file, var, 0);
4017       fprintf (dump_file, ": loop information indicates does not overflow\n");
4018     }
4019
4020   return false;
4021 }
4022
4023
4024 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4025
4026    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4027      all the values in the ranges.
4028
4029    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4030
4031    - Return NULL_TREE if it is not always possible to determine the
4032      value of the comparison.
4033
4034    Also set *STRICT_OVERFLOW_P to indicate whether a range with an
4035    overflow infinity was used in the test.  */
4036
4037
4038 static tree
4039 compare_ranges (enum tree_code comp, value_range_t *vr0, value_range_t *vr1,
4040                 bool *strict_overflow_p)
4041 {
4042   /* VARYING or UNDEFINED ranges cannot be compared.  */
4043   if (vr0->type == VR_VARYING
4044       || vr0->type == VR_UNDEFINED
4045       || vr1->type == VR_VARYING
4046       || vr1->type == VR_UNDEFINED)
4047     return NULL_TREE;
4048
4049   /* Anti-ranges need to be handled separately.  */
4050   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4051     {
4052       /* If both are anti-ranges, then we cannot compute any
4053          comparison.  */
4054       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4055         return NULL_TREE;
4056
4057       /* These comparisons are never statically computable.  */
4058       if (comp == GT_EXPR
4059           || comp == GE_EXPR
4060           || comp == LT_EXPR
4061           || comp == LE_EXPR)
4062         return NULL_TREE;
4063
4064       /* Equality can be computed only between a range and an
4065          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
4066       if (vr0->type == VR_RANGE)
4067         {
4068           /* To simplify processing, make VR0 the anti-range.  */
4069           value_range_t *tmp = vr0;
4070           vr0 = vr1;
4071           vr1 = tmp;
4072         }
4073
4074       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4075
4076       if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4077           && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4078         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4079
4080       return NULL_TREE;
4081     }
4082
4083   if (!usable_range_p (vr0, strict_overflow_p)
4084       || !usable_range_p (vr1, strict_overflow_p))
4085     return NULL_TREE;
4086
4087   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
4088      operands around and change the comparison code.  */
4089   if (comp == GT_EXPR || comp == GE_EXPR)
4090     {
4091       value_range_t *tmp;
4092       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4093       tmp = vr0;
4094       vr0 = vr1;
4095       vr1 = tmp;
4096     }
4097
4098   if (comp == EQ_EXPR)
4099     {
4100       /* Equality may only be computed if both ranges represent
4101          exactly one value.  */
4102       if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4103           && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4104         {
4105           int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4106                                               strict_overflow_p);
4107           int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4108                                               strict_overflow_p);
4109           if (cmp_min == 0 && cmp_max == 0)
4110             return boolean_true_node;
4111           else if (cmp_min != -2 && cmp_max != -2)
4112             return boolean_false_node;
4113         }
4114       /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1.  */
4115       else if (compare_values_warnv (vr0->min, vr1->max,
4116                                      strict_overflow_p) == 1
4117                || compare_values_warnv (vr1->min, vr0->max,
4118                                         strict_overflow_p) == 1)
4119         return boolean_false_node;
4120
4121       return NULL_TREE;
4122     }
4123   else if (comp == NE_EXPR)
4124     {
4125       int cmp1, cmp2;
4126
4127       /* If VR0 is completely to the left or completely to the right
4128          of VR1, they are always different.  Notice that we need to
4129          make sure that both comparisons yield similar results to
4130          avoid comparing values that cannot be compared at
4131          compile-time.  */
4132       cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4133       cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4134       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4135         return boolean_true_node;
4136
4137       /* If VR0 and VR1 represent a single value and are identical,
4138          return false.  */
4139       else if (compare_values_warnv (vr0->min, vr0->max,
4140                                      strict_overflow_p) == 0
4141                && compare_values_warnv (vr1->min, vr1->max,
4142                                         strict_overflow_p) == 0
4143                && compare_values_warnv (vr0->min, vr1->min,
4144                                         strict_overflow_p) == 0
4145                && compare_values_warnv (vr0->max, vr1->max,
4146                                         strict_overflow_p) == 0)
4147         return boolean_false_node;
4148
4149       /* Otherwise, they may or may not be different.  */
4150       else
4151         return NULL_TREE;
4152     }
4153   else if (comp == LT_EXPR || comp == LE_EXPR)
4154     {
4155       int tst;
4156
4157       /* If VR0 is to the left of VR1, return true.  */
4158       tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4159       if ((comp == LT_EXPR && tst == -1)
4160           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4161         {
4162           if (overflow_infinity_range_p (vr0)
4163               || overflow_infinity_range_p (vr1))
4164             *strict_overflow_p = true;
4165           return boolean_true_node;
4166         }
4167
4168       /* If VR0 is to the right of VR1, return false.  */
4169       tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4170       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4171           || (comp == LE_EXPR && tst == 1))
4172         {
4173           if (overflow_infinity_range_p (vr0)
4174               || overflow_infinity_range_p (vr1))
4175             *strict_overflow_p = true;
4176           return boolean_false_node;
4177         }
4178
4179       /* Otherwise, we don't know.  */
4180       return NULL_TREE;
4181     }
4182
4183   gcc_unreachable ();
4184 }
4185
4186
4187 /* Given a value range VR, a value VAL and a comparison code COMP, return
4188    BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4189    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
4190    always returns false.  Return NULL_TREE if it is not always
4191    possible to determine the value of the comparison.  Also set
4192    *STRICT_OVERFLOW_P to indicate whether a range with an overflow
4193    infinity was used in the test.  */
4194
4195 static tree
4196 compare_range_with_value (enum tree_code comp, value_range_t *vr, tree val,
4197                           bool *strict_overflow_p)
4198 {
4199   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4200     return NULL_TREE;
4201
4202   /* Anti-ranges need to be handled separately.  */
4203   if (vr->type == VR_ANTI_RANGE)
4204     {
4205       /* For anti-ranges, the only predicates that we can compute at
4206          compile time are equality and inequality.  */
4207       if (comp == GT_EXPR
4208           || comp == GE_EXPR
4209           || comp == LT_EXPR
4210           || comp == LE_EXPR)
4211         return NULL_TREE;
4212
4213       /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2.  */
4214       if (value_inside_range (val, vr->min, vr->max) == 1)
4215         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4216
4217       return NULL_TREE;
4218     }
4219
4220   if (!usable_range_p (vr, strict_overflow_p))
4221     return NULL_TREE;
4222
4223   if (comp == EQ_EXPR)
4224     {
4225       /* EQ_EXPR may only be computed if VR represents exactly
4226          one value.  */
4227       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4228         {
4229           int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4230           if (cmp == 0)
4231             return boolean_true_node;
4232           else if (cmp == -1 || cmp == 1 || cmp == 2)
4233             return boolean_false_node;
4234         }
4235       else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4236                || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4237         return boolean_false_node;
4238
4239       return NULL_TREE;
4240     }
4241   else if (comp == NE_EXPR)
4242     {
4243       /* If VAL is not inside VR, then they are always different.  */
4244       if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4245           || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4246         return boolean_true_node;
4247
4248       /* If VR represents exactly one value equal to VAL, then return
4249          false.  */
4250       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4251           && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4252         return boolean_false_node;
4253
4254       /* Otherwise, they may or may not be different.  */
4255       return NULL_TREE;
4256     }
4257   else if (comp == LT_EXPR || comp == LE_EXPR)
4258     {
4259       int tst;
4260
4261       /* If VR is to the left of VAL, return true.  */
4262       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4263       if ((comp == LT_EXPR && tst == -1)
4264           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4265         {
4266           if (overflow_infinity_range_p (vr))
4267             *strict_overflow_p = true;
4268           return boolean_true_node;
4269         }
4270
4271       /* If VR is to the right of VAL, return false.  */
4272       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4273       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4274           || (comp == LE_EXPR && tst == 1))
4275         {
4276           if (overflow_infinity_range_p (vr))
4277             *strict_overflow_p = true;
4278           return boolean_false_node;
4279         }
4280
4281       /* Otherwise, we don't know.  */
4282       return NULL_TREE;
4283     }
4284   else if (comp == GT_EXPR || comp == GE_EXPR)
4285     {
4286       int tst;
4287
4288       /* If VR is to the right of VAL, return true.  */
4289       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4290       if ((comp == GT_EXPR && tst == 1)
4291           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4292         {
4293           if (overflow_infinity_range_p (vr))
4294             *strict_overflow_p = true;
4295           return boolean_true_node;
4296         }
4297
4298       /* If VR is to the left of VAL, return false.  */
4299       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4300       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4301           || (comp == GE_EXPR && tst == -1))
4302         {
4303           if (overflow_infinity_range_p (vr))
4304             *strict_overflow_p = true;
4305           return boolean_false_node;
4306         }
4307
4308       /* Otherwise, we don't know.  */
4309       return NULL_TREE;
4310     }
4311
4312   gcc_unreachable ();
4313 }
4314
4315
4316 /* Debugging dumps.  */
4317
4318 void dump_value_range (FILE *, value_range_t *);
4319 void debug_value_range (value_range_t *);
4320 void dump_all_value_ranges (FILE *);
4321 void debug_all_value_ranges (void);
4322 void dump_vr_equiv (FILE *, bitmap);
4323 void debug_vr_equiv (bitmap);
4324
4325
4326 /* Dump value range VR to FILE.  */
4327
4328 void
4329 dump_value_range (FILE *file, value_range_t *vr)
4330 {
4331   if (vr == NULL)
4332     fprintf (file, "[]");
4333   else if (vr->type == VR_UNDEFINED)
4334     fprintf (file, "UNDEFINED");
4335   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4336     {
4337       tree type = TREE_TYPE (vr->min);
4338
4339       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4340
4341       if (is_negative_overflow_infinity (vr->min))
4342         fprintf (file, "-INF(OVF)");
4343       else if (INTEGRAL_TYPE_P (type)
4344                && !TYPE_UNSIGNED (type)
4345                && vrp_val_is_min (vr->min))
4346         fprintf (file, "-INF");
4347       else
4348         print_generic_expr (file, vr->min, 0);
4349
4350       fprintf (file, ", ");
4351
4352       if (is_positive_overflow_infinity (vr->max))
4353         fprintf (file, "+INF(OVF)");
4354       else if (INTEGRAL_TYPE_P (type)
4355                && vrp_val_is_max (vr->max))
4356         fprintf (file, "+INF");
4357       else
4358         print_generic_expr (file, vr->max, 0);
4359
4360       fprintf (file, "]");
4361
4362       if (vr->equiv)
4363         {
4364           bitmap_iterator bi;
4365           unsigned i, c = 0;
4366
4367           fprintf (file, "  EQUIVALENCES: { ");
4368
4369           EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4370             {
4371               print_generic_expr (file, ssa_name (i), 0);
4372               fprintf (file, " ");
4373               c++;
4374             }
4375
4376           fprintf (file, "} (%u elements)", c);
4377         }
4378     }
4379   else if (vr->type == VR_VARYING)
4380     fprintf (file, "VARYING");
4381   else
4382     fprintf (file, "INVALID RANGE");
4383 }
4384
4385
4386 /* Dump value range VR to stderr.  */
4387
4388 DEBUG_FUNCTION void
4389 debug_value_range (value_range_t *vr)
4390 {
4391   dump_value_range (stderr, vr);
4392   fprintf (stderr, "\n");
4393 }
4394
4395
4396 /* Dump value ranges of all SSA_NAMEs to FILE.  */
4397
4398 void
4399 dump_all_value_ranges (FILE *file)
4400 {
4401   size_t i;
4402
4403   for (i = 0; i < num_vr_values; i++)
4404     {
4405       if (vr_value[i])
4406         {
4407           print_generic_expr (file, ssa_name (i), 0);
4408           fprintf (file, ": ");
4409           dump_value_range (file, vr_value[i]);
4410           fprintf (file, "\n");
4411         }
4412     }
4413
4414   fprintf (file, "\n");
4415 }
4416
4417
4418 /* Dump all value ranges to stderr.  */
4419
4420 DEBUG_FUNCTION void
4421 debug_all_value_ranges (void)
4422 {
4423   dump_all_value_ranges (stderr);
4424 }
4425
4426
4427 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4428    create a new SSA name N and return the assertion assignment
4429    'V = ASSERT_EXPR <V, V OP W>'.  */
4430
4431 static gimple
4432 build_assert_expr_for (tree cond, tree v)
4433 {
4434   tree a;
4435   gimple assertion;
4436
4437   gcc_assert (TREE_CODE (v) == SSA_NAME
4438               && COMPARISON_CLASS_P (cond));
4439
4440   a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4441   assertion = gimple_build_assign (NULL_TREE, a);
4442
4443   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4444      operand of the ASSERT_EXPR.  Create it so the new name and the old one
4445      are registered in the replacement table so that we can fix the SSA web
4446      after adding all the ASSERT_EXPRs.  */
4447   create_new_def_for (v, assertion, NULL);
4448
4449   return assertion;
4450 }
4451
4452
4453 /* Return false if EXPR is a predicate expression involving floating
4454    point values.  */
4455
4456 static inline bool
4457 fp_predicate (gimple stmt)
4458 {
4459   GIMPLE_CHECK (stmt, GIMPLE_COND);
4460
4461   return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4462 }
4463
4464
4465 /* If the range of values taken by OP can be inferred after STMT executes,
4466    return the comparison code (COMP_CODE_P) and value (VAL_P) that
4467    describes the inferred range.  Return true if a range could be
4468    inferred.  */
4469
4470 static bool
4471 infer_value_range (gimple stmt, tree op, enum tree_code *comp_code_p, tree *val_p)
4472 {
4473   *val_p = NULL_TREE;
4474   *comp_code_p = ERROR_MARK;
4475
4476   /* Do not attempt to infer anything in names that flow through
4477      abnormal edges.  */
4478   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4479     return false;
4480
4481   /* Similarly, don't infer anything from statements that may throw
4482      exceptions.  */
4483   if (stmt_could_throw_p (stmt))
4484     return false;
4485
4486   /* If STMT is the last statement of a basic block with no
4487      successors, there is no point inferring anything about any of its
4488      operands.  We would not be able to find a proper insertion point
4489      for the assertion, anyway.  */
4490   if (stmt_ends_bb_p (stmt) && EDGE_COUNT (gimple_bb (stmt)->succs) == 0)
4491     return false;
4492
4493   /* We can only assume that a pointer dereference will yield
4494      non-NULL if -fdelete-null-pointer-checks is enabled.  */
4495   if (flag_delete_null_pointer_checks
4496       && POINTER_TYPE_P (TREE_TYPE (op))
4497       && gimple_code (stmt) != GIMPLE_ASM)
4498     {
4499       unsigned num_uses, num_loads, num_stores;
4500
4501       count_uses_and_derefs (op, stmt, &num_uses, &num_loads, &num_stores);
4502       if (num_loads + num_stores > 0)
4503         {
4504           *val_p = build_int_cst (TREE_TYPE (op), 0);
4505           *comp_code_p = NE_EXPR;
4506           return true;
4507         }
4508     }
4509
4510   return false;
4511 }
4512
4513
4514 void dump_asserts_for (FILE *, tree);
4515 void debug_asserts_for (tree);
4516 void dump_all_asserts (FILE *);
4517 void debug_all_asserts (void);
4518
4519 /* Dump all the registered assertions for NAME to FILE.  */
4520
4521 void
4522 dump_asserts_for (FILE *file, tree name)
4523 {
4524   assert_locus_t loc;
4525
4526   fprintf (file, "Assertions to be inserted for ");
4527   print_generic_expr (file, name, 0);
4528   fprintf (file, "\n");
4529
4530   loc = asserts_for[SSA_NAME_VERSION (name)];
4531   while (loc)
4532     {
4533       fprintf (file, "\t");
4534       print_gimple_stmt (file, gsi_stmt (loc->si), 0, 0);
4535       fprintf (file, "\n\tBB #%d", loc->bb->index);
4536       if (loc->e)
4537         {
4538           fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4539                    loc->e->dest->index);
4540           dump_edge_info (file, loc->e, dump_flags, 0);
4541         }
4542       fprintf (file, "\n\tPREDICATE: ");
4543       print_generic_expr (file, name, 0);
4544       fprintf (file, " %s ", tree_code_name[(int)loc->comp_code]);
4545       print_generic_expr (file, loc->val, 0);
4546       fprintf (file, "\n\n");
4547       loc = loc->next;
4548     }
4549
4550   fprintf (file, "\n");
4551 }
4552
4553
4554 /* Dump all the registered assertions for NAME to stderr.  */
4555
4556 DEBUG_FUNCTION void
4557 debug_asserts_for (tree name)
4558 {
4559   dump_asserts_for (stderr, name);
4560 }
4561
4562
4563 /* Dump all the registered assertions for all the names to FILE.  */
4564
4565 void
4566 dump_all_asserts (FILE *file)
4567 {
4568   unsigned i;
4569   bitmap_iterator bi;
4570
4571   fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4572   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4573     dump_asserts_for (file, ssa_name (i));
4574   fprintf (file, "\n");
4575 }
4576
4577
4578 /* Dump all the registered assertions for all the names to stderr.  */
4579
4580 DEBUG_FUNCTION void
4581 debug_all_asserts (void)
4582 {
4583   dump_all_asserts (stderr);
4584 }
4585
4586
4587 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4588    'EXPR COMP_CODE VAL' at a location that dominates block BB or
4589    E->DEST, then register this location as a possible insertion point
4590    for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4591
4592    BB, E and SI provide the exact insertion point for the new
4593    ASSERT_EXPR.  If BB is NULL, then the ASSERT_EXPR is to be inserted
4594    on edge E.  Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4595    BB.  If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4596    must not be NULL.  */
4597
4598 static void
4599 register_new_assert_for (tree name, tree expr,
4600                          enum tree_code comp_code,
4601                          tree val,
4602                          basic_block bb,
4603                          edge e,
4604                          gimple_stmt_iterator si)
4605 {
4606   assert_locus_t n, loc, last_loc;
4607   basic_block dest_bb;
4608
4609   gcc_checking_assert (bb == NULL || e == NULL);
4610
4611   if (e == NULL)
4612     gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4613                          && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4614
4615   /* Never build an assert comparing against an integer constant with
4616      TREE_OVERFLOW set.  This confuses our undefined overflow warning
4617      machinery.  */
4618   if (TREE_CODE (val) == INTEGER_CST
4619       && TREE_OVERFLOW (val))
4620     val = build_int_cst_wide (TREE_TYPE (val),
4621                               TREE_INT_CST_LOW (val), TREE_INT_CST_HIGH (val));
4622
4623   /* The new assertion A will be inserted at BB or E.  We need to
4624      determine if the new location is dominated by a previously
4625      registered location for A.  If we are doing an edge insertion,
4626      assume that A will be inserted at E->DEST.  Note that this is not
4627      necessarily true.
4628
4629      If E is a critical edge, it will be split.  But even if E is
4630      split, the new block will dominate the same set of blocks that
4631      E->DEST dominates.
4632
4633      The reverse, however, is not true, blocks dominated by E->DEST
4634      will not be dominated by the new block created to split E.  So,
4635      if the insertion location is on a critical edge, we will not use
4636      the new location to move another assertion previously registered
4637      at a block dominated by E->DEST.  */
4638   dest_bb = (bb) ? bb : e->dest;
4639
4640   /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4641      VAL at a block dominating DEST_BB, then we don't need to insert a new
4642      one.  Similarly, if the same assertion already exists at a block
4643      dominated by DEST_BB and the new location is not on a critical
4644      edge, then update the existing location for the assertion (i.e.,
4645      move the assertion up in the dominance tree).
4646
4647      Note, this is implemented as a simple linked list because there
4648      should not be more than a handful of assertions registered per
4649      name.  If this becomes a performance problem, a table hashed by
4650      COMP_CODE and VAL could be implemented.  */
4651   loc = asserts_for[SSA_NAME_VERSION (name)];
4652   last_loc = loc;
4653   while (loc)
4654     {
4655       if (loc->comp_code == comp_code
4656           && (loc->val == val
4657               || operand_equal_p (loc->val, val, 0))
4658           && (loc->expr == expr
4659               || operand_equal_p (loc->expr, expr, 0)))
4660         {
4661           /* If E is not a critical edge and DEST_BB
4662              dominates the existing location for the assertion, move
4663              the assertion up in the dominance tree by updating its
4664              location information.  */
4665           if ((e == NULL || !EDGE_CRITICAL_P (e))
4666               && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4667             {
4668               loc->bb = dest_bb;
4669               loc->e = e;
4670               loc->si = si;
4671               return;
4672             }
4673         }
4674
4675       /* Update the last node of the list and move to the next one.  */
4676       last_loc = loc;
4677       loc = loc->next;
4678     }
4679
4680   /* If we didn't find an assertion already registered for
4681      NAME COMP_CODE VAL, add a new one at the end of the list of
4682      assertions associated with NAME.  */
4683   n = XNEW (struct assert_locus_d);
4684   n->bb = dest_bb;
4685   n->e = e;
4686   n->si = si;
4687   n->comp_code = comp_code;
4688   n->val = val;
4689   n->expr = expr;
4690   n->next = NULL;
4691
4692   if (last_loc)
4693     last_loc->next = n;
4694   else
4695     asserts_for[SSA_NAME_VERSION (name)] = n;
4696
4697   bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
4698 }
4699
4700 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
4701    Extract a suitable test code and value and store them into *CODE_P and
4702    *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
4703
4704    If no extraction was possible, return FALSE, otherwise return TRUE.
4705
4706    If INVERT is true, then we invert the result stored into *CODE_P.  */
4707
4708 static bool
4709 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
4710                                          tree cond_op0, tree cond_op1,
4711                                          bool invert, enum tree_code *code_p,
4712                                          tree *val_p)
4713 {
4714   enum tree_code comp_code;
4715   tree val;
4716
4717   /* Otherwise, we have a comparison of the form NAME COMP VAL
4718      or VAL COMP NAME.  */
4719   if (name == cond_op1)
4720     {
4721       /* If the predicate is of the form VAL COMP NAME, flip
4722          COMP around because we need to register NAME as the
4723          first operand in the predicate.  */
4724       comp_code = swap_tree_comparison (cond_code);
4725       val = cond_op0;
4726     }
4727   else
4728     {
4729       /* The comparison is of the form NAME COMP VAL, so the
4730          comparison code remains unchanged.  */
4731       comp_code = cond_code;
4732       val = cond_op1;
4733     }
4734
4735   /* Invert the comparison code as necessary.  */
4736   if (invert)
4737     comp_code = invert_tree_comparison (comp_code, 0);
4738
4739   /* VRP does not handle float types.  */
4740   if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (val)))
4741     return false;
4742
4743   /* Do not register always-false predicates.
4744      FIXME:  this works around a limitation in fold() when dealing with
4745      enumerations.  Given 'enum { N1, N2 } x;', fold will not
4746      fold 'if (x > N2)' to 'if (0)'.  */
4747   if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
4748       && INTEGRAL_TYPE_P (TREE_TYPE (val)))
4749     {
4750       tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
4751       tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
4752
4753       if (comp_code == GT_EXPR
4754           && (!max
4755               || compare_values (val, max) == 0))
4756         return false;
4757
4758       if (comp_code == LT_EXPR
4759           && (!min
4760               || compare_values (val, min) == 0))
4761         return false;
4762     }
4763   *code_p = comp_code;
4764   *val_p = val;
4765   return true;
4766 }
4767
4768 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
4769    (otherwise return VAL).  VAL and MASK must be zero-extended for
4770    precision PREC.  If SGNBIT is non-zero, first xor VAL with SGNBIT
4771    (to transform signed values into unsigned) and at the end xor
4772    SGNBIT back.  */
4773
4774 static double_int
4775 masked_increment (double_int val, double_int mask, double_int sgnbit,
4776                   unsigned int prec)
4777 {
4778   double_int bit = double_int_one, res;
4779   unsigned int i;
4780
4781   val ^= sgnbit;
4782   for (i = 0; i < prec; i++, bit += bit)
4783     {
4784       res = mask;
4785       if ((res & bit).is_zero ())
4786         continue;
4787       res = bit - double_int_one;
4788       res = (val + bit).and_not (res);
4789       res &= mask;
4790       if (res.ugt (val))
4791         return res ^ sgnbit;
4792     }
4793   return val ^ sgnbit;
4794 }
4795
4796 /* Try to register an edge assertion for SSA name NAME on edge E for
4797    the condition COND contributing to the conditional jump pointed to by BSI.
4798    Invert the condition COND if INVERT is true.
4799    Return true if an assertion for NAME could be registered.  */
4800
4801 static bool
4802 register_edge_assert_for_2 (tree name, edge e, gimple_stmt_iterator bsi,
4803                             enum tree_code cond_code,
4804                             tree cond_op0, tree cond_op1, bool invert)
4805 {
4806   tree val;
4807   enum tree_code comp_code;
4808   bool retval = false;
4809
4810   if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
4811                                                 cond_op0,
4812                                                 cond_op1,
4813                                                 invert, &comp_code, &val))
4814     return false;
4815
4816   /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
4817      reachable from E.  */
4818   if (live_on_edge (e, name)
4819       && !has_single_use (name))
4820     {
4821       register_new_assert_for (name, name, comp_code, val, NULL, e, bsi);
4822       retval = true;
4823     }
4824
4825   /* In the case of NAME <= CST and NAME being defined as
4826      NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
4827      and NAME2 <= CST - CST2.  We can do the same for NAME > CST.
4828      This catches range and anti-range tests.  */
4829   if ((comp_code == LE_EXPR
4830        || comp_code == GT_EXPR)
4831       && TREE_CODE (val) == INTEGER_CST
4832       && TYPE_UNSIGNED (TREE_TYPE (val)))
4833     {
4834       gimple def_stmt = SSA_NAME_DEF_STMT (name);
4835       tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
4836
4837       /* Extract CST2 from the (optional) addition.  */
4838       if (is_gimple_assign (def_stmt)
4839           && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
4840         {
4841           name2 = gimple_assign_rhs1 (def_stmt);
4842           cst2 = gimple_assign_rhs2 (def_stmt);
4843           if (TREE_CODE (name2) == SSA_NAME
4844               && TREE_CODE (cst2) == INTEGER_CST)
4845             def_stmt = SSA_NAME_DEF_STMT (name2);
4846         }
4847
4848       /* Extract NAME2 from the (optional) sign-changing cast.  */
4849       if (gimple_assign_cast_p (def_stmt))
4850         {
4851           if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
4852               && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
4853               && (TYPE_PRECISION (gimple_expr_type (def_stmt))
4854                   == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
4855             name3 = gimple_assign_rhs1 (def_stmt);
4856         }
4857
4858       /* If name3 is used later, create an ASSERT_EXPR for it.  */
4859       if (name3 != NULL_TREE
4860           && TREE_CODE (name3) == SSA_NAME
4861           && (cst2 == NULL_TREE
4862               || TREE_CODE (cst2) == INTEGER_CST)
4863           && INTEGRAL_TYPE_P (TREE_TYPE (name3))
4864           && live_on_edge (e, name3)
4865           && !has_single_use (name3))
4866         {
4867           tree tmp;
4868
4869           /* Build an expression for the range test.  */
4870           tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
4871           if (cst2 != NULL_TREE)
4872             tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
4873
4874           if (dump_file)
4875             {
4876               fprintf (dump_file, "Adding assert for ");
4877               print_generic_expr (dump_file, name3, 0);
4878               fprintf (dump_file, " from ");
4879               print_generic_expr (dump_file, tmp, 0);
4880               fprintf (dump_file, "\n");
4881             }
4882
4883           register_new_assert_for (name3, tmp, comp_code, val, NULL, e, bsi);
4884
4885           retval = true;
4886         }
4887
4888       /* If name2 is used later, create an ASSERT_EXPR for it.  */
4889       if (name2 != NULL_TREE
4890           && TREE_CODE (name2) == SSA_NAME
4891           && TREE_CODE (cst2) == INTEGER_CST
4892           && INTEGRAL_TYPE_P (TREE_TYPE (name2))
4893           && live_on_edge (e, name2)
4894           && !has_single_use (name2))
4895         {
4896           tree tmp;
4897
4898           /* Build an expression for the range test.  */
4899           tmp = name2;
4900           if (TREE_TYPE (name) != TREE_TYPE (name2))
4901             tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
4902           if (cst2 != NULL_TREE)
4903             tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
4904
4905           if (dump_file)
4906             {
4907               fprintf (dump_file, "Adding assert for ");
4908               print_generic_expr (dump_file, name2, 0);
4909               fprintf (dump_file, " from ");
4910               print_generic_expr (dump_file, tmp, 0);
4911               fprintf (dump_file, "\n");
4912             }
4913
4914           register_new_assert_for (name2, tmp, comp_code, val, NULL, e, bsi);
4915
4916           retval = true;
4917         }
4918     }
4919
4920   /* In the case of post-in/decrement tests like if (i++) ... and uses
4921      of the in/decremented value on the edge the extra name we want to
4922      assert for is not on the def chain of the name compared.  Instead
4923      it is in the set of use stmts.  */
4924   if ((comp_code == NE_EXPR
4925        || comp_code == EQ_EXPR)
4926       && TREE_CODE (val) == INTEGER_CST)
4927     {
4928       imm_use_iterator ui;
4929       gimple use_stmt;
4930       FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
4931         {
4932           /* Cut off to use-stmts that are in the predecessor.  */
4933           if (gimple_bb (use_stmt) != e->src)
4934             continue;
4935
4936           if (!is_gimple_assign (use_stmt))
4937             continue;
4938
4939           enum tree_code code = gimple_assign_rhs_code (use_stmt);
4940           if (code != PLUS_EXPR
4941               && code != MINUS_EXPR)
4942             continue;
4943
4944           tree cst = gimple_assign_rhs2 (use_stmt);
4945           if (TREE_CODE (cst) != INTEGER_CST)
4946             continue;
4947
4948           tree name2 = gimple_assign_lhs (use_stmt);
4949           if (live_on_edge (e, name2))
4950             {
4951               cst = int_const_binop (code, val, cst);
4952               register_new_assert_for (name2, name2, comp_code, cst,
4953                                        NULL, e, bsi);
4954               retval = true;
4955             }
4956         }
4957     }
4958  
4959   if (TREE_CODE_CLASS (comp_code) == tcc_comparison
4960       && TREE_CODE (val) == INTEGER_CST)
4961     {
4962       gimple def_stmt = SSA_NAME_DEF_STMT (name);
4963       tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
4964       tree val2 = NULL_TREE;
4965       double_int mask = double_int_zero;
4966       unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
4967       unsigned int nprec = prec;
4968       enum tree_code rhs_code = ERROR_MARK;
4969
4970       if (is_gimple_assign (def_stmt))
4971         rhs_code = gimple_assign_rhs_code (def_stmt);
4972
4973       /* Add asserts for NAME cmp CST and NAME being defined
4974          as NAME = (int) NAME2.  */
4975       if (!TYPE_UNSIGNED (TREE_TYPE (val))
4976           && (comp_code == LE_EXPR || comp_code == LT_EXPR
4977               || comp_code == GT_EXPR || comp_code == GE_EXPR)
4978           && gimple_assign_cast_p (def_stmt))
4979         {
4980           name2 = gimple_assign_rhs1 (def_stmt);
4981           if (CONVERT_EXPR_CODE_P (rhs_code)
4982               && INTEGRAL_TYPE_P (TREE_TYPE (name2))
4983               && TYPE_UNSIGNED (TREE_TYPE (name2))
4984               && prec == TYPE_PRECISION (TREE_TYPE (name2))
4985               && (comp_code == LE_EXPR || comp_code == GT_EXPR
4986                   || !tree_int_cst_equal (val,
4987                                           TYPE_MIN_VALUE (TREE_TYPE (val))))
4988               && live_on_edge (e, name2)
4989               && !has_single_use (name2))
4990             {
4991               tree tmp, cst;
4992               enum tree_code new_comp_code = comp_code;
4993
4994               cst = fold_convert (TREE_TYPE (name2),
4995                                   TYPE_MIN_VALUE (TREE_TYPE (val)));
4996               /* Build an expression for the range test.  */
4997               tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
4998               cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
4999                                  fold_convert (TREE_TYPE (name2), val));
5000               if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5001                 {
5002                   new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5003                   cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5004                                      build_int_cst (TREE_TYPE (name2), 1));
5005                 }
5006
5007               if (dump_file)
5008                 {
5009                   fprintf (dump_file, "Adding assert for ");
5010                   print_generic_expr (dump_file, name2, 0);
5011                   fprintf (dump_file, " from ");
5012                   print_generic_expr (dump_file, tmp, 0);
5013                   fprintf (dump_file, "\n");
5014                 }
5015
5016               register_new_assert_for (name2, tmp, new_comp_code, cst, NULL,
5017                                        e, bsi);
5018
5019               retval = true;
5020             }
5021         }
5022
5023       /* Add asserts for NAME cmp CST and NAME being defined as
5024          NAME = NAME2 >> CST2.
5025
5026          Extract CST2 from the right shift.  */
5027       if (rhs_code == RSHIFT_EXPR)
5028         {
5029           name2 = gimple_assign_rhs1 (def_stmt);
5030           cst2 = gimple_assign_rhs2 (def_stmt);
5031           if (TREE_CODE (name2) == SSA_NAME
5032               && host_integerp (cst2, 1)
5033               && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5034               && IN_RANGE (tree_low_cst (cst2, 1), 1, prec - 1)
5035               && prec <= HOST_BITS_PER_DOUBLE_INT
5036               && prec == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (val)))
5037               && live_on_edge (e, name2)
5038               && !has_single_use (name2))
5039             {
5040               mask = double_int::mask (tree_low_cst (cst2, 1));
5041               val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5042             }
5043         }
5044       if (val2 != NULL_TREE
5045           && TREE_CODE (val2) == INTEGER_CST
5046           && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5047                                             TREE_TYPE (val),
5048                                             val2, cst2), val))
5049         {
5050           enum tree_code new_comp_code = comp_code;
5051           tree tmp, new_val;
5052
5053           tmp = name2;
5054           if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5055             {
5056               if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5057                 {
5058                   tree type = build_nonstandard_integer_type (prec, 1);
5059                   tmp = build1 (NOP_EXPR, type, name2);
5060                   val2 = fold_convert (type, val2);
5061                 }
5062               tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5063               new_val = double_int_to_tree (TREE_TYPE (tmp), mask);
5064               new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5065             }
5066           else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5067             {
5068               double_int minval
5069                 = double_int::min_value (prec, TYPE_UNSIGNED (TREE_TYPE (val)));
5070               new_val = val2;
5071               if (minval == tree_to_double_int (new_val))
5072                 new_val = NULL_TREE;
5073             }
5074           else
5075             {
5076               double_int maxval
5077                 = double_int::max_value (prec, TYPE_UNSIGNED (TREE_TYPE (val)));
5078               mask |= tree_to_double_int (val2);
5079               if (mask == maxval)
5080                 new_val = NULL_TREE;
5081               else
5082                 new_val = double_int_to_tree (TREE_TYPE (val2), mask);
5083             }
5084
5085           if (new_val)
5086             {
5087               if (dump_file)
5088                 {
5089                   fprintf (dump_file, "Adding assert for ");
5090                   print_generic_expr (dump_file, name2, 0);
5091                   fprintf (dump_file, " from ");
5092                   print_generic_expr (dump_file, tmp, 0);
5093                   fprintf (dump_file, "\n");
5094                 }
5095
5096               register_new_assert_for (name2, tmp, new_comp_code, new_val,
5097                                        NULL, e, bsi);
5098               retval = true;
5099             }
5100         }
5101
5102       /* Add asserts for NAME cmp CST and NAME being defined as
5103          NAME = NAME2 & CST2.
5104
5105          Extract CST2 from the and.
5106
5107          Also handle
5108          NAME = (unsigned) NAME2;
5109          casts where NAME's type is unsigned and has smaller precision
5110          than NAME2's type as if it was NAME = NAME2 & MASK.  */
5111       names[0] = NULL_TREE;
5112       names[1] = NULL_TREE;
5113       cst2 = NULL_TREE;
5114       if (rhs_code == BIT_AND_EXPR
5115           || (CONVERT_EXPR_CODE_P (rhs_code)
5116               && TREE_CODE (TREE_TYPE (val)) == INTEGER_TYPE
5117               && TYPE_UNSIGNED (TREE_TYPE (val))
5118               && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5119                  > prec
5120               && !retval))
5121         {
5122           name2 = gimple_assign_rhs1 (def_stmt);
5123           if (rhs_code == BIT_AND_EXPR)
5124             cst2 = gimple_assign_rhs2 (def_stmt);
5125           else
5126             {
5127               cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5128               nprec = TYPE_PRECISION (TREE_TYPE (name2));
5129             }
5130           if (TREE_CODE (name2) == SSA_NAME
5131               && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5132               && TREE_CODE (cst2) == INTEGER_CST
5133               && !integer_zerop (cst2)
5134               && nprec <= HOST_BITS_PER_DOUBLE_INT
5135               && (nprec > 1
5136                   || TYPE_UNSIGNED (TREE_TYPE (val))))
5137             {
5138               gimple def_stmt2 = SSA_NAME_DEF_STMT (name2);
5139               if (gimple_assign_cast_p (def_stmt2))
5140                 {
5141                   names[1] = gimple_assign_rhs1 (def_stmt2);
5142                   if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5143                       || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5144                       || (TYPE_PRECISION (TREE_TYPE (name2))
5145                           != TYPE_PRECISION (TREE_TYPE (names[1])))
5146                       || !live_on_edge (e, names[1])
5147                       || has_single_use (names[1]))
5148                     names[1] = NULL_TREE;
5149                 }
5150               if (live_on_edge (e, name2)
5151                   && !has_single_use (name2))
5152                 names[0] = name2;
5153             }
5154         }
5155       if (names[0] || names[1])
5156         {
5157           double_int minv, maxv = double_int_zero, valv, cst2v;
5158           double_int tem, sgnbit;
5159           bool valid_p = false, valn = false, cst2n = false;
5160           enum tree_code ccode = comp_code;
5161
5162           valv = tree_to_double_int (val).zext (nprec);
5163           cst2v = tree_to_double_int (cst2).zext (nprec);
5164           if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5165             {
5166               valn = valv.sext (nprec).is_negative ();
5167               cst2n = cst2v.sext (nprec).is_negative ();
5168             }
5169           /* If CST2 doesn't have most significant bit set,
5170              but VAL is negative, we have comparison like
5171              if ((x & 0x123) > -4) (always true).  Just give up.  */
5172           if (!cst2n && valn)
5173             ccode = ERROR_MARK;
5174           if (cst2n)
5175             sgnbit = double_int_one.llshift (nprec - 1, nprec).zext (nprec);
5176           else
5177             sgnbit = double_int_zero;
5178           minv = valv & cst2v;
5179           switch (ccode)
5180             {
5181             case EQ_EXPR:
5182               /* Minimum unsigned value for equality is VAL & CST2
5183                  (should be equal to VAL, otherwise we probably should
5184                  have folded the comparison into false) and
5185                  maximum unsigned value is VAL | ~CST2.  */
5186               maxv = valv | ~cst2v;
5187               maxv = maxv.zext (nprec);
5188               valid_p = true;
5189               break;
5190             case NE_EXPR:
5191               tem = valv | ~cst2v;
5192               tem = tem.zext (nprec);
5193               /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U.  */
5194               if (valv.is_zero ())
5195                 {
5196                   cst2n = false;
5197                   sgnbit = double_int_zero;
5198                   goto gt_expr;
5199                 }
5200               /* If (VAL | ~CST2) is all ones, handle it as
5201                  (X & CST2) < VAL.  */
5202               if (tem == double_int::mask (nprec))
5203                 {
5204                   cst2n = false;
5205                   valn = false;
5206                   sgnbit = double_int_zero;
5207                   goto lt_expr;
5208                 }
5209               if (!cst2n
5210                   && cst2v.sext (nprec).is_negative ())
5211                 sgnbit
5212                   = double_int_one.llshift (nprec - 1, nprec).zext (nprec);
5213               if (!sgnbit.is_zero ())
5214                 {
5215                   if (valv == sgnbit)
5216                     {
5217                       cst2n = true;
5218                       valn = true;
5219                       goto gt_expr;
5220                     }
5221                   if (tem == double_int::mask (nprec - 1))
5222                     {
5223                       cst2n = true;
5224                       goto lt_expr;
5225                     }
5226                   if (!cst2n)
5227                     sgnbit = double_int_zero;
5228                 }
5229               break;
5230             case GE_EXPR:
5231               /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5232                  is VAL and maximum unsigned value is ~0.  For signed
5233                  comparison, if CST2 doesn't have most significant bit
5234                  set, handle it similarly.  If CST2 has MSB set,
5235                  the minimum is the same, and maximum is ~0U/2.  */
5236               if (minv != valv)
5237                 {
5238                   /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5239                      VAL.  */
5240                   minv = masked_increment (valv, cst2v, sgnbit, nprec);
5241                   if (minv == valv)
5242                     break;
5243                 }
5244               maxv = double_int::mask (nprec - (cst2n ? 1 : 0));
5245               valid_p = true;
5246               break;
5247             case GT_EXPR:
5248             gt_expr:
5249               /* Find out smallest MINV where MINV > VAL
5250                  && (MINV & CST2) == MINV, if any.  If VAL is signed and
5251                  CST2 has MSB set, compute it biased by 1 << (nprec - 1).  */
5252               minv = masked_increment (valv, cst2v, sgnbit, nprec);
5253               if (minv == valv)
5254                 break;
5255               maxv = double_int::mask (nprec - (cst2n ? 1 : 0));
5256               valid_p = true;
5257               break;
5258             case LE_EXPR:
5259               /* Minimum unsigned value for <= is 0 and maximum
5260                  unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5261                  Otherwise, find smallest VAL2 where VAL2 > VAL
5262                  && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5263                  as maximum.
5264                  For signed comparison, if CST2 doesn't have most
5265                  significant bit set, handle it similarly.  If CST2 has
5266                  MSB set, the maximum is the same and minimum is INT_MIN.  */
5267               if (minv == valv)
5268                 maxv = valv;
5269               else
5270                 {
5271                   maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5272                   if (maxv == valv)
5273                     break;
5274                   maxv -= double_int_one;
5275                 }
5276               maxv |= ~cst2v;
5277               maxv = maxv.zext (nprec);
5278               minv = sgnbit;
5279               valid_p = true;
5280               break;
5281             case LT_EXPR:
5282             lt_expr:
5283               /* Minimum unsigned value for < is 0 and maximum
5284                  unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5285                  Otherwise, find smallest VAL2 where VAL2 > VAL
5286                  && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5287                  as maximum.
5288                  For signed comparison, if CST2 doesn't have most
5289                  significant bit set, handle it similarly.  If CST2 has
5290                  MSB set, the maximum is the same and minimum is INT_MIN.  */
5291               if (minv == valv)
5292                 {
5293                   if (valv == sgnbit)
5294                     break;
5295                   maxv = valv;
5296                 }
5297               else
5298                 {
5299                   maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5300                   if (maxv == valv)
5301                     break;
5302                 }
5303               maxv -= double_int_one;
5304               maxv |= ~cst2v;
5305               maxv = maxv.zext (nprec);
5306               minv = sgnbit;
5307               valid_p = true;
5308               break;
5309             default:
5310               break;
5311             }
5312           if (valid_p
5313               && (maxv - minv).zext (nprec) != double_int::mask (nprec))
5314             {
5315               tree tmp, new_val, type;
5316               int i;
5317
5318               for (i = 0; i < 2; i++)
5319                 if (names[i])
5320                   {
5321                     double_int maxv2 = maxv;
5322                     tmp = names[i];
5323                     type = TREE_TYPE (names[i]);
5324                     if (!TYPE_UNSIGNED (type))
5325                       {
5326                         type = build_nonstandard_integer_type (nprec, 1);
5327                         tmp = build1 (NOP_EXPR, type, names[i]);
5328                       }
5329                     if (!minv.is_zero ())
5330                       {
5331                         tmp = build2 (PLUS_EXPR, type, tmp,
5332                                       double_int_to_tree (type, -minv));
5333                         maxv2 = maxv - minv;
5334                       }
5335                     new_val = double_int_to_tree (type, maxv2);
5336
5337                     if (dump_file)
5338                       {
5339                         fprintf (dump_file, "Adding assert for ");
5340                         print_generic_expr (dump_file, names[i], 0);
5341                         fprintf (dump_file, " from ");
5342                         print_generic_expr (dump_file, tmp, 0);
5343                         fprintf (dump_file, "\n");
5344                       }
5345
5346                     register_new_assert_for (names[i], tmp, LE_EXPR,
5347                                              new_val, NULL, e, bsi);
5348                     retval = true;
5349                   }
5350             }
5351         }
5352     }
5353
5354   return retval;
5355 }
5356
5357 /* OP is an operand of a truth value expression which is known to have
5358    a particular value.  Register any asserts for OP and for any
5359    operands in OP's defining statement.
5360
5361    If CODE is EQ_EXPR, then we want to register OP is zero (false),
5362    if CODE is NE_EXPR, then we want to register OP is nonzero (true).   */
5363
5364 static bool
5365 register_edge_assert_for_1 (tree op, enum tree_code code,
5366                             edge e, gimple_stmt_iterator bsi)
5367 {
5368   bool retval = false;
5369   gimple op_def;
5370   tree val;
5371   enum tree_code rhs_code;
5372
5373   /* We only care about SSA_NAMEs.  */
5374   if (TREE_CODE (op) != SSA_NAME)
5375     return false;
5376
5377   /* We know that OP will have a zero or nonzero value.  If OP is used
5378      more than once go ahead and register an assert for OP.
5379
5380      The FOUND_IN_SUBGRAPH support is not helpful in this situation as
5381      it will always be set for OP (because OP is used in a COND_EXPR in
5382      the subgraph).  */
5383   if (!has_single_use (op))
5384     {
5385       val = build_int_cst (TREE_TYPE (op), 0);
5386       register_new_assert_for (op, op, code, val, NULL, e, bsi);
5387       retval = true;
5388     }
5389
5390   /* Now look at how OP is set.  If it's set from a comparison,
5391      a truth operation or some bit operations, then we may be able
5392      to register information about the operands of that assignment.  */
5393   op_def = SSA_NAME_DEF_STMT (op);
5394   if (gimple_code (op_def) != GIMPLE_ASSIGN)
5395     return retval;
5396
5397   rhs_code = gimple_assign_rhs_code (op_def);
5398
5399   if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5400     {
5401       bool invert = (code == EQ_EXPR ? true : false);
5402       tree op0 = gimple_assign_rhs1 (op_def);
5403       tree op1 = gimple_assign_rhs2 (op_def);
5404
5405       if (TREE_CODE (op0) == SSA_NAME)
5406         retval |= register_edge_assert_for_2 (op0, e, bsi, rhs_code, op0, op1,
5407                                               invert);
5408       if (TREE_CODE (op1) == SSA_NAME)
5409         retval |= register_edge_assert_for_2 (op1, e, bsi, rhs_code, op0, op1,
5410                                               invert);
5411     }
5412   else if ((code == NE_EXPR
5413             && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5414            || (code == EQ_EXPR
5415                && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5416     {
5417       /* Recurse on each operand.  */
5418       tree op0 = gimple_assign_rhs1 (op_def);
5419       tree op1 = gimple_assign_rhs2 (op_def);
5420       if (TREE_CODE (op0) == SSA_NAME
5421           && has_single_use (op0))
5422         retval |= register_edge_assert_for_1 (op0, code, e, bsi);
5423       if (TREE_CODE (op1) == SSA_NAME
5424           && has_single_use (op1))
5425         retval |= register_edge_assert_for_1 (op1, code, e, bsi);
5426     }
5427   else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5428            && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5429     {
5430       /* Recurse, flipping CODE.  */
5431       code = invert_tree_comparison (code, false);
5432       retval |= register_edge_assert_for_1 (gimple_assign_rhs1 (op_def),
5433                                             code, e, bsi);
5434     }
5435   else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5436     {
5437       /* Recurse through the copy.  */
5438       retval |= register_edge_assert_for_1 (gimple_assign_rhs1 (op_def),
5439                                             code, e, bsi);
5440     }
5441   else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5442     {
5443       /* Recurse through the type conversion.  */
5444       retval |= register_edge_assert_for_1 (gimple_assign_rhs1 (op_def),
5445                                             code, e, bsi);
5446     }
5447
5448   return retval;
5449 }
5450
5451 /* Try to register an edge assertion for SSA name NAME on edge E for
5452    the condition COND contributing to the conditional jump pointed to by SI.
5453    Return true if an assertion for NAME could be registered.  */
5454
5455 static bool
5456 register_edge_assert_for (tree name, edge e, gimple_stmt_iterator si,
5457                           enum tree_code cond_code, tree cond_op0,
5458                           tree cond_op1)
5459 {
5460   tree val;
5461   enum tree_code comp_code;
5462   bool retval = false;
5463   bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5464
5465   /* Do not attempt to infer anything in names that flow through
5466      abnormal edges.  */
5467   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5468     return false;
5469
5470   if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5471                                                 cond_op0, cond_op1,
5472                                                 is_else_edge,
5473                                                 &comp_code, &val))
5474     return false;
5475
5476   /* Register ASSERT_EXPRs for name.  */
5477   retval |= register_edge_assert_for_2 (name, e, si, cond_code, cond_op0,
5478                                         cond_op1, is_else_edge);
5479
5480
5481   /* If COND is effectively an equality test of an SSA_NAME against
5482      the value zero or one, then we may be able to assert values
5483      for SSA_NAMEs which flow into COND.  */
5484
5485   /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5486      statement of NAME we can assert both operands of the BIT_AND_EXPR
5487      have nonzero value.  */
5488   if (((comp_code == EQ_EXPR && integer_onep (val))
5489        || (comp_code == NE_EXPR && integer_zerop (val))))
5490     {
5491       gimple def_stmt = SSA_NAME_DEF_STMT (name);
5492
5493       if (is_gimple_assign (def_stmt)
5494           && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5495         {
5496           tree op0 = gimple_assign_rhs1 (def_stmt);
5497           tree op1 = gimple_assign_rhs2 (def_stmt);
5498           retval |= register_edge_assert_for_1 (op0, NE_EXPR, e, si);
5499           retval |= register_edge_assert_for_1 (op1, NE_EXPR, e, si);
5500         }
5501     }
5502
5503   /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5504      statement of NAME we can assert both operands of the BIT_IOR_EXPR
5505      have zero value.  */
5506   if (((comp_code == EQ_EXPR && integer_zerop (val))
5507        || (comp_code == NE_EXPR && integer_onep (val))))
5508     {
5509       gimple def_stmt = SSA_NAME_DEF_STMT (name);
5510
5511       /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5512          necessarily zero value, or if type-precision is one.  */
5513       if (is_gimple_assign (def_stmt)
5514           && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5515               && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5516                   || comp_code == EQ_EXPR)))
5517         {
5518           tree op0 = gimple_assign_rhs1 (def_stmt);
5519           tree op1 = gimple_assign_rhs2 (def_stmt);
5520           retval |= register_edge_assert_for_1 (op0, EQ_EXPR, e, si);
5521           retval |= register_edge_assert_for_1 (op1, EQ_EXPR, e, si);
5522         }
5523     }
5524
5525   return retval;
5526 }
5527
5528
5529 /* Determine whether the outgoing edges of BB should receive an
5530    ASSERT_EXPR for each of the operands of BB's LAST statement.
5531    The last statement of BB must be a COND_EXPR.
5532
5533    If any of the sub-graphs rooted at BB have an interesting use of
5534    the predicate operands, an assert location node is added to the
5535    list of assertions for the corresponding operands.  */
5536
5537 static bool
5538 find_conditional_asserts (basic_block bb, gimple last)
5539 {
5540   bool need_assert;
5541   gimple_stmt_iterator bsi;
5542   tree op;
5543   edge_iterator ei;
5544   edge e;
5545   ssa_op_iter iter;
5546
5547   need_assert = false;
5548   bsi = gsi_for_stmt (last);
5549
5550   /* Look for uses of the operands in each of the sub-graphs
5551      rooted at BB.  We need to check each of the outgoing edges
5552      separately, so that we know what kind of ASSERT_EXPR to
5553      insert.  */
5554   FOR_EACH_EDGE (e, ei, bb->succs)
5555     {
5556       if (e->dest == bb)
5557         continue;
5558
5559       /* Register the necessary assertions for each operand in the
5560          conditional predicate.  */
5561       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5562         {
5563           need_assert |= register_edge_assert_for (op, e, bsi,
5564                                                    gimple_cond_code (last),
5565                                                    gimple_cond_lhs (last),
5566                                                    gimple_cond_rhs (last));
5567         }
5568     }
5569
5570   return need_assert;
5571 }
5572
5573 struct case_info
5574 {
5575   tree expr;
5576   basic_block bb;
5577 };
5578
5579 /* Compare two case labels sorting first by the destination bb index
5580    and then by the case value.  */
5581
5582 static int
5583 compare_case_labels (const void *p1, const void *p2)
5584 {
5585   const struct case_info *ci1 = (const struct case_info *) p1;
5586   const struct case_info *ci2 = (const struct case_info *) p2;
5587   int idx1 = ci1->bb->index;
5588   int idx2 = ci2->bb->index;
5589
5590   if (idx1 < idx2)
5591     return -1;
5592   else if (idx1 == idx2)
5593     {
5594       /* Make sure the default label is first in a group.  */
5595       if (!CASE_LOW (ci1->expr))
5596         return -1;
5597       else if (!CASE_LOW (ci2->expr))
5598         return 1;
5599       else
5600         return tree_int_cst_compare (CASE_LOW (ci1->expr),
5601                                      CASE_LOW (ci2->expr));
5602     }
5603   else
5604     return 1;
5605 }
5606
5607 /* Determine whether the outgoing edges of BB should receive an
5608    ASSERT_EXPR for each of the operands of BB's LAST statement.
5609    The last statement of BB must be a SWITCH_EXPR.
5610
5611    If any of the sub-graphs rooted at BB have an interesting use of
5612    the predicate operands, an assert location node is added to the
5613    list of assertions for the corresponding operands.  */
5614
5615 static bool
5616 find_switch_asserts (basic_block bb, gimple last)
5617 {
5618   bool need_assert;
5619   gimple_stmt_iterator bsi;
5620   tree op;
5621   edge e;
5622   struct case_info *ci;
5623   size_t n = gimple_switch_num_labels (last);
5624 #if GCC_VERSION >= 4000
5625   unsigned int idx;
5626 #else
5627   /* Work around GCC 3.4 bug (PR 37086).  */
5628   volatile unsigned int idx;
5629 #endif
5630
5631   need_assert = false;
5632   bsi = gsi_for_stmt (last);
5633   op = gimple_switch_index (last);
5634   if (TREE_CODE (op) != SSA_NAME)
5635     return false;
5636
5637   /* Build a vector of case labels sorted by destination label.  */
5638   ci = XNEWVEC (struct case_info, n);
5639   for (idx = 0; idx < n; ++idx)
5640     {
5641       ci[idx].expr = gimple_switch_label (last, idx);
5642       ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
5643     }
5644   qsort (ci, n, sizeof (struct case_info), compare_case_labels);
5645
5646   for (idx = 0; idx < n; ++idx)
5647     {
5648       tree min, max;
5649       tree cl = ci[idx].expr;
5650       basic_block cbb = ci[idx].bb;
5651
5652       min = CASE_LOW (cl);
5653       max = CASE_HIGH (cl);
5654
5655       /* If there are multiple case labels with the same destination
5656          we need to combine them to a single value range for the edge.  */
5657       if (idx + 1 < n && cbb == ci[idx + 1].bb)
5658         {
5659           /* Skip labels until the last of the group.  */
5660           do {
5661             ++idx;
5662           } while (idx < n && cbb == ci[idx].bb);
5663           --idx;
5664
5665           /* Pick up the maximum of the case label range.  */
5666           if (CASE_HIGH (ci[idx].expr))
5667             max = CASE_HIGH (ci[idx].expr);
5668           else
5669             max = CASE_LOW (ci[idx].expr);
5670         }
5671
5672       /* Nothing to do if the range includes the default label until we
5673          can register anti-ranges.  */
5674       if (min == NULL_TREE)
5675         continue;
5676
5677       /* Find the edge to register the assert expr on.  */
5678       e = find_edge (bb, cbb);
5679
5680       /* Register the necessary assertions for the operand in the
5681          SWITCH_EXPR.  */
5682       need_assert |= register_edge_assert_for (op, e, bsi,
5683                                                max ? GE_EXPR : EQ_EXPR,
5684                                                op,
5685                                                fold_convert (TREE_TYPE (op),
5686                                                              min));
5687       if (max)
5688         {
5689           need_assert |= register_edge_assert_for (op, e, bsi, LE_EXPR,
5690                                                    op,
5691                                                    fold_convert (TREE_TYPE (op),
5692                                                                  max));
5693         }
5694     }
5695
5696   XDELETEVEC (ci);
5697   return need_assert;
5698 }
5699
5700
5701 /* Traverse all the statements in block BB looking for statements that
5702    may generate useful assertions for the SSA names in their operand.
5703    If a statement produces a useful assertion A for name N_i, then the
5704    list of assertions already generated for N_i is scanned to
5705    determine if A is actually needed.
5706
5707    If N_i already had the assertion A at a location dominating the
5708    current location, then nothing needs to be done.  Otherwise, the
5709    new location for A is recorded instead.
5710
5711    1- For every statement S in BB, all the variables used by S are
5712       added to bitmap FOUND_IN_SUBGRAPH.
5713
5714    2- If statement S uses an operand N in a way that exposes a known
5715       value range for N, then if N was not already generated by an
5716       ASSERT_EXPR, create a new assert location for N.  For instance,
5717       if N is a pointer and the statement dereferences it, we can
5718       assume that N is not NULL.
5719
5720    3- COND_EXPRs are a special case of #2.  We can derive range
5721       information from the predicate but need to insert different
5722       ASSERT_EXPRs for each of the sub-graphs rooted at the
5723       conditional block.  If the last statement of BB is a conditional
5724       expression of the form 'X op Y', then
5725
5726       a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
5727
5728       b) If the conditional is the only entry point to the sub-graph
5729          corresponding to the THEN_CLAUSE, recurse into it.  On
5730          return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
5731          an ASSERT_EXPR is added for the corresponding variable.
5732
5733       c) Repeat step (b) on the ELSE_CLAUSE.
5734
5735       d) Mark X and Y in FOUND_IN_SUBGRAPH.
5736
5737       For instance,
5738
5739             if (a == 9)
5740               b = a;
5741             else
5742               b = c + 1;
5743
5744       In this case, an assertion on the THEN clause is useful to
5745       determine that 'a' is always 9 on that edge.  However, an assertion
5746       on the ELSE clause would be unnecessary.
5747
5748    4- If BB does not end in a conditional expression, then we recurse
5749       into BB's dominator children.
5750
5751    At the end of the recursive traversal, every SSA name will have a
5752    list of locations where ASSERT_EXPRs should be added.  When a new
5753    location for name N is found, it is registered by calling
5754    register_new_assert_for.  That function keeps track of all the
5755    registered assertions to prevent adding unnecessary assertions.
5756    For instance, if a pointer P_4 is dereferenced more than once in a
5757    dominator tree, only the location dominating all the dereference of
5758    P_4 will receive an ASSERT_EXPR.
5759
5760    If this function returns true, then it means that there are names
5761    for which we need to generate ASSERT_EXPRs.  Those assertions are
5762    inserted by process_assert_insertions.  */
5763
5764 static bool
5765 find_assert_locations_1 (basic_block bb, sbitmap live)
5766 {
5767   gimple_stmt_iterator si;
5768   gimple last;
5769   bool need_assert;
5770
5771   need_assert = false;
5772   last = last_stmt (bb);
5773
5774   /* If BB's last statement is a conditional statement involving integer
5775      operands, determine if we need to add ASSERT_EXPRs.  */
5776   if (last
5777       && gimple_code (last) == GIMPLE_COND
5778       && !fp_predicate (last)
5779       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
5780     need_assert |= find_conditional_asserts (bb, last);
5781
5782   /* If BB's last statement is a switch statement involving integer
5783      operands, determine if we need to add ASSERT_EXPRs.  */
5784   if (last
5785       && gimple_code (last) == GIMPLE_SWITCH
5786       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
5787     need_assert |= find_switch_asserts (bb, last);
5788
5789   /* Traverse all the statements in BB marking used names and looking
5790      for statements that may infer assertions for their used operands.  */
5791   for (si = gsi_last_bb (bb); !gsi_end_p (si); gsi_prev (&si))
5792     {
5793       gimple stmt;
5794       tree op;
5795       ssa_op_iter i;
5796
5797       stmt = gsi_stmt (si);
5798
5799       if (is_gimple_debug (stmt))
5800         continue;
5801
5802       /* See if we can derive an assertion for any of STMT's operands.  */
5803       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
5804         {
5805           tree value;
5806           enum tree_code comp_code;
5807
5808           /* If op is not live beyond this stmt, do not bother to insert
5809              asserts for it.  */
5810           if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
5811             continue;
5812
5813           /* If OP is used in such a way that we can infer a value
5814              range for it, and we don't find a previous assertion for
5815              it, create a new assertion location node for OP.  */
5816           if (infer_value_range (stmt, op, &comp_code, &value))
5817             {
5818               /* If we are able to infer a nonzero value range for OP,
5819                  then walk backwards through the use-def chain to see if OP
5820                  was set via a typecast.
5821
5822                  If so, then we can also infer a nonzero value range
5823                  for the operand of the NOP_EXPR.  */
5824               if (comp_code == NE_EXPR && integer_zerop (value))
5825                 {
5826                   tree t = op;
5827                   gimple def_stmt = SSA_NAME_DEF_STMT (t);
5828
5829                   while (is_gimple_assign (def_stmt)
5830                          && gimple_assign_rhs_code (def_stmt)  == NOP_EXPR
5831                          && TREE_CODE
5832                              (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
5833                          && POINTER_TYPE_P
5834                              (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
5835                     {
5836                       t = gimple_assign_rhs1 (def_stmt);
5837                       def_stmt = SSA_NAME_DEF_STMT (t);
5838
5839                       /* Note we want to register the assert for the
5840                          operand of the NOP_EXPR after SI, not after the
5841                          conversion.  */
5842                       if (! has_single_use (t))
5843                         {
5844                           register_new_assert_for (t, t, comp_code, value,
5845                                                    bb, NULL, si);
5846                           need_assert = true;
5847                         }
5848                     }
5849                 }
5850
5851               register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
5852               need_assert = true;
5853             }
5854         }
5855
5856       /* Update live.  */
5857       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
5858         bitmap_set_bit (live, SSA_NAME_VERSION (op));
5859       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
5860         bitmap_clear_bit (live, SSA_NAME_VERSION (op));
5861     }
5862
5863   /* Traverse all PHI nodes in BB, updating live.  */
5864   for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
5865     {
5866       use_operand_p arg_p;
5867       ssa_op_iter i;
5868       gimple phi = gsi_stmt (si);
5869       tree res = gimple_phi_result (phi);
5870
5871       if (virtual_operand_p (res))
5872         continue;
5873
5874       FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
5875         {
5876           tree arg = USE_FROM_PTR (arg_p);
5877           if (TREE_CODE (arg) == SSA_NAME)
5878             bitmap_set_bit (live, SSA_NAME_VERSION (arg));
5879         }
5880
5881       bitmap_clear_bit (live, SSA_NAME_VERSION (res));
5882     }
5883
5884   return need_assert;
5885 }
5886
5887 /* Do an RPO walk over the function computing SSA name liveness
5888    on-the-fly and deciding on assert expressions to insert.
5889    Returns true if there are assert expressions to be inserted.  */
5890
5891 static bool
5892 find_assert_locations (void)
5893 {
5894   int *rpo = XNEWVEC (int, last_basic_block);
5895   int *bb_rpo = XNEWVEC (int, last_basic_block);
5896   int *last_rpo = XCNEWVEC (int, last_basic_block);
5897   int rpo_cnt, i;
5898   bool need_asserts;
5899
5900   live = XCNEWVEC (sbitmap, last_basic_block);
5901   rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
5902   for (i = 0; i < rpo_cnt; ++i)
5903     bb_rpo[rpo[i]] = i;
5904
5905   need_asserts = false;
5906   for (i = rpo_cnt - 1; i >= 0; --i)
5907     {
5908       basic_block bb = BASIC_BLOCK (rpo[i]);
5909       edge e;
5910       edge_iterator ei;
5911
5912       if (!live[rpo[i]])
5913         {
5914           live[rpo[i]] = sbitmap_alloc (num_ssa_names);
5915           bitmap_clear (live[rpo[i]]);
5916         }
5917
5918       /* Process BB and update the live information with uses in
5919          this block.  */
5920       need_asserts |= find_assert_locations_1 (bb, live[rpo[i]]);
5921
5922       /* Merge liveness into the predecessor blocks and free it.  */
5923       if (!bitmap_empty_p (live[rpo[i]]))
5924         {
5925           int pred_rpo = i;
5926           FOR_EACH_EDGE (e, ei, bb->preds)
5927             {
5928               int pred = e->src->index;
5929               if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
5930                 continue;
5931
5932               if (!live[pred])
5933                 {
5934                   live[pred] = sbitmap_alloc (num_ssa_names);
5935                   bitmap_clear (live[pred]);
5936                 }
5937               bitmap_ior (live[pred], live[pred], live[rpo[i]]);
5938
5939               if (bb_rpo[pred] < pred_rpo)
5940                 pred_rpo = bb_rpo[pred];
5941             }
5942
5943           /* Record the RPO number of the last visited block that needs
5944              live information from this block.  */
5945           last_rpo[rpo[i]] = pred_rpo;
5946         }
5947       else
5948         {
5949           sbitmap_free (live[rpo[i]]);
5950           live[rpo[i]] = NULL;
5951         }
5952
5953       /* We can free all successors live bitmaps if all their
5954          predecessors have been visited already.  */
5955       FOR_EACH_EDGE (e, ei, bb->succs)
5956         if (last_rpo[e->dest->index] == i
5957             && live[e->dest->index])
5958           {
5959             sbitmap_free (live[e->dest->index]);
5960             live[e->dest->index] = NULL;
5961           }
5962     }
5963
5964   XDELETEVEC (rpo);
5965   XDELETEVEC (bb_rpo);
5966   XDELETEVEC (last_rpo);
5967   for (i = 0; i < last_basic_block; ++i)
5968     if (live[i])
5969       sbitmap_free (live[i]);
5970   XDELETEVEC (live);
5971
5972   return need_asserts;
5973 }
5974
5975 /* Create an ASSERT_EXPR for NAME and insert it in the location
5976    indicated by LOC.  Return true if we made any edge insertions.  */
5977
5978 static bool
5979 process_assert_insertions_for (tree name, assert_locus_t loc)
5980 {
5981   /* Build the comparison expression NAME_i COMP_CODE VAL.  */
5982   gimple stmt;
5983   tree cond;
5984   gimple assert_stmt;
5985   edge_iterator ei;
5986   edge e;
5987
5988   /* If we have X <=> X do not insert an assert expr for that.  */
5989   if (loc->expr == loc->val)
5990     return false;
5991
5992   cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
5993   assert_stmt = build_assert_expr_for (cond, name);
5994   if (loc->e)
5995     {
5996       /* We have been asked to insert the assertion on an edge.  This
5997          is used only by COND_EXPR and SWITCH_EXPR assertions.  */
5998       gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
5999                            || (gimple_code (gsi_stmt (loc->si))
6000                                == GIMPLE_SWITCH));
6001
6002       gsi_insert_on_edge (loc->e, assert_stmt);
6003       return true;
6004     }
6005
6006   /* Otherwise, we can insert right after LOC->SI iff the
6007      statement must not be the last statement in the block.  */
6008   stmt = gsi_stmt (loc->si);
6009   if (!stmt_ends_bb_p (stmt))
6010     {
6011       gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6012       return false;
6013     }
6014
6015   /* If STMT must be the last statement in BB, we can only insert new
6016      assertions on the non-abnormal edge out of BB.  Note that since
6017      STMT is not control flow, there may only be one non-abnormal edge
6018      out of BB.  */
6019   FOR_EACH_EDGE (e, ei, loc->bb->succs)
6020     if (!(e->flags & EDGE_ABNORMAL))
6021       {
6022         gsi_insert_on_edge (e, assert_stmt);
6023         return true;
6024       }
6025
6026   gcc_unreachable ();
6027 }
6028
6029
6030 /* Process all the insertions registered for every name N_i registered
6031    in NEED_ASSERT_FOR.  The list of assertions to be inserted are
6032    found in ASSERTS_FOR[i].  */
6033
6034 static void
6035 process_assert_insertions (void)
6036 {
6037   unsigned i;
6038   bitmap_iterator bi;
6039   bool update_edges_p = false;
6040   int num_asserts = 0;
6041
6042   if (dump_file && (dump_flags & TDF_DETAILS))
6043     dump_all_asserts (dump_file);
6044
6045   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6046     {
6047       assert_locus_t loc = asserts_for[i];
6048       gcc_assert (loc);
6049
6050       while (loc)
6051         {
6052           assert_locus_t next = loc->next;
6053           update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6054           free (loc);
6055           loc = next;
6056           num_asserts++;
6057         }
6058     }
6059
6060   if (update_edges_p)
6061     gsi_commit_edge_inserts ();
6062
6063   statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6064                             num_asserts);
6065 }
6066
6067
6068 /* Traverse the flowgraph looking for conditional jumps to insert range
6069    expressions.  These range expressions are meant to provide information
6070    to optimizations that need to reason in terms of value ranges.  They
6071    will not be expanded into RTL.  For instance, given:
6072
6073    x = ...
6074    y = ...
6075    if (x < y)
6076      y = x - 2;
6077    else
6078      x = y + 3;
6079
6080    this pass will transform the code into:
6081
6082    x = ...
6083    y = ...
6084    if (x < y)
6085     {
6086       x = ASSERT_EXPR <x, x < y>
6087       y = x - 2
6088     }
6089    else
6090     {
6091       y = ASSERT_EXPR <y, x <= y>
6092       x = y + 3
6093     }
6094
6095    The idea is that once copy and constant propagation have run, other
6096    optimizations will be able to determine what ranges of values can 'x'
6097    take in different paths of the code, simply by checking the reaching
6098    definition of 'x'.  */
6099
6100 static void
6101 insert_range_assertions (void)
6102 {
6103   need_assert_for = BITMAP_ALLOC (NULL);
6104   asserts_for = XCNEWVEC (assert_locus_t, num_ssa_names);
6105
6106   calculate_dominance_info (CDI_DOMINATORS);
6107
6108   if (find_assert_locations ())
6109     {
6110       process_assert_insertions ();
6111       update_ssa (TODO_update_ssa_no_phi);
6112     }
6113
6114   if (dump_file && (dump_flags & TDF_DETAILS))
6115     {
6116       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6117       dump_function_to_file (current_function_decl, dump_file, dump_flags);
6118     }
6119
6120   free (asserts_for);
6121   BITMAP_FREE (need_assert_for);
6122 }
6123
6124 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6125    and "struct" hacks. If VRP can determine that the
6126    array subscript is a constant, check if it is outside valid
6127    range. If the array subscript is a RANGE, warn if it is
6128    non-overlapping with valid range.
6129    IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR.  */
6130
6131 static void
6132 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6133 {
6134   value_range_t* vr = NULL;
6135   tree low_sub, up_sub;
6136   tree low_bound, up_bound, up_bound_p1;
6137   tree base;
6138
6139   if (TREE_NO_WARNING (ref))
6140     return;
6141
6142   low_sub = up_sub = TREE_OPERAND (ref, 1);
6143   up_bound = array_ref_up_bound (ref);
6144
6145   /* Can not check flexible arrays.  */
6146   if (!up_bound
6147       || TREE_CODE (up_bound) != INTEGER_CST)
6148     return;
6149
6150   /* Accesses to trailing arrays via pointers may access storage
6151      beyond the types array bounds.  */
6152   base = get_base_address (ref);
6153   if (base && TREE_CODE (base) == MEM_REF)
6154     {
6155       tree cref, next = NULL_TREE;
6156
6157       if (TREE_CODE (TREE_OPERAND (ref, 0)) != COMPONENT_REF)
6158         return;
6159
6160       cref = TREE_OPERAND (ref, 0);
6161       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (cref, 0))) == RECORD_TYPE)
6162         for (next = DECL_CHAIN (TREE_OPERAND (cref, 1));
6163              next && TREE_CODE (next) != FIELD_DECL;
6164              next = DECL_CHAIN (next))
6165           ;
6166
6167       /* If this is the last field in a struct type or a field in a
6168          union type do not warn.  */
6169       if (!next)
6170         return;
6171     }
6172
6173   low_bound = array_ref_low_bound (ref);
6174   up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound, integer_one_node);
6175
6176   if (TREE_CODE (low_sub) == SSA_NAME)
6177     {
6178       vr = get_value_range (low_sub);
6179       if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6180         {
6181           low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6182           up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6183         }
6184     }
6185
6186   if (vr && vr->type == VR_ANTI_RANGE)
6187     {
6188       if (TREE_CODE (up_sub) == INTEGER_CST
6189           && tree_int_cst_lt (up_bound, up_sub)
6190           && TREE_CODE (low_sub) == INTEGER_CST
6191           && tree_int_cst_lt (low_sub, low_bound))
6192         {
6193           warning_at (location, OPT_Warray_bounds,
6194                       "array subscript is outside array bounds");
6195           TREE_NO_WARNING (ref) = 1;
6196         }
6197     }
6198   else if (TREE_CODE (up_sub) == INTEGER_CST
6199            && (ignore_off_by_one
6200                ? (tree_int_cst_lt (up_bound, up_sub)
6201                   && !tree_int_cst_equal (up_bound_p1, up_sub))
6202                : (tree_int_cst_lt (up_bound, up_sub)
6203                   || tree_int_cst_equal (up_bound_p1, up_sub))))
6204     {
6205       if (dump_file && (dump_flags & TDF_DETAILS))
6206         {
6207           fprintf (dump_file, "Array bound warning for ");
6208           dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6209           fprintf (dump_file, "\n");
6210         }
6211       warning_at (location, OPT_Warray_bounds,
6212                   "array subscript is above array bounds");
6213       TREE_NO_WARNING (ref) = 1;
6214     }
6215   else if (TREE_CODE (low_sub) == INTEGER_CST
6216            && tree_int_cst_lt (low_sub, low_bound))
6217     {
6218       if (dump_file && (dump_flags & TDF_DETAILS))
6219         {
6220           fprintf (dump_file, "Array bound warning for ");
6221           dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6222           fprintf (dump_file, "\n");
6223         }
6224       warning_at (location, OPT_Warray_bounds,
6225                   "array subscript is below array bounds");
6226       TREE_NO_WARNING (ref) = 1;
6227     }
6228 }
6229
6230 /* Searches if the expr T, located at LOCATION computes
6231    address of an ARRAY_REF, and call check_array_ref on it.  */
6232
6233 static void
6234 search_for_addr_array (tree t, location_t location)
6235 {
6236   while (TREE_CODE (t) == SSA_NAME)
6237     {
6238       gimple g = SSA_NAME_DEF_STMT (t);
6239
6240       if (gimple_code (g) != GIMPLE_ASSIGN)
6241         return;
6242
6243       if (get_gimple_rhs_class (gimple_assign_rhs_code (g))
6244           != GIMPLE_SINGLE_RHS)
6245         return;
6246
6247       t = gimple_assign_rhs1 (g);
6248     }
6249
6250
6251   /* We are only interested in addresses of ARRAY_REF's.  */
6252   if (TREE_CODE (t) != ADDR_EXPR)
6253     return;
6254
6255   /* Check each ARRAY_REFs in the reference chain. */
6256   do
6257     {
6258       if (TREE_CODE (t) == ARRAY_REF)
6259         check_array_ref (location, t, true /*ignore_off_by_one*/);
6260
6261       t = TREE_OPERAND (t, 0);
6262     }
6263   while (handled_component_p (t));
6264
6265   if (TREE_CODE (t) == MEM_REF
6266       && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6267       && !TREE_NO_WARNING (t))
6268     {
6269       tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6270       tree low_bound, up_bound, el_sz;
6271       double_int idx;
6272       if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6273           || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6274           || !TYPE_DOMAIN (TREE_TYPE (tem)))
6275         return;
6276
6277       low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6278       up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6279       el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6280       if (!low_bound
6281           || TREE_CODE (low_bound) != INTEGER_CST
6282           || !up_bound
6283           || TREE_CODE (up_bound) != INTEGER_CST
6284           || !el_sz
6285           || TREE_CODE (el_sz) != INTEGER_CST)
6286         return;
6287
6288       idx = mem_ref_offset (t);
6289       idx = idx.sdiv (tree_to_double_int (el_sz), TRUNC_DIV_EXPR);
6290       if (idx.slt (double_int_zero))
6291         {
6292           if (dump_file && (dump_flags & TDF_DETAILS))
6293             {
6294               fprintf (dump_file, "Array bound warning for ");
6295               dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6296               fprintf (dump_file, "\n");
6297             }
6298           warning_at (location, OPT_Warray_bounds,
6299                       "array subscript is below array bounds");
6300           TREE_NO_WARNING (t) = 1;
6301         }
6302       else if (idx.sgt (tree_to_double_int (up_bound)
6303                         - tree_to_double_int (low_bound)
6304                         + double_int_one))
6305         {
6306           if (dump_file && (dump_flags & TDF_DETAILS))
6307             {
6308               fprintf (dump_file, "Array bound warning for ");
6309               dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6310               fprintf (dump_file, "\n");
6311             }
6312           warning_at (location, OPT_Warray_bounds,
6313                       "array subscript is above array bounds");
6314           TREE_NO_WARNING (t) = 1;
6315         }
6316     }
6317 }
6318
6319 /* walk_tree() callback that checks if *TP is
6320    an ARRAY_REF inside an ADDR_EXPR (in which an array
6321    subscript one outside the valid range is allowed). Call
6322    check_array_ref for each ARRAY_REF found. The location is
6323    passed in DATA.  */
6324
6325 static tree
6326 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6327 {
6328   tree t = *tp;
6329   struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6330   location_t location;
6331
6332   if (EXPR_HAS_LOCATION (t))
6333     location = EXPR_LOCATION (t);
6334   else
6335     {
6336       location_t *locp = (location_t *) wi->info;
6337       location = *locp;
6338     }
6339
6340   *walk_subtree = TRUE;
6341
6342   if (TREE_CODE (t) == ARRAY_REF)
6343     check_array_ref (location, t, false /*ignore_off_by_one*/);
6344
6345   if (TREE_CODE (t) == MEM_REF
6346       || (TREE_CODE (t) == RETURN_EXPR && TREE_OPERAND (t, 0)))
6347     search_for_addr_array (TREE_OPERAND (t, 0), location);
6348
6349   if (TREE_CODE (t) == ADDR_EXPR)
6350     *walk_subtree = FALSE;
6351
6352   return NULL_TREE;
6353 }
6354
6355 /* Walk over all statements of all reachable BBs and call check_array_bounds
6356    on them.  */
6357
6358 static void
6359 check_all_array_refs (void)
6360 {
6361   basic_block bb;
6362   gimple_stmt_iterator si;
6363
6364   FOR_EACH_BB (bb)
6365     {
6366       edge_iterator ei;
6367       edge e;
6368       bool executable = false;
6369
6370       /* Skip blocks that were found to be unreachable.  */
6371       FOR_EACH_EDGE (e, ei, bb->preds)
6372         executable |= !!(e->flags & EDGE_EXECUTABLE);
6373       if (!executable)
6374         continue;
6375
6376       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6377         {
6378           gimple stmt = gsi_stmt (si);
6379           struct walk_stmt_info wi;
6380           if (!gimple_has_location (stmt))
6381             continue;
6382
6383           if (is_gimple_call (stmt))
6384             {
6385               size_t i;
6386               size_t n = gimple_call_num_args (stmt);
6387               for (i = 0; i < n; i++)
6388                 {
6389                   tree arg = gimple_call_arg (stmt, i);
6390                   search_for_addr_array (arg, gimple_location (stmt));
6391                 }
6392             }
6393           else
6394             {
6395               memset (&wi, 0, sizeof (wi));
6396               wi.info = CONST_CAST (void *, (const void *)
6397                                     gimple_location_ptr (stmt));
6398
6399               walk_gimple_op (gsi_stmt (si),
6400                               check_array_bounds,
6401                               &wi);
6402             }
6403         }
6404     }
6405 }
6406
6407 /* Convert range assertion expressions into the implied copies and
6408    copy propagate away the copies.  Doing the trivial copy propagation
6409    here avoids the need to run the full copy propagation pass after
6410    VRP.
6411
6412    FIXME, this will eventually lead to copy propagation removing the
6413    names that had useful range information attached to them.  For
6414    instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6415    then N_i will have the range [3, +INF].
6416
6417    However, by converting the assertion into the implied copy
6418    operation N_i = N_j, we will then copy-propagate N_j into the uses
6419    of N_i and lose the range information.  We may want to hold on to
6420    ASSERT_EXPRs a little while longer as the ranges could be used in
6421    things like jump threading.
6422
6423    The problem with keeping ASSERT_EXPRs around is that passes after
6424    VRP need to handle them appropriately.
6425
6426    Another approach would be to make the range information a first
6427    class property of the SSA_NAME so that it can be queried from
6428    any pass.  This is made somewhat more complex by the need for
6429    multiple ranges to be associated with one SSA_NAME.  */
6430
6431 static void
6432 remove_range_assertions (void)
6433 {
6434   basic_block bb;
6435   gimple_stmt_iterator si;
6436
6437   /* Note that the BSI iterator bump happens at the bottom of the
6438      loop and no bump is necessary if we're removing the statement
6439      referenced by the current BSI.  */
6440   FOR_EACH_BB (bb)
6441     for (si = gsi_start_bb (bb); !gsi_end_p (si);)
6442       {
6443         gimple stmt = gsi_stmt (si);
6444         gimple use_stmt;
6445
6446         if (is_gimple_assign (stmt)
6447             && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
6448           {
6449             tree rhs = gimple_assign_rhs1 (stmt);
6450             tree var;
6451             tree cond = fold (ASSERT_EXPR_COND (rhs));
6452             use_operand_p use_p;
6453             imm_use_iterator iter;
6454
6455             gcc_assert (cond != boolean_false_node);
6456
6457             /* Propagate the RHS into every use of the LHS.  */
6458             var = ASSERT_EXPR_VAR (rhs);
6459             FOR_EACH_IMM_USE_STMT (use_stmt, iter,
6460                                    gimple_assign_lhs (stmt))
6461               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
6462                 {
6463                   SET_USE (use_p, var);
6464                   gcc_assert (TREE_CODE (var) == SSA_NAME);
6465                 }
6466
6467             /* And finally, remove the copy, it is not needed.  */
6468             gsi_remove (&si, true);
6469             release_defs (stmt);
6470           }
6471         else
6472           gsi_next (&si);
6473       }
6474 }
6475
6476
6477 /* Return true if STMT is interesting for VRP.  */
6478
6479 static bool
6480 stmt_interesting_for_vrp (gimple stmt)
6481 {
6482   if (gimple_code (stmt) == GIMPLE_PHI)
6483     {
6484       tree res = gimple_phi_result (stmt);
6485       return (!virtual_operand_p (res)
6486               && (INTEGRAL_TYPE_P (TREE_TYPE (res))
6487                   || POINTER_TYPE_P (TREE_TYPE (res))));
6488     }
6489   else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
6490     {
6491       tree lhs = gimple_get_lhs (stmt);
6492
6493       /* In general, assignments with virtual operands are not useful
6494          for deriving ranges, with the obvious exception of calls to
6495          builtin functions.  */
6496       if (lhs && TREE_CODE (lhs) == SSA_NAME
6497           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6498               || POINTER_TYPE_P (TREE_TYPE (lhs)))
6499           && ((is_gimple_call (stmt)
6500                && gimple_call_fndecl (stmt) != NULL_TREE
6501                && (DECL_BUILT_IN (gimple_call_fndecl (stmt))
6502                    || DECL_IS_OPERATOR_NEW (gimple_call_fndecl (stmt))))
6503               || !gimple_vuse (stmt)))
6504         return true;
6505     }
6506   else if (gimple_code (stmt) == GIMPLE_COND
6507            || gimple_code (stmt) == GIMPLE_SWITCH)
6508     return true;
6509
6510   return false;
6511 }
6512
6513
6514 /* Initialize local data structures for VRP.  */
6515
6516 static void
6517 vrp_initialize (void)
6518 {
6519   basic_block bb;
6520
6521   values_propagated = false;
6522   num_vr_values = num_ssa_names;
6523   vr_value = XCNEWVEC (value_range_t *, num_vr_values);
6524   vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
6525
6526   FOR_EACH_BB (bb)
6527     {
6528       gimple_stmt_iterator si;
6529
6530       for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
6531         {
6532           gimple phi = gsi_stmt (si);
6533           if (!stmt_interesting_for_vrp (phi))
6534             {
6535               tree lhs = PHI_RESULT (phi);
6536               set_value_range_to_varying (get_value_range (lhs));
6537               prop_set_simulate_again (phi, false);
6538             }
6539           else
6540             prop_set_simulate_again (phi, true);
6541         }
6542
6543       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6544         {
6545           gimple stmt = gsi_stmt (si);
6546
6547           /* If the statement is a control insn, then we do not
6548              want to avoid simulating the statement once.  Failure
6549              to do so means that those edges will never get added.  */
6550           if (stmt_ends_bb_p (stmt))
6551             prop_set_simulate_again (stmt, true);
6552           else if (!stmt_interesting_for_vrp (stmt))
6553             {
6554               ssa_op_iter i;
6555               tree def;
6556               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
6557                 set_value_range_to_varying (get_value_range (def));
6558               prop_set_simulate_again (stmt, false);
6559             }
6560           else
6561             prop_set_simulate_again (stmt, true);
6562         }
6563     }
6564 }
6565
6566 /* Return the singleton value-range for NAME or NAME.  */
6567
6568 static inline tree
6569 vrp_valueize (tree name)
6570 {
6571   if (TREE_CODE (name) == SSA_NAME)
6572     {
6573       value_range_t *vr = get_value_range (name);
6574       if (vr->type == VR_RANGE
6575           && (vr->min == vr->max
6576               || operand_equal_p (vr->min, vr->max, 0)))
6577         return vr->min;
6578     }
6579   return name;
6580 }
6581
6582 /* Visit assignment STMT.  If it produces an interesting range, record
6583    the SSA name in *OUTPUT_P.  */
6584
6585 static enum ssa_prop_result
6586 vrp_visit_assignment_or_call (gimple stmt, tree *output_p)
6587 {
6588   tree def, lhs;
6589   ssa_op_iter iter;
6590   enum gimple_code code = gimple_code (stmt);
6591   lhs = gimple_get_lhs (stmt);
6592
6593   /* We only keep track of ranges in integral and pointer types.  */
6594   if (TREE_CODE (lhs) == SSA_NAME
6595       && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6596            /* It is valid to have NULL MIN/MAX values on a type.  See
6597               build_range_type.  */
6598            && TYPE_MIN_VALUE (TREE_TYPE (lhs))
6599            && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
6600           || POINTER_TYPE_P (TREE_TYPE (lhs))))
6601     {
6602       value_range_t new_vr = VR_INITIALIZER;
6603
6604       /* Try folding the statement to a constant first.  */
6605       tree tem = gimple_fold_stmt_to_constant (stmt, vrp_valueize);
6606       if (tem && !is_overflow_infinity (tem))
6607         set_value_range (&new_vr, VR_RANGE, tem, tem, NULL);
6608       /* Then dispatch to value-range extracting functions.  */
6609       else if (code == GIMPLE_CALL)
6610         extract_range_basic (&new_vr, stmt);
6611       else
6612         extract_range_from_assignment (&new_vr, stmt);
6613
6614       if (update_value_range (lhs, &new_vr))
6615         {
6616           *output_p = lhs;
6617
6618           if (dump_file && (dump_flags & TDF_DETAILS))
6619             {
6620               fprintf (dump_file, "Found new range for ");
6621               print_generic_expr (dump_file, lhs, 0);
6622               fprintf (dump_file, ": ");
6623               dump_value_range (dump_file, &new_vr);
6624               fprintf (dump_file, "\n\n");
6625             }
6626
6627           if (new_vr.type == VR_VARYING)
6628             return SSA_PROP_VARYING;
6629
6630           return SSA_PROP_INTERESTING;
6631         }
6632
6633       return SSA_PROP_NOT_INTERESTING;
6634     }
6635
6636   /* Every other statement produces no useful ranges.  */
6637   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
6638     set_value_range_to_varying (get_value_range (def));
6639
6640   return SSA_PROP_VARYING;
6641 }
6642
6643 /* Helper that gets the value range of the SSA_NAME with version I
6644    or a symbolic range containing the SSA_NAME only if the value range
6645    is varying or undefined.  */
6646
6647 static inline value_range_t
6648 get_vr_for_comparison (int i)
6649 {
6650   value_range_t vr = *get_value_range (ssa_name (i));
6651
6652   /* If name N_i does not have a valid range, use N_i as its own
6653      range.  This allows us to compare against names that may
6654      have N_i in their ranges.  */
6655   if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
6656     {
6657       vr.type = VR_RANGE;
6658       vr.min = ssa_name (i);
6659       vr.max = ssa_name (i);
6660     }
6661
6662   return vr;
6663 }
6664
6665 /* Compare all the value ranges for names equivalent to VAR with VAL
6666    using comparison code COMP.  Return the same value returned by
6667    compare_range_with_value, including the setting of
6668    *STRICT_OVERFLOW_P.  */
6669
6670 static tree
6671 compare_name_with_value (enum tree_code comp, tree var, tree val,
6672                          bool *strict_overflow_p)
6673 {
6674   bitmap_iterator bi;
6675   unsigned i;
6676   bitmap e;
6677   tree retval, t;
6678   int used_strict_overflow;
6679   bool sop;
6680   value_range_t equiv_vr;
6681
6682   /* Get the set of equivalences for VAR.  */
6683   e = get_value_range (var)->equiv;
6684
6685   /* Start at -1.  Set it to 0 if we do a comparison without relying
6686      on overflow, or 1 if all comparisons rely on overflow.  */
6687   used_strict_overflow = -1;
6688
6689   /* Compare vars' value range with val.  */
6690   equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
6691   sop = false;
6692   retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
6693   if (retval)
6694     used_strict_overflow = sop ? 1 : 0;
6695
6696   /* If the equiv set is empty we have done all work we need to do.  */
6697   if (e == NULL)
6698     {
6699       if (retval
6700           && used_strict_overflow > 0)
6701         *strict_overflow_p = true;
6702       return retval;
6703     }
6704
6705   EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
6706     {
6707       equiv_vr = get_vr_for_comparison (i);
6708       sop = false;
6709       t = compare_range_with_value (comp, &equiv_vr, val, &sop);
6710       if (t)
6711         {
6712           /* If we get different answers from different members
6713              of the equivalence set this check must be in a dead
6714              code region.  Folding it to a trap representation
6715              would be correct here.  For now just return don't-know.  */
6716           if (retval != NULL
6717               && t != retval)
6718             {
6719               retval = NULL_TREE;
6720               break;
6721             }
6722           retval = t;
6723
6724           if (!sop)
6725             used_strict_overflow = 0;
6726           else if (used_strict_overflow < 0)
6727             used_strict_overflow = 1;
6728         }
6729     }
6730
6731   if (retval
6732       && used_strict_overflow > 0)
6733     *strict_overflow_p = true;
6734
6735   return retval;
6736 }
6737
6738
6739 /* Given a comparison code COMP and names N1 and N2, compare all the
6740    ranges equivalent to N1 against all the ranges equivalent to N2
6741    to determine the value of N1 COMP N2.  Return the same value
6742    returned by compare_ranges.  Set *STRICT_OVERFLOW_P to indicate
6743    whether we relied on an overflow infinity in the comparison.  */
6744
6745
6746 static tree
6747 compare_names (enum tree_code comp, tree n1, tree n2,
6748                bool *strict_overflow_p)
6749 {
6750   tree t, retval;
6751   bitmap e1, e2;
6752   bitmap_iterator bi1, bi2;
6753   unsigned i1, i2;
6754   int used_strict_overflow;
6755   static bitmap_obstack *s_obstack = NULL;
6756   static bitmap s_e1 = NULL, s_e2 = NULL;
6757
6758   /* Compare the ranges of every name equivalent to N1 against the
6759      ranges of every name equivalent to N2.  */
6760   e1 = get_value_range (n1)->equiv;
6761   e2 = get_value_range (n2)->equiv;
6762
6763   /* Use the fake bitmaps if e1 or e2 are not available.  */
6764   if (s_obstack == NULL)
6765     {
6766       s_obstack = XNEW (bitmap_obstack);
6767       bitmap_obstack_initialize (s_obstack);
6768       s_e1 = BITMAP_ALLOC (s_obstack);
6769       s_e2 = BITMAP_ALLOC (s_obstack);
6770     }
6771   if (e1 == NULL)
6772     e1 = s_e1;
6773   if (e2 == NULL)
6774     e2 = s_e2;
6775
6776   /* Add N1 and N2 to their own set of equivalences to avoid
6777      duplicating the body of the loop just to check N1 and N2
6778      ranges.  */
6779   bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
6780   bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
6781
6782   /* If the equivalence sets have a common intersection, then the two
6783      names can be compared without checking their ranges.  */
6784   if (bitmap_intersect_p (e1, e2))
6785     {
6786       bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
6787       bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
6788
6789       return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
6790              ? boolean_true_node
6791              : boolean_false_node;
6792     }
6793
6794   /* Start at -1.  Set it to 0 if we do a comparison without relying
6795      on overflow, or 1 if all comparisons rely on overflow.  */
6796   used_strict_overflow = -1;
6797
6798   /* Otherwise, compare all the equivalent ranges.  First, add N1 and
6799      N2 to their own set of equivalences to avoid duplicating the body
6800      of the loop just to check N1 and N2 ranges.  */
6801   EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
6802     {
6803       value_range_t vr1 = get_vr_for_comparison (i1);
6804
6805       t = retval = NULL_TREE;
6806       EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
6807         {
6808           bool sop = false;
6809
6810           value_range_t vr2 = get_vr_for_comparison (i2);
6811
6812           t = compare_ranges (comp, &vr1, &vr2, &sop);
6813           if (t)
6814             {
6815               /* If we get different answers from different members
6816                  of the equivalence set this check must be in a dead
6817                  code region.  Folding it to a trap representation
6818                  would be correct here.  For now just return don't-know.  */
6819               if (retval != NULL
6820                   && t != retval)
6821                 {
6822                   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
6823                   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
6824                   return NULL_TREE;
6825                 }
6826               retval = t;
6827
6828               if (!sop)
6829                 used_strict_overflow = 0;
6830               else if (used_strict_overflow < 0)
6831                 used_strict_overflow = 1;
6832             }
6833         }
6834
6835       if (retval)
6836         {
6837           bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
6838           bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
6839           if (used_strict_overflow > 0)
6840             *strict_overflow_p = true;
6841           return retval;
6842         }
6843     }
6844
6845   /* None of the equivalent ranges are useful in computing this
6846      comparison.  */
6847   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
6848   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
6849   return NULL_TREE;
6850 }
6851
6852 /* Helper function for vrp_evaluate_conditional_warnv.  */
6853
6854 static tree
6855 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
6856                                                       tree op0, tree op1,
6857                                                       bool * strict_overflow_p)
6858 {
6859   value_range_t *vr0, *vr1;
6860
6861   vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
6862   vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
6863
6864   if (vr0 && vr1)
6865     return compare_ranges (code, vr0, vr1, strict_overflow_p);
6866   else if (vr0 && vr1 == NULL)
6867     return compare_range_with_value (code, vr0, op1, strict_overflow_p);
6868   else if (vr0 == NULL && vr1)
6869     return (compare_range_with_value
6870             (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
6871   return NULL;
6872 }
6873
6874 /* Helper function for vrp_evaluate_conditional_warnv. */
6875
6876 static tree
6877 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
6878                                          tree op1, bool use_equiv_p,
6879                                          bool *strict_overflow_p, bool *only_ranges)
6880 {
6881   tree ret;
6882   if (only_ranges)
6883     *only_ranges = true;
6884
6885   /* We only deal with integral and pointer types.  */
6886   if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
6887       && !POINTER_TYPE_P (TREE_TYPE (op0)))
6888     return NULL_TREE;
6889
6890   if (use_equiv_p)
6891     {
6892       if (only_ranges
6893           && (ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
6894                       (code, op0, op1, strict_overflow_p)))
6895         return ret;
6896       *only_ranges = false;
6897       if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME)
6898         return compare_names (code, op0, op1, strict_overflow_p);
6899       else if (TREE_CODE (op0) == SSA_NAME)
6900         return compare_name_with_value (code, op0, op1, strict_overflow_p);
6901       else if (TREE_CODE (op1) == SSA_NAME)
6902         return (compare_name_with_value
6903                 (swap_tree_comparison (code), op1, op0, strict_overflow_p));
6904     }
6905   else
6906     return vrp_evaluate_conditional_warnv_with_ops_using_ranges (code, op0, op1,
6907                                                                  strict_overflow_p);
6908   return NULL_TREE;
6909 }
6910
6911 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
6912    information.  Return NULL if the conditional can not be evaluated.
6913    The ranges of all the names equivalent with the operands in COND
6914    will be used when trying to compute the value.  If the result is
6915    based on undefined signed overflow, issue a warning if
6916    appropriate.  */
6917
6918 static tree
6919 vrp_evaluate_conditional (enum tree_code code, tree op0, tree op1, gimple stmt)
6920 {
6921   bool sop;
6922   tree ret;
6923   bool only_ranges;
6924
6925   /* Some passes and foldings leak constants with overflow flag set
6926      into the IL.  Avoid doing wrong things with these and bail out.  */
6927   if ((TREE_CODE (op0) == INTEGER_CST
6928        && TREE_OVERFLOW (op0))
6929       || (TREE_CODE (op1) == INTEGER_CST
6930           && TREE_OVERFLOW (op1)))
6931     return NULL_TREE;
6932
6933   sop = false;
6934   ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
6935                                                  &only_ranges);
6936
6937   if (ret && sop)
6938     {
6939       enum warn_strict_overflow_code wc;
6940       const char* warnmsg;
6941
6942       if (is_gimple_min_invariant (ret))
6943         {
6944           wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
6945           warnmsg = G_("assuming signed overflow does not occur when "
6946                        "simplifying conditional to constant");
6947         }
6948       else
6949         {
6950           wc = WARN_STRICT_OVERFLOW_COMPARISON;
6951           warnmsg = G_("assuming signed overflow does not occur when "
6952                        "simplifying conditional");
6953         }
6954
6955       if (issue_strict_overflow_warning (wc))
6956         {
6957           location_t location;
6958
6959           if (!gimple_has_location (stmt))
6960             location = input_location;
6961           else
6962             location = gimple_location (stmt);
6963           warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
6964         }
6965     }
6966
6967   if (warn_type_limits
6968       && ret && only_ranges
6969       && TREE_CODE_CLASS (code) == tcc_comparison
6970       && TREE_CODE (op0) == SSA_NAME)
6971     {
6972       /* If the comparison is being folded and the operand on the LHS
6973          is being compared against a constant value that is outside of
6974          the natural range of OP0's type, then the predicate will
6975          always fold regardless of the value of OP0.  If -Wtype-limits
6976          was specified, emit a warning.  */
6977       tree type = TREE_TYPE (op0);
6978       value_range_t *vr0 = get_value_range (op0);
6979
6980       if (vr0->type != VR_VARYING
6981           && INTEGRAL_TYPE_P (type)
6982           && vrp_val_is_min (vr0->min)
6983           && vrp_val_is_max (vr0->max)
6984           && is_gimple_min_invariant (op1))
6985         {
6986           location_t location;
6987
6988           if (!gimple_has_location (stmt))
6989             location = input_location;
6990           else
6991             location = gimple_location (stmt);
6992
6993           warning_at (location, OPT_Wtype_limits,
6994                       integer_zerop (ret)
6995                       ? G_("comparison always false "
6996                            "due to limited range of data type")
6997                       : G_("comparison always true "
6998                            "due to limited range of data type"));
6999         }
7000     }
7001
7002   return ret;
7003 }
7004
7005
7006 /* Visit conditional statement STMT.  If we can determine which edge
7007    will be taken out of STMT's basic block, record it in
7008    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
7009    SSA_PROP_VARYING.  */
7010
7011 static enum ssa_prop_result
7012 vrp_visit_cond_stmt (gimple stmt, edge *taken_edge_p)
7013 {
7014   tree val;
7015   bool sop;
7016
7017   *taken_edge_p = NULL;
7018
7019   if (dump_file && (dump_flags & TDF_DETAILS))
7020     {
7021       tree use;
7022       ssa_op_iter i;
7023
7024       fprintf (dump_file, "\nVisiting conditional with predicate: ");
7025       print_gimple_stmt (dump_file, stmt, 0, 0);
7026       fprintf (dump_file, "\nWith known ranges\n");
7027
7028       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7029         {
7030           fprintf (dump_file, "\t");
7031           print_generic_expr (dump_file, use, 0);
7032           fprintf (dump_file, ": ");
7033           dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7034         }
7035
7036       fprintf (dump_file, "\n");
7037     }
7038
7039   /* Compute the value of the predicate COND by checking the known
7040      ranges of each of its operands.
7041
7042      Note that we cannot evaluate all the equivalent ranges here
7043      because those ranges may not yet be final and with the current
7044      propagation strategy, we cannot determine when the value ranges
7045      of the names in the equivalence set have changed.
7046
7047      For instance, given the following code fragment
7048
7049         i_5 = PHI <8, i_13>
7050         ...
7051         i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7052         if (i_14 == 1)
7053           ...
7054
7055      Assume that on the first visit to i_14, i_5 has the temporary
7056      range [8, 8] because the second argument to the PHI function is
7057      not yet executable.  We derive the range ~[0, 0] for i_14 and the
7058      equivalence set { i_5 }.  So, when we visit 'if (i_14 == 1)' for
7059      the first time, since i_14 is equivalent to the range [8, 8], we
7060      determine that the predicate is always false.
7061
7062      On the next round of propagation, i_13 is determined to be
7063      VARYING, which causes i_5 to drop down to VARYING.  So, another
7064      visit to i_14 is scheduled.  In this second visit, we compute the
7065      exact same range and equivalence set for i_14, namely ~[0, 0] and
7066      { i_5 }.  But we did not have the previous range for i_5
7067      registered, so vrp_visit_assignment thinks that the range for
7068      i_14 has not changed.  Therefore, the predicate 'if (i_14 == 1)'
7069      is not visited again, which stops propagation from visiting
7070      statements in the THEN clause of that if().
7071
7072      To properly fix this we would need to keep the previous range
7073      value for the names in the equivalence set.  This way we would've
7074      discovered that from one visit to the other i_5 changed from
7075      range [8, 8] to VR_VARYING.
7076
7077      However, fixing this apparent limitation may not be worth the
7078      additional checking.  Testing on several code bases (GCC, DLV,
7079      MICO, TRAMP3D and SPEC2000) showed that doing this results in
7080      4 more predicates folded in SPEC.  */
7081   sop = false;
7082
7083   val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7084                                                  gimple_cond_lhs (stmt),
7085                                                  gimple_cond_rhs (stmt),
7086                                                  false, &sop, NULL);
7087   if (val)
7088     {
7089       if (!sop)
7090         *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7091       else
7092         {
7093           if (dump_file && (dump_flags & TDF_DETAILS))
7094             fprintf (dump_file,
7095                      "\nIgnoring predicate evaluation because "
7096                      "it assumes that signed overflow is undefined");
7097           val = NULL_TREE;
7098         }
7099     }
7100
7101   if (dump_file && (dump_flags & TDF_DETAILS))
7102     {
7103       fprintf (dump_file, "\nPredicate evaluates to: ");
7104       if (val == NULL_TREE)
7105         fprintf (dump_file, "DON'T KNOW\n");
7106       else
7107         print_generic_stmt (dump_file, val, 0);
7108     }
7109
7110   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
7111 }
7112
7113 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7114    that includes the value VAL.  The search is restricted to the range
7115    [START_IDX, n - 1] where n is the size of VEC.
7116
7117    If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7118    returned.
7119
7120    If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7121    it is placed in IDX and false is returned.
7122
7123    If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7124    returned. */
7125
7126 static bool
7127 find_case_label_index (gimple stmt, size_t start_idx, tree val, size_t *idx)
7128 {
7129   size_t n = gimple_switch_num_labels (stmt);
7130   size_t low, high;
7131
7132   /* Find case label for minimum of the value range or the next one.
7133      At each iteration we are searching in [low, high - 1]. */
7134
7135   for (low = start_idx, high = n; high != low; )
7136     {
7137       tree t;
7138       int cmp;
7139       /* Note that i != high, so we never ask for n. */
7140       size_t i = (high + low) / 2;
7141       t = gimple_switch_label (stmt, i);
7142
7143       /* Cache the result of comparing CASE_LOW and val.  */
7144       cmp = tree_int_cst_compare (CASE_LOW (t), val);
7145
7146       if (cmp == 0)
7147         {
7148           /* Ranges cannot be empty. */
7149           *idx = i;
7150           return true;
7151         }
7152       else if (cmp > 0)
7153         high = i;
7154       else
7155         {
7156           low = i + 1;
7157           if (CASE_HIGH (t) != NULL
7158               && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7159             {
7160               *idx = i;
7161               return true;
7162             }
7163         }
7164     }
7165
7166   *idx = high;
7167   return false;
7168 }
7169
7170 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7171    for values between MIN and MAX. The first index is placed in MIN_IDX. The
7172    last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7173    then MAX_IDX < MIN_IDX.
7174    Returns true if the default label is not needed. */
7175
7176 static bool
7177 find_case_label_range (gimple stmt, tree min, tree max, size_t *min_idx,
7178                        size_t *max_idx)
7179 {
7180   size_t i, j;
7181   bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7182   bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7183
7184   if (i == j
7185       && min_take_default
7186       && max_take_default)
7187     {
7188       /* Only the default case label reached.
7189          Return an empty range. */
7190       *min_idx = 1;
7191       *max_idx = 0;
7192       return false;
7193     }
7194   else
7195     {
7196       bool take_default = min_take_default || max_take_default;
7197       tree low, high;
7198       size_t k;
7199
7200       if (max_take_default)
7201         j--;
7202
7203       /* If the case label range is continuous, we do not need
7204          the default case label.  Verify that.  */
7205       high = CASE_LOW (gimple_switch_label (stmt, i));
7206       if (CASE_HIGH (gimple_switch_label (stmt, i)))
7207         high = CASE_HIGH (gimple_switch_label (stmt, i));
7208       for (k = i + 1; k <= j; ++k)
7209         {
7210           low = CASE_LOW (gimple_switch_label (stmt, k));
7211           if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7212             {
7213               take_default = true;
7214               break;
7215             }
7216           high = low;
7217           if (CASE_HIGH (gimple_switch_label (stmt, k)))
7218             high = CASE_HIGH (gimple_switch_label (stmt, k));
7219         }
7220
7221       *min_idx = i;
7222       *max_idx = j;
7223       return !take_default;
7224     }
7225 }
7226
7227 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7228    used in range VR.  The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7229    MAX_IDX2.  If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7230    Returns true if the default label is not needed.  */
7231
7232 static bool
7233 find_case_label_ranges (gimple stmt, value_range_t *vr, size_t *min_idx1,
7234                         size_t *max_idx1, size_t *min_idx2,
7235                         size_t *max_idx2)
7236 {
7237   size_t i, j, k, l;
7238   unsigned int n = gimple_switch_num_labels (stmt);
7239   bool take_default;
7240   tree case_low, case_high;
7241   tree min = vr->min, max = vr->max;
7242
7243   gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7244
7245   take_default = !find_case_label_range (stmt, min, max, &i, &j);
7246
7247   /* Set second range to emtpy.  */
7248   *min_idx2 = 1;
7249   *max_idx2 = 0;
7250
7251   if (vr->type == VR_RANGE)
7252     {
7253       *min_idx1 = i;
7254       *max_idx1 = j;
7255       return !take_default;
7256     }
7257
7258   /* Set first range to all case labels.  */
7259   *min_idx1 = 1;
7260   *max_idx1 = n - 1;
7261
7262   if (i > j)
7263     return false;
7264
7265   /* Make sure all the values of case labels [i , j] are contained in
7266      range [MIN, MAX].  */
7267   case_low = CASE_LOW (gimple_switch_label (stmt, i));
7268   case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7269   if (tree_int_cst_compare (case_low, min) < 0)
7270     i += 1;
7271   if (case_high != NULL_TREE
7272       && tree_int_cst_compare (max, case_high) < 0)
7273     j -= 1;
7274
7275   if (i > j)
7276     return false;
7277
7278   /* If the range spans case labels [i, j], the corresponding anti-range spans
7279      the labels [1, i - 1] and [j + 1, n -  1].  */
7280   k = j + 1;
7281   l = n - 1;
7282   if (k > l)
7283     {
7284       k = 1;
7285       l = 0;
7286     }
7287
7288   j = i - 1;
7289   i = 1;
7290   if (i > j)
7291     {
7292       i = k;
7293       j = l;
7294       k = 1;
7295       l = 0;
7296     }
7297
7298   *min_idx1 = i;
7299   *max_idx1 = j;
7300   *min_idx2 = k;
7301   *max_idx2 = l;
7302   return false;
7303 }
7304
7305 /* Visit switch statement STMT.  If we can determine which edge
7306    will be taken out of STMT's basic block, record it in
7307    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
7308    SSA_PROP_VARYING.  */
7309
7310 static enum ssa_prop_result
7311 vrp_visit_switch_stmt (gimple stmt, edge *taken_edge_p)
7312 {
7313   tree op, val;
7314   value_range_t *vr;
7315   size_t i = 0, j = 0, k, l;
7316   bool take_default;
7317
7318   *taken_edge_p = NULL;
7319   op = gimple_switch_index (stmt);
7320   if (TREE_CODE (op) != SSA_NAME)
7321     return SSA_PROP_VARYING;
7322
7323   vr = get_value_range (op);
7324   if (dump_file && (dump_flags & TDF_DETAILS))
7325     {
7326       fprintf (dump_file, "\nVisiting switch expression with operand ");
7327       print_generic_expr (dump_file, op, 0);
7328       fprintf (dump_file, " with known range ");
7329       dump_value_range (dump_file, vr);
7330       fprintf (dump_file, "\n");
7331     }
7332
7333   if ((vr->type != VR_RANGE
7334        && vr->type != VR_ANTI_RANGE)
7335       || symbolic_range_p (vr))
7336     return SSA_PROP_VARYING;
7337
7338   /* Find the single edge that is taken from the switch expression.  */
7339   take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
7340
7341   /* Check if the range spans no CASE_LABEL. If so, we only reach the default
7342      label */
7343   if (j < i)
7344     {
7345       gcc_assert (take_default);
7346       val = gimple_switch_default_label (stmt);
7347     }
7348   else
7349     {
7350       /* Check if labels with index i to j and maybe the default label
7351          are all reaching the same label.  */
7352
7353       val = gimple_switch_label (stmt, i);
7354       if (take_default
7355           && CASE_LABEL (gimple_switch_default_label (stmt))
7356           != CASE_LABEL (val))
7357         {
7358           if (dump_file && (dump_flags & TDF_DETAILS))
7359             fprintf (dump_file, "  not a single destination for this "
7360                      "range\n");
7361           return SSA_PROP_VARYING;
7362         }
7363       for (++i; i <= j; ++i)
7364         {
7365           if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
7366             {
7367               if (dump_file && (dump_flags & TDF_DETAILS))
7368                 fprintf (dump_file, "  not a single destination for this "
7369                          "range\n");
7370               return SSA_PROP_VARYING;
7371             }
7372         }
7373       for (; k <= l; ++k)
7374         {
7375           if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
7376             {
7377               if (dump_file && (dump_flags & TDF_DETAILS))
7378                 fprintf (dump_file, "  not a single destination for this "
7379                          "range\n");
7380               return SSA_PROP_VARYING;
7381             }
7382         }
7383     }
7384
7385   *taken_edge_p = find_edge (gimple_bb (stmt),
7386                              label_to_block (CASE_LABEL (val)));
7387
7388   if (dump_file && (dump_flags & TDF_DETAILS))
7389     {
7390       fprintf (dump_file, "  will take edge to ");
7391       print_generic_stmt (dump_file, CASE_LABEL (val), 0);
7392     }
7393
7394   return SSA_PROP_INTERESTING;
7395 }
7396
7397
7398 /* Evaluate statement STMT.  If the statement produces a useful range,
7399    return SSA_PROP_INTERESTING and record the SSA name with the
7400    interesting range into *OUTPUT_P.
7401
7402    If STMT is a conditional branch and we can determine its truth
7403    value, the taken edge is recorded in *TAKEN_EDGE_P.
7404
7405    If STMT produces a varying value, return SSA_PROP_VARYING.  */
7406
7407 static enum ssa_prop_result
7408 vrp_visit_stmt (gimple stmt, edge *taken_edge_p, tree *output_p)
7409 {
7410   tree def;
7411   ssa_op_iter iter;
7412
7413   if (dump_file && (dump_flags & TDF_DETAILS))
7414     {
7415       fprintf (dump_file, "\nVisiting statement:\n");
7416       print_gimple_stmt (dump_file, stmt, 0, dump_flags);
7417       fprintf (dump_file, "\n");
7418     }
7419
7420   if (!stmt_interesting_for_vrp (stmt))
7421     gcc_assert (stmt_ends_bb_p (stmt));
7422   else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7423     return vrp_visit_assignment_or_call (stmt, output_p);
7424   else if (gimple_code (stmt) == GIMPLE_COND)
7425     return vrp_visit_cond_stmt (stmt, taken_edge_p);
7426   else if (gimple_code (stmt) == GIMPLE_SWITCH)
7427     return vrp_visit_switch_stmt (stmt, taken_edge_p);
7428
7429   /* All other statements produce nothing of interest for VRP, so mark
7430      their outputs varying and prevent further simulation.  */
7431   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
7432     set_value_range_to_varying (get_value_range (def));
7433
7434   return SSA_PROP_VARYING;
7435 }
7436
7437 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
7438    { VR1TYPE, VR0MIN, VR0MAX } and store the result
7439    in { *VR0TYPE, *VR0MIN, *VR0MAX }.  This may not be the smallest
7440    possible such range.  The resulting range is not canonicalized.  */
7441
7442 static void
7443 union_ranges (enum value_range_type *vr0type,
7444               tree *vr0min, tree *vr0max,
7445               enum value_range_type vr1type,
7446               tree vr1min, tree vr1max)
7447 {
7448   bool mineq = operand_equal_p (*vr0min, vr1min, 0);
7449   bool maxeq = operand_equal_p (*vr0max, vr1max, 0);
7450
7451   /* [] is vr0, () is vr1 in the following classification comments.  */
7452   if (mineq && maxeq)
7453     {
7454       /* [(  )] */
7455       if (*vr0type == vr1type)
7456         /* Nothing to do for equal ranges.  */
7457         ;
7458       else if ((*vr0type == VR_RANGE
7459                 && vr1type == VR_ANTI_RANGE)
7460                || (*vr0type == VR_ANTI_RANGE
7461                    && vr1type == VR_RANGE))
7462         {
7463           /* For anti-range with range union the result is varying.  */
7464           goto give_up;
7465         }
7466       else
7467         gcc_unreachable ();
7468     }
7469   else if (operand_less_p (*vr0max, vr1min) == 1
7470            || operand_less_p (vr1max, *vr0min) == 1)
7471     {
7472       /* [ ] ( ) or ( ) [ ]
7473          If the ranges have an empty intersection, result of the union
7474          operation is the anti-range or if both are anti-ranges
7475          it covers all.  */
7476       if (*vr0type == VR_ANTI_RANGE
7477           && vr1type == VR_ANTI_RANGE)
7478         goto give_up;
7479       else if (*vr0type == VR_ANTI_RANGE
7480                && vr1type == VR_RANGE)
7481         ;
7482       else if (*vr0type == VR_RANGE
7483                && vr1type == VR_ANTI_RANGE)
7484         {
7485           *vr0type = vr1type;
7486           *vr0min = vr1min;
7487           *vr0max = vr1max;
7488         }
7489       else if (*vr0type == VR_RANGE
7490                && vr1type == VR_RANGE)
7491         {
7492           /* The result is the convex hull of both ranges.  */
7493           if (operand_less_p (*vr0max, vr1min) == 1)
7494             {
7495               /* If the result can be an anti-range, create one.  */
7496               if (TREE_CODE (*vr0max) == INTEGER_CST
7497                   && TREE_CODE (vr1min) == INTEGER_CST
7498                   && vrp_val_is_min (*vr0min)
7499                   && vrp_val_is_max (vr1max))
7500                 {
7501                   tree min = int_const_binop (PLUS_EXPR,
7502                                               *vr0max, integer_one_node);
7503                   tree max = int_const_binop (MINUS_EXPR,
7504                                               vr1min, integer_one_node);
7505                   if (!operand_less_p (max, min))
7506                     {
7507                       *vr0type = VR_ANTI_RANGE;
7508                       *vr0min = min;
7509                       *vr0max = max;
7510                     }
7511                   else
7512                     *vr0max = vr1max;
7513                 }
7514               else
7515                 *vr0max = vr1max;
7516             }
7517           else
7518             {
7519               /* If the result can be an anti-range, create one.  */
7520               if (TREE_CODE (vr1max) == INTEGER_CST
7521                   && TREE_CODE (*vr0min) == INTEGER_CST
7522                   && vrp_val_is_min (vr1min)
7523                   && vrp_val_is_max (*vr0max))
7524                 {
7525                   tree min = int_const_binop (PLUS_EXPR,
7526                                               vr1max, integer_one_node);
7527                   tree max = int_const_binop (MINUS_EXPR,
7528                                               *vr0min, integer_one_node);
7529                   if (!operand_less_p (max, min))
7530                     {
7531                       *vr0type = VR_ANTI_RANGE;
7532                       *vr0min = min;
7533                       *vr0max = max;
7534                     }
7535                   else
7536                     *vr0min = vr1min;
7537                 }
7538               else
7539                 *vr0min = vr1min;
7540             }
7541         }
7542       else
7543         gcc_unreachable ();
7544     }
7545   else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
7546            && (mineq || operand_less_p (*vr0min, vr1min) == 1))
7547     {
7548       /* [ (  ) ] or [(  ) ] or [ (  )] */
7549       if (*vr0type == VR_RANGE
7550           && vr1type == VR_RANGE)
7551         ;
7552       else if (*vr0type == VR_ANTI_RANGE
7553                && vr1type == VR_ANTI_RANGE)
7554         {
7555           *vr0type = vr1type;
7556           *vr0min = vr1min;
7557           *vr0max = vr1max;
7558         }
7559       else if (*vr0type == VR_ANTI_RANGE
7560                && vr1type == VR_RANGE)
7561         {
7562           /* Arbitrarily choose the right or left gap.  */
7563           if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
7564             *vr0max = int_const_binop (MINUS_EXPR, vr1min, integer_one_node);
7565           else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
7566             *vr0min = int_const_binop (PLUS_EXPR, vr1max, integer_one_node);
7567           else
7568             goto give_up;
7569         }
7570       else if (*vr0type == VR_RANGE
7571                && vr1type == VR_ANTI_RANGE)
7572         /* The result covers everything.  */
7573         goto give_up;
7574       else
7575         gcc_unreachable ();
7576     }
7577   else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
7578            && (mineq || operand_less_p (vr1min, *vr0min) == 1))
7579     {
7580       /* ( [  ] ) or ([  ] ) or ( [  ]) */
7581       if (*vr0type == VR_RANGE
7582           && vr1type == VR_RANGE)
7583         {
7584           *vr0type = vr1type;
7585           *vr0min = vr1min;
7586           *vr0max = vr1max;
7587         }
7588       else if (*vr0type == VR_ANTI_RANGE
7589                && vr1type == VR_ANTI_RANGE)
7590         ;
7591       else if (*vr0type == VR_RANGE
7592                && vr1type == VR_ANTI_RANGE)
7593         {
7594           *vr0type = VR_ANTI_RANGE;
7595           if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
7596             {
7597               *vr0max = int_const_binop (MINUS_EXPR, *vr0min, integer_one_node);
7598               *vr0min = vr1min;
7599             }
7600           else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
7601             {
7602               *vr0min = int_const_binop (PLUS_EXPR, *vr0max, integer_one_node);
7603               *vr0max = vr1max;
7604             }
7605           else
7606             goto give_up;
7607         }
7608       else if (*vr0type == VR_ANTI_RANGE
7609                && vr1type == VR_RANGE)
7610         /* The result covers everything.  */
7611         goto give_up;
7612       else
7613         gcc_unreachable ();
7614     }
7615   else if ((operand_less_p (vr1min, *vr0max) == 1
7616             || operand_equal_p (vr1min, *vr0max, 0))
7617            && operand_less_p (*vr0min, vr1min) == 1)
7618     {
7619       /* [  (  ]  ) or [   ](   ) */
7620       if (*vr0type == VR_RANGE
7621           && vr1type == VR_RANGE)
7622         *vr0max = vr1max;
7623       else if (*vr0type == VR_ANTI_RANGE
7624                && vr1type == VR_ANTI_RANGE)
7625         *vr0min = vr1min;
7626       else if (*vr0type == VR_ANTI_RANGE
7627                && vr1type == VR_RANGE)
7628         {
7629           if (TREE_CODE (vr1min) == INTEGER_CST)
7630             *vr0max = int_const_binop (MINUS_EXPR, vr1min, integer_one_node);
7631           else
7632             goto give_up;
7633         }
7634       else if (*vr0type == VR_RANGE
7635                && vr1type == VR_ANTI_RANGE)
7636         {
7637           if (TREE_CODE (*vr0max) == INTEGER_CST)
7638             {
7639               *vr0type = vr1type;
7640               *vr0min = int_const_binop (PLUS_EXPR, *vr0max, integer_one_node);
7641               *vr0max = vr1max;
7642             }
7643           else
7644             goto give_up;
7645         }
7646       else
7647         gcc_unreachable ();
7648     }
7649   else if ((operand_less_p (*vr0min, vr1max) == 1
7650             || operand_equal_p (*vr0min, vr1max, 0))
7651            && operand_less_p (vr1min, *vr0min) == 1)
7652     {
7653       /* (  [  )  ] or (   )[   ] */
7654       if (*vr0type == VR_RANGE
7655           && vr1type == VR_RANGE)
7656         *vr0min = vr1min;
7657       else if (*vr0type == VR_ANTI_RANGE
7658                && vr1type == VR_ANTI_RANGE)
7659         *vr0max = vr1max;
7660       else if (*vr0type == VR_ANTI_RANGE
7661                && vr1type == VR_RANGE)
7662         {
7663           if (TREE_CODE (vr1max) == INTEGER_CST)
7664             *vr0min = int_const_binop (PLUS_EXPR, vr1max, integer_one_node);
7665           else
7666             goto give_up;
7667         }
7668       else if (*vr0type == VR_RANGE
7669                && vr1type == VR_ANTI_RANGE)
7670         {
7671           if (TREE_CODE (*vr0min) == INTEGER_CST)
7672             {
7673               *vr0type = vr1type;
7674               *vr0min = vr1min;
7675               *vr0max = int_const_binop (MINUS_EXPR, *vr0min, integer_one_node);
7676             }
7677           else
7678             goto give_up;
7679         }
7680       else
7681         gcc_unreachable ();
7682     }
7683   else
7684     goto give_up;
7685
7686   return;
7687
7688 give_up:
7689   *vr0type = VR_VARYING;
7690   *vr0min = NULL_TREE;
7691   *vr0max = NULL_TREE;
7692 }
7693
7694 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
7695    { VR1TYPE, VR0MIN, VR0MAX } and store the result
7696    in { *VR0TYPE, *VR0MIN, *VR0MAX }.  This may not be the smallest
7697    possible such range.  The resulting range is not canonicalized.  */
7698
7699 static void
7700 intersect_ranges (enum value_range_type *vr0type,
7701                   tree *vr0min, tree *vr0max,
7702                   enum value_range_type vr1type,
7703                   tree vr1min, tree vr1max)
7704 {
7705   bool mineq = operand_equal_p (*vr0min, vr1min, 0);
7706   bool maxeq = operand_equal_p (*vr0max, vr1max, 0);
7707
7708   /* [] is vr0, () is vr1 in the following classification comments.  */
7709   if (mineq && maxeq)
7710     {
7711       /* [(  )] */
7712       if (*vr0type == vr1type)
7713         /* Nothing to do for equal ranges.  */
7714         ;
7715       else if ((*vr0type == VR_RANGE
7716                 && vr1type == VR_ANTI_RANGE)
7717                || (*vr0type == VR_ANTI_RANGE
7718                    && vr1type == VR_RANGE))
7719         {
7720           /* For anti-range with range intersection the result is empty.  */
7721           *vr0type = VR_UNDEFINED;
7722           *vr0min = NULL_TREE;
7723           *vr0max = NULL_TREE;
7724         }
7725       else
7726         gcc_unreachable ();
7727     }
7728   else if (operand_less_p (*vr0max, vr1min) == 1
7729            || operand_less_p (vr1max, *vr0min) == 1)
7730     {
7731       /* [ ] ( ) or ( ) [ ]
7732          If the ranges have an empty intersection, the result of the
7733          intersect operation is the range for intersecting an
7734          anti-range with a range or empty when intersecting two ranges.  */
7735       if (*vr0type == VR_RANGE
7736           && vr1type == VR_ANTI_RANGE)
7737         ;
7738       else if (*vr0type == VR_ANTI_RANGE
7739                && vr1type == VR_RANGE)
7740         {
7741           *vr0type = vr1type;
7742           *vr0min = vr1min;
7743           *vr0max = vr1max;
7744         }
7745       else if (*vr0type == VR_RANGE
7746                && vr1type == VR_RANGE)
7747         {
7748           *vr0type = VR_UNDEFINED;
7749           *vr0min = NULL_TREE;
7750           *vr0max = NULL_TREE;
7751         }
7752       else if (*vr0type == VR_ANTI_RANGE
7753                && vr1type == VR_ANTI_RANGE)
7754         {
7755           /* If the anti-ranges are adjacent to each other merge them.  */
7756           if (TREE_CODE (*vr0max) == INTEGER_CST
7757               && TREE_CODE (vr1min) == INTEGER_CST
7758               && operand_less_p (*vr0max, vr1min) == 1
7759               && integer_onep (int_const_binop (MINUS_EXPR,
7760                                                 vr1min, *vr0max)))
7761             *vr0max = vr1max;
7762           else if (TREE_CODE (vr1max) == INTEGER_CST
7763                    && TREE_CODE (*vr0min) == INTEGER_CST
7764                    && operand_less_p (vr1max, *vr0min) == 1
7765                    && integer_onep (int_const_binop (MINUS_EXPR,
7766                                                      *vr0min, vr1max)))
7767             *vr0min = vr1min;
7768           /* Else arbitrarily take VR0.  */
7769         }
7770     }
7771   else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
7772            && (mineq || operand_less_p (*vr0min, vr1min) == 1))
7773     {
7774       /* [ (  ) ] or [(  ) ] or [ (  )] */
7775       if (*vr0type == VR_RANGE
7776           && vr1type == VR_RANGE)
7777         {
7778           /* If both are ranges the result is the inner one.  */
7779           *vr0type = vr1type;
7780           *vr0min = vr1min;
7781           *vr0max = vr1max;
7782         }
7783       else if (*vr0type == VR_RANGE
7784                && vr1type == VR_ANTI_RANGE)
7785         {
7786           /* Choose the right gap if the left one is empty.  */
7787           if (mineq)
7788             {
7789               if (TREE_CODE (vr1max) == INTEGER_CST)
7790                 *vr0min = int_const_binop (PLUS_EXPR, vr1max, integer_one_node);
7791               else
7792                 *vr0min = vr1max;
7793             }
7794           /* Choose the left gap if the right one is empty.  */
7795           else if (maxeq)
7796             {
7797               if (TREE_CODE (vr1min) == INTEGER_CST)
7798                 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
7799                                            integer_one_node);
7800               else
7801                 *vr0max = vr1min;
7802             }
7803           /* Choose the anti-range if the range is effectively varying.  */
7804           else if (vrp_val_is_min (*vr0min)
7805                    && vrp_val_is_max (*vr0max))
7806             {
7807               *vr0type = vr1type;
7808               *vr0min = vr1min;
7809               *vr0max = vr1max;
7810             }
7811           /* Else choose the range.  */
7812         }
7813       else if (*vr0type == VR_ANTI_RANGE
7814                && vr1type == VR_ANTI_RANGE)
7815         /* If both are anti-ranges the result is the outer one.  */
7816         ;
7817       else if (*vr0type == VR_ANTI_RANGE
7818                && vr1type == VR_RANGE)
7819         {
7820           /* The intersection is empty.  */
7821           *vr0type = VR_UNDEFINED;
7822           *vr0min = NULL_TREE;
7823           *vr0max = NULL_TREE;
7824         }
7825       else
7826         gcc_unreachable ();
7827     }
7828   else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
7829            && (mineq || operand_less_p (vr1min, *vr0min) == 1))
7830     {
7831       /* ( [  ] ) or ([  ] ) or ( [  ]) */
7832       if (*vr0type == VR_RANGE
7833           && vr1type == VR_RANGE)
7834         /* Choose the inner range.  */
7835         ;
7836       else if (*vr0type == VR_ANTI_RANGE
7837                && vr1type == VR_RANGE)
7838         {
7839           /* Choose the right gap if the left is empty.  */
7840           if (mineq)
7841             {
7842               *vr0type = VR_RANGE;
7843               if (TREE_CODE (*vr0max) == INTEGER_CST)
7844                 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
7845                                            integer_one_node);
7846               else
7847                 *vr0min = *vr0max;
7848               *vr0max = vr1max;
7849             }
7850           /* Choose the left gap if the right is empty.  */
7851           else if (maxeq)
7852             {
7853               *vr0type = VR_RANGE;
7854               if (TREE_CODE (*vr0min) == INTEGER_CST)
7855                 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
7856                                            integer_one_node);
7857               else
7858                 *vr0max = *vr0min;
7859               *vr0min = vr1min;
7860             }
7861           /* Choose the anti-range if the range is effectively varying.  */
7862           else if (vrp_val_is_min (vr1min)
7863                    && vrp_val_is_max (vr1max))
7864             ;
7865           /* Else choose the range.  */
7866           else
7867             {
7868               *vr0type = vr1type;
7869               *vr0min = vr1min;
7870               *vr0max = vr1max;
7871             }
7872         }
7873       else if (*vr0type == VR_ANTI_RANGE
7874                && vr1type == VR_ANTI_RANGE)
7875         {
7876           /* If both are anti-ranges the result is the outer one.  */
7877           *vr0type = vr1type;
7878           *vr0min = vr1min;
7879           *vr0max = vr1max;
7880         }
7881       else if (vr1type == VR_ANTI_RANGE
7882                && *vr0type == VR_RANGE)
7883         {
7884           /* The intersection is empty.  */
7885           *vr0type = VR_UNDEFINED;
7886           *vr0min = NULL_TREE;
7887           *vr0max = NULL_TREE;
7888         }
7889       else
7890         gcc_unreachable ();
7891     }
7892   else if ((operand_less_p (vr1min, *vr0max) == 1
7893             || operand_equal_p (vr1min, *vr0max, 0))
7894            && operand_less_p (*vr0min, vr1min) == 1)
7895     {
7896       /* [  (  ]  ) or [  ](  ) */
7897       if (*vr0type == VR_ANTI_RANGE
7898           && vr1type == VR_ANTI_RANGE)
7899         *vr0max = vr1max;
7900       else if (*vr0type == VR_RANGE
7901                && vr1type == VR_RANGE)
7902         *vr0min = vr1min;
7903       else if (*vr0type == VR_RANGE
7904                && vr1type == VR_ANTI_RANGE)
7905         {
7906           if (TREE_CODE (vr1min) == INTEGER_CST)
7907             *vr0max = int_const_binop (MINUS_EXPR, vr1min,
7908                                        integer_one_node);
7909           else
7910             *vr0max = vr1min;
7911         }
7912       else if (*vr0type == VR_ANTI_RANGE
7913                && vr1type == VR_RANGE)
7914         {
7915           *vr0type = VR_RANGE;
7916           if (TREE_CODE (*vr0max) == INTEGER_CST)
7917             *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
7918                                        integer_one_node);
7919           else
7920             *vr0min = *vr0max;
7921           *vr0max = vr1max;
7922         }
7923       else
7924         gcc_unreachable ();
7925     }
7926   else if ((operand_less_p (*vr0min, vr1max) == 1
7927             || operand_equal_p (*vr0min, vr1max, 0))
7928            && operand_less_p (vr1min, *vr0min) == 1)
7929     {
7930       /* (  [  )  ] or (  )[  ] */
7931       if (*vr0type == VR_ANTI_RANGE
7932           && vr1type == VR_ANTI_RANGE)
7933         *vr0min = vr1min;
7934       else if (*vr0type == VR_RANGE
7935                && vr1type == VR_RANGE)
7936         *vr0max = vr1max;
7937       else if (*vr0type == VR_RANGE
7938                && vr1type == VR_ANTI_RANGE)
7939         {
7940           if (TREE_CODE (vr1max) == INTEGER_CST)
7941             *vr0min = int_const_binop (PLUS_EXPR, vr1max,
7942                                        integer_one_node);
7943           else
7944             *vr0min = vr1max;
7945         }
7946       else if (*vr0type == VR_ANTI_RANGE
7947                && vr1type == VR_RANGE)
7948         {
7949           *vr0type = VR_RANGE;
7950           if (TREE_CODE (*vr0min) == INTEGER_CST)
7951             *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
7952                                        integer_one_node);
7953           else
7954             *vr0max = *vr0min;
7955           *vr0min = vr1min;
7956         }
7957       else
7958         gcc_unreachable ();
7959     }
7960
7961   /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
7962      result for the intersection.  That's always a conservative
7963      correct estimate.  */
7964
7965   return;
7966 }
7967
7968
7969 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
7970    in *VR0.  This may not be the smallest possible such range.  */
7971
7972 static void
7973 vrp_intersect_ranges_1 (value_range_t *vr0, value_range_t *vr1)
7974 {
7975   value_range_t saved;
7976
7977   /* If either range is VR_VARYING the other one wins.  */
7978   if (vr1->type == VR_VARYING)
7979     return;
7980   if (vr0->type == VR_VARYING)
7981     {
7982       copy_value_range (vr0, vr1);
7983       return;
7984     }
7985
7986   /* When either range is VR_UNDEFINED the resulting range is
7987      VR_UNDEFINED, too.  */
7988   if (vr0->type == VR_UNDEFINED)
7989     return;
7990   if (vr1->type == VR_UNDEFINED)
7991     {
7992       set_value_range_to_undefined (vr0);
7993       return;
7994     }
7995
7996   /* Save the original vr0 so we can return it as conservative intersection
7997      result when our worker turns things to varying.  */
7998   saved = *vr0;
7999   intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8000                     vr1->type, vr1->min, vr1->max);
8001   /* Make sure to canonicalize the result though as the inversion of a
8002      VR_RANGE can still be a VR_RANGE.  */
8003   set_and_canonicalize_value_range (vr0, vr0->type,
8004                                     vr0->min, vr0->max, vr0->equiv);
8005   /* If that failed, use the saved original VR0.  */
8006   if (vr0->type == VR_VARYING)
8007     {
8008       *vr0 = saved;
8009       return;
8010     }
8011   /* If the result is VR_UNDEFINED there is no need to mess with
8012      the equivalencies.  */
8013   if (vr0->type == VR_UNDEFINED)
8014     return;
8015
8016   /* The resulting set of equivalences for range intersection is the union of
8017      the two sets.  */
8018   if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8019     bitmap_ior_into (vr0->equiv, vr1->equiv);
8020   else if (vr1->equiv && !vr0->equiv)
8021     bitmap_copy (vr0->equiv, vr1->equiv);
8022 }
8023
8024 static void
8025 vrp_intersect_ranges (value_range_t *vr0, value_range_t *vr1)
8026 {
8027   if (dump_file && (dump_flags & TDF_DETAILS))
8028     {
8029       fprintf (dump_file, "Intersecting\n  ");
8030       dump_value_range (dump_file, vr0);
8031       fprintf (dump_file, "\nand\n  ");
8032       dump_value_range (dump_file, vr1);
8033       fprintf (dump_file, "\n");
8034     }
8035   vrp_intersect_ranges_1 (vr0, vr1);
8036   if (dump_file && (dump_flags & TDF_DETAILS))
8037     {
8038       fprintf (dump_file, "to\n  ");
8039       dump_value_range (dump_file, vr0);
8040       fprintf (dump_file, "\n");
8041     }
8042 }
8043
8044 /* Meet operation for value ranges.  Given two value ranges VR0 and
8045    VR1, store in VR0 a range that contains both VR0 and VR1.  This
8046    may not be the smallest possible such range.  */
8047
8048 static void
8049 vrp_meet_1 (value_range_t *vr0, value_range_t *vr1)
8050 {
8051   value_range_t saved;
8052
8053   if (vr0->type == VR_UNDEFINED)
8054     {
8055       set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8056       return;
8057     }
8058
8059   if (vr1->type == VR_UNDEFINED)
8060     {
8061       /* VR0 already has the resulting range.  */
8062       return;
8063     }
8064
8065   if (vr0->type == VR_VARYING)
8066     {
8067       /* Nothing to do.  VR0 already has the resulting range.  */
8068       return;
8069     }
8070
8071   if (vr1->type == VR_VARYING)
8072     {
8073       set_value_range_to_varying (vr0);
8074       return;
8075     }
8076
8077   saved = *vr0;
8078   union_ranges (&vr0->type, &vr0->min, &vr0->max,
8079                 vr1->type, vr1->min, vr1->max);
8080   if (vr0->type == VR_VARYING)
8081     {
8082       /* Failed to find an efficient meet.  Before giving up and setting
8083          the result to VARYING, see if we can at least derive a useful
8084          anti-range.  FIXME, all this nonsense about distinguishing
8085          anti-ranges from ranges is necessary because of the odd
8086          semantics of range_includes_zero_p and friends.  */
8087       if (((saved.type == VR_RANGE
8088             && range_includes_zero_p (saved.min, saved.max) == 0)
8089            || (saved.type == VR_ANTI_RANGE
8090                && range_includes_zero_p (saved.min, saved.max) == 1))
8091           && ((vr1->type == VR_RANGE
8092                && range_includes_zero_p (vr1->min, vr1->max) == 0)
8093               || (vr1->type == VR_ANTI_RANGE
8094                   && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8095         {
8096           set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8097
8098           /* Since this meet operation did not result from the meeting of
8099              two equivalent names, VR0 cannot have any equivalences.  */
8100           if (vr0->equiv)
8101             bitmap_clear (vr0->equiv);
8102           return;
8103         }
8104
8105       set_value_range_to_varying (vr0);
8106       return;
8107     }
8108   set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8109                                     vr0->equiv);
8110   if (vr0->type == VR_VARYING)
8111     return;
8112
8113   /* The resulting set of equivalences is always the intersection of
8114      the two sets.  */
8115   if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8116     bitmap_and_into (vr0->equiv, vr1->equiv);
8117   else if (vr0->equiv && !vr1->equiv)
8118     bitmap_clear (vr0->equiv);
8119 }
8120
8121 static void
8122 vrp_meet (value_range_t *vr0, value_range_t *vr1)
8123 {
8124   if (dump_file && (dump_flags & TDF_DETAILS))
8125     {
8126       fprintf (dump_file, "Meeting\n  ");
8127       dump_value_range (dump_file, vr0);
8128       fprintf (dump_file, "\nand\n  ");
8129       dump_value_range (dump_file, vr1);
8130       fprintf (dump_file, "\n");
8131     }
8132   vrp_meet_1 (vr0, vr1);
8133   if (dump_file && (dump_flags & TDF_DETAILS))
8134     {
8135       fprintf (dump_file, "to\n  ");
8136       dump_value_range (dump_file, vr0);
8137       fprintf (dump_file, "\n");
8138     }
8139 }
8140
8141
8142 /* Visit all arguments for PHI node PHI that flow through executable
8143    edges.  If a valid value range can be derived from all the incoming
8144    value ranges, set a new range for the LHS of PHI.  */
8145
8146 static enum ssa_prop_result
8147 vrp_visit_phi_node (gimple phi)
8148 {
8149   size_t i;
8150   tree lhs = PHI_RESULT (phi);
8151   value_range_t *lhs_vr = get_value_range (lhs);
8152   value_range_t vr_result = VR_INITIALIZER;
8153   bool first = true;
8154   int edges, old_edges;
8155   struct loop *l;
8156
8157   if (dump_file && (dump_flags & TDF_DETAILS))
8158     {
8159       fprintf (dump_file, "\nVisiting PHI node: ");
8160       print_gimple_stmt (dump_file, phi, 0, dump_flags);
8161     }
8162
8163   edges = 0;
8164   for (i = 0; i < gimple_phi_num_args (phi); i++)
8165     {
8166       edge e = gimple_phi_arg_edge (phi, i);
8167
8168       if (dump_file && (dump_flags & TDF_DETAILS))
8169         {
8170           fprintf (dump_file,
8171               "\n    Argument #%d (%d -> %d %sexecutable)\n",
8172               (int) i, e->src->index, e->dest->index,
8173               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8174         }
8175
8176       if (e->flags & EDGE_EXECUTABLE)
8177         {
8178           tree arg = PHI_ARG_DEF (phi, i);
8179           value_range_t vr_arg;
8180
8181           ++edges;
8182
8183           if (TREE_CODE (arg) == SSA_NAME)
8184             {
8185               vr_arg = *(get_value_range (arg));
8186               /* Do not allow equivalences or symbolic ranges to leak in from
8187                  backedges.  That creates invalid equivalencies.
8188                  See PR53465 and PR54767.  */
8189               if (e->flags & EDGE_DFS_BACK
8190                   && (vr_arg.type == VR_RANGE
8191                       || vr_arg.type == VR_ANTI_RANGE))
8192                 {
8193                   vr_arg.equiv = NULL;
8194                   if (symbolic_range_p (&vr_arg))
8195                     {
8196                       vr_arg.type = VR_VARYING;
8197                       vr_arg.min = NULL_TREE;
8198                       vr_arg.max = NULL_TREE;
8199                     }
8200                 }
8201             }
8202           else
8203             {
8204               if (is_overflow_infinity (arg))
8205                 {
8206                   arg = copy_node (arg);
8207                   TREE_OVERFLOW (arg) = 0;
8208                 }
8209
8210               vr_arg.type = VR_RANGE;
8211               vr_arg.min = arg;
8212               vr_arg.max = arg;
8213               vr_arg.equiv = NULL;
8214             }
8215
8216           if (dump_file && (dump_flags & TDF_DETAILS))
8217             {
8218               fprintf (dump_file, "\t");
8219               print_generic_expr (dump_file, arg, dump_flags);
8220               fprintf (dump_file, "\n\tValue: ");
8221               dump_value_range (dump_file, &vr_arg);
8222               fprintf (dump_file, "\n");
8223             }
8224
8225           if (first)
8226             copy_value_range (&vr_result, &vr_arg);
8227           else
8228             vrp_meet (&vr_result, &vr_arg);
8229           first = false;
8230
8231           if (vr_result.type == VR_VARYING)
8232             break;
8233         }
8234     }
8235
8236   if (vr_result.type == VR_VARYING)
8237     goto varying;
8238   else if (vr_result.type == VR_UNDEFINED)
8239     goto update_range;
8240
8241   old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
8242   vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
8243
8244   /* To prevent infinite iterations in the algorithm, derive ranges
8245      when the new value is slightly bigger or smaller than the
8246      previous one.  We don't do this if we have seen a new executable
8247      edge; this helps us avoid an overflow infinity for conditionals
8248      which are not in a loop.  If the old value-range was VR_UNDEFINED
8249      use the updated range and iterate one more time.  */
8250   if (edges > 0
8251       && gimple_phi_num_args (phi) > 1
8252       && edges == old_edges
8253       && lhs_vr->type != VR_UNDEFINED)
8254     {
8255       int cmp_min = compare_values (lhs_vr->min, vr_result.min);
8256       int cmp_max = compare_values (lhs_vr->max, vr_result.max);
8257
8258       /* For non VR_RANGE or for pointers fall back to varying if
8259          the range changed.  */
8260       if ((lhs_vr->type != VR_RANGE || vr_result.type != VR_RANGE
8261            || POINTER_TYPE_P (TREE_TYPE (lhs)))
8262           && (cmp_min != 0 || cmp_max != 0))
8263         goto varying;
8264
8265       /* If the new minimum is smaller or larger than the previous
8266          one, go all the way to -INF.  In the first case, to avoid
8267          iterating millions of times to reach -INF, and in the
8268          other case to avoid infinite bouncing between different
8269          minimums.  */
8270       if (cmp_min > 0 || cmp_min < 0)
8271         {
8272           if (!needs_overflow_infinity (TREE_TYPE (vr_result.min))
8273               || !vrp_var_may_overflow (lhs, phi))
8274             vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
8275           else if (supports_overflow_infinity (TREE_TYPE (vr_result.min)))
8276             vr_result.min =
8277                 negative_overflow_infinity (TREE_TYPE (vr_result.min));
8278         }
8279
8280       /* Similarly, if the new maximum is smaller or larger than
8281          the previous one, go all the way to +INF.  */
8282       if (cmp_max < 0 || cmp_max > 0)
8283         {
8284           if (!needs_overflow_infinity (TREE_TYPE (vr_result.max))
8285               || !vrp_var_may_overflow (lhs, phi))
8286             vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
8287           else if (supports_overflow_infinity (TREE_TYPE (vr_result.max)))
8288             vr_result.max =
8289                 positive_overflow_infinity (TREE_TYPE (vr_result.max));
8290         }
8291
8292       /* If we dropped either bound to +-INF then if this is a loop
8293          PHI node SCEV may known more about its value-range.  */
8294       if ((cmp_min > 0 || cmp_min < 0
8295            || cmp_max < 0 || cmp_max > 0)
8296           && current_loops
8297           && (l = loop_containing_stmt (phi))
8298           && l->header == gimple_bb (phi))
8299         adjust_range_with_scev (&vr_result, l, phi, lhs);
8300
8301       /* If we will end up with a (-INF, +INF) range, set it to
8302          VARYING.  Same if the previous max value was invalid for
8303          the type and we end up with vr_result.min > vr_result.max.  */
8304       if ((vrp_val_is_max (vr_result.max)
8305            && vrp_val_is_min (vr_result.min))
8306           || compare_values (vr_result.min,
8307                              vr_result.max) > 0)
8308         goto varying;
8309     }
8310
8311   /* If the new range is different than the previous value, keep
8312      iterating.  */
8313 update_range:
8314   if (update_value_range (lhs, &vr_result))
8315     {
8316       if (dump_file && (dump_flags & TDF_DETAILS))
8317         {
8318           fprintf (dump_file, "Found new range for ");
8319           print_generic_expr (dump_file, lhs, 0);
8320           fprintf (dump_file, ": ");
8321           dump_value_range (dump_file, &vr_result);
8322           fprintf (dump_file, "\n\n");
8323         }
8324
8325       return SSA_PROP_INTERESTING;
8326     }
8327
8328   /* Nothing changed, don't add outgoing edges.  */
8329   return SSA_PROP_NOT_INTERESTING;
8330
8331   /* No match found.  Set the LHS to VARYING.  */
8332 varying:
8333   set_value_range_to_varying (lhs_vr);
8334   return SSA_PROP_VARYING;
8335 }
8336
8337 /* Simplify boolean operations if the source is known
8338    to be already a boolean.  */
8339 static bool
8340 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
8341 {
8342   enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
8343   tree lhs, op0, op1;
8344   bool need_conversion;
8345
8346   /* We handle only !=/== case here.  */
8347   gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
8348
8349   op0 = gimple_assign_rhs1 (stmt);
8350   if (!op_with_boolean_value_range_p (op0))
8351     return false;
8352
8353   op1 = gimple_assign_rhs2 (stmt);
8354   if (!op_with_boolean_value_range_p (op1))
8355     return false;
8356
8357   /* Reduce number of cases to handle to NE_EXPR.  As there is no
8358      BIT_XNOR_EXPR we cannot replace A == B with a single statement.  */
8359   if (rhs_code == EQ_EXPR)
8360     {
8361       if (TREE_CODE (op1) == INTEGER_CST)
8362         op1 = int_const_binop (BIT_XOR_EXPR, op1, integer_one_node);
8363       else
8364         return false;
8365     }
8366
8367   lhs = gimple_assign_lhs (stmt);
8368   need_conversion
8369     = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
8370
8371   /* Make sure to not sign-extend a 1-bit 1 when converting the result.  */
8372   if (need_conversion
8373       && !TYPE_UNSIGNED (TREE_TYPE (op0))
8374       && TYPE_PRECISION (TREE_TYPE (op0)) == 1
8375       && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
8376     return false;
8377
8378   /* For A != 0 we can substitute A itself.  */
8379   if (integer_zerop (op1))
8380     gimple_assign_set_rhs_with_ops (gsi,
8381                                     need_conversion
8382                                     ? NOP_EXPR : TREE_CODE (op0),
8383                                     op0, NULL_TREE);
8384   /* For A != B we substitute A ^ B.  Either with conversion.  */
8385   else if (need_conversion)
8386     {
8387       tree tem = make_ssa_name (TREE_TYPE (op0), NULL);
8388       gimple newop = gimple_build_assign_with_ops (BIT_XOR_EXPR, tem, op0, op1);
8389       gsi_insert_before (gsi, newop, GSI_SAME_STMT);
8390       gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem, NULL_TREE);
8391     }
8392   /* Or without.  */
8393   else
8394     gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
8395   update_stmt (gsi_stmt (*gsi));
8396
8397   return true;
8398 }
8399
8400 /* Simplify a division or modulo operator to a right shift or
8401    bitwise and if the first operand is unsigned or is greater
8402    than zero and the second operand is an exact power of two.  */
8403
8404 static bool
8405 simplify_div_or_mod_using_ranges (gimple stmt)
8406 {
8407   enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
8408   tree val = NULL;
8409   tree op0 = gimple_assign_rhs1 (stmt);
8410   tree op1 = gimple_assign_rhs2 (stmt);
8411   value_range_t *vr = get_value_range (gimple_assign_rhs1 (stmt));
8412
8413   if (TYPE_UNSIGNED (TREE_TYPE (op0)))
8414     {
8415       val = integer_one_node;
8416     }
8417   else
8418     {
8419       bool sop = false;
8420
8421       val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
8422
8423       if (val
8424           && sop
8425           && integer_onep (val)
8426           && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
8427         {
8428           location_t location;
8429
8430           if (!gimple_has_location (stmt))
8431             location = input_location;
8432           else
8433             location = gimple_location (stmt);
8434           warning_at (location, OPT_Wstrict_overflow,
8435                       "assuming signed overflow does not occur when "
8436                       "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
8437         }
8438     }
8439
8440   if (val && integer_onep (val))
8441     {
8442       tree t;
8443
8444       if (rhs_code == TRUNC_DIV_EXPR)
8445         {
8446           t = build_int_cst (integer_type_node, tree_log2 (op1));
8447           gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
8448           gimple_assign_set_rhs1 (stmt, op0);
8449           gimple_assign_set_rhs2 (stmt, t);
8450         }
8451       else
8452         {
8453           t = build_int_cst (TREE_TYPE (op1), 1);
8454           t = int_const_binop (MINUS_EXPR, op1, t);
8455           t = fold_convert (TREE_TYPE (op0), t);
8456
8457           gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
8458           gimple_assign_set_rhs1 (stmt, op0);
8459           gimple_assign_set_rhs2 (stmt, t);
8460         }
8461
8462       update_stmt (stmt);
8463       return true;
8464     }
8465
8466   return false;
8467 }
8468
8469 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
8470    ABS_EXPR.  If the operand is <= 0, then simplify the
8471    ABS_EXPR into a NEGATE_EXPR.  */
8472
8473 static bool
8474 simplify_abs_using_ranges (gimple stmt)
8475 {
8476   tree val = NULL;
8477   tree op = gimple_assign_rhs1 (stmt);
8478   tree type = TREE_TYPE (op);
8479   value_range_t *vr = get_value_range (op);
8480
8481   if (TYPE_UNSIGNED (type))
8482     {
8483       val = integer_zero_node;
8484     }
8485   else if (vr)
8486     {
8487       bool sop = false;
8488
8489       val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
8490       if (!val)
8491         {
8492           sop = false;
8493           val = compare_range_with_value (GE_EXPR, vr, integer_zero_node,
8494                                           &sop);
8495
8496           if (val)
8497             {
8498               if (integer_zerop (val))
8499                 val = integer_one_node;
8500               else if (integer_onep (val))
8501                 val = integer_zero_node;
8502             }
8503         }
8504
8505       if (val
8506           && (integer_onep (val) || integer_zerop (val)))
8507         {
8508           if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
8509             {
8510               location_t location;
8511
8512               if (!gimple_has_location (stmt))
8513                 location = input_location;
8514               else
8515                 location = gimple_location (stmt);
8516               warning_at (location, OPT_Wstrict_overflow,
8517                           "assuming signed overflow does not occur when "
8518                           "simplifying %<abs (X)%> to %<X%> or %<-X%>");
8519             }
8520
8521           gimple_assign_set_rhs1 (stmt, op);
8522           if (integer_onep (val))
8523             gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
8524           else
8525             gimple_assign_set_rhs_code (stmt, SSA_NAME);
8526           update_stmt (stmt);
8527           return true;
8528         }
8529     }
8530
8531   return false;
8532 }
8533
8534 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
8535    If all the bits that are being cleared by & are already
8536    known to be zero from VR, or all the bits that are being
8537    set by | are already known to be one from VR, the bit
8538    operation is redundant.  */
8539
8540 static bool
8541 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
8542 {
8543   tree op0 = gimple_assign_rhs1 (stmt);
8544   tree op1 = gimple_assign_rhs2 (stmt);
8545   tree op = NULL_TREE;
8546   value_range_t vr0 = VR_INITIALIZER;
8547   value_range_t vr1 = VR_INITIALIZER;
8548   double_int may_be_nonzero0, may_be_nonzero1;
8549   double_int must_be_nonzero0, must_be_nonzero1;
8550   double_int mask;
8551
8552   if (TREE_CODE (op0) == SSA_NAME)
8553     vr0 = *(get_value_range (op0));
8554   else if (is_gimple_min_invariant (op0))
8555     set_value_range_to_value (&vr0, op0, NULL);
8556   else
8557     return false;
8558
8559   if (TREE_CODE (op1) == SSA_NAME)
8560     vr1 = *(get_value_range (op1));
8561   else if (is_gimple_min_invariant (op1))
8562     set_value_range_to_value (&vr1, op1, NULL);
8563   else
8564     return false;
8565
8566   if (!zero_nonzero_bits_from_vr (&vr0, &may_be_nonzero0, &must_be_nonzero0))
8567     return false;
8568   if (!zero_nonzero_bits_from_vr (&vr1, &may_be_nonzero1, &must_be_nonzero1))
8569     return false;
8570
8571   switch (gimple_assign_rhs_code (stmt))
8572     {
8573     case BIT_AND_EXPR:
8574       mask = may_be_nonzero0.and_not (must_be_nonzero1);
8575       if (mask.is_zero ())
8576         {
8577           op = op0;
8578           break;
8579         }
8580       mask = may_be_nonzero1.and_not (must_be_nonzero0);
8581       if (mask.is_zero ())
8582         {
8583           op = op1;
8584           break;
8585         }
8586       break;
8587     case BIT_IOR_EXPR:
8588       mask = may_be_nonzero0.and_not (must_be_nonzero1);
8589       if (mask.is_zero ())
8590         {
8591           op = op1;
8592           break;
8593         }
8594       mask = may_be_nonzero1.and_not (must_be_nonzero0);
8595       if (mask.is_zero ())
8596         {
8597           op = op0;
8598           break;
8599         }
8600       break;
8601     default:
8602       gcc_unreachable ();
8603     }
8604
8605   if (op == NULL_TREE)
8606     return false;
8607
8608   gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op, NULL);
8609   update_stmt (gsi_stmt (*gsi));
8610   return true;
8611 }
8612
8613 /* We are comparing trees OP0 and OP1 using COND_CODE.  OP0 has
8614    a known value range VR.
8615
8616    If there is one and only one value which will satisfy the
8617    conditional, then return that value.  Else return NULL.  */
8618
8619 static tree
8620 test_for_singularity (enum tree_code cond_code, tree op0,
8621                       tree op1, value_range_t *vr)
8622 {
8623   tree min = NULL;
8624   tree max = NULL;
8625
8626   /* Extract minimum/maximum values which satisfy the
8627      the conditional as it was written.  */
8628   if (cond_code == LE_EXPR || cond_code == LT_EXPR)
8629     {
8630       /* This should not be negative infinity; there is no overflow
8631          here.  */
8632       min = TYPE_MIN_VALUE (TREE_TYPE (op0));
8633
8634       max = op1;
8635       if (cond_code == LT_EXPR && !is_overflow_infinity (max))
8636         {
8637           tree one = build_int_cst (TREE_TYPE (op0), 1);
8638           max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
8639           if (EXPR_P (max))
8640             TREE_NO_WARNING (max) = 1;
8641         }
8642     }
8643   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
8644     {
8645       /* This should not be positive infinity; there is no overflow
8646          here.  */
8647       max = TYPE_MAX_VALUE (TREE_TYPE (op0));
8648
8649       min = op1;
8650       if (cond_code == GT_EXPR && !is_overflow_infinity (min))
8651         {
8652           tree one = build_int_cst (TREE_TYPE (op0), 1);
8653           min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
8654           if (EXPR_P (min))
8655             TREE_NO_WARNING (min) = 1;
8656         }
8657     }
8658
8659   /* Now refine the minimum and maximum values using any
8660      value range information we have for op0.  */
8661   if (min && max)
8662     {
8663       if (compare_values (vr->min, min) == 1)
8664         min = vr->min;
8665       if (compare_values (vr->max, max) == -1)
8666         max = vr->max;
8667
8668       /* If the new min/max values have converged to a single value,
8669          then there is only one value which can satisfy the condition,
8670          return that value.  */
8671       if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
8672         return min;
8673     }
8674   return NULL;
8675 }
8676
8677 /* Return whether the value range *VR fits in an integer type specified
8678    by PRECISION and UNSIGNED_P.  */
8679
8680 static bool
8681 range_fits_type_p (value_range_t *vr, unsigned precision, bool unsigned_p)
8682 {
8683   tree src_type;
8684   unsigned src_precision;
8685   double_int tem;
8686
8687   /* We can only handle integral and pointer types.  */
8688   src_type = TREE_TYPE (vr->min);
8689   if (!INTEGRAL_TYPE_P (src_type)
8690       && !POINTER_TYPE_P (src_type))
8691     return false;
8692
8693   /* An extension is fine unless VR is signed and unsigned_p,
8694      and so is an identity transform.  */
8695   src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
8696   if ((src_precision < precision
8697        && !(unsigned_p && !TYPE_UNSIGNED (src_type)))
8698       || (src_precision == precision
8699           && TYPE_UNSIGNED (src_type) == unsigned_p))
8700     return true;
8701
8702   /* Now we can only handle ranges with constant bounds.  */
8703   if (vr->type != VR_RANGE
8704       || TREE_CODE (vr->min) != INTEGER_CST
8705       || TREE_CODE (vr->max) != INTEGER_CST)
8706     return false;
8707
8708   /* For sign changes, the MSB of the double_int has to be clear.
8709      An unsigned value with its MSB set cannot be represented by
8710      a signed double_int, while a negative value cannot be represented
8711      by an unsigned double_int.  */
8712   if (TYPE_UNSIGNED (src_type) != unsigned_p
8713       && (TREE_INT_CST_HIGH (vr->min) | TREE_INT_CST_HIGH (vr->max)) < 0)
8714     return false;
8715
8716   /* Then we can perform the conversion on both ends and compare
8717      the result for equality.  */
8718   tem = tree_to_double_int (vr->min).ext (precision, unsigned_p);
8719   if (tree_to_double_int (vr->min) != tem)
8720     return false;
8721   tem = tree_to_double_int (vr->max).ext (precision, unsigned_p);
8722   if (tree_to_double_int (vr->max) != tem)
8723     return false;
8724
8725   return true;
8726 }
8727
8728 /* Simplify a conditional using a relational operator to an equality
8729    test if the range information indicates only one value can satisfy
8730    the original conditional.  */
8731
8732 static bool
8733 simplify_cond_using_ranges (gimple stmt)
8734 {
8735   tree op0 = gimple_cond_lhs (stmt);
8736   tree op1 = gimple_cond_rhs (stmt);
8737   enum tree_code cond_code = gimple_cond_code (stmt);
8738
8739   if (cond_code != NE_EXPR
8740       && cond_code != EQ_EXPR
8741       && TREE_CODE (op0) == SSA_NAME
8742       && INTEGRAL_TYPE_P (TREE_TYPE (op0))
8743       && is_gimple_min_invariant (op1))
8744     {
8745       value_range_t *vr = get_value_range (op0);
8746
8747       /* If we have range information for OP0, then we might be
8748          able to simplify this conditional. */
8749       if (vr->type == VR_RANGE)
8750         {
8751           tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
8752
8753           if (new_tree)
8754             {
8755               if (dump_file)
8756                 {
8757                   fprintf (dump_file, "Simplified relational ");
8758                   print_gimple_stmt (dump_file, stmt, 0, 0);
8759                   fprintf (dump_file, " into ");
8760                 }
8761
8762               gimple_cond_set_code (stmt, EQ_EXPR);
8763               gimple_cond_set_lhs (stmt, op0);
8764               gimple_cond_set_rhs (stmt, new_tree);
8765
8766               update_stmt (stmt);
8767
8768               if (dump_file)
8769                 {
8770                   print_gimple_stmt (dump_file, stmt, 0, 0);
8771                   fprintf (dump_file, "\n");
8772                 }
8773
8774               return true;
8775             }
8776
8777           /* Try again after inverting the condition.  We only deal
8778              with integral types here, so no need to worry about
8779              issues with inverting FP comparisons.  */
8780           cond_code = invert_tree_comparison (cond_code, false);
8781           new_tree = test_for_singularity (cond_code, op0, op1, vr);
8782
8783           if (new_tree)
8784             {
8785               if (dump_file)
8786                 {
8787                   fprintf (dump_file, "Simplified relational ");
8788                   print_gimple_stmt (dump_file, stmt, 0, 0);
8789                   fprintf (dump_file, " into ");
8790                 }
8791
8792               gimple_cond_set_code (stmt, NE_EXPR);
8793               gimple_cond_set_lhs (stmt, op0);
8794               gimple_cond_set_rhs (stmt, new_tree);
8795
8796               update_stmt (stmt);
8797
8798               if (dump_file)
8799                 {
8800                   print_gimple_stmt (dump_file, stmt, 0, 0);
8801                   fprintf (dump_file, "\n");
8802                 }
8803
8804               return true;
8805             }
8806         }
8807     }
8808
8809   /* If we have a comparison of an SSA_NAME (OP0) against a constant,
8810      see if OP0 was set by a type conversion where the source of
8811      the conversion is another SSA_NAME with a range that fits
8812      into the range of OP0's type.
8813
8814      If so, the conversion is redundant as the earlier SSA_NAME can be
8815      used for the comparison directly if we just massage the constant in the
8816      comparison.  */
8817   if (TREE_CODE (op0) == SSA_NAME
8818       && TREE_CODE (op1) == INTEGER_CST)
8819     {
8820       gimple def_stmt = SSA_NAME_DEF_STMT (op0);
8821       tree innerop;
8822
8823       if (!is_gimple_assign (def_stmt)
8824           || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
8825         return false;
8826
8827       innerop = gimple_assign_rhs1 (def_stmt);
8828
8829       if (TREE_CODE (innerop) == SSA_NAME
8830           && !POINTER_TYPE_P (TREE_TYPE (innerop)))
8831         {
8832           value_range_t *vr = get_value_range (innerop);
8833
8834           if (range_int_cst_p (vr)
8835               && range_fits_type_p (vr,
8836                                     TYPE_PRECISION (TREE_TYPE (op0)),
8837                                     TYPE_UNSIGNED (TREE_TYPE (op0)))
8838               && int_fits_type_p (op1, TREE_TYPE (innerop))
8839               /* The range must not have overflowed, or if it did overflow
8840                  we must not be wrapping/trapping overflow and optimizing
8841                  with strict overflow semantics.  */
8842               && ((!is_negative_overflow_infinity (vr->min)
8843                    && !is_positive_overflow_infinity (vr->max))
8844                   || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (innerop))))
8845             {
8846               /* If the range overflowed and the user has asked for warnings
8847                  when strict overflow semantics were used to optimize code,
8848                  issue an appropriate warning.  */
8849               if ((is_negative_overflow_infinity (vr->min)
8850                    || is_positive_overflow_infinity (vr->max))
8851                   && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_CONDITIONAL))
8852                 {
8853                   location_t location;
8854
8855                   if (!gimple_has_location (stmt))
8856                     location = input_location;
8857                   else
8858                     location = gimple_location (stmt);
8859                   warning_at (location, OPT_Wstrict_overflow,
8860                       "assuming signed overflow does not occur when "
8861                       "simplifying conditional");
8862                 }
8863
8864               tree newconst = fold_convert (TREE_TYPE (innerop), op1);
8865               gimple_cond_set_lhs (stmt, innerop);
8866               gimple_cond_set_rhs (stmt, newconst);
8867               return true;
8868             }
8869         }
8870     }
8871
8872   return false;
8873 }
8874
8875 /* Simplify a switch statement using the value range of the switch
8876    argument.  */
8877
8878 static bool
8879 simplify_switch_using_ranges (gimple stmt)
8880 {
8881   tree op = gimple_switch_index (stmt);
8882   value_range_t *vr;
8883   bool take_default;
8884   edge e;
8885   edge_iterator ei;
8886   size_t i = 0, j = 0, n, n2;
8887   tree vec2;
8888   switch_update su;
8889   size_t k = 1, l = 0;
8890
8891   if (TREE_CODE (op) == SSA_NAME)
8892     {
8893       vr = get_value_range (op);
8894
8895       /* We can only handle integer ranges.  */
8896       if ((vr->type != VR_RANGE
8897            && vr->type != VR_ANTI_RANGE)
8898           || symbolic_range_p (vr))
8899         return false;
8900
8901       /* Find case label for min/max of the value range.  */
8902       take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
8903     }
8904   else if (TREE_CODE (op) == INTEGER_CST)
8905     {
8906       take_default = !find_case_label_index (stmt, 1, op, &i);
8907       if (take_default)
8908         {
8909           i = 1;
8910           j = 0;
8911         }
8912       else
8913         {
8914           j = i;
8915         }
8916     }
8917   else
8918     return false;
8919
8920   n = gimple_switch_num_labels (stmt);
8921
8922   /* Bail out if this is just all edges taken.  */
8923   if (i == 1
8924       && j == n - 1
8925       && take_default)
8926     return false;
8927
8928   /* Build a new vector of taken case labels.  */
8929   vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
8930   n2 = 0;
8931
8932   /* Add the default edge, if necessary.  */
8933   if (take_default)
8934     TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
8935
8936   for (; i <= j; ++i, ++n2)
8937     TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
8938
8939   for (; k <= l; ++k, ++n2)
8940     TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
8941
8942   /* Mark needed edges.  */
8943   for (i = 0; i < n2; ++i)
8944     {
8945       e = find_edge (gimple_bb (stmt),
8946                      label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
8947       e->aux = (void *)-1;
8948     }
8949
8950   /* Queue not needed edges for later removal.  */
8951   FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
8952     {
8953       if (e->aux == (void *)-1)
8954         {
8955           e->aux = NULL;
8956           continue;
8957         }
8958
8959       if (dump_file && (dump_flags & TDF_DETAILS))
8960         {
8961           fprintf (dump_file, "removing unreachable case label\n");
8962         }
8963       to_remove_edges.safe_push (e);
8964       e->flags &= ~EDGE_EXECUTABLE;
8965     }
8966
8967   /* And queue an update for the stmt.  */
8968   su.stmt = stmt;
8969   su.vec = vec2;
8970   to_update_switch_stmts.safe_push (su);
8971   return false;
8972 }
8973
8974 /* Simplify an integral conversion from an SSA name in STMT.  */
8975
8976 static bool
8977 simplify_conversion_using_ranges (gimple stmt)
8978 {
8979   tree innerop, middleop, finaltype;
8980   gimple def_stmt;
8981   value_range_t *innervr;
8982   bool inner_unsigned_p, middle_unsigned_p, final_unsigned_p;
8983   unsigned inner_prec, middle_prec, final_prec;
8984   double_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
8985
8986   finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
8987   if (!INTEGRAL_TYPE_P (finaltype))
8988     return false;
8989   middleop = gimple_assign_rhs1 (stmt);
8990   def_stmt = SSA_NAME_DEF_STMT (middleop);
8991   if (!is_gimple_assign (def_stmt)
8992       || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
8993     return false;
8994   innerop = gimple_assign_rhs1 (def_stmt);
8995   if (TREE_CODE (innerop) != SSA_NAME
8996       || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
8997     return false;
8998
8999   /* Get the value-range of the inner operand.  */
9000   innervr = get_value_range (innerop);
9001   if (innervr->type != VR_RANGE
9002       || TREE_CODE (innervr->min) != INTEGER_CST
9003       || TREE_CODE (innervr->max) != INTEGER_CST)
9004     return false;
9005
9006   /* Simulate the conversion chain to check if the result is equal if
9007      the middle conversion is removed.  */
9008   innermin = tree_to_double_int (innervr->min);
9009   innermax = tree_to_double_int (innervr->max);
9010
9011   inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
9012   middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
9013   final_prec = TYPE_PRECISION (finaltype);
9014
9015   /* If the first conversion is not injective, the second must not
9016      be widening.  */
9017   if ((innermax - innermin).ugt (double_int::mask (middle_prec))
9018       && middle_prec < final_prec)
9019     return false;
9020   /* We also want a medium value so that we can track the effect that
9021      narrowing conversions with sign change have.  */
9022   inner_unsigned_p = TYPE_UNSIGNED (TREE_TYPE (innerop));
9023   if (inner_unsigned_p)
9024     innermed = double_int::mask (inner_prec).lrshift (1, inner_prec);
9025   else
9026     innermed = double_int_zero;
9027   if (innermin.cmp (innermed, inner_unsigned_p) >= 0
9028       || innermed.cmp (innermax, inner_unsigned_p) >= 0)
9029     innermed = innermin;
9030
9031   middle_unsigned_p = TYPE_UNSIGNED (TREE_TYPE (middleop));
9032   middlemin = innermin.ext (middle_prec, middle_unsigned_p);
9033   middlemed = innermed.ext (middle_prec, middle_unsigned_p);
9034   middlemax = innermax.ext (middle_prec, middle_unsigned_p);
9035
9036   /* Require that the final conversion applied to both the original
9037      and the intermediate range produces the same result.  */
9038   final_unsigned_p = TYPE_UNSIGNED (finaltype);
9039   if (middlemin.ext (final_prec, final_unsigned_p)
9040          != innermin.ext (final_prec, final_unsigned_p)
9041       || middlemed.ext (final_prec, final_unsigned_p)
9042          != innermed.ext (final_prec, final_unsigned_p)
9043       || middlemax.ext (final_prec, final_unsigned_p)
9044          != innermax.ext (final_prec, final_unsigned_p))
9045     return false;
9046
9047   gimple_assign_set_rhs1 (stmt, innerop);
9048   update_stmt (stmt);
9049   return true;
9050 }
9051
9052 /* Simplify a conversion from integral SSA name to float in STMT.  */
9053
9054 static bool
9055 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
9056 {
9057   tree rhs1 = gimple_assign_rhs1 (stmt);
9058   value_range_t *vr = get_value_range (rhs1);
9059   enum machine_mode fltmode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
9060   enum machine_mode mode;
9061   tree tem;
9062   gimple conv;
9063
9064   /* We can only handle constant ranges.  */
9065   if (vr->type != VR_RANGE
9066       || TREE_CODE (vr->min) != INTEGER_CST
9067       || TREE_CODE (vr->max) != INTEGER_CST)
9068     return false;
9069
9070   /* First check if we can use a signed type in place of an unsigned.  */
9071   if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
9072       && (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)), 0)
9073           != CODE_FOR_nothing)
9074       && range_fits_type_p (vr, GET_MODE_PRECISION
9075                                   (TYPE_MODE (TREE_TYPE (rhs1))), 0))
9076     mode = TYPE_MODE (TREE_TYPE (rhs1));
9077   /* If we can do the conversion in the current input mode do nothing.  */
9078   else if (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)),
9079                         TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
9080     return false;
9081   /* Otherwise search for a mode we can use, starting from the narrowest
9082      integer mode available.  */
9083   else
9084     {
9085       mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
9086       do
9087         {
9088           /* If we cannot do a signed conversion to float from mode
9089              or if the value-range does not fit in the signed type
9090              try with a wider mode.  */
9091           if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
9092               && range_fits_type_p (vr, GET_MODE_PRECISION (mode), 0))
9093             break;
9094
9095           mode = GET_MODE_WIDER_MODE (mode);
9096           /* But do not widen the input.  Instead leave that to the
9097              optabs expansion code.  */
9098           if (GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
9099             return false;
9100         }
9101       while (mode != VOIDmode);
9102       if (mode == VOIDmode)
9103         return false;
9104     }
9105
9106   /* It works, insert a truncation or sign-change before the
9107      float conversion.  */
9108   tem = make_ssa_name (build_nonstandard_integer_type
9109                           (GET_MODE_PRECISION (mode), 0), NULL);
9110   conv = gimple_build_assign_with_ops (NOP_EXPR, tem, rhs1, NULL_TREE);
9111   gsi_insert_before (gsi, conv, GSI_SAME_STMT);
9112   gimple_assign_set_rhs1 (stmt, tem);
9113   update_stmt (stmt);
9114
9115   return true;
9116 }
9117
9118 /* Simplify STMT using ranges if possible.  */
9119
9120 static bool
9121 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
9122 {
9123   gimple stmt = gsi_stmt (*gsi);
9124   if (is_gimple_assign (stmt))
9125     {
9126       enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9127       tree rhs1 = gimple_assign_rhs1 (stmt);
9128
9129       switch (rhs_code)
9130         {
9131         case EQ_EXPR:
9132         case NE_EXPR:
9133           /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
9134              if the RHS is zero or one, and the LHS are known to be boolean
9135              values.  */
9136           if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9137             return simplify_truth_ops_using_ranges (gsi, stmt);
9138           break;
9139
9140       /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
9141          and BIT_AND_EXPR respectively if the first operand is greater
9142          than zero and the second operand is an exact power of two.  */
9143         case TRUNC_DIV_EXPR:
9144         case TRUNC_MOD_EXPR:
9145           if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
9146               && integer_pow2p (gimple_assign_rhs2 (stmt)))
9147             return simplify_div_or_mod_using_ranges (stmt);
9148           break;
9149
9150       /* Transform ABS (X) into X or -X as appropriate.  */
9151         case ABS_EXPR:
9152           if (TREE_CODE (rhs1) == SSA_NAME
9153               && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9154             return simplify_abs_using_ranges (stmt);
9155           break;
9156
9157         case BIT_AND_EXPR:
9158         case BIT_IOR_EXPR:
9159           /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
9160              if all the bits being cleared are already cleared or
9161              all the bits being set are already set.  */
9162           if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9163             return simplify_bit_ops_using_ranges (gsi, stmt);
9164           break;
9165
9166         CASE_CONVERT:
9167           if (TREE_CODE (rhs1) == SSA_NAME
9168               && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9169             return simplify_conversion_using_ranges (stmt);
9170           break;
9171
9172         case FLOAT_EXPR:
9173           if (TREE_CODE (rhs1) == SSA_NAME
9174               && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9175             return simplify_float_conversion_using_ranges (gsi, stmt);
9176           break;
9177
9178         default:
9179           break;
9180         }
9181     }
9182   else if (gimple_code (stmt) == GIMPLE_COND)
9183     return simplify_cond_using_ranges (stmt);
9184   else if (gimple_code (stmt) == GIMPLE_SWITCH)
9185     return simplify_switch_using_ranges (stmt);
9186
9187   return false;
9188 }
9189
9190 /* If the statement pointed by SI has a predicate whose value can be
9191    computed using the value range information computed by VRP, compute
9192    its value and return true.  Otherwise, return false.  */
9193
9194 static bool
9195 fold_predicate_in (gimple_stmt_iterator *si)
9196 {
9197   bool assignment_p = false;
9198   tree val;
9199   gimple stmt = gsi_stmt (*si);
9200
9201   if (is_gimple_assign (stmt)
9202       && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
9203     {
9204       assignment_p = true;
9205       val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
9206                                       gimple_assign_rhs1 (stmt),
9207                                       gimple_assign_rhs2 (stmt),
9208                                       stmt);
9209     }
9210   else if (gimple_code (stmt) == GIMPLE_COND)
9211     val = vrp_evaluate_conditional (gimple_cond_code (stmt),
9212                                     gimple_cond_lhs (stmt),
9213                                     gimple_cond_rhs (stmt),
9214                                     stmt);
9215   else
9216     return false;
9217
9218   if (val)
9219     {
9220       if (assignment_p)
9221         val = fold_convert (gimple_expr_type (stmt), val);
9222
9223       if (dump_file)
9224         {
9225           fprintf (dump_file, "Folding predicate ");
9226           print_gimple_expr (dump_file, stmt, 0, 0);
9227           fprintf (dump_file, " to ");
9228           print_generic_expr (dump_file, val, 0);
9229           fprintf (dump_file, "\n");
9230         }
9231
9232       if (is_gimple_assign (stmt))
9233         gimple_assign_set_rhs_from_tree (si, val);
9234       else
9235         {
9236           gcc_assert (gimple_code (stmt) == GIMPLE_COND);
9237           if (integer_zerop (val))
9238             gimple_cond_make_false (stmt);
9239           else if (integer_onep (val))
9240             gimple_cond_make_true (stmt);
9241           else
9242             gcc_unreachable ();
9243         }
9244
9245       return true;
9246     }
9247
9248   return false;
9249 }
9250
9251 /* Callback for substitute_and_fold folding the stmt at *SI.  */
9252
9253 static bool
9254 vrp_fold_stmt (gimple_stmt_iterator *si)
9255 {
9256   if (fold_predicate_in (si))
9257     return true;
9258
9259   return simplify_stmt_using_ranges (si);
9260 }
9261
9262 /* Stack of dest,src equivalency pairs that need to be restored after
9263    each attempt to thread a block's incoming edge to an outgoing edge.
9264
9265    A NULL entry is used to mark the end of pairs which need to be
9266    restored.  */
9267 static vec<tree> equiv_stack;
9268
9269 /* A trivial wrapper so that we can present the generic jump threading
9270    code with a simple API for simplifying statements.  STMT is the
9271    statement we want to simplify, WITHIN_STMT provides the location
9272    for any overflow warnings.  */
9273
9274 static tree
9275 simplify_stmt_for_jump_threading (gimple stmt, gimple within_stmt)
9276 {
9277   if (gimple_code (stmt) == GIMPLE_COND)
9278     return vrp_evaluate_conditional (gimple_cond_code (stmt),
9279                                      gimple_cond_lhs (stmt),
9280                                      gimple_cond_rhs (stmt), within_stmt);
9281
9282   if (gimple_code (stmt) == GIMPLE_ASSIGN)
9283     {
9284       value_range_t new_vr = VR_INITIALIZER;
9285       tree lhs = gimple_assign_lhs (stmt);
9286
9287       if (TREE_CODE (lhs) == SSA_NAME
9288           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
9289               || POINTER_TYPE_P (TREE_TYPE (lhs))))
9290         {
9291           extract_range_from_assignment (&new_vr, stmt);
9292           if (range_int_cst_singleton_p (&new_vr))
9293             return new_vr.min;
9294         }
9295     }
9296
9297   return NULL_TREE;
9298 }
9299
9300 /* Blocks which have more than one predecessor and more than
9301    one successor present jump threading opportunities, i.e.,
9302    when the block is reached from a specific predecessor, we
9303    may be able to determine which of the outgoing edges will
9304    be traversed.  When this optimization applies, we are able
9305    to avoid conditionals at runtime and we may expose secondary
9306    optimization opportunities.
9307
9308    This routine is effectively a driver for the generic jump
9309    threading code.  It basically just presents the generic code
9310    with edges that may be suitable for jump threading.
9311
9312    Unlike DOM, we do not iterate VRP if jump threading was successful.
9313    While iterating may expose new opportunities for VRP, it is expected
9314    those opportunities would be very limited and the compile time cost
9315    to expose those opportunities would be significant.
9316
9317    As jump threading opportunities are discovered, they are registered
9318    for later realization.  */
9319
9320 static void
9321 identify_jump_threads (void)
9322 {
9323   basic_block bb;
9324   gimple dummy;
9325   int i;
9326   edge e;
9327
9328   /* Ugh.  When substituting values earlier in this pass we can
9329      wipe the dominance information.  So rebuild the dominator
9330      information as we need it within the jump threading code.  */
9331   calculate_dominance_info (CDI_DOMINATORS);
9332
9333   /* We do not allow VRP information to be used for jump threading
9334      across a back edge in the CFG.  Otherwise it becomes too
9335      difficult to avoid eliminating loop exit tests.  Of course
9336      EDGE_DFS_BACK is not accurate at this time so we have to
9337      recompute it.  */
9338   mark_dfs_back_edges ();
9339
9340   /* Do not thread across edges we are about to remove.  Just marking
9341      them as EDGE_DFS_BACK will do.  */
9342   FOR_EACH_VEC_ELT (to_remove_edges, i, e)
9343     e->flags |= EDGE_DFS_BACK;
9344
9345   /* Allocate our unwinder stack to unwind any temporary equivalences
9346      that might be recorded.  */
9347   equiv_stack.create (20);
9348
9349   /* To avoid lots of silly node creation, we create a single
9350      conditional and just modify it in-place when attempting to
9351      thread jumps.  */
9352   dummy = gimple_build_cond (EQ_EXPR,
9353                              integer_zero_node, integer_zero_node,
9354                              NULL, NULL);
9355
9356   /* Walk through all the blocks finding those which present a
9357      potential jump threading opportunity.  We could set this up
9358      as a dominator walker and record data during the walk, but
9359      I doubt it's worth the effort for the classes of jump
9360      threading opportunities we are trying to identify at this
9361      point in compilation.  */
9362   FOR_EACH_BB (bb)
9363     {
9364       gimple last;
9365
9366       /* If the generic jump threading code does not find this block
9367          interesting, then there is nothing to do.  */
9368       if (! potentially_threadable_block (bb))
9369         continue;
9370
9371       /* We only care about blocks ending in a COND_EXPR.  While there
9372          may be some value in handling SWITCH_EXPR here, I doubt it's
9373          terribly important.  */
9374       last = gsi_stmt (gsi_last_bb (bb));
9375
9376       /* We're basically looking for a switch or any kind of conditional with
9377          integral or pointer type arguments.  Note the type of the second
9378          argument will be the same as the first argument, so no need to
9379          check it explicitly.  */
9380       if (gimple_code (last) == GIMPLE_SWITCH
9381           || (gimple_code (last) == GIMPLE_COND
9382               && TREE_CODE (gimple_cond_lhs (last)) == SSA_NAME
9383               && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (last)))
9384                   || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (last))))
9385               && (TREE_CODE (gimple_cond_rhs (last)) == SSA_NAME
9386                   || is_gimple_min_invariant (gimple_cond_rhs (last)))))
9387         {
9388           edge_iterator ei;
9389
9390           /* We've got a block with multiple predecessors and multiple
9391              successors which also ends in a suitable conditional or
9392              switch statement.  For each predecessor, see if we can thread
9393              it to a specific successor.  */
9394           FOR_EACH_EDGE (e, ei, bb->preds)
9395             {
9396               /* Do not thread across back edges or abnormal edges
9397                  in the CFG.  */
9398               if (e->flags & (EDGE_DFS_BACK | EDGE_COMPLEX))
9399                 continue;
9400
9401               thread_across_edge (dummy, e, true, &equiv_stack,
9402                                   simplify_stmt_for_jump_threading);
9403             }
9404         }
9405     }
9406
9407   /* We do not actually update the CFG or SSA graphs at this point as
9408      ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
9409      handle ASSERT_EXPRs gracefully.  */
9410 }
9411
9412 /* We identified all the jump threading opportunities earlier, but could
9413    not transform the CFG at that time.  This routine transforms the
9414    CFG and arranges for the dominator tree to be rebuilt if necessary.
9415
9416    Note the SSA graph update will occur during the normal TODO
9417    processing by the pass manager.  */
9418 static void
9419 finalize_jump_threads (void)
9420 {
9421   thread_through_all_blocks (false);
9422   equiv_stack.release ();
9423 }
9424
9425
9426 /* Traverse all the blocks folding conditionals with known ranges.  */
9427
9428 static void
9429 vrp_finalize (void)
9430 {
9431   size_t i;
9432
9433   values_propagated = true;
9434
9435   if (dump_file)
9436     {
9437       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
9438       dump_all_value_ranges (dump_file);
9439       fprintf (dump_file, "\n");
9440     }
9441
9442   substitute_and_fold (op_with_constant_singleton_value_range,
9443                        vrp_fold_stmt, false);
9444
9445   if (warn_array_bounds)
9446     check_all_array_refs ();
9447
9448   /* We must identify jump threading opportunities before we release
9449      the datastructures built by VRP.  */
9450   identify_jump_threads ();
9451
9452   /* Set value range to non pointer SSA_NAMEs.  */
9453   for (i  = 0; i < num_vr_values; i++)
9454     if (vr_value[i])
9455       {
9456         tree name = ssa_name (i);
9457
9458       if (!name
9459           || POINTER_TYPE_P (TREE_TYPE (name))
9460           || (vr_value[i]->type == VR_VARYING)
9461           || (vr_value[i]->type == VR_UNDEFINED))
9462         continue;
9463
9464         if ((TREE_CODE (vr_value[i]->min) == INTEGER_CST)
9465             && (TREE_CODE (vr_value[i]->max) == INTEGER_CST))
9466           {
9467             if (vr_value[i]->type == VR_RANGE)
9468               set_range_info (name,
9469                               tree_to_double_int (vr_value[i]->min),
9470                               tree_to_double_int (vr_value[i]->max));
9471             else if (vr_value[i]->type == VR_ANTI_RANGE)
9472               {
9473                 /* VR_ANTI_RANGE ~[min, max] is encoded compactly as
9474                    [max + 1, min - 1] without additional attributes.
9475                    When min value > max value, we know that it is
9476                    VR_ANTI_RANGE; it is VR_RANGE otherwise.  */
9477
9478                 /* ~[0,0] anti-range is represented as
9479                    range.  */
9480                 if (TYPE_UNSIGNED (TREE_TYPE (name))
9481                     && integer_zerop (vr_value[i]->min)
9482                     && integer_zerop (vr_value[i]->max))
9483                   set_range_info (name,
9484                                   double_int_one,
9485                                   double_int::max_value
9486                                   (TYPE_PRECISION (TREE_TYPE (name)), true));
9487                 else
9488                   set_range_info (name,
9489                                   tree_to_double_int (vr_value[i]->max)
9490                                   + double_int_one,
9491                                   tree_to_double_int (vr_value[i]->min)
9492                                   - double_int_one);
9493               }
9494           }
9495       }
9496
9497   /* Free allocated memory.  */
9498   for (i = 0; i < num_vr_values; i++)
9499     if (vr_value[i])
9500       {
9501         BITMAP_FREE (vr_value[i]->equiv);
9502         free (vr_value[i]);
9503       }
9504
9505   free (vr_value);
9506   free (vr_phi_edge_counts);
9507
9508   /* So that we can distinguish between VRP data being available
9509      and not available.  */
9510   vr_value = NULL;
9511   vr_phi_edge_counts = NULL;
9512 }
9513
9514
9515 /* Main entry point to VRP (Value Range Propagation).  This pass is
9516    loosely based on J. R. C. Patterson, ``Accurate Static Branch
9517    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
9518    Programming Language Design and Implementation, pp. 67-78, 1995.
9519    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
9520
9521    This is essentially an SSA-CCP pass modified to deal with ranges
9522    instead of constants.
9523
9524    While propagating ranges, we may find that two or more SSA name
9525    have equivalent, though distinct ranges.  For instance,
9526
9527      1  x_9 = p_3->a;
9528      2  p_4 = ASSERT_EXPR <p_3, p_3 != 0>
9529      3  if (p_4 == q_2)
9530      4    p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
9531      5  endif
9532      6  if (q_2)
9533
9534    In the code above, pointer p_5 has range [q_2, q_2], but from the
9535    code we can also determine that p_5 cannot be NULL and, if q_2 had
9536    a non-varying range, p_5's range should also be compatible with it.
9537
9538    These equivalences are created by two expressions: ASSERT_EXPR and
9539    copy operations.  Since p_5 is an assertion on p_4, and p_4 was the
9540    result of another assertion, then we can use the fact that p_5 and
9541    p_4 are equivalent when evaluating p_5's range.
9542
9543    Together with value ranges, we also propagate these equivalences
9544    between names so that we can take advantage of information from
9545    multiple ranges when doing final replacement.  Note that this
9546    equivalency relation is transitive but not symmetric.
9547
9548    In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
9549    cannot assert that q_2 is equivalent to p_5 because q_2 may be used
9550    in contexts where that assertion does not hold (e.g., in line 6).
9551
9552    TODO, the main difference between this pass and Patterson's is that
9553    we do not propagate edge probabilities.  We only compute whether
9554    edges can be taken or not.  That is, instead of having a spectrum
9555    of jump probabilities between 0 and 1, we only deal with 0, 1 and
9556    DON'T KNOW.  In the future, it may be worthwhile to propagate
9557    probabilities to aid branch prediction.  */
9558
9559 static unsigned int
9560 execute_vrp (void)
9561 {
9562   int i;
9563   edge e;
9564   switch_update *su;
9565
9566   loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
9567   rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
9568   scev_initialize ();
9569
9570   /* ???  This ends up using stale EDGE_DFS_BACK for liveness computation.
9571      Inserting assertions may split edges which will invalidate
9572      EDGE_DFS_BACK.  */
9573   insert_range_assertions ();
9574
9575   to_remove_edges.create (10);
9576   to_update_switch_stmts.create (5);
9577   threadedge_initialize_values ();
9578
9579   /* For visiting PHI nodes we need EDGE_DFS_BACK computed.  */
9580   mark_dfs_back_edges ();
9581
9582   vrp_initialize ();
9583   ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
9584   vrp_finalize ();
9585
9586   free_numbers_of_iterations_estimates ();
9587
9588   /* ASSERT_EXPRs must be removed before finalizing jump threads
9589      as finalizing jump threads calls the CFG cleanup code which
9590      does not properly handle ASSERT_EXPRs.  */
9591   remove_range_assertions ();
9592
9593   /* If we exposed any new variables, go ahead and put them into
9594      SSA form now, before we handle jump threading.  This simplifies
9595      interactions between rewriting of _DECL nodes into SSA form
9596      and rewriting SSA_NAME nodes into SSA form after block
9597      duplication and CFG manipulation.  */
9598   update_ssa (TODO_update_ssa);
9599
9600   finalize_jump_threads ();
9601
9602   /* Remove dead edges from SWITCH_EXPR optimization.  This leaves the
9603      CFG in a broken state and requires a cfg_cleanup run.  */
9604   FOR_EACH_VEC_ELT (to_remove_edges, i, e)
9605     remove_edge (e);
9606   /* Update SWITCH_EXPR case label vector.  */
9607   FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
9608     {
9609       size_t j;
9610       size_t n = TREE_VEC_LENGTH (su->vec);
9611       tree label;
9612       gimple_switch_set_num_labels (su->stmt, n);
9613       for (j = 0; j < n; j++)
9614         gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
9615       /* As we may have replaced the default label with a regular one
9616          make sure to make it a real default label again.  This ensures
9617          optimal expansion.  */
9618       label = gimple_switch_label (su->stmt, 0);
9619       CASE_LOW (label) = NULL_TREE;
9620       CASE_HIGH (label) = NULL_TREE;
9621     }
9622
9623   if (to_remove_edges.length () > 0)
9624     {
9625       free_dominance_info (CDI_DOMINATORS);
9626       if (current_loops)
9627         loops_state_set (LOOPS_NEED_FIXUP);
9628     }
9629
9630   to_remove_edges.release ();
9631   to_update_switch_stmts.release ();
9632   threadedge_finalize_values ();
9633
9634   scev_finalize ();
9635   loop_optimizer_finalize ();
9636   return 0;
9637 }
9638
9639 static bool
9640 gate_vrp (void)
9641 {
9642   return flag_tree_vrp != 0;
9643 }
9644
9645 namespace {
9646
9647 const pass_data pass_data_vrp =
9648 {
9649   GIMPLE_PASS, /* type */
9650   "vrp", /* name */
9651   OPTGROUP_NONE, /* optinfo_flags */
9652   true, /* has_gate */
9653   true, /* has_execute */
9654   TV_TREE_VRP, /* tv_id */
9655   PROP_ssa, /* properties_required */
9656   0, /* properties_provided */
9657   0, /* properties_destroyed */
9658   0, /* todo_flags_start */
9659   ( TODO_cleanup_cfg | TODO_update_ssa
9660     | TODO_verify_ssa
9661     | TODO_verify_flow ), /* todo_flags_finish */
9662 };
9663
9664 class pass_vrp : public gimple_opt_pass
9665 {
9666 public:
9667   pass_vrp (gcc::context *ctxt)
9668     : gimple_opt_pass (pass_data_vrp, ctxt)
9669   {}
9670
9671   /* opt_pass methods: */
9672   opt_pass * clone () { return new pass_vrp (m_ctxt); }
9673   bool gate () { return gate_vrp (); }
9674   unsigned int execute () { return execute_vrp (); }
9675
9676 }; // class pass_vrp
9677
9678 } // anon namespace
9679
9680 gimple_opt_pass *
9681 make_pass_vrp (gcc::context *ctxt)
9682 {
9683   return new pass_vrp (ctxt);
9684 }