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