OSDN Git Service

2005-06-01 Daniel Berlin <dberlin@dberlin.org>
[pf3gnuchains/gcc-fork.git] / gcc / tree-vrp.c
1 /* Support routines for Value Range Propagation (VRP).
2    Copyright (C) 2005 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, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, 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 "cfgloop.h"
36 #include "tree-scalar-evolution.h"
37 #include "tree-ssa-propagate.h"
38 #include "tree-chrec.h"
39
40 /* Set of SSA names found during the dominator traversal of a
41    sub-graph in find_assert_locations.  */
42 static sbitmap found_in_subgraph;
43
44 /* Loop structure of the program.  Used to analyze scalar evolutions
45    inside adjust_range_with_scev.  */
46 static struct loops *cfg_loops;
47
48 /* Local functions.  */
49 static int compare_values (tree val1, tree val2);
50
51 /* Location information for ASSERT_EXPRs.  Each instance of this
52    structure describes an ASSERT_EXPR for an SSA name.  Since a single
53    SSA name may have more than one assertion associated with it, these
54    locations are kept in a linked list attached to the corresponding
55    SSA name.  */
56 struct assert_locus_d
57 {
58   /* Basic block where the assertion would be inserted.  */
59   basic_block bb;
60
61   /* Some assertions need to be inserted on an edge (e.g., assertions
62      generated by COND_EXPRs).  In those cases, BB will be NULL.  */
63   edge e;
64
65   /* Pointer to the statement that generated this assertion.  */
66   block_stmt_iterator si;
67
68   /* Predicate code for the ASSERT_EXPR.  Must be COMPARISON_CLASS_P.  */
69   enum tree_code comp_code;
70
71   /* Value being compared against.  */
72   tree val;
73
74   /* Next node in the linked list.  */
75   struct assert_locus_d *next;
76 };
77
78 typedef struct assert_locus_d *assert_locus_t;
79
80 /* If bit I is present, it means that SSA name N_i has a list of
81    assertions that should be inserted in the IL.  */
82 static bitmap need_assert_for;
83
84 /* Array of locations lists where to insert assertions.  ASSERTS_FOR[I]
85    holds a list of ASSERT_LOCUS_T nodes that describe where
86    ASSERT_EXPRs for SSA name N_I should be inserted.  */
87 static assert_locus_t *asserts_for;
88
89 /* Set of blocks visited in find_assert_locations.  Used to avoid
90    visiting the same block more than once.  */
91 static sbitmap blocks_visited;
92
93 /* Value range array.  After propagation, VR_VALUE[I] holds the range
94    of values that SSA name N_I may take.  */
95 static value_range_t **vr_value;
96
97 /* Given a comparison code, return its opposite.  Note that this is *not*
98    the same as inverting its truth value (invert_tree_comparison).  Here we
99    just want to literally flip the comparison around.
100    
101    So, '<' gets '>', '<=' gets '>='.  Both '==' and '!=' are returned
102    unchanged.  */
103
104 static enum tree_code
105 opposite_comparison (enum tree_code code)
106 {
107   switch (code)
108     {
109     case EQ_EXPR:
110     case NE_EXPR:
111     case ORDERED_EXPR:
112     case UNORDERED_EXPR:
113     case LTGT_EXPR:
114     case UNEQ_EXPR:
115       return code;
116     case GT_EXPR:
117       return LT_EXPR;
118     case GE_EXPR:
119       return LE_EXPR;
120     case LT_EXPR:
121       return GT_EXPR;
122     case LE_EXPR:
123       return GE_EXPR;
124     case UNGT_EXPR:
125       return UNLT_EXPR;
126     case UNGE_EXPR:
127       return UNLE_EXPR;
128     case UNLT_EXPR:
129       return UNGT_EXPR;
130     case UNLE_EXPR:
131       return UNGE_EXPR;
132     default:
133       gcc_unreachable ();
134     }
135 }
136
137
138 /* Return true if EXPR computes a non-zero value.  */
139
140 bool
141 expr_computes_nonzero (tree expr)
142 {
143   /* Type casts won't change anything, so just strip them.  */
144   STRIP_NOPS (expr);
145
146   /* Calling alloca, guarantees that the value is non-NULL.  */
147   if (alloca_call_p (expr))
148     return true;
149
150   /* The address of a non-weak symbol is never NULL, unless the user
151      has requested not to remove NULL pointer checks.  */
152   if (flag_delete_null_pointer_checks
153       && TREE_CODE (expr) == ADDR_EXPR
154       && DECL_P (TREE_OPERAND (expr, 0))
155       && !DECL_WEAK (TREE_OPERAND (expr, 0)))
156     return true;
157
158   /* IOR of any value with a nonzero value will result in a nonzero
159      value.  */
160   if (TREE_CODE (expr) == BIT_IOR_EXPR
161       && integer_nonzerop (TREE_OPERAND (expr, 1)))
162     return true;
163
164   return false;
165 }
166
167
168 /* Return true if ARG is marked with the nonnull attribute in the
169    current function signature.  */
170
171 static bool
172 nonnull_arg_p (tree arg)
173 {
174   tree t, attrs, fntype;
175   unsigned HOST_WIDE_INT arg_num;
176
177   gcc_assert (TREE_CODE (arg) == PARM_DECL && POINTER_TYPE_P (TREE_TYPE (arg)));
178
179   fntype = TREE_TYPE (current_function_decl);
180   attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (fntype));
181
182   /* If "nonnull" wasn't specified, we know nothing about the argument.  */
183   if (attrs == NULL_TREE)
184     return false;
185
186   /* If "nonnull" applies to all the arguments, then ARG is non-null.  */
187   if (TREE_VALUE (attrs) == NULL_TREE)
188     return true;
189
190   /* Get the position number for ARG in the function signature.  */
191   for (arg_num = 1, t = DECL_ARGUMENTS (current_function_decl);
192        t;
193        t = TREE_CHAIN (t), arg_num++)
194     {
195       if (t == arg)
196         break;
197     }
198
199   gcc_assert (t == arg);
200
201   /* Now see if ARG_NUM is mentioned in the nonnull list.  */
202   for (t = TREE_VALUE (attrs); t; t = TREE_CHAIN (t))
203     {
204       if (compare_tree_int (TREE_VALUE (t), arg_num) == 0)
205         return true;
206     }
207
208   return false;
209 }
210
211
212 /* Set value range VR to {T, MIN, MAX, EQUIV}.  */
213
214 static void
215 set_value_range (value_range_t *vr, enum value_range_type t, tree min,
216                  tree max, bitmap equiv)
217 {
218 #if defined ENABLE_CHECKING
219   /* Check the validity of the range.  */
220   if (t == VR_RANGE || t == VR_ANTI_RANGE)
221     {
222       int cmp;
223
224       gcc_assert (min && max);
225
226       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
227         gcc_assert (min != TYPE_MIN_VALUE (TREE_TYPE (min))
228                     || max != TYPE_MAX_VALUE (TREE_TYPE (max)));
229
230       cmp = compare_values (min, max);
231       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
232     }
233
234   if (t == VR_UNDEFINED || t == VR_VARYING)
235     gcc_assert (min == NULL_TREE && max == NULL_TREE);
236
237   if (t == VR_UNDEFINED || t == VR_VARYING)
238     gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
239 #endif
240
241   vr->type = t;
242   vr->min = min;
243   vr->max = max;
244
245   /* Since updating the equivalence set involves deep copying the
246      bitmaps, only do it if absolutely necessary.  */
247   if (vr->equiv == NULL)
248     vr->equiv = BITMAP_ALLOC (NULL);
249
250   if (equiv != vr->equiv)
251     {
252       if (equiv && !bitmap_empty_p (equiv))
253         bitmap_copy (vr->equiv, equiv);
254       else
255         bitmap_clear (vr->equiv);
256     }
257 }
258
259
260 /* Copy value range FROM into value range TO.  */
261
262 static inline void
263 copy_value_range (value_range_t *to, value_range_t *from)
264 {
265   set_value_range (to, from->type, from->min, from->max, from->equiv);
266 }
267
268
269 /* Set value range VR to a non-NULL range of type TYPE.  */
270
271 static inline void
272 set_value_range_to_nonnull (value_range_t *vr, tree type)
273 {
274   tree zero = build_int_cst (type, 0);
275   set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
276 }
277
278
279 /* Set value range VR to a NULL range of type TYPE.  */
280
281 static inline void
282 set_value_range_to_null (value_range_t *vr, tree type)
283 {
284   tree zero = build_int_cst (type, 0);
285   set_value_range (vr, VR_RANGE, zero, zero, vr->equiv);
286 }
287
288
289 /* Set value range VR to VR_VARYING.  */
290
291 static inline void
292 set_value_range_to_varying (value_range_t *vr)
293 {
294   vr->type = VR_VARYING;
295   vr->min = vr->max = NULL_TREE;
296   if (vr->equiv)
297     bitmap_clear (vr->equiv);
298 }
299
300
301 /* Set value range VR to VR_UNDEFINED.  */
302
303 static inline void
304 set_value_range_to_undefined (value_range_t *vr)
305 {
306   vr->type = VR_UNDEFINED;
307   vr->min = vr->max = NULL_TREE;
308   if (vr->equiv)
309     bitmap_clear (vr->equiv);
310 }
311
312
313 /* Return value range information for VAR.  Create an empty range
314    if none existed.  */
315
316 static value_range_t *
317 get_value_range (tree var)
318 {
319   value_range_t *vr;
320   tree sym;
321   unsigned ver = SSA_NAME_VERSION (var);
322
323   vr = vr_value[ver];
324   if (vr)
325     return vr;
326
327   /* Create a default value range.  */
328   vr_value[ver] = vr = xmalloc (sizeof (*vr));
329   memset (vr, 0, sizeof (*vr));
330
331   /* Allocate an equivalence set.  */
332   vr->equiv = BITMAP_ALLOC (NULL);
333
334   /* If VAR is a default definition, the variable can take any value
335      in VAR's type.  */
336   sym = SSA_NAME_VAR (var);
337   if (var == var_ann (sym)->default_def)
338     {
339       /* Try to use the "nonnull" attribute to create ~[0, 0]
340          anti-ranges for pointers.  Note that this is only valid with
341          default definitions of PARM_DECLs.  */
342       if (TREE_CODE (sym) == PARM_DECL
343           && POINTER_TYPE_P (TREE_TYPE (sym))
344           && nonnull_arg_p (sym))
345         set_value_range_to_nonnull (vr, TREE_TYPE (sym));
346       else
347         set_value_range_to_varying (vr);
348     }
349
350   return vr;
351 }
352
353
354 /* Update the value range and equivalence set for variable VAR to
355    NEW_VR.  Return true if NEW_VR is different from VAR's previous
356    value.
357
358    NOTE: This function assumes that NEW_VR is a temporary value range
359    object created for the sole purpose of updating VAR's range.  The
360    storage used by the equivalence set from NEW_VR will be freed by
361    this function.  Do not call update_value_range when NEW_VR
362    is the range object associated with another SSA name.  */
363
364 static inline bool
365 update_value_range (tree var, value_range_t *new_vr)
366 {
367   value_range_t *old_vr;
368   bool is_new;
369
370   /* Update the value range, if necessary.  */
371   old_vr = get_value_range (var);
372   is_new = old_vr->type != new_vr->type
373            || old_vr->min != new_vr->min
374            || old_vr->max != new_vr->max
375            || (old_vr->equiv == NULL && new_vr->equiv)
376            || (old_vr->equiv && new_vr->equiv == NULL)
377            || (!bitmap_equal_p (old_vr->equiv, new_vr->equiv));
378
379   if (is_new)
380     set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
381                      new_vr->equiv);
382
383   BITMAP_FREE (new_vr->equiv);
384   new_vr->equiv = NULL;
385
386   return is_new;
387 }
388
389
390 /* Add VAR and VAR's equivalence set to EQUIV.  */
391
392 static void
393 add_equivalence (bitmap equiv, tree var)
394 {
395   unsigned ver = SSA_NAME_VERSION (var);
396   value_range_t *vr = vr_value[ver];
397
398   bitmap_set_bit (equiv, ver);
399   if (vr && vr->equiv)
400     bitmap_ior_into (equiv, vr->equiv);
401 }
402
403
404 /* Return true if VR is ~[0, 0].  */
405
406 static inline bool
407 range_is_nonnull (value_range_t *vr)
408 {
409   return vr->type == VR_ANTI_RANGE
410          && integer_zerop (vr->min)
411          && integer_zerop (vr->max);
412 }
413
414
415 /* Return true if VR is [0, 0].  */
416
417 static inline bool
418 range_is_null (value_range_t *vr)
419 {
420   return vr->type == VR_RANGE
421          && integer_zerop (vr->min)
422          && integer_zerop (vr->max);
423 }
424
425
426 /* Return true if value range VR involves at least one symbol.  */
427
428 static inline bool
429 symbolic_range_p (value_range_t *vr)
430 {
431   return (!is_gimple_min_invariant (vr->min)
432           || !is_gimple_min_invariant (vr->max));
433 }
434
435
436 /* Like expr_computes_nonzero, but this function uses value ranges
437    obtained so far.  */
438
439 static bool
440 vrp_expr_computes_nonzero (tree expr)
441 {
442   if (expr_computes_nonzero (expr))
443     return true;
444
445   /* If we have an expression of the form &X->a, then the expression
446      is nonnull if X is nonnull.  */
447   if (TREE_CODE (expr) == ADDR_EXPR)
448     {
449       tree base = get_base_address (TREE_OPERAND (expr, 0));
450
451       if (base != NULL_TREE
452           && TREE_CODE (base) == INDIRECT_REF
453           && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
454         {
455           value_range_t *vr = get_value_range (TREE_OPERAND (base, 0));
456           if (range_is_nonnull (vr))
457             return true;
458         }
459     }
460
461   return false;
462 }
463
464
465 /* Compare two values VAL1 and VAL2.  Return
466    
467         -2 if VAL1 and VAL2 cannot be compared at compile-time,
468         -1 if VAL1 < VAL2,
469          0 if VAL1 == VAL2,
470         +1 if VAL1 > VAL2, and
471         +2 if VAL1 != VAL2
472
473    This is similar to tree_int_cst_compare but supports pointer values
474    and values that cannot be compared at compile time.  */
475
476 static int
477 compare_values (tree val1, tree val2)
478 {
479   if (val1 == val2)
480     return 0;
481
482   /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
483      both integers.  */
484   gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
485               == POINTER_TYPE_P (TREE_TYPE (val2)));
486
487   /* Do some limited symbolic comparisons.  */
488   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
489     {
490       /* We can determine some comparisons against +INF and -INF even
491          if the other value is an expression.  */
492       if (val1 == TYPE_MAX_VALUE (TREE_TYPE (val1))
493           && TREE_CODE (val2) == MINUS_EXPR)
494         {
495           /* +INF > NAME - CST.  */
496           return 1;
497         }
498       else if (val1 == TYPE_MIN_VALUE (TREE_TYPE (val1))
499                && TREE_CODE (val2) == PLUS_EXPR)
500         {
501           /* -INF < NAME + CST.  */
502           return -1;
503         }
504       else if (TREE_CODE (val1) == MINUS_EXPR
505                && val2 == TYPE_MAX_VALUE (TREE_TYPE (val2)))
506         {
507           /* NAME - CST < +INF.  */
508           return -1;
509         }
510       else if (TREE_CODE (val1) == PLUS_EXPR
511                && val2 == TYPE_MIN_VALUE (TREE_TYPE (val2)))
512         {
513           /* NAME + CST > -INF.  */
514           return 1;
515         }
516     }
517
518   if ((TREE_CODE (val1) == SSA_NAME
519        || TREE_CODE (val1) == PLUS_EXPR
520        || TREE_CODE (val1) == MINUS_EXPR)
521       && (TREE_CODE (val2) == SSA_NAME
522           || TREE_CODE (val2) == PLUS_EXPR
523           || TREE_CODE (val2) == MINUS_EXPR))
524     {
525       tree n1, c1, n2, c2;
526   
527       /* If VAL1 and VAL2 are of the form 'NAME [+-] CST' or 'NAME',
528          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
529          same name, return -2.  */
530       if (TREE_CODE (val1) == SSA_NAME)
531         {
532           n1 = val1;
533           c1 = NULL_TREE;
534         }
535       else
536         {
537           n1 = TREE_OPERAND (val1, 0);
538           c1 = TREE_OPERAND (val1, 1);
539         }
540
541       if (TREE_CODE (val2) == SSA_NAME)
542         {
543           n2 = val2;
544           c2 = NULL_TREE;
545         }
546       else
547         {
548           n2 = TREE_OPERAND (val2, 0);
549           c2 = TREE_OPERAND (val2, 1);
550         }
551
552       /* Both values must use the same name.  */
553       if (n1 != n2)
554         return -2;
555
556       if (TREE_CODE (val1) == SSA_NAME)
557         {
558           if (TREE_CODE (val2) == SSA_NAME)
559             /* NAME == NAME  */
560             return 0;
561           else if (TREE_CODE (val2) == PLUS_EXPR)
562             /* NAME < NAME + CST  */
563             return -1;
564           else if (TREE_CODE (val2) == MINUS_EXPR)
565             /* NAME > NAME - CST  */
566             return 1;
567         }
568       else if (TREE_CODE (val1) == PLUS_EXPR)
569         {
570           if (TREE_CODE (val2) == SSA_NAME)
571             /* NAME + CST > NAME  */
572             return 1;
573           else if (TREE_CODE (val2) == PLUS_EXPR)
574             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
575             return compare_values (c1, c2);
576           else if (TREE_CODE (val2) == MINUS_EXPR)
577             /* NAME + CST1 > NAME - CST2  */
578             return 1;
579         }
580       else if (TREE_CODE (val1) == MINUS_EXPR)
581         {
582           if (TREE_CODE (val2) == SSA_NAME)
583             /* NAME - CST < NAME  */
584             return -1;
585           else if (TREE_CODE (val2) == PLUS_EXPR)
586             /* NAME - CST1 < NAME + CST2  */
587             return -1;
588           else if (TREE_CODE (val2) == MINUS_EXPR)
589             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
590                C1 and C2 are swapped in the call to compare_values.  */
591             return compare_values (c2, c1);
592         }
593
594       gcc_unreachable ();
595     }
596
597   /* We cannot compare non-constants.  */
598   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
599     return -2;
600
601   /* We cannot compare overflowed values.  */
602   if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
603     return -2;
604
605   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
606     return tree_int_cst_compare (val1, val2);
607   else
608     {
609       tree t;
610
611       /* First see if VAL1 and VAL2 are not the same.  */
612       if (val1 == val2 || operand_equal_p (val1, val2, 0))
613         return 0;
614       
615       /* If VAL1 is a lower address than VAL2, return -1.  */
616       t = fold_binary (LT_EXPR, boolean_type_node, val1, val2);
617       if (t == boolean_true_node)
618         return -1;
619
620       /* If VAL1 is a higher address than VAL2, return +1.  */
621       t = fold_binary (GT_EXPR, boolean_type_node, val1, val2);
622       if (t == boolean_true_node)
623         return 1;
624
625       /* If VAL1 is different than VAL2, return +2.  */
626       t = fold_binary (NE_EXPR, boolean_type_node, val1, val2);
627       if (t == boolean_true_node)
628         return 2;
629
630       return -2;
631     }
632 }
633
634
635 /* Return 1 if VAL is inside value range VR (VR->MIN <= VAL <= VR->MAX),
636           0 if VAL is not inside VR,
637          -2 if we cannot tell either way.  */
638
639 static inline int
640 value_inside_range (tree val, value_range_t *vr)
641 {
642   int cmp1, cmp2;
643
644   cmp1 = compare_values (val, vr->min);
645   if (cmp1 == -2 || cmp1 == 2)
646     return -2;
647
648   cmp2 = compare_values (val, vr->max);
649   if (cmp2 == -2 || cmp2 == 2)
650     return -2;
651
652   return (cmp1 == 0 || cmp1 == 1) && (cmp2 == -1 || cmp2 == 0);
653 }
654
655
656 /* Return true if value ranges VR0 and VR1 have a non-empty
657    intersection.  */
658
659 static inline bool
660 value_ranges_intersect_p (value_range_t *vr0, value_range_t *vr1)
661 {
662   return (value_inside_range (vr1->min, vr0) == 1
663           || value_inside_range (vr1->max, vr0) == 1
664           || value_inside_range (vr0->min, vr1) == 1
665           || value_inside_range (vr0->max, vr1) == 1);
666 }
667
668
669 /* Return true if VR includes the value zero, false otherwise.  */
670
671 static inline bool
672 range_includes_zero_p (value_range_t *vr)
673 {
674   tree zero;
675
676   gcc_assert (vr->type != VR_UNDEFINED
677               && vr->type != VR_VARYING
678               && !symbolic_range_p (vr));
679
680   zero = build_int_cst (TREE_TYPE (vr->min), 0);
681   return (value_inside_range (zero, vr) == 1);
682 }
683
684
685 /* Extract value range information from an ASSERT_EXPR EXPR and store
686    it in *VR_P.  */
687
688 static void
689 extract_range_from_assert (value_range_t *vr_p, tree expr)
690 {
691   tree var, cond, limit, min, max, type;
692   value_range_t *var_vr, *limit_vr;
693   enum tree_code cond_code;
694
695   var = ASSERT_EXPR_VAR (expr);
696   cond = ASSERT_EXPR_COND (expr);
697
698   gcc_assert (COMPARISON_CLASS_P (cond));
699
700   /* Find VAR in the ASSERT_EXPR conditional.  */
701   if (var == TREE_OPERAND (cond, 0))
702     {
703       /* If the predicate is of the form VAR COMP LIMIT, then we just
704          take LIMIT from the RHS and use the same comparison code.  */
705       limit = TREE_OPERAND (cond, 1);
706       cond_code = TREE_CODE (cond);
707     }
708   else
709     {
710       /* If the predicate is of the form LIMIT COMP VAR, then we need
711          to flip around the comparison code to create the proper range
712          for VAR.  */
713       limit = TREE_OPERAND (cond, 0);
714       cond_code = opposite_comparison (TREE_CODE (cond));
715     }
716
717   type = TREE_TYPE (limit);
718   gcc_assert (limit != var);
719
720   /* For pointer arithmetic, we only keep track of pointer equality
721      and inequality.  */
722   if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
723     {
724       set_value_range_to_varying (vr_p);
725       return;
726     }
727
728   /* If LIMIT is another SSA name and LIMIT has a range of its own,
729      try to use LIMIT's range to avoid creating symbolic ranges
730      unnecessarily. */
731   limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
732
733   /* LIMIT's range is only interesting if it has any useful information.  */
734   if (limit_vr
735       && (limit_vr->type == VR_UNDEFINED
736           || limit_vr->type == VR_VARYING
737           || symbolic_range_p (limit_vr)))
738     limit_vr = NULL;
739
740   /* Special handling for integral types with super-types.  Some FEs
741      construct integral types derived from other types and restrict
742      the range of values these new types may take.
743
744      It may happen that LIMIT is actually smaller than TYPE's minimum
745      value.  For instance, the Ada FE is generating code like this
746      during bootstrap:
747
748             D.1480_32 = nam_30 - 300000361;
749             if (D.1480_32 <= 1) goto <L112>; else goto <L52>;
750             <L112>:;
751             D.1480_94 = ASSERT_EXPR <D.1480_32, D.1480_32 <= 1>;
752
753      All the names are of type types__name_id___XDLU_300000000__399999999
754      which has min == 300000000 and max == 399999999.  This means that
755      the ASSERT_EXPR would try to create the range [3000000, 1] which
756      is invalid.
757
758      The fact that the type specifies MIN and MAX values does not
759      automatically mean that every variable of that type will always
760      be within that range, so the predicate may well be true at run
761      time.  If we had symbolic -INF and +INF values, we could
762      represent this range, but we currently represent -INF and +INF
763      using the type's min and max values.
764          
765      So, the only sensible thing we can do for now is set the
766      resulting range to VR_VARYING.  TODO, would having symbolic -INF
767      and +INF values be worth the trouble?  */
768   if (TREE_CODE (limit) != SSA_NAME
769       && INTEGRAL_TYPE_P (type)
770       && TREE_TYPE (type))
771     {
772       if (cond_code == LE_EXPR || cond_code == LT_EXPR)
773         {
774           tree type_min = TYPE_MIN_VALUE (type);
775           int cmp = compare_values (limit, type_min);
776
777           /* For < or <= comparisons, if LIMIT is smaller than
778              TYPE_MIN, set the range to VR_VARYING.  */
779           if (cmp == -1 || cmp == 0)
780             {
781               set_value_range_to_varying (vr_p);
782               return;
783             }
784         }
785       else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
786         {
787           tree type_max = TYPE_MIN_VALUE (type);
788           int cmp = compare_values (limit, type_max);
789
790           /* For > or >= comparisons, if LIMIT is bigger than
791              TYPE_MAX, set the range to VR_VARYING.  */
792           if (cmp == 1 || cmp == 0)
793             {
794               set_value_range_to_varying (vr_p);
795               return;
796             }
797         }
798     }
799
800   /* The new range has the same set of equivalences of VAR's range.  */
801   gcc_assert (vr_p->equiv == NULL);
802   vr_p->equiv = BITMAP_ALLOC (NULL);
803   add_equivalence (vr_p->equiv, var);
804
805   /* Extract a new range based on the asserted comparison for VAR and
806      LIMIT's value range.  Notice that if LIMIT has an anti-range, we
807      will only use it for equality comparisons (EQ_EXPR).  For any
808      other kind of assertion, we cannot derive a range from LIMIT's
809      anti-range that can be used to describe the new range.  For
810      instance, ASSERT_EXPR <x_2, x_2 <= b_4>.  If b_4 is ~[2, 10],
811      then b_4 takes on the ranges [-INF, 1] and [11, +INF].  There is
812      no single range for x_2 that could describe LE_EXPR, so we might
813      as well build the range [b_4, +INF] for it.  */
814   if (cond_code == EQ_EXPR)
815     {
816       enum value_range_type range_type;
817
818       if (limit_vr)
819         {
820           range_type = limit_vr->type;
821           min = limit_vr->min;
822           max = limit_vr->max;
823         }
824       else
825         {
826           range_type = VR_RANGE;
827           min = limit;
828           max = limit;
829         }
830
831       set_value_range (vr_p, range_type, min, max, vr_p->equiv);
832
833       /* When asserting the equality VAR == LIMIT and LIMIT is another
834          SSA name, the new range will also inherit the equivalence set
835          from LIMIT.  */
836       if (TREE_CODE (limit) == SSA_NAME)
837         add_equivalence (vr_p->equiv, limit);
838     }
839   else if (cond_code == NE_EXPR)
840     {
841       /* As described above, when LIMIT's range is an anti-range and
842          this assertion is an inequality (NE_EXPR), then we cannot
843          derive anything from the anti-range.  For instance, if
844          LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
845          not imply that VAR's range is [0, 0].  So, in the case of
846          anti-ranges, we just assert the inequality using LIMIT and
847          not its anti-range.  */
848       if (limit_vr == NULL
849           || limit_vr->type == VR_ANTI_RANGE)
850         {
851           min = limit;
852           max = limit;
853         }
854       else
855         {
856           min = limit_vr->min;
857           max = limit_vr->max;
858         }
859
860       /* If MIN and MAX cover the whole range for their type, then
861          just use the original LIMIT.  */
862       if (INTEGRAL_TYPE_P (type)
863           && min == TYPE_MIN_VALUE (type)
864           && max == TYPE_MAX_VALUE (type))
865         min = max = limit;
866
867       set_value_range (vr_p, VR_ANTI_RANGE, min, max, vr_p->equiv);
868     }
869   else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
870     {
871       min = TYPE_MIN_VALUE (type);
872
873       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
874         max = limit;
875       else
876         {
877           /* If LIMIT_VR is of the form [N1, N2], we need to build the
878              range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
879              LT_EXPR.  */
880           max = limit_vr->max;
881         }
882
883       /* For LT_EXPR, we create the range [MIN, MAX - 1].  */
884       if (cond_code == LT_EXPR)
885         {
886           tree one = build_int_cst (type, 1);
887           max = fold (build (MINUS_EXPR, type, max, one));
888         }
889
890       set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
891     }
892   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
893     {
894       max = TYPE_MAX_VALUE (type);
895
896       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
897         min = limit;
898       else
899         {
900           /* If LIMIT_VR is of the form [N1, N2], we need to build the
901              range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
902              GT_EXPR.  */
903           min = limit_vr->min;
904         }
905
906       /* For GT_EXPR, we create the range [MIN + 1, MAX].  */
907       if (cond_code == GT_EXPR)
908         {
909           tree one = build_int_cst (type, 1);
910           min = fold (build (PLUS_EXPR, type, min, one));
911         }
912
913       set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
914     }
915   else
916     gcc_unreachable ();
917
918   /* If VAR already had a known range and the two ranges have a
919      non-empty intersection, we can refine the resulting range.
920      Since the assert expression creates an equivalency and at the
921      same time it asserts a predicate, we can take the intersection of
922      the two ranges to get better precision.  */
923   var_vr = get_value_range (var);
924   if (var_vr->type == VR_RANGE
925       && vr_p->type == VR_RANGE
926       && value_ranges_intersect_p (var_vr, vr_p))
927     {
928       /* Use the larger of the two minimums.  */
929       if (compare_values (vr_p->min, var_vr->min) == -1)
930         min = var_vr->min;
931       else
932         min = vr_p->min;
933
934       /* Use the smaller of the two maximums.  */
935       if (compare_values (vr_p->max, var_vr->max) == 1)
936         max = var_vr->max;
937       else
938         max = vr_p->max;
939
940       set_value_range (vr_p, vr_p->type, min, max, vr_p->equiv);
941     }
942 }
943
944
945 /* Extract range information from SSA name VAR and store it in VR.  If
946    VAR has an interesting range, use it.  Otherwise, create the
947    range [VAR, VAR] and return it.  This is useful in situations where
948    we may have conditionals testing values of VARYING names.  For
949    instance,
950
951         x_3 = y_5;
952         if (x_3 > y_5)
953           ...
954
955     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
956     always false.  */
957
958 static void
959 extract_range_from_ssa_name (value_range_t *vr, tree var)
960 {
961   value_range_t *var_vr = get_value_range (var);
962
963   if (var_vr->type != VR_UNDEFINED && var_vr->type != VR_VARYING)
964     copy_value_range (vr, var_vr);
965   else
966     set_value_range (vr, VR_RANGE, var, var, NULL);
967
968   add_equivalence (vr->equiv, var);
969 }
970
971
972 /* Extract range information from a binary expression EXPR based on
973    the ranges of each of its operands and the expression code.  */
974
975 static void
976 extract_range_from_binary_expr (value_range_t *vr, tree expr)
977 {
978   enum tree_code code = TREE_CODE (expr);
979   tree op0, op1, min, max;
980   int cmp;
981   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
982   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
983
984   /* Not all binary expressions can be applied to ranges in a
985      meaningful way.  Handle only arithmetic operations.  */
986   if (code != PLUS_EXPR
987       && code != MINUS_EXPR
988       && code != MULT_EXPR
989       && code != TRUNC_DIV_EXPR
990       && code != FLOOR_DIV_EXPR
991       && code != CEIL_DIV_EXPR
992       && code != EXACT_DIV_EXPR
993       && code != ROUND_DIV_EXPR
994       && code != MIN_EXPR
995       && code != MAX_EXPR
996       && code != TRUTH_ANDIF_EXPR
997       && code != TRUTH_ORIF_EXPR
998       && code != TRUTH_AND_EXPR
999       && code != TRUTH_OR_EXPR
1000       && code != TRUTH_XOR_EXPR)
1001     {
1002       set_value_range_to_varying (vr);
1003       return;
1004     }
1005
1006   /* Get value ranges for each operand.  For constant operands, create
1007      a new value range with the operand to simplify processing.  */
1008   op0 = TREE_OPERAND (expr, 0);
1009   if (TREE_CODE (op0) == SSA_NAME)
1010     vr0 = *(get_value_range (op0));
1011   else if (is_gimple_min_invariant (op0))
1012     set_value_range (&vr0, VR_RANGE, op0, op0, NULL);
1013   else
1014     set_value_range_to_varying (&vr0);
1015
1016   op1 = TREE_OPERAND (expr, 1);
1017   if (TREE_CODE (op1) == SSA_NAME)
1018     vr1 = *(get_value_range (op1));
1019   else if (is_gimple_min_invariant (op1))
1020     set_value_range (&vr1, VR_RANGE, op1, op1, NULL);
1021   else
1022     set_value_range_to_varying (&vr1);
1023
1024   /* If either range is UNDEFINED, so is the result.  */
1025   if (vr0.type == VR_UNDEFINED || vr1.type == VR_UNDEFINED)
1026     {
1027       set_value_range_to_undefined (vr);
1028       return;
1029     }
1030
1031   /* Refuse to operate on VARYING ranges, ranges of different kinds
1032      and symbolic ranges.  TODO, we may be able to derive anti-ranges
1033      in some cases.  */
1034   if (vr0.type == VR_VARYING
1035       || vr1.type == VR_VARYING
1036       || vr0.type != vr1.type
1037       || symbolic_range_p (&vr0)
1038       || symbolic_range_p (&vr1))
1039     {
1040       set_value_range_to_varying (vr);
1041       return;
1042     }
1043
1044   /* Now evaluate the expression to determine the new range.  */
1045   if (POINTER_TYPE_P (TREE_TYPE (expr))
1046       || POINTER_TYPE_P (TREE_TYPE (op0))
1047       || POINTER_TYPE_P (TREE_TYPE (op1)))
1048     {
1049       /* For pointer types, we are really only interested in asserting
1050          whether the expression evaluates to non-NULL.  FIXME, we used
1051          to gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR), but
1052          ivopts is generating expressions with pointer multiplication
1053          in them.  */
1054       if (code == PLUS_EXPR)
1055         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1056       else
1057         {
1058           /* Subtracting from a pointer, may yield 0, so just drop the
1059              resulting range to varying.  */
1060           set_value_range_to_varying (vr);
1061         }
1062
1063       return;
1064     }
1065
1066   /* For integer ranges, apply the operation to each end of the
1067      range and see what we end up with.  */
1068   if (code == TRUTH_ANDIF_EXPR
1069       || code == TRUTH_ORIF_EXPR
1070       || code == TRUTH_AND_EXPR
1071       || code == TRUTH_OR_EXPR
1072       || code == TRUTH_XOR_EXPR)
1073     {
1074       /* Boolean expressions cannot be folded with int_const_binop.  */
1075       min = fold_binary (code, TREE_TYPE (expr), vr0.min, vr1.min);
1076       max = fold_binary (code, TREE_TYPE (expr), vr0.max, vr1.max);
1077     }
1078   else if (code == PLUS_EXPR
1079            || code == MULT_EXPR
1080            || code == MIN_EXPR
1081            || code == MAX_EXPR)
1082     {
1083       /* For operations that make the resulting range directly
1084          proportional to the original ranges, apply the operation to
1085          the same end of each range.  */
1086       min = int_const_binop (code, vr0.min, vr1.min, 0);
1087       max = int_const_binop (code, vr0.max, vr1.max, 0);
1088     }
1089   else if (code == TRUNC_DIV_EXPR
1090            || code == FLOOR_DIV_EXPR
1091            || code == CEIL_DIV_EXPR
1092            || code == EXACT_DIV_EXPR
1093            || code == ROUND_DIV_EXPR)
1094     {
1095       tree zero;
1096
1097       /* Divisions are a bit tricky to handle, depending on the mix of
1098          signs we have in the two range, we will need to divide
1099          different values to get the minimum and maximum values for
1100          the new range.  If VR1 includes zero, the result is VARYING.  */
1101       if (range_includes_zero_p (&vr1))
1102         {
1103           set_value_range_to_varying (vr);
1104           return;
1105         }
1106
1107       /* We have three main variations to handle for VR0: all negative
1108          values, all positive values and a mix of negative and
1109          positive.  For each of these, we need to consider if VR1 is
1110          all negative or all positive.  In total, there are 6
1111          combinations to handle.  */
1112       zero = build_int_cst (TREE_TYPE (expr), 0);
1113       if (compare_values (vr0.max, zero) == -1)
1114         {
1115           /* VR0 is all negative.  */
1116           if (compare_values (vr1.min, zero) == 1)
1117             {
1118               /* If VR1 is all positive, the new range is obtained
1119                  with [VR0.MIN / VR1.MIN, VR0.MAX / VR1.MAX].  */
1120               min = int_const_binop (code, vr0.min, vr1.min, 0);
1121               max = int_const_binop (code, vr0.max, vr1.max, 0);
1122             }
1123           else
1124             {
1125               /* If VR1 is all negative, the new range is obtained
1126                  with [VR0.MAX / VR1.MIN, VR0.MIN / VR1.MAX].  */
1127               gcc_assert (compare_values (vr1.max, zero) == -1);
1128               min = int_const_binop (code, vr0.max, vr1.min, 0);
1129               max = int_const_binop (code, vr0.min, vr1.max, 0);
1130             }
1131         }
1132       else if (range_includes_zero_p (&vr0))
1133         {
1134           /* VR0 is a mix of negative and positive values.  */
1135           if (compare_values (vr1.min, zero) == 1)
1136             {
1137               /* If VR1 is all positive, the new range is obtained
1138                  with [VR0.MIN / VR1.MIN, VR0.MAX / VR1.MIN].  */
1139               min = int_const_binop (code, vr0.min, vr1.min, 0);
1140               max = int_const_binop (code, vr0.max, vr1.min, 0);
1141             }
1142           else
1143             {
1144               /* If VR1 is all negative, the new range is obtained
1145                  with [VR0.MAX / VR1.MAX, VR0.MIN / VR1.MAX].  */
1146               gcc_assert (compare_values (vr1.max, zero) == -1);
1147               min = int_const_binop (code, vr0.max, vr1.max, 0);
1148               max = int_const_binop (code, vr0.min, vr1.max, 0);
1149             }
1150         }
1151       else
1152         {
1153           /* VR0 is all positive.  */
1154           gcc_assert (compare_values (vr0.min, zero) == 1);
1155           if (compare_values (vr1.min, zero) == 1)
1156             {
1157               /* If VR1 is all positive, the new range is obtained
1158                  with [VR0.MIN / VR1.MAX, VR0.MAX / VR1.MIN].  */
1159               min = int_const_binop (code, vr0.min, vr1.max, 0);
1160               max = int_const_binop (code, vr0.max, vr1.min, 0);
1161             }
1162           else
1163             {
1164               /* If VR1 is all negative, the new range is obtained
1165                  with [VR0.MAX / VR1.MAX, VR0.MIN / VR1.MIN].  */
1166               gcc_assert (compare_values (vr1.max, zero) == -1);
1167               min = int_const_binop (code, vr0.max, vr1.max, 0);
1168               max = int_const_binop (code, vr0.min, vr1.min, 0);
1169             }
1170         }
1171     }
1172   else if (code == MINUS_EXPR)
1173     {
1174       /* For MINUS_EXPR, apply the operation to the opposite ends of
1175          each range.  */
1176       min = int_const_binop (code, vr0.min, vr1.max, 0);
1177       max = int_const_binop (code, vr0.max, vr1.min, 0);
1178     }
1179   else
1180     gcc_unreachable ();
1181
1182   /* If MAX overflowed, then the result depends on whether we are
1183      using wrapping arithmetic or not.  */
1184   if (TREE_OVERFLOW (max))
1185     {
1186       /* If we are using wrapping arithmetic, set the result to
1187          VARYING.  */
1188       if (flag_wrapv)
1189         {
1190           set_value_range_to_varying (vr);
1191           return;
1192         }
1193
1194       /* Otherwise, set MAX to +INF.  */
1195       max = TYPE_MAX_VALUE (TREE_TYPE (expr));
1196     }
1197
1198   /* If MIN overflowed, then the result depends on whether we are
1199      using wrapping arithmetic or not.  */
1200   if (TREE_OVERFLOW (min))
1201     {
1202       /* If we are using wrapping arithmetic, set the result to
1203          VARYING.  */
1204       if (flag_wrapv)
1205         {
1206           set_value_range_to_varying (vr);
1207           return;
1208         }
1209
1210       /* Otherwise, set MIN to -INF.  */
1211       min = TYPE_MIN_VALUE (TREE_TYPE (expr));
1212     }
1213
1214   cmp = compare_values (min, max);
1215   if (cmp == -2 || cmp == 1)
1216     {
1217       /* If the new range has its limits swapped around (MIN > MAX),
1218          then the operation caused one of them to wrap around, mark
1219          the new range VARYING.  */
1220       set_value_range_to_varying (vr);
1221     }
1222   else
1223     set_value_range (vr, vr0.type, min, max, NULL);
1224 }
1225
1226
1227 /* Extract range information from a unary expression EXPR based on
1228    the range of its operand and the expression code.  */
1229
1230 static void
1231 extract_range_from_unary_expr (value_range_t *vr, tree expr)
1232 {
1233   enum tree_code code = TREE_CODE (expr);
1234   tree min, max, op0;
1235   int cmp;
1236   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
1237
1238   /* Refuse to operate on certain unary expressions for which we
1239      cannot easily determine a resulting range.  */
1240   if (code == FIX_TRUNC_EXPR
1241       || code == FIX_CEIL_EXPR
1242       || code == FIX_FLOOR_EXPR
1243       || code == FIX_ROUND_EXPR
1244       || code == FLOAT_EXPR
1245       || code == BIT_NOT_EXPR
1246       || code == NON_LVALUE_EXPR
1247       || code == CONJ_EXPR)
1248     {
1249       set_value_range_to_varying (vr);
1250       return;
1251     }
1252
1253   /* Get value ranges for the operand.  For constant operands, create
1254      a new value range with the operand to simplify processing.  */
1255   op0 = TREE_OPERAND (expr, 0);
1256   if (TREE_CODE (op0) == SSA_NAME)
1257     vr0 = *(get_value_range (op0));
1258   else if (is_gimple_min_invariant (op0))
1259     set_value_range (&vr0, VR_RANGE, op0, op0, NULL);
1260   else
1261     set_value_range_to_varying (&vr0);
1262
1263   /* If VR0 is UNDEFINED, so is the result.  */
1264   if (vr0.type == VR_UNDEFINED)
1265     {
1266       set_value_range_to_undefined (vr);
1267       return;
1268     }
1269
1270   /* Refuse to operate on varying and symbolic ranges.  Also, if the
1271      operand is neither a pointer nor an integral type, set the
1272      resulting range to VARYING.  TODO, in some cases we may be able
1273      to derive anti-ranges (like non-zero values).  */
1274   if (vr0.type == VR_VARYING
1275       || (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
1276           && !POINTER_TYPE_P (TREE_TYPE (op0)))
1277       || symbolic_range_p (&vr0))
1278     {
1279       set_value_range_to_varying (vr);
1280       return;
1281     }
1282
1283   /* If the expression involves pointers, we are only interested in
1284      determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
1285   if (POINTER_TYPE_P (TREE_TYPE (expr)) || POINTER_TYPE_P (TREE_TYPE (op0)))
1286     {
1287       if (range_is_nonnull (&vr0) || expr_computes_nonzero (expr))
1288         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1289       else if (range_is_null (&vr0))
1290         set_value_range_to_null (vr, TREE_TYPE (expr));
1291       else
1292         set_value_range_to_varying (vr);
1293
1294       return;
1295     }
1296
1297   /* Handle unary expressions on integer ranges.  */
1298   if (code == NOP_EXPR || code == CONVERT_EXPR)
1299     {
1300       tree inner_type = TREE_TYPE (op0);
1301       tree outer_type = TREE_TYPE (expr);
1302
1303       /* When converting types of different sizes, set the result to
1304          VARYING.  Things like sign extensions and precision loss may
1305          change the range.  For instance, if x_3 is of type 'long long
1306          int' and 'y_5 = (unsigned short) x_3', if x_3 is ~[0, 0], it
1307          is impossible to know at compile time whether y_5 will be
1308          ~[0, 0].  */
1309       if (TYPE_SIZE (inner_type) != TYPE_SIZE (outer_type)
1310           || TYPE_PRECISION (inner_type) != TYPE_PRECISION (outer_type))
1311         {
1312           set_value_range_to_varying (vr);
1313           return;
1314         }
1315     }
1316
1317   /* Apply the operation to each end of the range and see what we end
1318      up with.  */
1319   if (code == NEGATE_EXPR
1320       && !TYPE_UNSIGNED (TREE_TYPE (expr)))
1321     {
1322       /* Negating an anti-range doesn't really do anything to it.  The
1323          new range will also not take on the same range of values
1324          excluded by the original anti-range.  */
1325       if (vr0.type == VR_ANTI_RANGE)
1326         {
1327           copy_value_range (vr, &vr0);
1328           return;
1329         }
1330
1331       /* NEGATE_EXPR flips the range around.  */
1332       min = (vr0.max == TYPE_MAX_VALUE (TREE_TYPE (expr)))
1333             ? TYPE_MIN_VALUE (TREE_TYPE (expr))
1334             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1335
1336       max = (vr0.min == TYPE_MIN_VALUE (TREE_TYPE (expr)))
1337             ? TYPE_MAX_VALUE (TREE_TYPE (expr))
1338             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1339     }
1340   else if (code == ABS_EXPR
1341            && !TYPE_UNSIGNED (TREE_TYPE (expr)))
1342     {
1343       /* ABS_EXPR may flip the range around, if the original range
1344          included negative values.  */
1345       min = (vr0.min == TYPE_MIN_VALUE (TREE_TYPE (expr)))
1346             ? TYPE_MAX_VALUE (TREE_TYPE (expr))
1347             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1348
1349       max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1350
1351       /* If the range was reversed, swap MIN and MAX.  */
1352       if (compare_values (min, max) == 1)
1353         {
1354           tree t = min;
1355           min = max;
1356           max = t;
1357         }
1358     }
1359   else
1360     {
1361       /* Otherwise, operate on each end of the range.  */
1362       min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1363       max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1364     }
1365
1366   cmp = compare_values (min, max);
1367   if (cmp == -2 || cmp == 1)
1368     {
1369       /* If the new range has its limits swapped around (MIN > MAX),
1370          then the operation caused one of them to wrap around, mark
1371          the new range VARYING.  */
1372       set_value_range_to_varying (vr);
1373     }
1374   else
1375     set_value_range (vr, vr0.type, min, max, NULL);
1376 }
1377
1378
1379 /* Extract range information from a comparison expression EXPR based
1380    on the range of its operand and the expression code.  */
1381
1382 static void
1383 extract_range_from_comparison (value_range_t *vr, tree expr)
1384 {
1385   tree val = vrp_evaluate_conditional (expr, false);
1386   if (val)
1387     {
1388       /* Since this expression was found on the RHS of an assignment,
1389          its type may be different from _Bool.  Convert VAL to EXPR's
1390          type.  */
1391       val = fold_convert (TREE_TYPE (expr), val);
1392       set_value_range (vr, VR_RANGE, val, val, vr->equiv);
1393     }
1394   else
1395     set_value_range_to_varying (vr);
1396 }
1397
1398
1399 /* Try to compute a useful range out of expression EXPR and store it
1400    in *VR.  */
1401
1402 static void
1403 extract_range_from_expr (value_range_t *vr, tree expr)
1404 {
1405   enum tree_code code = TREE_CODE (expr);
1406
1407   if (code == ASSERT_EXPR)
1408     extract_range_from_assert (vr, expr);
1409   else if (code == SSA_NAME)
1410     extract_range_from_ssa_name (vr, expr);
1411   else if (TREE_CODE_CLASS (code) == tcc_binary
1412            || code == TRUTH_ANDIF_EXPR
1413            || code == TRUTH_ORIF_EXPR
1414            || code == TRUTH_AND_EXPR
1415            || code == TRUTH_OR_EXPR
1416            || code == TRUTH_XOR_EXPR)
1417     extract_range_from_binary_expr (vr, expr);
1418   else if (TREE_CODE_CLASS (code) == tcc_unary)
1419     extract_range_from_unary_expr (vr, expr);
1420   else if (TREE_CODE_CLASS (code) == tcc_comparison)
1421     extract_range_from_comparison (vr, expr);
1422   else if (vrp_expr_computes_nonzero (expr))
1423     set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1424   else if (is_gimple_min_invariant (expr))
1425     set_value_range (vr, VR_RANGE, expr, expr, NULL);
1426   else
1427     set_value_range_to_varying (vr);
1428 }
1429
1430
1431 /* Given a range VR, a loop L and a variable VAR, determine whether it
1432    would be profitable to adjust VR using scalar evolution information
1433    for VAR.  If so, update VR with the new limits.  */
1434
1435 static void
1436 adjust_range_with_scev (value_range_t *vr, struct loop *l, tree var)
1437 {
1438   tree init, step, chrec;
1439   bool init_is_max;
1440
1441   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
1442      better opportunities than a regular range, but I'm not sure.  */
1443   if (vr->type == VR_ANTI_RANGE)
1444     return;
1445
1446   chrec = analyze_scalar_evolution (l, var);
1447   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
1448     return;
1449
1450   init = CHREC_LEFT (chrec);
1451   step = CHREC_RIGHT (chrec);
1452
1453   /* If STEP is symbolic, we can't know whether INIT will be the
1454      minimum or maximum value in the range.  */
1455   if (!is_gimple_min_invariant (step))
1456     return;
1457
1458   /* FIXME.  When dealing with unsigned types,
1459      analyze_scalar_evolution sets STEP to very large unsigned values
1460      when the evolution goes backwards.  This confuses this analysis
1461      because we think that INIT is the smallest value that the range
1462      can take, instead of the largest.  Ignore these chrecs for now.  */
1463   if (INTEGRAL_TYPE_P (TREE_TYPE (step)) && TYPE_UNSIGNED (TREE_TYPE (step)))
1464     return;
1465
1466   /* Do not adjust ranges when using wrapping arithmetic.  */
1467   if (flag_wrapv)
1468     return;
1469
1470   /* If STEP is negative, then INIT is the maximum value the range
1471      will take.  Otherwise, INIT is the minimum value.  */
1472   init_is_max = (tree_int_cst_sgn (step) < 0);
1473
1474   if (!POINTER_TYPE_P (TREE_TYPE (init))
1475       && (vr->type == VR_VARYING || vr->type == VR_UNDEFINED))
1476     {
1477       /* For VARYING or UNDEFINED ranges, just about anything we get
1478          from scalar evolutions should be better.  */
1479       if (init_is_max)
1480         set_value_range (vr, VR_RANGE, TYPE_MIN_VALUE (TREE_TYPE (init)),
1481                          init, vr->equiv);
1482       else
1483         set_value_range (vr, VR_RANGE, init, TYPE_MAX_VALUE (TREE_TYPE (init)),
1484                          vr->equiv);
1485     }
1486   else if (vr->type == VR_RANGE)
1487     {
1488       tree min = vr->min;
1489       tree max = vr->max;
1490
1491       if (init_is_max)
1492         {
1493           /* INIT is the maximum value.  If INIT is lower than VR->MAX
1494              but no smaller than VR->MIN, set VR->MAX to INIT.  */
1495           if (compare_values (init, max) == -1)
1496             {
1497               max = init;
1498
1499               /* If we just created an invalid range with the minimum
1500                  greater than the maximum, take the minimum all the
1501                  way to -INF.  */
1502               if (compare_values (min, max) == 1)
1503                 min = TYPE_MIN_VALUE (TREE_TYPE (min));
1504             }
1505         }
1506       else
1507         {
1508           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
1509           if (compare_values (init, min) == 1)
1510             {
1511               min = init;
1512
1513               /* If we just created an invalid range with the minimum
1514                  greater than the maximum, take the maximum all the
1515                  way to +INF.  */
1516               if (compare_values (min, max) == 1)
1517                 max = TYPE_MAX_VALUE (TREE_TYPE (max));
1518             }
1519         }
1520
1521       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
1522     }
1523 }
1524
1525
1526 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
1527    
1528    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
1529      all the values in the ranges.
1530
1531    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
1532
1533    - Return NULL_TREE if it is not always possible to determine the
1534      value of the comparison.  */
1535
1536
1537 static tree
1538 compare_ranges (enum tree_code comp, value_range_t *vr0, value_range_t *vr1)
1539 {
1540   /* VARYING or UNDEFINED ranges cannot be compared.  */
1541   if (vr0->type == VR_VARYING
1542       || vr0->type == VR_UNDEFINED
1543       || vr1->type == VR_VARYING
1544       || vr1->type == VR_UNDEFINED)
1545     return NULL_TREE;
1546
1547   /* Anti-ranges need to be handled separately.  */
1548   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
1549     {
1550       /* If both are anti-ranges, then we cannot compute any
1551          comparison.  */
1552       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
1553         return NULL_TREE;
1554
1555       /* These comparisons are never statically computable.  */
1556       if (comp == GT_EXPR
1557           || comp == GE_EXPR
1558           || comp == LT_EXPR
1559           || comp == LE_EXPR)
1560         return NULL_TREE;
1561
1562       /* Equality can be computed only between a range and an
1563          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
1564       if (vr0->type == VR_RANGE)
1565         {
1566           /* To simplify processing, make VR0 the anti-range.  */
1567           value_range_t *tmp = vr0;
1568           vr0 = vr1;
1569           vr1 = tmp;
1570         }
1571
1572       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
1573
1574       if (compare_values (vr0->min, vr1->min) == 0
1575           && compare_values (vr0->max, vr1->max) == 0)
1576         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1577
1578       return NULL_TREE;
1579     }
1580
1581   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
1582      operands around and change the comparison code.  */
1583   if (comp == GT_EXPR || comp == GE_EXPR)
1584     {
1585       value_range_t *tmp;
1586       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
1587       tmp = vr0;
1588       vr0 = vr1;
1589       vr1 = tmp;
1590     }
1591
1592   if (comp == EQ_EXPR)
1593     {
1594       /* Equality may only be computed if both ranges represent
1595          exactly one value.  */
1596       if (compare_values (vr0->min, vr0->max) == 0
1597           && compare_values (vr1->min, vr1->max) == 0)
1598         {
1599           int cmp_min = compare_values (vr0->min, vr1->min);
1600           int cmp_max = compare_values (vr0->max, vr1->max);
1601           if (cmp_min == 0 && cmp_max == 0)
1602             return boolean_true_node;
1603           else if (cmp_min != -2 && cmp_max != -2)
1604             return boolean_false_node;
1605         }
1606
1607       return NULL_TREE;
1608     }
1609   else if (comp == NE_EXPR)
1610     {
1611       int cmp1, cmp2;
1612
1613       /* If VR0 is completely to the left or completely to the right
1614          of VR1, they are always different.  Notice that we need to
1615          make sure that both comparisons yield similar results to
1616          avoid comparing values that cannot be compared at
1617          compile-time.  */
1618       cmp1 = compare_values (vr0->max, vr1->min);
1619       cmp2 = compare_values (vr0->min, vr1->max);
1620       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1621         return boolean_true_node;
1622
1623       /* If VR0 and VR1 represent a single value and are identical,
1624          return false.  */
1625       else if (compare_values (vr0->min, vr0->max) == 0
1626                && compare_values (vr1->min, vr1->max) == 0
1627                && compare_values (vr0->min, vr1->min) == 0
1628                && compare_values (vr0->max, vr1->max) == 0)
1629         return boolean_false_node;
1630
1631       /* Otherwise, they may or may not be different.  */
1632       else
1633         return NULL_TREE;
1634     }
1635   else if (comp == LT_EXPR || comp == LE_EXPR)
1636     {
1637       int tst;
1638
1639       /* If VR0 is to the left of VR1, return true.  */
1640       tst = compare_values (vr0->max, vr1->min);
1641       if ((comp == LT_EXPR && tst == -1)
1642           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1643         return boolean_true_node;
1644
1645       /* If VR0 is to the right of VR1, return false.  */
1646       tst = compare_values (vr0->min, vr1->max);
1647       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1648           || (comp == LE_EXPR && tst == 1))
1649         return boolean_false_node;
1650
1651       /* Otherwise, we don't know.  */
1652       return NULL_TREE;
1653     }
1654     
1655   gcc_unreachable ();
1656 }
1657
1658
1659 /* Given a value range VR, a value VAL and a comparison code COMP, return
1660    BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
1661    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
1662    always returns false.  Return NULL_TREE if it is not always
1663    possible to determine the value of the comparison.  */
1664
1665 static tree
1666 compare_range_with_value (enum tree_code comp, value_range_t *vr, tree val)
1667 {
1668   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
1669     return NULL_TREE;
1670
1671   /* Anti-ranges need to be handled separately.  */
1672   if (vr->type == VR_ANTI_RANGE)
1673     {
1674       /* For anti-ranges, the only predicates that we can compute at
1675          compile time are equality and inequality.  */
1676       if (comp == GT_EXPR
1677           || comp == GE_EXPR
1678           || comp == LT_EXPR
1679           || comp == LE_EXPR)
1680         return NULL_TREE;
1681
1682       /* ~[VAL, VAL] == VAL is always false.  */
1683       if (compare_values (vr->min, val) == 0
1684           && compare_values (vr->max, val) == 0)
1685         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1686
1687       return NULL_TREE;
1688     }
1689
1690   if (comp == EQ_EXPR)
1691     {
1692       /* EQ_EXPR may only be computed if VR represents exactly
1693          one value.  */
1694       if (compare_values (vr->min, vr->max) == 0)
1695         {
1696           int cmp = compare_values (vr->min, val);
1697           if (cmp == 0)
1698             return boolean_true_node;
1699           else if (cmp == -1 || cmp == 1 || cmp == 2)
1700             return boolean_false_node;
1701         }
1702       else if (compare_values (val, vr->min) == -1
1703                || compare_values (vr->max, val) == -1)
1704         return boolean_false_node;
1705
1706       return NULL_TREE;
1707     }
1708   else if (comp == NE_EXPR)
1709     {
1710       /* If VAL is not inside VR, then they are always different.  */
1711       if (compare_values (vr->max, val) == -1
1712           || compare_values (vr->min, val) == 1)
1713         return boolean_true_node;
1714
1715       /* If VR represents exactly one value equal to VAL, then return
1716          false.  */
1717       if (compare_values (vr->min, vr->max) == 0
1718           && compare_values (vr->min, val) == 0)
1719         return boolean_false_node;
1720
1721       /* Otherwise, they may or may not be different.  */
1722       return NULL_TREE;
1723     }
1724   else if (comp == LT_EXPR || comp == LE_EXPR)
1725     {
1726       int tst;
1727
1728       /* If VR is to the left of VAL, return true.  */
1729       tst = compare_values (vr->max, val);
1730       if ((comp == LT_EXPR && tst == -1)
1731           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1732         return boolean_true_node;
1733
1734       /* If VR is to the right of VAL, return false.  */
1735       tst = compare_values (vr->min, val);
1736       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1737           || (comp == LE_EXPR && tst == 1))
1738         return boolean_false_node;
1739
1740       /* Otherwise, we don't know.  */
1741       return NULL_TREE;
1742     }
1743   else if (comp == GT_EXPR || comp == GE_EXPR)
1744     {
1745       int tst;
1746
1747       /* If VR is to the right of VAL, return true.  */
1748       tst = compare_values (vr->min, val);
1749       if ((comp == GT_EXPR && tst == 1)
1750           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1751         return boolean_true_node;
1752
1753       /* If VR is to the left of VAL, return false.  */
1754       tst = compare_values (vr->max, val);
1755       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1756           || (comp == GE_EXPR && tst == -1))
1757         return boolean_false_node;
1758
1759       /* Otherwise, we don't know.  */
1760       return NULL_TREE;
1761     }
1762
1763   gcc_unreachable ();
1764 }
1765
1766
1767 /* Debugging dumps.  */
1768
1769 void dump_value_range (FILE *, value_range_t *);
1770 void debug_value_range (value_range_t *);
1771 void dump_all_value_ranges (FILE *);
1772 void debug_all_value_ranges (void);
1773 void dump_vr_equiv (FILE *, bitmap);
1774 void debug_vr_equiv (bitmap);
1775
1776
1777 /* Dump value range VR to FILE.  */
1778
1779 void
1780 dump_value_range (FILE *file, value_range_t *vr)
1781 {
1782   if (vr == NULL)
1783     fprintf (file, "[]");
1784   else if (vr->type == VR_UNDEFINED)
1785     fprintf (file, "UNDEFINED");
1786   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1787     {
1788       tree type = TREE_TYPE (vr->min);
1789
1790       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1791
1792       if (INTEGRAL_TYPE_P (type)
1793           && !TYPE_UNSIGNED (type)
1794           && vr->min == TYPE_MIN_VALUE (type))
1795         fprintf (file, "-INF");
1796       else
1797         print_generic_expr (file, vr->min, 0);
1798
1799       fprintf (file, ", ");
1800
1801       if (INTEGRAL_TYPE_P (type)
1802           && vr->max == TYPE_MAX_VALUE (type))
1803         fprintf (file, "+INF");
1804       else
1805         print_generic_expr (file, vr->max, 0);
1806
1807       fprintf (file, "]");
1808
1809       if (vr->equiv)
1810         {
1811           bitmap_iterator bi;
1812           unsigned i, c = 0;
1813
1814           fprintf (file, "  EQUIVALENCES: { ");
1815
1816           EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
1817             {
1818               print_generic_expr (file, ssa_name (i), 0);
1819               fprintf (file, " ");
1820               c++;
1821             }
1822
1823           fprintf (file, "} (%u elements)", c);
1824         }
1825     }
1826   else if (vr->type == VR_VARYING)
1827     fprintf (file, "VARYING");
1828   else
1829     fprintf (file, "INVALID RANGE");
1830 }
1831
1832
1833 /* Dump value range VR to stderr.  */
1834
1835 void
1836 debug_value_range (value_range_t *vr)
1837 {
1838   dump_value_range (stderr, vr);
1839 }
1840
1841
1842 /* Dump value ranges of all SSA_NAMEs to FILE.  */
1843
1844 void
1845 dump_all_value_ranges (FILE *file)
1846 {
1847   size_t i;
1848
1849   for (i = 0; i < num_ssa_names; i++)
1850     {
1851       if (vr_value[i])
1852         {
1853           print_generic_expr (file, ssa_name (i), 0);
1854           fprintf (file, ": ");
1855           dump_value_range (file, vr_value[i]);
1856           fprintf (file, "\n");
1857         }
1858     }
1859
1860   fprintf (file, "\n");
1861 }
1862
1863
1864 /* Dump all value ranges to stderr.  */
1865
1866 void
1867 debug_all_value_ranges (void)
1868 {
1869   dump_all_value_ranges (stderr);
1870 }
1871
1872
1873 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1874    create a new SSA name N and return the assertion assignment
1875    'V = ASSERT_EXPR <V, V OP W>'.  */
1876
1877 static tree
1878 build_assert_expr_for (tree cond, tree v)
1879 {
1880   tree n, assertion;
1881
1882   gcc_assert (TREE_CODE (v) == SSA_NAME);
1883   n = duplicate_ssa_name (v, NULL_TREE);
1884
1885   if (COMPARISON_CLASS_P (cond))
1886     {
1887       tree a = build (ASSERT_EXPR, TREE_TYPE (v), v, cond); 
1888       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, a);
1889     }
1890   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1891     {
1892       /* Given !V, build the assignment N = false.  */
1893       tree op0 = TREE_OPERAND (cond, 0);
1894       gcc_assert (op0 == v);
1895       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_false_node);
1896     }
1897   else if (TREE_CODE (cond) == SSA_NAME)
1898     {
1899       /* Given V, build the assignment N = true.  */
1900       gcc_assert (v == cond);
1901       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_true_node);
1902     }
1903   else
1904     gcc_unreachable ();
1905
1906   SSA_NAME_DEF_STMT (n) = assertion;
1907
1908   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1909      operand of the ASSERT_EXPR. Register the new name and the old one
1910      in the replacement table so that we can fix the SSA web after
1911      adding all the ASSERT_EXPRs.  */
1912   register_new_name_mapping (n, v);
1913
1914   return assertion;
1915 }
1916
1917
1918 /* Return false if EXPR is a predicate expression involving floating
1919    point values.  */
1920
1921 static inline bool
1922 fp_predicate (tree expr)
1923 {
1924   return (COMPARISON_CLASS_P (expr)
1925           && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0))));
1926 }
1927
1928
1929 /* If the range of values taken by OP can be inferred after STMT executes,
1930    return the comparison code (COMP_CODE_P) and value (VAL_P) that
1931    describes the inferred range.  Return true if a range could be
1932    inferred.  */
1933
1934 static bool
1935 infer_value_range (tree stmt, tree op, enum tree_code *comp_code_p, tree *val_p)
1936 {
1937   *val_p = NULL_TREE;
1938   *comp_code_p = ERROR_MARK;
1939
1940   /* Do not attempt to infer anything in names that flow through
1941      abnormal edges.  */
1942   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1943     return false;
1944
1945   /* Similarly, don't infer anything from statements that may throw
1946      exceptions.  */
1947   if (tree_could_throw_p (stmt))
1948     return false;
1949
1950   if (POINTER_TYPE_P (TREE_TYPE (op)))
1951     {
1952       bool is_store;
1953       unsigned num_uses, num_derefs;
1954
1955       count_uses_and_derefs (op, stmt, &num_uses, &num_derefs, &is_store);
1956       if (num_derefs > 0 && flag_delete_null_pointer_checks)
1957         {
1958           /* We can only assume that a pointer dereference will yield
1959              non-NULL if -fdelete-null-pointer-checks is enabled.  */
1960           *val_p = build_int_cst (TREE_TYPE (op), 0);
1961           *comp_code_p = NE_EXPR;
1962           return true;
1963         }
1964     }
1965
1966   return false;
1967 }
1968
1969
1970 void dump_asserts_for (FILE *, tree);
1971 void debug_asserts_for (tree);
1972 void dump_all_asserts (FILE *);
1973 void debug_all_asserts (void);
1974
1975 /* Dump all the registered assertions for NAME to FILE.  */
1976
1977 void
1978 dump_asserts_for (FILE *file, tree name)
1979 {
1980   assert_locus_t loc;
1981
1982   fprintf (file, "Assertions to be inserted for ");
1983   print_generic_expr (file, name, 0);
1984   fprintf (file, "\n");
1985
1986   loc = asserts_for[SSA_NAME_VERSION (name)];
1987   while (loc)
1988     {
1989       fprintf (file, "\t");
1990       print_generic_expr (file, bsi_stmt (loc->si), 0);
1991       fprintf (file, "\n\tBB #%d", loc->bb->index);
1992       if (loc->e)
1993         {
1994           fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
1995                    loc->e->dest->index);
1996           dump_edge_info (file, loc->e, 0);
1997         }
1998       fprintf (file, "\n\tPREDICATE: ");
1999       print_generic_expr (file, name, 0);
2000       fprintf (file, " %s ", tree_code_name[(int)loc->comp_code]);
2001       print_generic_expr (file, loc->val, 0);
2002       fprintf (file, "\n\n");
2003       loc = loc->next;
2004     }
2005
2006   fprintf (file, "\n");
2007 }
2008
2009
2010 /* Dump all the registered assertions for NAME to stderr.  */
2011
2012 void
2013 debug_asserts_for (tree name)
2014 {
2015   dump_asserts_for (stderr, name);
2016 }
2017
2018
2019 /* Dump all the registered assertions for all the names to FILE.  */
2020
2021 void
2022 dump_all_asserts (FILE *file)
2023 {
2024   unsigned i;
2025   bitmap_iterator bi;
2026
2027   fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2028   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2029     dump_asserts_for (file, ssa_name (i));
2030   fprintf (file, "\n");
2031 }
2032
2033
2034 /* Dump all the registered assertions for all the names to stderr.  */
2035
2036 void
2037 debug_all_asserts (void)
2038 {
2039   dump_all_asserts (stderr);
2040 }
2041
2042
2043 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2044    'NAME COMP_CODE VAL' at a location that dominates block BB or
2045    E->DEST, then register this location as a possible insertion point
2046    for ASSERT_EXPR <NAME, NAME COMP_CODE VAL>.
2047
2048    BB, E and SI provide the exact insertion point for the new
2049    ASSERT_EXPR.  If BB is NULL, then the ASSERT_EXPR is to be inserted
2050    on edge E.  Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2051    BB.  If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2052    must not be NULL.  */
2053
2054 static void
2055 register_new_assert_for (tree name,
2056                          enum tree_code comp_code,
2057                          tree val,
2058                          basic_block bb,
2059                          edge e,
2060                          block_stmt_iterator si)
2061 {
2062   assert_locus_t n, loc, last_loc;
2063   bool found;
2064   basic_block dest_bb;
2065
2066 #if defined ENABLE_CHECKING
2067   gcc_assert (bb == NULL || e == NULL);
2068
2069   if (e == NULL)
2070     gcc_assert (TREE_CODE (bsi_stmt (si)) != COND_EXPR
2071                 && TREE_CODE (bsi_stmt (si)) != SWITCH_EXPR);
2072 #endif
2073
2074   /* The new assertion A will be inserted at BB or E.  We need to
2075      determine if the new location is dominated by a previously
2076      registered location for A.  If we are doing an edge insertion,
2077      assume that A will be inserted at E->DEST.  Note that this is not
2078      necessarily true.
2079      
2080      If E is a critical edge, it will be split.  But even if E is
2081      split, the new block will dominate the same set of blocks that
2082      E->DEST dominates.
2083      
2084      The reverse, however, is not true, blocks dominated by E->DEST
2085      will not be dominated by the new block created to split E.  So,
2086      if the insertion location is on a critical edge, we will not use
2087      the new location to move another assertion previously registered
2088      at a block dominated by E->DEST.  */
2089   dest_bb = (bb) ? bb : e->dest;
2090
2091   /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2092      VAL at a block dominating DEST_BB, then we don't need to insert a new
2093      one.  Similarly, if the same assertion already exists at a block
2094      dominated by DEST_BB and the new location is not on a critical
2095      edge, then update the existing location for the assertion (i.e.,
2096      move the assertion up in the dominance tree).
2097
2098      Note, this is implemented as a simple linked list because there
2099      should not be more than a handful of assertions registered per
2100      name.  If this becomes a performance problem, a table hashed by
2101      COMP_CODE and VAL could be implemented.  */
2102   loc = asserts_for[SSA_NAME_VERSION (name)];
2103   last_loc = loc;
2104   found = false;
2105   while (loc)
2106     {
2107       if (loc->comp_code == comp_code
2108           && (loc->val == val
2109               || operand_equal_p (loc->val, val, 0)))
2110         {
2111           /* If the assertion NAME COMP_CODE VAL has already been
2112              registered at a basic block that dominates DEST_BB, then
2113              we don't need to insert the same assertion again.  Note
2114              that we don't check strict dominance here to avoid
2115              replicating the same assertion inside the same basic
2116              block more than once (e.g., when a pointer is
2117              dereferenced several times inside a block).
2118
2119              An exception to this rule are edge insertions.  If the
2120              new assertion is to be inserted on edge E, then it will
2121              dominate all the other insertions that we may want to
2122              insert in DEST_BB.  So, if we are doing an edge
2123              insertion, don't do this dominance check.  */
2124           if (e == NULL
2125               && dominated_by_p (CDI_DOMINATORS, dest_bb, loc->bb))
2126             return;
2127
2128           /* Otherwise, if E is not a critical edge and DEST_BB
2129              dominates the existing location for the assertion, move
2130              the assertion up in the dominance tree by updating its
2131              location information.  */
2132           if ((e == NULL || !EDGE_CRITICAL_P (e))
2133               && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2134             {
2135               loc->bb = dest_bb;
2136               loc->e = e;
2137               loc->si = si;
2138               return;
2139             }
2140         }
2141
2142       /* Update the last node of the list and move to the next one.  */
2143       last_loc = loc;
2144       loc = loc->next;
2145     }
2146
2147   /* If we didn't find an assertion already registered for
2148      NAME COMP_CODE VAL, add a new one at the end of the list of
2149      assertions associated with NAME.  */
2150   n = xmalloc (sizeof (*n));
2151   n->bb = dest_bb;
2152   n->e = e;
2153   n->si = si;
2154   n->comp_code = comp_code;
2155   n->val = val;
2156   n->next = NULL;
2157
2158   if (last_loc)
2159     last_loc->next = n;
2160   else
2161     asserts_for[SSA_NAME_VERSION (name)] = n;
2162
2163   bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2164 }
2165
2166
2167 /* Try to register an edge assertion for SSA name NAME on edge E for
2168    the conditional jump pointed by SI.  Return true if an assertion
2169    for NAME could be registered.  */
2170
2171 static bool
2172 register_edge_assert_for (tree name, edge e, block_stmt_iterator si)
2173 {
2174   tree val, stmt;
2175   enum tree_code comp_code;
2176
2177   stmt = bsi_stmt (si);
2178
2179   /* Do not attempt to infer anything in names that flow through
2180      abnormal edges.  */
2181   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
2182     return false;
2183
2184   /* If NAME was not found in the sub-graph reachable from E, then
2185      there's nothing to do.  */
2186   if (!TEST_BIT (found_in_subgraph, SSA_NAME_VERSION (name)))
2187     return false;
2188
2189   /* We found a use of NAME in the sub-graph rooted at E->DEST.
2190      Register an assertion for NAME according to the value that NAME
2191      takes on edge E.  */
2192   if (TREE_CODE (stmt) == COND_EXPR)
2193     {
2194       /* If BB ends in a COND_EXPR then NAME then we should insert
2195          the original predicate on EDGE_TRUE_VALUE and the
2196          opposite predicate on EDGE_FALSE_VALUE.  */
2197       tree cond = COND_EXPR_COND (stmt);
2198       bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
2199
2200       /* Predicates may be a single SSA name or NAME OP VAL.  */
2201       if (cond == name)
2202         {
2203           /* If the predicate is a name, it must be NAME, in which
2204              case we create the predicate NAME == true or
2205              NAME == false accordingly.  */
2206           comp_code = EQ_EXPR;
2207           val = (is_else_edge) ? boolean_false_node : boolean_true_node;
2208         }
2209       else
2210         {
2211           /* Otherwise, we have a comparison of the form NAME COMP VAL
2212              or VAL COMP NAME.  */
2213           if (name == TREE_OPERAND (cond, 1))
2214             {
2215               /* If the predicate is of the form VAL COMP NAME, flip
2216                  COMP around because we need to register NAME as the
2217                  first operand in the predicate.  */
2218               comp_code = opposite_comparison (TREE_CODE (cond));
2219               val = TREE_OPERAND (cond, 0);
2220             }
2221           else
2222             {
2223               /* The comparison is of the form NAME COMP VAL, so the
2224                  comparison code remains unchanged.  */
2225               comp_code = TREE_CODE (cond);
2226               val = TREE_OPERAND (cond, 1);
2227             }
2228
2229           /* If we are inserting the assertion on the ELSE edge, we
2230              need to invert the sign comparison.  */
2231           if (is_else_edge)
2232             comp_code = invert_tree_comparison (comp_code, 0);
2233         }
2234     }
2235   else
2236     {
2237       /* FIXME.  Handle SWITCH_EXPR.  */
2238       gcc_unreachable ();
2239     }
2240
2241   register_new_assert_for (name, comp_code, val, NULL, e, si);
2242   return true;
2243 }
2244
2245
2246 static bool find_assert_locations (basic_block bb);
2247
2248 /* Determine whether the outgoing edges of BB should receive an
2249    ASSERT_EXPR for each of the operands of BB's last statement.  The
2250    last statement of BB must be a COND_EXPR or a SWITCH_EXPR.
2251
2252    If any of the sub-graphs rooted at BB have an interesting use of
2253    the predicate operands, an assert location node is added to the
2254    list of assertions for the corresponding operands.  */
2255
2256 static bool
2257 find_conditional_asserts (basic_block bb)
2258 {
2259   bool need_assert;
2260   block_stmt_iterator last_si;
2261   tree op, last;
2262   edge_iterator ei;
2263   edge e;
2264   ssa_op_iter iter;
2265
2266   need_assert = false;
2267   last_si = bsi_last (bb);
2268   last = bsi_stmt (last_si);
2269
2270   /* Look for uses of the operands in each of the sub-graphs
2271      rooted at BB.  We need to check each of the outgoing edges
2272      separately, so that we know what kind of ASSERT_EXPR to
2273      insert.  */
2274   FOR_EACH_EDGE (e, ei, bb->succs)
2275     {
2276       if (e->dest == bb)
2277         continue;
2278
2279       /* Remove the COND_EXPR operands from the FOUND_IN_SUBGRAPH bitmap.
2280          Otherwise, when we finish traversing each of the sub-graphs, we
2281          won't know whether the variables were found in the sub-graphs or
2282          if they had been found in a block upstream from BB.  */
2283       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2284         RESET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2285
2286       /* Traverse the strictly dominated sub-graph rooted at E->DEST
2287          to determine if any of the operands in the conditional
2288          predicate are used.  */
2289       if (e->dest != bb)
2290         need_assert |= find_assert_locations (e->dest);
2291
2292       /* Register the necessary assertions for each operand in the
2293          conditional predicate.  */
2294       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2295         need_assert |= register_edge_assert_for (op, e, last_si);
2296     }
2297
2298   /* Finally, indicate that we have found the operands in the
2299      conditional.  */
2300   FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2301     SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2302
2303   return need_assert;
2304 }
2305
2306
2307 /* Traverse all the statements in block BB looking for statements that
2308    may generate useful assertions for the SSA names in their operand.
2309    If a statement produces a useful assertion A for name N_i, then the
2310    list of assertions already generated for N_i is scanned to
2311    determine if A is actually needed.
2312    
2313    If N_i already had the assertion A at a location dominating the
2314    current location, then nothing needs to be done.  Otherwise, the
2315    new location for A is recorded instead.
2316
2317    1- For every statement S in BB, all the variables used by S are
2318       added to bitmap FOUND_IN_SUBGRAPH.
2319
2320    2- If statement S uses an operand N in a way that exposes a known
2321       value range for N, then if N was not already generated by an
2322       ASSERT_EXPR, create a new assert location for N.  For instance,
2323       if N is a pointer and the statement dereferences it, we can
2324       assume that N is not NULL.
2325
2326    3- COND_EXPRs are a special case of #2.  We can derive range
2327       information from the predicate but need to insert different
2328       ASSERT_EXPRs for each of the sub-graphs rooted at the
2329       conditional block.  If the last statement of BB is a conditional
2330       expression of the form 'X op Y', then
2331
2332       a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
2333
2334       b) If the conditional is the only entry point to the sub-graph
2335          corresponding to the THEN_CLAUSE, recurse into it.  On
2336          return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
2337          an ASSERT_EXPR is added for the corresponding variable.
2338
2339       c) Repeat step (b) on the ELSE_CLAUSE.
2340
2341       d) Mark X and Y in FOUND_IN_SUBGRAPH.
2342
2343       For instance,
2344
2345             if (a == 9)
2346               b = a;
2347             else
2348               b = c + 1;
2349
2350       In this case, an assertion on the THEN clause is useful to
2351       determine that 'a' is always 9 on that edge.  However, an assertion
2352       on the ELSE clause would be unnecessary.
2353
2354    4- If BB does not end in a conditional expression, then we recurse
2355       into BB's dominator children.
2356    
2357    At the end of the recursive traversal, every SSA name will have a
2358    list of locations where ASSERT_EXPRs should be added.  When a new
2359    location for name N is found, it is registered by calling
2360    register_new_assert_for.  That function keeps track of all the
2361    registered assertions to prevent adding unnecessary assertions.
2362    For instance, if a pointer P_4 is dereferenced more than once in a
2363    dominator tree, only the location dominating all the dereference of
2364    P_4 will receive an ASSERT_EXPR.
2365
2366    If this function returns true, then it means that there are names
2367    for which we need to generate ASSERT_EXPRs.  Those assertions are
2368    inserted by process_assert_insertions.
2369
2370    TODO.  Handle SWITCH_EXPR.  */
2371
2372 static bool
2373 find_assert_locations (basic_block bb)
2374 {
2375   block_stmt_iterator si;
2376   tree last, phi;
2377   bool need_assert;
2378   basic_block son;
2379
2380   if (TEST_BIT (blocks_visited, bb->index))
2381     return false;
2382
2383   SET_BIT (blocks_visited, bb->index);
2384
2385   need_assert = false;
2386
2387   /* Traverse all PHI nodes in BB marking used operands.  */
2388   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2389     {
2390       use_operand_p arg_p;
2391       ssa_op_iter i;
2392
2393       FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
2394         {
2395           tree arg = USE_FROM_PTR (arg_p);
2396           if (TREE_CODE (arg) == SSA_NAME)
2397             {
2398               gcc_assert (is_gimple_reg (PHI_RESULT (phi)));
2399               SET_BIT (found_in_subgraph, SSA_NAME_VERSION (arg));
2400             }
2401         }
2402     }
2403
2404   /* Traverse all the statements in BB marking used names and looking
2405      for statements that may infer assertions for their used operands.  */
2406   last = NULL_TREE;
2407   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2408     {
2409       tree stmt, op;
2410       ssa_op_iter i;
2411
2412       stmt = bsi_stmt (si);
2413
2414       /* See if we can derive an assertion for any of STMT's operands.  */
2415       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
2416         {
2417           tree value;
2418           enum tree_code comp_code;
2419
2420           /* Mark OP in bitmap FOUND_IN_SUBGRAPH.  If STMT is inside
2421              the sub-graph of a conditional block, when we return from
2422              this recursive walk, our parent will use the
2423              FOUND_IN_SUBGRAPH bitset to determine if one of the
2424              operands it was looking for was present in the sub-graph.  */
2425           SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2426
2427           /* If OP is used only once, namely in this STMT, don't
2428              bother creating an ASSERT_EXPR for it.  Such an
2429              ASSERT_EXPR would do nothing but increase compile time.
2430              Experiments show that with this simple check, we can save
2431              more than 20% of ASSERT_EXPRs.  */
2432           if (has_single_use (op))
2433             continue;
2434
2435           /* If OP is used in such a way that we can infer a value
2436              range for it, and we don't find a previous assertion for
2437              it, create a new assertion location node for OP.  */
2438           if (infer_value_range (stmt, op, &comp_code, &value))
2439             {
2440               register_new_assert_for (op, comp_code, value, bb, NULL, si);
2441               need_assert = true;
2442             }
2443         }
2444
2445       /* Remember the last statement of the block.  */
2446       last = stmt;
2447     }
2448
2449   /* If BB's last statement is a conditional expression
2450      involving integer operands, recurse into each of the sub-graphs
2451      rooted at BB to determine if we need to add ASSERT_EXPRs.  */
2452   if (last
2453       && TREE_CODE (last) == COND_EXPR
2454       && !fp_predicate (COND_EXPR_COND (last))
2455       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
2456     need_assert |= find_conditional_asserts (bb);
2457
2458   /* Recurse into the dominator children of BB.  */
2459   for (son = first_dom_son (CDI_DOMINATORS, bb);
2460        son;
2461        son = next_dom_son (CDI_DOMINATORS, son))
2462     need_assert |= find_assert_locations (son);
2463
2464   return need_assert;
2465 }
2466
2467
2468 /* Create an ASSERT_EXPR for NAME and insert it in the location
2469    indicated by LOC.  Return true if we made any edge insertions.  */
2470
2471 static bool
2472 process_assert_insertions_for (tree name, assert_locus_t loc)
2473 {
2474   /* Build the comparison expression NAME_i COMP_CODE VAL.  */
2475   tree stmt, cond, assert_expr;
2476   edge_iterator ei;
2477   edge e;
2478
2479   cond = build (loc->comp_code, boolean_type_node, name, loc->val);
2480   assert_expr = build_assert_expr_for (cond, name);
2481
2482   if (loc->e)
2483     {
2484       /* We have been asked to insert the assertion on an edge.  This
2485          is used only by COND_EXPR and SWITCH_EXPR assertions.  */
2486 #if defined ENABLE_CHECKING
2487       gcc_assert (TREE_CODE (bsi_stmt (loc->si)) == COND_EXPR
2488           || TREE_CODE (bsi_stmt (loc->si)) == SWITCH_EXPR);
2489 #endif
2490
2491       bsi_insert_on_edge (loc->e, assert_expr);
2492       return true;
2493     }
2494
2495   /* Otherwise, we can insert right after LOC->SI iff the
2496      statement must not be the last statement in the block.  */
2497   stmt = bsi_stmt (loc->si);
2498   if (!stmt_ends_bb_p (stmt))
2499     {
2500       bsi_insert_after (&loc->si, assert_expr, BSI_SAME_STMT);
2501       return false;
2502     }
2503
2504   /* If STMT must be the last statement in BB, we can only insert new
2505      assertions on the non-abnormal edge out of BB.  Note that since
2506      STMT is not control flow, there may only be one non-abnormal edge
2507      out of BB.  */
2508   FOR_EACH_EDGE (e, ei, loc->bb->succs)
2509     if (!(e->flags & EDGE_ABNORMAL))
2510       {
2511         bsi_insert_on_edge (e, assert_expr);
2512         return true;
2513       }
2514
2515   gcc_unreachable ();
2516 }
2517
2518
2519 /* Process all the insertions registered for every name N_i registered
2520    in NEED_ASSERT_FOR.  The list of assertions to be inserted are
2521    found in ASSERTS_FOR[i].  */
2522
2523 static void
2524 process_assert_insertions (void)
2525 {
2526   unsigned i;
2527   bitmap_iterator bi;
2528   bool update_edges_p = false;
2529   int num_asserts = 0;
2530
2531   if (dump_file && (dump_flags & TDF_DETAILS))
2532     dump_all_asserts (dump_file);
2533
2534   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2535     {
2536       assert_locus_t loc = asserts_for[i];
2537       gcc_assert (loc);
2538
2539       while (loc)
2540         {
2541           assert_locus_t next = loc->next;
2542           update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
2543           free (loc);
2544           loc = next;
2545           num_asserts++;
2546         }
2547     }
2548
2549   if (update_edges_p)
2550     bsi_commit_edge_inserts ();
2551
2552   if (dump_file && (dump_flags & TDF_STATS))
2553     fprintf (dump_file, "\nNumber of ASSERT_EXPR expressions inserted: %d\n\n",
2554              num_asserts);
2555 }
2556
2557
2558 /* Traverse the flowgraph looking for conditional jumps to insert range
2559    expressions.  These range expressions are meant to provide information
2560    to optimizations that need to reason in terms of value ranges.  They
2561    will not be expanded into RTL.  For instance, given:
2562
2563    x = ...
2564    y = ...
2565    if (x < y)
2566      y = x - 2;
2567    else
2568      x = y + 3;
2569
2570    this pass will transform the code into:
2571
2572    x = ...
2573    y = ...
2574    if (x < y)
2575     {
2576       x = ASSERT_EXPR <x, x < y>
2577       y = x - 2
2578     }
2579    else
2580     {
2581       y = ASSERT_EXPR <y, x <= y>
2582       x = y + 3
2583     }
2584
2585    The idea is that once copy and constant propagation have run, other
2586    optimizations will be able to determine what ranges of values can 'x'
2587    take in different paths of the code, simply by checking the reaching
2588    definition of 'x'.  */
2589
2590 static void
2591 insert_range_assertions (void)
2592 {
2593   edge e;
2594   edge_iterator ei;
2595   bool update_ssa_p;
2596   
2597   found_in_subgraph = sbitmap_alloc (num_ssa_names);
2598   sbitmap_zero (found_in_subgraph);
2599
2600   blocks_visited = sbitmap_alloc (last_basic_block);
2601   sbitmap_zero (blocks_visited);
2602
2603   need_assert_for = BITMAP_ALLOC (NULL);
2604   asserts_for = xmalloc (num_ssa_names * sizeof (assert_locus_t));
2605   memset (asserts_for, 0, num_ssa_names * sizeof (assert_locus_t));
2606
2607   calculate_dominance_info (CDI_DOMINATORS);
2608
2609   update_ssa_p = false;
2610   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2611     if (find_assert_locations (e->dest))
2612       update_ssa_p = true;
2613
2614   if (update_ssa_p)
2615     {
2616       process_assert_insertions ();
2617       update_ssa (TODO_update_ssa_no_phi);
2618     }
2619
2620   if (dump_file && (dump_flags & TDF_DETAILS))
2621     {
2622       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
2623       dump_function_to_file (current_function_decl, dump_file, dump_flags);
2624     }
2625
2626   sbitmap_free (found_in_subgraph);
2627   free (asserts_for);
2628   BITMAP_FREE (need_assert_for);
2629 }
2630
2631
2632 /* Convert range assertion expressions into the implied copies.
2633    
2634    FIXME, this will eventually lead to copy propagation removing the
2635    names that had useful range information attached to them.  For
2636    instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
2637    then N_i will have the range [3, +INF].
2638    
2639    However, by converting the assertion into the implied copy
2640    operation N_i = N_j, we will then copy-propagate N_j into the uses
2641    of N_i and lose the range information.  We may want to hold on to
2642    ASSERT_EXPRs a little while longer as the ranges could be used in
2643    things like jump threading.
2644    
2645    The problem with keeping ASSERT_EXPRs around is that passes after
2646    VRP need to handle them appropriately.  */
2647
2648 static void
2649 remove_range_assertions (void)
2650 {
2651   basic_block bb;
2652   block_stmt_iterator si;
2653
2654   FOR_EACH_BB (bb)
2655     for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2656       {
2657         tree stmt = bsi_stmt (si);
2658
2659         if (TREE_CODE (stmt) == MODIFY_EXPR
2660             && TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
2661           {
2662             tree rhs = TREE_OPERAND (stmt, 1);
2663             tree cond = fold (ASSERT_EXPR_COND (rhs));
2664             gcc_assert (cond != boolean_false_node);
2665             TREE_OPERAND (stmt, 1) = ASSERT_EXPR_VAR (rhs);
2666             update_stmt (stmt);
2667           }
2668       }
2669 }
2670
2671
2672 /* Return true if STMT is interesting for VRP.  */
2673
2674 static bool
2675 stmt_interesting_for_vrp (tree stmt)
2676 {
2677   if (TREE_CODE (stmt) == PHI_NODE
2678       && is_gimple_reg (PHI_RESULT (stmt))
2679       && (INTEGRAL_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))
2680           || POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))))
2681     return true;
2682   else if (TREE_CODE (stmt) == MODIFY_EXPR)
2683     {
2684       tree lhs = TREE_OPERAND (stmt, 0);
2685
2686       if (TREE_CODE (lhs) == SSA_NAME
2687           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2688               || POINTER_TYPE_P (TREE_TYPE (lhs)))
2689           && ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
2690         return true;
2691     }
2692   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
2693     return true;
2694
2695   return false;
2696 }
2697
2698
2699 /* Initialize local data structures for VRP.  Return true if VRP
2700    is worth running (i.e. if we found any statements that could
2701    benefit from range information).  */
2702
2703 static void
2704 vrp_initialize (void)
2705 {
2706   basic_block bb;
2707
2708   vr_value = xmalloc (num_ssa_names * sizeof (value_range_t *));
2709   memset (vr_value, 0, num_ssa_names * sizeof (value_range_t *));
2710
2711   FOR_EACH_BB (bb)
2712     {
2713       block_stmt_iterator si;
2714       tree phi;
2715
2716       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2717         {
2718           if (!stmt_interesting_for_vrp (phi))
2719             {
2720               tree lhs = PHI_RESULT (phi);
2721               set_value_range_to_varying (get_value_range (lhs));
2722               DONT_SIMULATE_AGAIN (phi) = true;
2723             }
2724           else
2725             DONT_SIMULATE_AGAIN (phi) = false;
2726         }
2727
2728       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2729         {
2730           tree stmt = bsi_stmt (si);
2731
2732           if (!stmt_interesting_for_vrp (stmt))
2733             {
2734               ssa_op_iter i;
2735               tree def;
2736               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
2737                 set_value_range_to_varying (get_value_range (def));
2738               DONT_SIMULATE_AGAIN (stmt) = true;
2739             }
2740           else
2741             {
2742               DONT_SIMULATE_AGAIN (stmt) = false;
2743             }
2744         }
2745     }
2746 }
2747
2748
2749 /* Visit assignment STMT.  If it produces an interesting range, record
2750    the SSA name in *OUTPUT_P.  */
2751
2752 static enum ssa_prop_result
2753 vrp_visit_assignment (tree stmt, tree *output_p)
2754 {
2755   tree lhs, rhs, def;
2756   ssa_op_iter iter;
2757
2758   lhs = TREE_OPERAND (stmt, 0);
2759   rhs = TREE_OPERAND (stmt, 1);
2760
2761   /* We only keep track of ranges in integral and pointer types.  */
2762   if (TREE_CODE (lhs) == SSA_NAME
2763       && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2764           || POINTER_TYPE_P (TREE_TYPE (lhs))))
2765     {
2766       struct loop *l;
2767       value_range_t new_vr = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2768
2769       extract_range_from_expr (&new_vr, rhs);
2770
2771       /* If STMT is inside a loop, we may be able to know something
2772          else about the range of LHS by examining scalar evolution
2773          information.  */
2774       if (cfg_loops && (l = loop_containing_stmt (stmt)))
2775         adjust_range_with_scev (&new_vr, l, lhs);
2776
2777       if (update_value_range (lhs, &new_vr))
2778         {
2779           *output_p = lhs;
2780
2781           if (dump_file && (dump_flags & TDF_DETAILS))
2782             {
2783               fprintf (dump_file, "Found new range for ");
2784               print_generic_expr (dump_file, lhs, 0);
2785               fprintf (dump_file, ": ");
2786               dump_value_range (dump_file, &new_vr);
2787               fprintf (dump_file, "\n\n");
2788             }
2789
2790           if (new_vr.type == VR_VARYING)
2791             return SSA_PROP_VARYING;
2792
2793           return SSA_PROP_INTERESTING;
2794         }
2795
2796       return SSA_PROP_NOT_INTERESTING;
2797     }
2798   
2799   /* Every other statement produces no useful ranges.  */
2800   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
2801     set_value_range_to_varying (get_value_range (def));
2802
2803   return SSA_PROP_VARYING;
2804 }
2805
2806
2807 /* Compare all the value ranges for names equivalent to VAR with VAL
2808    using comparison code COMP.  Return the same value returned by
2809    compare_range_with_value.  */
2810
2811 static tree
2812 compare_name_with_value (enum tree_code comp, tree var, tree val)
2813 {
2814   bitmap_iterator bi;
2815   unsigned i;
2816   bitmap e;
2817   tree retval, t;
2818   
2819   t = retval = NULL_TREE;
2820
2821   /* Get the set of equivalences for VAR.  */
2822   e = get_value_range (var)->equiv;
2823
2824   /* Add VAR to its own set of equivalences so that VAR's value range
2825      is processed by this loop (otherwise, we would have to replicate
2826      the body of the loop just to check VAR's value range).  */
2827   bitmap_set_bit (e, SSA_NAME_VERSION (var));
2828
2829   EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
2830     {
2831       value_range_t equiv_vr = *(vr_value[i]);
2832
2833       /* If name N_i does not have a valid range, use N_i as its own
2834          range.  This allows us to compare against names that may
2835          have N_i in their ranges.  */
2836       if (equiv_vr.type == VR_VARYING || equiv_vr.type == VR_UNDEFINED)
2837         {
2838           equiv_vr.type = VR_RANGE;
2839           equiv_vr.min = ssa_name (i);
2840           equiv_vr.max = ssa_name (i);
2841         }
2842
2843       t = compare_range_with_value (comp, &equiv_vr, val);
2844       if (t)
2845         {
2846           /* All the ranges should compare the same against VAL.  */
2847           gcc_assert (retval == NULL || t == retval);
2848           retval = t;
2849         }
2850     }
2851
2852   /* Remove VAR from its own equivalence set.  */
2853   bitmap_clear_bit (e, SSA_NAME_VERSION (var));
2854
2855   if (retval)
2856     return retval;
2857
2858   /* We couldn't find a non-NULL value for the predicate.  */
2859   return NULL_TREE;
2860 }
2861
2862
2863 /* Given a comparison code COMP and names N1 and N2, compare all the
2864    ranges equivalent to N1 against all the ranges equivalent to N2
2865    to determine the value of N1 COMP N2.  Return the same value
2866    returned by compare_ranges.  */
2867
2868 static tree
2869 compare_names (enum tree_code comp, tree n1, tree n2)
2870 {
2871   tree t, retval;
2872   bitmap e1, e2;
2873   bitmap_iterator bi1, bi2;
2874   unsigned i1, i2;
2875
2876   /* Compare the ranges of every name equivalent to N1 against the
2877      ranges of every name equivalent to N2.  */
2878   e1 = get_value_range (n1)->equiv;
2879   e2 = get_value_range (n2)->equiv;
2880
2881   /* Add N1 and N2 to their own set of equivalences to avoid
2882      duplicating the body of the loop just to check N1 and N2
2883      ranges.  */
2884   bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
2885   bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
2886
2887   /* If the equivalence sets have a common intersection, then the two
2888      names can be compared without checking their ranges.  */
2889   if (bitmap_intersect_p (e1, e2))
2890     {
2891       bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2892       bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2893
2894       return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
2895              ? boolean_true_node
2896              : boolean_false_node;
2897     }
2898
2899   /* Otherwise, compare all the equivalent ranges.  First, add N1 and
2900      N2 to their own set of equivalences to avoid duplicating the body
2901      of the loop just to check N1 and N2 ranges.  */
2902   EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
2903     {
2904       value_range_t vr1 = *(vr_value[i1]);
2905
2906       /* If the range is VARYING or UNDEFINED, use the name itself.  */
2907       if (vr1.type == VR_VARYING || vr1.type == VR_UNDEFINED)
2908         {
2909           vr1.type = VR_RANGE;
2910           vr1.min = ssa_name (i1);
2911           vr1.max = ssa_name (i1);
2912         }
2913
2914       t = retval = NULL_TREE;
2915       EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
2916         {
2917           value_range_t vr2 = *(vr_value[i2]);
2918
2919           if (vr2.type == VR_VARYING || vr2.type == VR_UNDEFINED)
2920             {
2921               vr2.type = VR_RANGE;
2922               vr2.min = ssa_name (i2);
2923               vr2.max = ssa_name (i2);
2924             }
2925
2926           t = compare_ranges (comp, &vr1, &vr2);
2927           if (t)
2928             {
2929               /* All the ranges in the equivalent sets should compare
2930                  the same.  */
2931               gcc_assert (retval == NULL || t == retval);
2932               retval = t;
2933             }
2934         }
2935
2936       if (retval)
2937         {
2938           bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2939           bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2940           return retval;
2941         }
2942     }
2943
2944   /* None of the equivalent ranges are useful in computing this
2945      comparison.  */
2946   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2947   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2948   return NULL_TREE;
2949 }
2950
2951
2952 /* Given a conditional predicate COND, try to determine if COND yields
2953    true or false based on the value ranges of its operands.  Return
2954    BOOLEAN_TRUE_NODE if the conditional always evaluates to true,
2955    BOOLEAN_FALSE_NODE if the conditional always evaluates to false, and,
2956    NULL if the conditional cannot be evaluated at compile time.
2957
2958    If USE_EQUIV_P is true, the ranges of all the names equivalent with
2959    the operands in COND are used when trying to compute its value.
2960    This is only used during final substitution.  During propagation,
2961    we only check the range of each variable and not its equivalents.  */
2962
2963 tree
2964 vrp_evaluate_conditional (tree cond, bool use_equiv_p)
2965 {
2966   gcc_assert (TREE_CODE (cond) == SSA_NAME
2967               || TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
2968
2969   if (TREE_CODE (cond) == SSA_NAME)
2970     {
2971       value_range_t *vr;
2972       tree retval;
2973
2974       if (use_equiv_p)
2975         retval = compare_name_with_value (NE_EXPR, cond, boolean_false_node);
2976       else
2977         {
2978           value_range_t *vr = get_value_range (cond);
2979           retval = compare_range_with_value (NE_EXPR, vr, boolean_false_node);
2980         }
2981
2982       /* If COND has a known boolean range, return it.  */
2983       if (retval)
2984         return retval;
2985
2986       /* Otherwise, if COND has a symbolic range of exactly one value,
2987          return it.  */
2988       vr = get_value_range (cond);
2989       if (vr->type == VR_RANGE && vr->min == vr->max)
2990         return vr->min;
2991     }
2992   else
2993     {
2994       tree op0 = TREE_OPERAND (cond, 0);
2995       tree op1 = TREE_OPERAND (cond, 1);
2996
2997       /* We only deal with integral and pointer types.  */
2998       if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
2999           && !POINTER_TYPE_P (TREE_TYPE (op0)))
3000         return NULL_TREE;
3001
3002       if (use_equiv_p)
3003         {
3004           if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME)
3005             return compare_names (TREE_CODE (cond), op0, op1);
3006           else if (TREE_CODE (op0) == SSA_NAME)
3007             return compare_name_with_value (TREE_CODE (cond), op0, op1);
3008           else if (TREE_CODE (op1) == SSA_NAME)
3009             return compare_name_with_value (
3010                     opposite_comparison (TREE_CODE (cond)), op1, op0);
3011         }
3012       else
3013         {
3014           value_range_t *vr0, *vr1;
3015
3016           vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
3017           vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
3018
3019           if (vr0 && vr1)
3020             return compare_ranges (TREE_CODE (cond), vr0, vr1);
3021           else if (vr0 && vr1 == NULL)
3022             return compare_range_with_value (TREE_CODE (cond), vr0, op1);
3023           else if (vr0 == NULL && vr1)
3024             return compare_range_with_value (
3025                     opposite_comparison (TREE_CODE (cond)), vr1, op0);
3026         }
3027     }
3028
3029   /* Anything else cannot be computed statically.  */
3030   return NULL_TREE;
3031 }
3032
3033
3034 /* Visit conditional statement STMT.  If we can determine which edge
3035    will be taken out of STMT's basic block, record it in
3036    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
3037    SSA_PROP_VARYING.  */
3038
3039 static enum ssa_prop_result
3040 vrp_visit_cond_stmt (tree stmt, edge *taken_edge_p)
3041 {
3042   tree cond, val;
3043
3044   *taken_edge_p = NULL;
3045
3046   /* FIXME.  Handle SWITCH_EXPRs.  But first, the assert pass needs to
3047      add ASSERT_EXPRs for them.  */
3048   if (TREE_CODE (stmt) == SWITCH_EXPR)
3049     return SSA_PROP_VARYING;
3050
3051   cond = COND_EXPR_COND (stmt);
3052
3053   if (dump_file && (dump_flags & TDF_DETAILS))
3054     {
3055       tree use;
3056       ssa_op_iter i;
3057
3058       fprintf (dump_file, "\nVisiting conditional with predicate: ");
3059       print_generic_expr (dump_file, cond, 0);
3060       fprintf (dump_file, "\nWith known ranges\n");
3061       
3062       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
3063         {
3064           fprintf (dump_file, "\t");
3065           print_generic_expr (dump_file, use, 0);
3066           fprintf (dump_file, ": ");
3067           dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
3068         }
3069
3070       fprintf (dump_file, "\n");
3071     }
3072
3073   /* Compute the value of the predicate COND by checking the known
3074      ranges of each of its operands.
3075      
3076      Note that we cannot evaluate all the equivalent ranges here
3077      because those ranges may not yet be final and with the current
3078      propagation strategy, we cannot determine when the value ranges
3079      of the names in the equivalence set have changed.
3080
3081      For instance, given the following code fragment
3082
3083         i_5 = PHI <8, i_13>
3084         ...
3085         i_14 = ASSERT_EXPR <i_5, i_5 != 0>
3086         if (i_14 == 1)
3087           ...
3088
3089      Assume that on the first visit to i_14, i_5 has the temporary
3090      range [8, 8] because the second argument to the PHI function is
3091      not yet executable.  We derive the range ~[0, 0] for i_14 and the
3092      equivalence set { i_5 }.  So, when we visit 'if (i_14 == 1)' for
3093      the first time, since i_14 is equivalent to the range [8, 8], we
3094      determine that the predicate is always false.
3095
3096      On the next round of propagation, i_13 is determined to be
3097      VARYING, which causes i_5 to drop down to VARYING.  So, another
3098      visit to i_14 is scheduled.  In this second visit, we compute the
3099      exact same range and equivalence set for i_14, namely ~[0, 0] and
3100      { i_5 }.  But we did not have the previous range for i_5
3101      registered, so vrp_visit_assignment thinks that the range for
3102      i_14 has not changed.  Therefore, the predicate 'if (i_14 == 1)'
3103      is not visited again, which stops propagation from visiting
3104      statements in the THEN clause of that if().
3105
3106      To properly fix this we would need to keep the previous range
3107      value for the names in the equivalence set.  This way we would've
3108      discovered that from one visit to the other i_5 changed from
3109      range [8, 8] to VR_VARYING.
3110
3111      However, fixing this apparent limitation may not be worth the
3112      additional checking.  Testing on several code bases (GCC, DLV,
3113      MICO, TRAMP3D and SPEC2000) showed that doing this results in
3114      4 more predicates folded in SPEC.  */
3115   val = vrp_evaluate_conditional (cond, false);
3116   if (val)
3117     *taken_edge_p = find_taken_edge (bb_for_stmt (stmt), val);
3118
3119   if (dump_file && (dump_flags & TDF_DETAILS))
3120     {
3121       fprintf (dump_file, "\nPredicate evaluates to: ");
3122       if (val == NULL_TREE)
3123         fprintf (dump_file, "DON'T KNOW\n");
3124       else
3125         print_generic_stmt (dump_file, val, 0);
3126     }
3127
3128   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
3129 }
3130
3131
3132 /* Evaluate statement STMT.  If the statement produces a useful range,
3133    return SSA_PROP_INTERESTING and record the SSA name with the
3134    interesting range into *OUTPUT_P.
3135
3136    If STMT is a conditional branch and we can determine its truth
3137    value, the taken edge is recorded in *TAKEN_EDGE_P.
3138
3139    If STMT produces a varying value, return SSA_PROP_VARYING.  */
3140
3141 static enum ssa_prop_result
3142 vrp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
3143 {
3144   tree def;
3145   ssa_op_iter iter;
3146   stmt_ann_t ann;
3147
3148   if (dump_file && (dump_flags & TDF_DETAILS))
3149     {
3150       fprintf (dump_file, "\nVisiting statement:\n");
3151       print_generic_stmt (dump_file, stmt, dump_flags);
3152       fprintf (dump_file, "\n");
3153     }
3154
3155   ann = stmt_ann (stmt);
3156   if (TREE_CODE (stmt) == MODIFY_EXPR
3157       && ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
3158     return vrp_visit_assignment (stmt, output_p);
3159   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
3160     return vrp_visit_cond_stmt (stmt, taken_edge_p);
3161
3162   /* All other statements produce nothing of interest for VRP, so mark
3163      their outputs varying and prevent further simulation.  */
3164   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
3165     set_value_range_to_varying (get_value_range (def));
3166
3167   return SSA_PROP_VARYING;
3168 }
3169
3170
3171 /* Meet operation for value ranges.  Given two value ranges VR0 and
3172    VR1, store in VR0 the result of meeting VR0 and VR1.
3173    
3174    The meeting rules are as follows:
3175
3176    1- If VR0 and VR1 have an empty intersection, set VR0 to VR_VARYING.
3177
3178    2- If VR0 and VR1 have a non-empty intersection, set VR0 to the
3179       union of VR0 and VR1.  */
3180
3181 static void
3182 vrp_meet (value_range_t *vr0, value_range_t *vr1)
3183 {
3184   if (vr0->type == VR_UNDEFINED)
3185     {
3186       copy_value_range (vr0, vr1);
3187       return;
3188     }
3189
3190   if (vr1->type == VR_UNDEFINED)
3191     {
3192       /* Nothing to do.  VR0 already has the resulting range.  */
3193       return;
3194     }
3195
3196   if (vr0->type == VR_VARYING)
3197     {
3198       /* Nothing to do.  VR0 already has the resulting range.  */
3199       return;
3200     }
3201
3202   if (vr1->type == VR_VARYING)
3203     {
3204       set_value_range_to_varying (vr0);
3205       return;
3206     }
3207
3208   if (vr0->type == VR_RANGE && vr1->type == VR_RANGE)
3209     {
3210       /* If VR0 and VR1 have a non-empty intersection, compute the
3211          union of both ranges.  */
3212       if (value_ranges_intersect_p (vr0, vr1))
3213         {
3214           int cmp;
3215           tree min, max;
3216
3217           /* The lower limit of the new range is the minimum of the
3218              two ranges.  If they cannot be compared, the result is
3219              VARYING.  */
3220           cmp = compare_values (vr0->min, vr1->min);
3221           if (cmp == 0 || cmp == 1)
3222             min = vr1->min;
3223           else if (cmp == -1)
3224             min = vr0->min;
3225           else
3226             {
3227               set_value_range_to_varying (vr0);
3228               return;
3229             }
3230
3231           /* Similarly, the upper limit of the new range is the
3232              maximum of the two ranges.  If they cannot be compared,
3233              the result is VARYING.  */
3234           cmp = compare_values (vr0->max, vr1->max);
3235           if (cmp == 0 || cmp == -1)
3236             max = vr1->max;
3237           else if (cmp == 1)
3238             max = vr0->max;
3239           else
3240             {
3241               set_value_range_to_varying (vr0);
3242               return;
3243             }
3244
3245           /* The resulting set of equivalences is the intersection of
3246              the two sets.  */
3247           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
3248             bitmap_and_into (vr0->equiv, vr1->equiv);
3249
3250           set_value_range (vr0, vr0->type, min, max, vr0->equiv);
3251         }
3252       else
3253         goto no_meet;
3254     }
3255   else if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
3256     {
3257       /* Two anti-ranges meet only if they are both identical.  */
3258       if (compare_values (vr0->min, vr1->min) == 0
3259           && compare_values (vr0->max, vr1->max) == 0
3260           && compare_values (vr0->min, vr0->max) == 0)
3261         {
3262           /* The resulting set of equivalences is the intersection of
3263              the two sets.  */
3264           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
3265             bitmap_and_into (vr0->equiv, vr1->equiv);
3266         }
3267       else
3268         goto no_meet;
3269     }
3270   else if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
3271     {
3272       /* A numeric range [VAL1, VAL2] and an anti-range ~[VAL3, VAL4]
3273          meet only if the ranges have an empty intersection.  The
3274          result of the meet operation is the anti-range.  */
3275       if (!symbolic_range_p (vr0)
3276           && !symbolic_range_p (vr1)
3277           && !value_ranges_intersect_p (vr0, vr1))
3278         {
3279           if (vr1->type == VR_ANTI_RANGE)
3280             copy_value_range (vr0, vr1);
3281         }
3282       else
3283         goto no_meet;
3284     }
3285   else
3286     gcc_unreachable ();
3287
3288   return;
3289
3290 no_meet:
3291   /* The two range VR0 and VR1 do not meet.  Before giving up and
3292      setting the result to VARYING, see if we can at least derive a
3293      useful anti-range.  */
3294   if (!symbolic_range_p (vr0)
3295       && !range_includes_zero_p (vr0)
3296       && !symbolic_range_p (vr1)
3297       && !range_includes_zero_p (vr1))
3298     set_value_range_to_nonnull (vr0, TREE_TYPE (vr0->min));
3299   else
3300     set_value_range_to_varying (vr0);
3301 }
3302
3303
3304 /* Visit all arguments for PHI node PHI that flow through executable
3305    edges.  If a valid value range can be derived from all the incoming
3306    value ranges, set a new range for the LHS of PHI.  */
3307
3308 static enum ssa_prop_result
3309 vrp_visit_phi_node (tree phi)
3310 {
3311   int i;
3312   tree lhs = PHI_RESULT (phi);
3313   value_range_t *lhs_vr = get_value_range (lhs);
3314   value_range_t vr_result = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
3315
3316   copy_value_range (&vr_result, lhs_vr);
3317
3318   if (dump_file && (dump_flags & TDF_DETAILS))
3319     {
3320       fprintf (dump_file, "\nVisiting PHI node: ");
3321       print_generic_expr (dump_file, phi, dump_flags);
3322     }
3323
3324   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
3325     {
3326       edge e = PHI_ARG_EDGE (phi, i);
3327
3328       if (dump_file && (dump_flags & TDF_DETAILS))
3329         {
3330           fprintf (dump_file,
3331               "\n    Argument #%d (%d -> %d %sexecutable)\n",
3332               i, e->src->index, e->dest->index,
3333               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
3334         }
3335
3336       if (e->flags & EDGE_EXECUTABLE)
3337         {
3338           tree arg = PHI_ARG_DEF (phi, i);
3339           value_range_t vr_arg;
3340
3341           if (TREE_CODE (arg) == SSA_NAME)
3342             vr_arg = *(get_value_range (arg));
3343           else
3344             {
3345               vr_arg.type = VR_RANGE;
3346               vr_arg.min = arg;
3347               vr_arg.max = arg;
3348               vr_arg.equiv = NULL;
3349             }
3350
3351           if (dump_file && (dump_flags & TDF_DETAILS))
3352             {
3353               fprintf (dump_file, "\t");
3354               print_generic_expr (dump_file, arg, dump_flags);
3355               fprintf (dump_file, "\n\tValue: ");
3356               dump_value_range (dump_file, &vr_arg);
3357               fprintf (dump_file, "\n");
3358             }
3359
3360           vrp_meet (&vr_result, &vr_arg);
3361
3362           if (vr_result.type == VR_VARYING)
3363             break;
3364         }
3365     }
3366
3367   if (vr_result.type == VR_VARYING)
3368     goto varying;
3369
3370   /* To prevent infinite iterations in the algorithm, derive ranges
3371      when the new value is slightly bigger or smaller than the
3372      previous one.  */
3373   if (lhs_vr->type == VR_RANGE)
3374     {
3375       if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
3376         {
3377           int cmp_min = compare_values (lhs_vr->min, vr_result.min);
3378           int cmp_max = compare_values (lhs_vr->max, vr_result.max);
3379
3380           /* If the new minimum is smaller or larger than the previous
3381              one, go all the way to -INF.  In the first case, to avoid
3382              iterating millions of times to reach -INF, and in the
3383              other case to avoid infinite bouncing between different
3384              minimums.  */
3385           if (cmp_min > 0 || cmp_min < 0)
3386             vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
3387
3388           /* Similarly, if the new maximum is smaller or larger than
3389              the previous one, go all the way to +INF.  */
3390           if (cmp_max < 0 || cmp_max > 0)
3391             vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
3392
3393           /* If we ended up with a (-INF, +INF) range, set it to
3394              VARYING.  */
3395           if (vr_result.min == TYPE_MIN_VALUE (TREE_TYPE (vr_result.min))
3396               && vr_result.max == TYPE_MAX_VALUE (TREE_TYPE (vr_result.max)))
3397             goto varying;
3398         }
3399     }
3400
3401   /* If the new range is different than the previous value, keep
3402      iterating.  */
3403   if (update_value_range (lhs, &vr_result))
3404     return SSA_PROP_INTERESTING;
3405
3406   /* Nothing changed, don't add outgoing edges.  */
3407   return SSA_PROP_NOT_INTERESTING;
3408
3409   /* No match found.  Set the LHS to VARYING.  */
3410 varying:
3411   set_value_range_to_varying (lhs_vr);
3412   return SSA_PROP_VARYING;
3413 }
3414
3415
3416 /* Traverse all the blocks folding conditionals with known ranges.  */
3417
3418 static void
3419 vrp_finalize (void)
3420 {
3421   size_t i;
3422   prop_value_t *single_val_range;
3423   bool do_value_subst_p;
3424
3425   if (dump_file)
3426     {
3427       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
3428       dump_all_value_ranges (dump_file);
3429       fprintf (dump_file, "\n");
3430     }
3431
3432   /* We may have ended with ranges that have exactly one value.  Those
3433      values can be substituted as any other copy/const propagated
3434      value using substitute_and_fold.  */
3435   single_val_range = xmalloc (num_ssa_names * sizeof (*single_val_range));
3436   memset (single_val_range, 0, num_ssa_names * sizeof (*single_val_range));
3437
3438   do_value_subst_p = false;
3439   for (i = 0; i < num_ssa_names; i++)
3440     if (vr_value[i]
3441         && vr_value[i]->type == VR_RANGE
3442         && vr_value[i]->min == vr_value[i]->max)
3443       {
3444         single_val_range[i].value = vr_value[i]->min;
3445         do_value_subst_p = true;
3446       }
3447
3448   if (!do_value_subst_p)
3449     {
3450       /* We found no single-valued ranges, don't waste time trying to
3451          do single value substitution in substitute_and_fold.  */
3452       free (single_val_range);
3453       single_val_range = NULL;
3454     }
3455
3456   substitute_and_fold (single_val_range, true);
3457
3458   /* Free allocated memory.  */
3459   for (i = 0; i < num_ssa_names; i++)
3460     if (vr_value[i])
3461       {
3462         BITMAP_FREE (vr_value[i]->equiv);
3463         free (vr_value[i]);
3464       }
3465
3466   free (single_val_range);
3467   free (vr_value);
3468 }
3469
3470
3471 /* Main entry point to VRP (Value Range Propagation).  This pass is
3472    loosely based on J. R. C. Patterson, ``Accurate Static Branch
3473    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
3474    Programming Language Design and Implementation, pp. 67-78, 1995.
3475    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
3476
3477    This is essentially an SSA-CCP pass modified to deal with ranges
3478    instead of constants.
3479
3480    While propagating ranges, we may find that two or more SSA name
3481    have equivalent, though distinct ranges.  For instance,
3482
3483      1  x_9 = p_3->a;
3484      2  p_4 = ASSERT_EXPR <p_3, p_3 != 0>
3485      3  if (p_4 == q_2)
3486      4    p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
3487      5  endif
3488      6  if (q_2)
3489         
3490    In the code above, pointer p_5 has range [q_2, q_2], but from the
3491    code we can also determine that p_5 cannot be NULL and, if q_2 had
3492    a non-varying range, p_5's range should also be compatible with it.
3493
3494    These equivalences are created by two expressions: ASSERT_EXPR and
3495    copy operations.  Since p_5 is an assertion on p_4, and p_4 was the
3496    result of another assertion, then we can use the fact that p_5 and
3497    p_4 are equivalent when evaluating p_5's range.
3498
3499    Together with value ranges, we also propagate these equivalences
3500    between names so that we can take advantage of information from
3501    multiple ranges when doing final replacement.  Note that this
3502    equivalency relation is transitive but not symmetric.
3503    
3504    In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
3505    cannot assert that q_2 is equivalent to p_5 because q_2 may be used
3506    in contexts where that assertion does not hold (e.g., in line 6).
3507
3508    TODO, the main difference between this pass and Patterson's is that
3509    we do not propagate edge probabilities.  We only compute whether
3510    edges can be taken or not.  That is, instead of having a spectrum
3511    of jump probabilities between 0 and 1, we only deal with 0, 1 and
3512    DON'T KNOW.  In the future, it may be worthwhile to propagate
3513    probabilities to aid branch prediction.  */
3514
3515 static void
3516 execute_vrp (void)
3517 {
3518   insert_range_assertions ();
3519
3520   cfg_loops = loop_optimizer_init (NULL);
3521   if (cfg_loops)
3522     scev_initialize (cfg_loops);
3523
3524   vrp_initialize ();
3525   ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
3526   vrp_finalize ();
3527
3528   if (cfg_loops)
3529     {
3530       scev_finalize ();
3531       loop_optimizer_finalize (cfg_loops, NULL);
3532       current_loops = NULL;
3533     }
3534
3535   remove_range_assertions ();
3536 }
3537
3538 static bool
3539 gate_vrp (void)
3540 {
3541   return flag_tree_vrp != 0;
3542 }
3543
3544 struct tree_opt_pass pass_vrp =
3545 {
3546   "vrp",                                /* name */
3547   gate_vrp,                             /* gate */
3548   execute_vrp,                          /* execute */
3549   NULL,                                 /* sub */
3550   NULL,                                 /* next */
3551   0,                                    /* static_pass_number */
3552   TV_TREE_VRP,                          /* tv_id */
3553   PROP_ssa | PROP_alias,                /* properties_required */
3554   0,                                    /* properties_provided */
3555   0,                                    /* properties_destroyed */
3556   0,                                    /* todo_flags_start */
3557   TODO_cleanup_cfg
3558     | TODO_ggc_collect
3559     | TODO_verify_ssa
3560     | TODO_dump_func
3561     | TODO_update_ssa,                  /* todo_flags_finish */
3562   0                                     /* letter */
3563 };