OSDN Git Service

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