OSDN Git Service

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