OSDN Git Service

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