OSDN Git Service

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