OSDN Git Service

PR tree-optimization/21088
[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 maybe_add_assert_expr.  */
42 static sbitmap found;
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 /* Given a conditional predicate COND that has WHICH as one of its
52    operands, return the other operand.  No error checking is done.
53    This helper assumes that COND is a comparison and WHICH is one of
54    its operands.  */
55
56 static inline tree
57 get_opposite_operand (tree cond, tree which)
58 {
59   if (TREE_OPERAND (cond, 0) == which)
60     return TREE_OPERAND (cond, 1);
61   else
62     return TREE_OPERAND (cond, 0);
63 }
64
65
66 /* Given a comparison code, return its opposite.  Note that this is *not*
67    the same as inverting its truth value (invert_tree_comparison).  Here we
68    just want to literally flip the comparison around.
69    
70    So, '<' gets '>', '<=' gets '>='.  Both '==' and '!=' are returned
71    unchanged.  */
72
73 static enum tree_code
74 opposite_comparison (enum tree_code code)
75 {
76   switch (code)
77     {
78     case EQ_EXPR:
79     case NE_EXPR:
80     case ORDERED_EXPR:
81     case UNORDERED_EXPR:
82     case LTGT_EXPR:
83     case UNEQ_EXPR:
84       return code;
85     case GT_EXPR:
86       return LT_EXPR;
87     case GE_EXPR:
88       return LE_EXPR;
89     case LT_EXPR:
90       return GT_EXPR;
91     case LE_EXPR:
92       return GE_EXPR;
93     case UNGT_EXPR:
94       return UNLT_EXPR;
95     case UNGE_EXPR:
96       return UNLE_EXPR;
97     case UNLT_EXPR:
98       return UNGT_EXPR;
99     case UNLE_EXPR:
100       return UNGE_EXPR;
101     default:
102       gcc_unreachable ();
103     }
104 }
105
106
107 /* Set value range VR to {T, MIN, MAX}.  */
108
109 static inline void
110 set_value_range (value_range *vr, enum value_range_type t, tree min, tree max)
111 {
112 #if defined ENABLE_CHECKING
113   if (t == VR_RANGE || t == VR_ANTI_RANGE)
114     {
115       int cmp;
116
117       gcc_assert (min && max);
118
119       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
120         gcc_assert (min != TYPE_MIN_VALUE (TREE_TYPE (min))
121                     || max != TYPE_MAX_VALUE (TREE_TYPE (max)));
122
123       cmp = compare_values (min, max);
124       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
125     }
126 #endif
127
128   if (t == VR_RANGE
129       && INTEGRAL_TYPE_P (TREE_TYPE (min))
130       && min == TYPE_MIN_VALUE (TREE_TYPE (min))
131       && max == TYPE_MAX_VALUE (TREE_TYPE (max)))
132     {
133       /* Ranges that cover all the possible values for the type decay
134          to VARYING.  */
135       vr->type = VR_VARYING;
136       vr->min = NULL_TREE;
137       vr->max = NULL_TREE;
138       return;
139     }
140
141   vr->type = t;
142   vr->min = min;
143   vr->max = max;
144 }
145
146
147 /* Similar to set_value_range but return true if any field of VR
148    changed from its previous value.  */
149
150 static inline bool
151 update_value_range (value_range *vr, enum value_range_type t, tree min,
152                     tree max)
153 {
154   bool is_new = vr->type != t || vr->min != min || vr->max != max;
155   if (is_new)
156     set_value_range (vr, t, min, max);
157
158   return is_new;
159 }
160
161
162 /* Return value range information for VAR.  Create an empty range if
163    none existed.  */
164
165 value_range *
166 get_value_range (tree var)
167 {
168   value_range *vr;
169   tree sym;
170
171   vr = SSA_NAME_VALUE_RANGE (var);
172   if (vr)
173     return vr;
174
175   /* Create a default value range.  */
176   vr = ggc_alloc (sizeof (*vr));
177   memset ((void *) vr, 0, sizeof (*vr));
178   SSA_NAME_VALUE_RANGE (var) = vr;
179
180   /* If VAR is a default definition for a PARM_DECL, then we have to
181      assume a VARYING range for it.  */
182   sym = SSA_NAME_VAR (var);
183   if (TREE_CODE (sym) == PARM_DECL && var == var_ann (sym)->default_def)
184     set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
185
186   return vr;
187 }
188
189
190 /* Return true if value range VR involves at least one symbol.  */
191
192 static inline bool
193 symbolic_range_p (value_range *vr)
194 {
195   return (!is_gimple_min_invariant (vr->min)
196           || !is_gimple_min_invariant (vr->max));
197 }
198
199
200 /* Return true if EXPR computes a non-zero value.  */
201
202 bool
203 expr_computes_nonzero (tree expr)
204 {
205   /* Type casts won't change anything, so just strip it.  */
206   STRIP_NOPS (expr);
207
208   /* Calling alloca, guarantees that the value is non-NULL.  */
209   if (alloca_call_p (expr))
210     return true;
211
212   /* The address of a non-weak symbol is never NULL, unless the user
213      has requested not to remove NULL pointer checks.  */
214   if (flag_delete_null_pointer_checks
215       && TREE_CODE (expr) == ADDR_EXPR
216       && DECL_P (TREE_OPERAND (expr, 0))
217       && !DECL_WEAK (TREE_OPERAND (expr, 0)))
218     return true;
219
220   /* IOR of any value with a nonzero value will result in a nonzero
221      value.  */
222   if (TREE_CODE (expr) == BIT_IOR_EXPR
223       && integer_nonzerop (TREE_OPERAND (expr, 1)))
224     return true;
225
226   return false;
227 }
228
229
230 /* Return true if VR is ~[0, 0].  */
231
232 static inline bool
233 range_is_nonnull (value_range *vr)
234 {
235   return vr->type == VR_ANTI_RANGE
236          && integer_zerop (vr->min)
237          && integer_zerop (vr->max);
238 }
239
240
241 /* Return true if VR is [0, 0].  */
242
243 static inline bool
244 range_is_null (value_range *vr)
245 {
246   return vr->type == VR_RANGE
247          && integer_zerop (vr->min)
248          && integer_zerop (vr->max);
249 }
250
251
252 /* Set value range VR to a non-NULL range of type TYPE.  */
253
254 static void
255 set_value_range_to_nonnull (value_range *vr, tree type)
256 {
257   tree zero = build_int_cst (type, 0);
258   set_value_range (vr, VR_ANTI_RANGE, zero, zero);
259 }
260
261
262 /* Set value range VR to a NULL range of type TYPE.  */
263
264 static void
265 set_value_range_to_null (value_range *vr, tree type)
266 {
267   tree zero = build_int_cst (type, 0);
268   set_value_range (vr, VR_RANGE, zero, zero);
269 }
270
271
272 /* Compare two values VAL1 and VAL2.  Return
273    
274         -2 if VAL1 and VAL2 cannot be compared at compile-time,
275         -1 if VAL1 < VAL2,
276          0 if VAL1 == VAL2,
277         +1 if VAL1 > VAL2, and
278         +2 if VAL1 != VAL2
279
280    This is similar to tree_int_cst_compare but supports pointer values
281    and values that cannot be compared at compile time.  */
282
283 static int
284 compare_values (tree val1, tree val2)
285 {
286   if (val1 == val2)
287     return 0;
288
289   /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
290      both integers.  */
291   gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
292               == POINTER_TYPE_P (TREE_TYPE (val2)));
293
294   /* Do some limited symbolic comparisons.  */
295   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
296     {
297       /* We can determine some comparisons against +INF and -INF even
298          if the other value is an expression.  */
299       if (val1 == TYPE_MAX_VALUE (TREE_TYPE (val1))
300           && TREE_CODE (val2) == MINUS_EXPR)
301         {
302           /* +INF > NAME - CST.  */
303           return 1;
304         }
305       else if (val1 == TYPE_MIN_VALUE (TREE_TYPE (val1))
306                && TREE_CODE (val2) == PLUS_EXPR)
307         {
308           /* -INF < NAME + CST.  */
309           return -1;
310         }
311       else if (TREE_CODE (val1) == MINUS_EXPR
312                && val2 == TYPE_MAX_VALUE (TREE_TYPE (val2)))
313         {
314           /* NAME - CST < +INF.  */
315           return -1;
316         }
317       else if (TREE_CODE (val1) == PLUS_EXPR
318                && val2 == TYPE_MIN_VALUE (TREE_TYPE (val2)))
319         {
320           /* NAME + CST > -INF.  */
321           return 1;
322         }
323     }
324
325   if ((TREE_CODE (val1) == SSA_NAME
326        || TREE_CODE (val1) == PLUS_EXPR
327        || TREE_CODE (val1) == MINUS_EXPR)
328       && (TREE_CODE (val2) == SSA_NAME
329           || TREE_CODE (val2) == PLUS_EXPR
330           || TREE_CODE (val2) == MINUS_EXPR))
331     {
332       tree n1, c1, n2, c2;
333   
334       /* If VAL1 and VAL2 are of the form 'NAME [+-] CST' or 'NAME',
335          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
336          same name, return -2.  */
337       if (TREE_CODE (val1) == SSA_NAME)
338         {
339           n1 = val1;
340           c1 = NULL_TREE;
341         }
342       else
343         {
344           n1 = TREE_OPERAND (val1, 0);
345           c1 = TREE_OPERAND (val1, 1);
346         }
347
348       if (TREE_CODE (val2) == SSA_NAME)
349         {
350           n2 = val2;
351           c2 = NULL_TREE;
352         }
353       else
354         {
355           n2 = TREE_OPERAND (val2, 0);
356           c2 = TREE_OPERAND (val2, 1);
357         }
358
359       /* Both values must use the same name.  */
360       if (n1 != n2)
361         return -2;
362
363       if (TREE_CODE (val1) == SSA_NAME)
364         {
365           if (TREE_CODE (val2) == SSA_NAME)
366             /* NAME == NAME  */
367             return 0;
368           else if (TREE_CODE (val2) == PLUS_EXPR)
369             /* NAME < NAME + CST  */
370             return -1;
371           else if (TREE_CODE (val2) == MINUS_EXPR)
372             /* NAME > NAME - CST  */
373             return 1;
374         }
375       else if (TREE_CODE (val1) == PLUS_EXPR)
376         {
377           if (TREE_CODE (val2) == SSA_NAME)
378             /* NAME + CST > NAME  */
379             return 1;
380           else if (TREE_CODE (val2) == PLUS_EXPR)
381             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
382             return compare_values (c1, c2);
383           else if (TREE_CODE (val2) == MINUS_EXPR)
384             /* NAME + CST1 > NAME - CST2  */
385             return 1;
386         }
387       else if (TREE_CODE (val1) == MINUS_EXPR)
388         {
389           if (TREE_CODE (val2) == SSA_NAME)
390             /* NAME - CST < NAME  */
391             return -1;
392           else if (TREE_CODE (val2) == PLUS_EXPR)
393             /* NAME - CST1 < NAME + CST2  */
394             return -1;
395           else if (TREE_CODE (val2) == MINUS_EXPR)
396             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
397                C1 and C2 are swapped in the call to compare_values.  */
398             return compare_values (c2, c1);
399         }
400
401       gcc_unreachable ();
402     }
403
404   /* We cannot compare non-constants.  */
405   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
406     return -2;
407
408   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
409     return tree_int_cst_compare (val1, val2);
410   else
411     {
412       tree t;
413
414       /* First see if VAL1 and VAL2 are not the same.  */
415       if (val1 == val2 || operand_equal_p (val1, val2, 0))
416         return 0;
417       
418       /* If VAL1 is a lower address than VAL2, return -1.  */
419       t = fold_binary (LT_EXPR, boolean_type_node, val1, val2);
420       if (t == boolean_true_node)
421         return -1;
422
423       /* If VAL1 is a higher address than VAL2, return +1.  */
424       t = fold_binary (GT_EXPR, boolean_type_node, val1, val2);
425       if (t == boolean_true_node)
426         return 1;
427
428       /* If VAL1 is different than VAL2, return +2.  */
429       t = fold_binary (NE_EXPR, boolean_type_node, val1, val2);
430       if (t == boolean_true_node)
431         return 2;
432
433       return -2;
434     }
435 }
436
437
438 /* Return 1 if VAL is inside value range VR (VR->MIN <= VAL <= VR->MAX),
439           0 if VAL is not inside VR,
440          -2 if we cannot tell either way.  */
441
442 static inline int
443 value_inside_range (tree val, value_range *vr)
444 {
445   int cmp1, cmp2;
446
447   cmp1 = compare_values (val, vr->min);
448   if (cmp1 == -2 || cmp1 == 2)
449     return -2;
450
451   cmp2 = compare_values (val, vr->max);
452   if (cmp2 == -2 || cmp2 == 2)
453     return -2;
454
455   return (cmp1 == 0 || cmp1 == 1) && (cmp2 == -1 || cmp2 == 0);
456 }
457
458
459 /* Return true if value ranges VR0 and VR1 have a non-empty
460    intersection.  */
461
462 static inline bool
463 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
464 {
465   return (value_inside_range (vr1->min, vr0) == 1
466           || value_inside_range (vr1->max, vr0) == 1
467           || value_inside_range (vr0->min, vr1) == 1
468           || value_inside_range (vr0->max, vr1) == 1);
469 }
470
471
472 /* Extract value range information from an ASSERT_EXPR EXPR and store
473    it in *VR_P.  */
474
475 static void
476 extract_range_from_assert (value_range *vr_p, tree expr)
477 {
478   tree var, cond, limit, type;
479   value_range *var_vr;
480
481   var = ASSERT_EXPR_VAR (expr);
482   cond = ASSERT_EXPR_COND (expr);
483
484   gcc_assert (TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
485
486   /* Find VAR in the ASSERT_EXPR conditional.  */
487   limit = get_opposite_operand (cond, var);
488   type = TREE_TYPE (limit);
489
490   gcc_assert (limit != var);
491
492   /* For pointer arithmetic, we only keep track of anti-ranges
493      (NE_EXPR).  Notice that we don't need to handle EQ_EXPR in these
494      cases because assertions with equalities are never generated.
495      The assert pass generates straight assignments in those cases.  */
496   if (POINTER_TYPE_P (type) && TREE_CODE (cond) != NE_EXPR)
497     {
498       set_value_range (vr_p, VR_VARYING, NULL_TREE, NULL_TREE);
499       return;
500     }
501
502   if (TREE_CODE (cond) == NE_EXPR)
503     set_value_range (vr_p, VR_ANTI_RANGE, limit, limit);
504   else if (TREE_CODE (cond) == LE_EXPR)
505     set_value_range (vr_p, VR_RANGE, TYPE_MIN_VALUE (type), limit);
506   else if (TREE_CODE (cond) == LT_EXPR)
507     {
508       tree one = build_int_cst (type, 1);
509       set_value_range (vr_p, VR_RANGE, TYPE_MIN_VALUE (type),
510                        fold (build (MINUS_EXPR, type, limit, one)));
511     }
512   else if (TREE_CODE (cond) == GE_EXPR)
513     set_value_range (vr_p, VR_RANGE, limit, TYPE_MAX_VALUE (type));
514   else if (TREE_CODE (cond) == GT_EXPR)
515     {
516       tree one = build_int_cst (type, 1);
517       set_value_range (vr_p, VR_RANGE,
518                        fold (build (PLUS_EXPR, type, limit, one)),
519                        TYPE_MAX_VALUE (type));
520     }
521   else
522     gcc_unreachable ();
523
524   /* If VAR already has a known range and the two ranges have a
525      non-empty intersection, we can refine the resulting range.
526      Since the assert expression creates an equivalency and at the
527      same time it asserts a predicate, we can take the intersection of
528      the two ranges to get better precision.  */
529   var_vr = get_value_range (var);
530   if (var_vr->type == VR_RANGE
531       && vr_p->type == VR_RANGE
532       && value_ranges_intersect_p (var_vr, vr_p))
533     {
534       tree min, max;
535
536       /* Use the larger of the two minimums.  */
537       if (compare_values (vr_p->min, var_vr->min) == -1)
538         min = var_vr->min;
539       else
540         min = vr_p->min;
541
542       /* Use the smaller of the two maximums.  */
543       if (compare_values (vr_p->max, var_vr->max) == 1)
544         max = var_vr->max;
545       else
546         max = vr_p->max;
547
548       set_value_range (vr_p, vr_p->type, min, max);
549     }
550 }
551
552
553 /* Extract range information from SSA name VAR and store it in VR.  If
554    VAR has an interesting range, use it.  Otherwise, create the
555    range [VAR, VAR] and return it.  This is useful in situations where
556    we may have conditionals testing values of VARYING names.  For
557    instance,
558
559         x_3 = y_5;
560         if (x_3 > y_5)
561           ...
562
563     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
564     always false.  */
565
566 static void
567 extract_range_from_ssa_name (value_range *vr, tree var)
568 {
569   value_range *var_vr = get_value_range (var);
570
571   if (var_vr->type != VR_UNDEFINED && var_vr->type != VR_VARYING)
572     *vr = *var_vr;
573   else
574     set_value_range (vr, VR_RANGE, var, var);
575 }
576
577
578 /* Extract range information from a binary expression EXPR based on
579    the ranges of each of its operands and the expression code.  */
580
581 static void
582 extract_range_from_binary_expr (value_range *vr, tree expr)
583 {
584   enum tree_code code = TREE_CODE (expr);
585   tree op0, op1, min, max;
586   value_range vr0, vr1;
587   int cmp;
588
589   /* Not all binary expressions can be applied to ranges in a
590      meaningful way.  Handle only arithmetic operations.  */
591   if (code != PLUS_EXPR
592       && code != MINUS_EXPR
593       && code != MULT_EXPR
594       && code != TRUNC_DIV_EXPR
595       && code != FLOOR_DIV_EXPR
596       && code != CEIL_DIV_EXPR
597       && code != EXACT_DIV_EXPR
598       && code != ROUND_DIV_EXPR
599       && code != MIN_EXPR
600       && code != MAX_EXPR)
601     {
602       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
603       return;
604     }
605
606   /* Get value ranges for each operand.  For constant operands, create
607      a new value range with the operand to simplify processing.  */
608   op0 = TREE_OPERAND (expr, 0);
609   if (TREE_CODE (op0) == SSA_NAME)
610     vr0 = *(get_value_range (op0));
611   else
612     {
613       if (is_gimple_min_invariant (op0))
614         set_value_range (&vr0, VR_RANGE, op0, op0);
615       else
616         set_value_range (&vr0, VR_VARYING, NULL_TREE, NULL_TREE);
617     }
618
619   op1 = TREE_OPERAND (expr, 1);
620   if (TREE_CODE (op1) == SSA_NAME)
621     vr1 = *(get_value_range (op1));
622   else
623     {
624       if (is_gimple_min_invariant (op1))
625         set_value_range (&vr1, VR_RANGE, op1, op1);
626       else
627         set_value_range (&vr1, VR_VARYING, 0, 0);
628     }
629
630   /* If either range is UNDEFINED, so is the result.  */
631   if (vr0.type == VR_UNDEFINED || vr1.type == VR_UNDEFINED)
632     {
633       set_value_range (vr, VR_UNDEFINED, NULL_TREE, NULL_TREE);
634       return;
635     }
636
637   /* If either range is VARYING, so is the result.  */
638   if (vr0.type == VR_VARYING || vr1.type == VR_VARYING)
639     {
640       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
641       return;
642     }
643
644   /* If the ranges are of different types, the result is VARYING.  */
645   if (vr0.type != vr1.type)
646     {
647       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
648       return;
649     }
650
651   /* TODO.  Refuse to do any symbolic range operations for now.  */
652   if (symbolic_range_p (&vr0) || symbolic_range_p (&vr1))
653     {
654       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
655       return;
656     }
657
658   /* Now evaluate the expression to determine the new range.  */
659   if (POINTER_TYPE_P (TREE_TYPE (expr))
660       || POINTER_TYPE_P (TREE_TYPE (op0))
661       || POINTER_TYPE_P (TREE_TYPE (op1)))
662     {
663       /* For pointer types, we are really only interested in asserting
664          whether the expression evaluates to non-NULL.  FIXME.  We
665          used to gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR),
666          but ivopts is generating expressions with pointer
667          multiplication in them.  */
668       if (code == PLUS_EXPR)
669         {
670           /* Assume that pointers can never wrap around.  FIXME, Is
671              this always safe?  */
672           tree zero = build_int_cst (TREE_TYPE (expr), 0);
673           set_value_range (vr, VR_ANTI_RANGE, zero, zero);
674         }
675       else
676         {
677           /* Subtracting from a pointer, may yield 0, so just drop the
678              resulting range to varying.  */
679           set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
680         }
681
682       return;
683     }
684
685   /* For integer ranges, apply the operation to each end of the
686      range and see what we end up with.  */
687   if (code == PLUS_EXPR
688       || code == MULT_EXPR
689       || code == MIN_EXPR
690       || code == MAX_EXPR)
691     {
692       /* For operations that make the resulting range directly
693          proportional to the original ranges, apply the operation to
694          the same end of each range.  */
695       min = int_const_binop (code, vr0.min, vr1.min, 0);
696       max = int_const_binop (code, vr0.max, vr1.max, 0);
697     }
698   else
699     {
700       /* For operations that make the resulting range inversely
701          proportional to the original ranges (-, /), apply the
702          operation to the opposite ends of each range.  */
703       min = int_const_binop (code, vr0.min, vr1.max, 0);
704       max = int_const_binop (code, vr0.max, vr1.min, 0);
705     }
706
707   cmp = compare_values (min, max);
708   if (cmp == -2 || cmp == 1)
709     {
710       /* If the new range has its limits swapped around (MIN > MAX),
711          then the operation caused one of them to wrap around, mark
712          the new range VARYING.  */
713       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
714     }
715   else
716     set_value_range (vr, vr0.type, min, max);
717 }
718
719
720 /* Extract range information from a unary expression EXPR based on
721    the range of its operand and the expression code.  */
722
723 static void
724 extract_range_from_unary_expr (value_range *vr, tree expr)
725 {
726   enum tree_code code = TREE_CODE (expr);
727   tree min, max, op0;
728   value_range vr0;
729   int cmp;
730
731   /* Get value ranges for the operand.  For constant operands, create
732      a new value range with the operand to simplify processing.  */
733   op0 = TREE_OPERAND (expr, 0);
734   if (TREE_CODE (op0) == SSA_NAME)
735     vr0 = *(get_value_range (op0));
736   else
737     {
738       if (is_gimple_min_invariant (op0))
739         set_value_range (&vr0, VR_RANGE, op0, op0);
740       else
741         set_value_range (&vr0, VR_VARYING, NULL_TREE, NULL_TREE);
742     }
743
744   /* If VR0 is UNDEFINED, so is the result.  */
745   if (vr0.type == VR_UNDEFINED)
746     {
747       set_value_range (vr, VR_UNDEFINED, NULL_TREE, NULL_TREE);
748       return;
749     }
750
751   /* If VR0 is VARYING, so is the result.  */
752   if (vr0.type == VR_VARYING)
753     {
754       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
755       return;
756     }
757
758   /* TODO.  Refuse to do any symbolic range operations for now.  */
759   if (symbolic_range_p (&vr0))
760     {
761       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
762       return;
763     }
764
765   /* If the operand is neither a pointer nor an integral type, set the
766      range to VARYING.  TODO, we may set the range to non-zero.  */
767   if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
768       && !POINTER_TYPE_P (TREE_TYPE (op0)))
769     {
770       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
771       return;
772     }
773
774   /* If the expression involves pointers, we are only interested in
775      determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
776   if (POINTER_TYPE_P (TREE_TYPE (expr)) || POINTER_TYPE_P (TREE_TYPE (op0)))
777     {
778       if (range_is_nonnull (&vr0) || expr_computes_nonzero (expr))
779         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
780       else if (range_is_null (&vr0))
781         set_value_range_to_null (vr, TREE_TYPE (expr));
782       else
783         set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
784
785       return;
786     }
787
788   /* Handle unary expressions on integer ranges.  */
789   if ((code == NOP_EXPR || code == CONVERT_EXPR)
790       && (TYPE_SIZE (TREE_TYPE (vr0.min)) != TYPE_SIZE (TREE_TYPE (expr))))
791     {
792       /* When converting types of different sizes, set the result to
793          VARYING.  Things like sign extensions and precision loss may
794          change the range.  For instance, if x_3 is of type 'long long
795          int' and 'y_5 = (unsigned short) x_3', if x_3 is ~[0, 0], it
796          is impossible to know at compile time whether y_5 will be
797          ~[0, 0].  */
798       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
799       return;
800     }
801
802   /* Apply the operation to each end of the range and see what we end
803      up with.  */
804   min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
805   max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
806
807   cmp = compare_values (min, max);
808   if (cmp == -2 || cmp == 1)
809     {
810       /* If the new range has its limits swapped around (MIN > MAX),
811          then the operation caused one of them to wrap around, mark
812          the new range VARYING.  */
813       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
814     }
815   else
816     set_value_range (vr, vr0.type, min, max);
817 }
818
819
820 /* Try to compute a useful range out of expression EXPR and store it
821    in *VR_P.  */
822
823 static void
824 extract_range_from_expr (value_range *vr, tree expr)
825 {
826   enum tree_code code = TREE_CODE (expr);
827
828   if (code == ASSERT_EXPR)
829     extract_range_from_assert (vr, expr);
830   else if (code == SSA_NAME)
831     extract_range_from_ssa_name (vr, expr);
832   else if (TREE_CODE_CLASS (code) == tcc_binary)
833     extract_range_from_binary_expr (vr, expr);
834   else if (TREE_CODE_CLASS (code) == tcc_unary)
835     extract_range_from_unary_expr (vr, expr);
836   else if (expr_computes_nonzero (expr))
837     set_value_range_to_nonnull (vr, TREE_TYPE (expr));
838   else if (TREE_CODE (expr) == INTEGER_CST)
839     set_value_range (vr, VR_RANGE, expr, expr);
840   else
841     set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
842 }
843
844
845 /* Given a range VR, a loop L and a variable VAR, determine whether it
846    would be profitable to adjust VR using scalar evolution information
847    for VAR.  If so, update VR with the new limits.  */
848
849 static void
850 adjust_range_with_scev (value_range *vr, struct loop *l, tree var)
851 {
852   tree init, step, chrec;
853   bool init_is_max;
854
855   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
856      better opportunities than a regular range, but I'm not sure.  */
857   if (vr->type == VR_ANTI_RANGE)
858     return;
859
860   chrec = analyze_scalar_evolution (l, var);
861   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
862     return;
863
864   init = CHREC_LEFT (chrec);
865   step = CHREC_RIGHT (chrec);
866
867   /* If STEP is symbolic, we can't know whether INIT will be the
868      minimum or maximum value in the range.  */
869   if (!is_gimple_min_invariant (step))
870     return;
871
872   /* FIXME.  When dealing with unsigned types,
873      analyze_scalar_evolution sets STEP to very large unsigned values
874      when the evolution goes backwards.  This confuses this analysis
875      because we think that INIT is the smallest value that the range
876      can take, instead of the largest.  Ignore these chrecs for now.  */
877   if (INTEGRAL_TYPE_P (TREE_TYPE (step)) && TYPE_UNSIGNED (TREE_TYPE (step)))
878     return;
879
880   /* If STEP is negative, then INIT is the maximum value the range
881      will take.  Otherwise, INIT is the minimum value.  */
882   init_is_max = (tree_int_cst_sgn (step) < 0);
883
884   if (!POINTER_TYPE_P (TREE_TYPE (init))
885       && (vr->type == VR_VARYING || vr->type == VR_UNDEFINED))
886     {
887       /* For VARYING or UNDEFINED ranges, just about anything we get
888          from scalar evolutions should be better.  */
889       if (init_is_max)
890         set_value_range (vr, VR_RANGE, TYPE_MIN_VALUE (TREE_TYPE (init)), init);
891       else
892         set_value_range (vr, VR_RANGE, init, TYPE_MAX_VALUE (TREE_TYPE (init)));
893     }
894   else if (vr->type == VR_RANGE)
895     {
896       if (init_is_max)
897         {
898           /* INIT is the maximum value.  If INIT is lower than
899              VR->MAX, set VR->MAX to INIT.  */
900           if (compare_values (init, vr->max) == -1)
901             set_value_range (vr, VR_RANGE, vr->min, init);
902         }
903       else
904         {
905           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
906           if (compare_values (init, vr->min) == 1)
907             set_value_range (vr, VR_RANGE, init, vr->max);
908         }
909     }
910 }
911
912
913 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
914    
915    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for all the
916      values in the ranges.
917
918    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
919
920    - Return NULL_TREE if it is not always possible to determine the value of
921      the comparison.  */
922
923 static tree
924 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1)
925 {
926   /* VARYING or UNDEFINED ranges cannot be compared.  */
927   if (vr0->type == VR_VARYING
928       || vr0->type == VR_UNDEFINED
929       || vr1->type == VR_VARYING
930       || vr1->type == VR_UNDEFINED)
931     return NULL_TREE;
932
933   /* Anti-ranges need to be handled separately.  */
934   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
935     {
936       /* If both are anti-ranges, then we cannot compute any
937          comparison.  */
938       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
939         return NULL_TREE;
940
941       /* These comparisons are never statically computable.  */
942       if (comp == GT_EXPR
943           || comp == GE_EXPR
944           || comp == LT_EXPR
945           || comp == LE_EXPR)
946         return NULL_TREE;
947
948       /* Equality can be computed only between a range and an
949          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
950       if (vr0->type == VR_RANGE)
951         {
952           /* To simplify processing, make VR0 the anti-range.  */
953           value_range *tmp = vr0;
954           vr0 = vr1;
955           vr1 = tmp;
956         }
957
958       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
959
960       if (compare_values (vr0->min, vr1->min) == 0
961           && compare_values (vr0->max, vr1->max) == 0)
962         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
963
964       return NULL_TREE;
965     }
966
967   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
968      operands around and change the comparison code.  */
969   if (comp == GT_EXPR || comp == GE_EXPR)
970     {
971       value_range *tmp;
972       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
973       tmp = vr0;
974       vr0 = vr1;
975       vr1 = tmp;
976     }
977
978   if (comp == EQ_EXPR)
979     {
980       /* Equality may only be computed if both ranges represent
981          exactly one value.  */
982       if (compare_values (vr0->min, vr0->max) == 0
983           && compare_values (vr1->min, vr1->max) == 0)
984         {
985           int cmp_min = compare_values (vr0->min, vr1->min);
986           int cmp_max = compare_values (vr0->max, vr1->max);
987           if (cmp_min == 0 && cmp_max == 0)
988             return boolean_true_node;
989           else if (cmp_min != -2 && cmp_max != -2)
990             return boolean_false_node;
991         }
992
993       return NULL_TREE;
994     }
995   else if (comp == NE_EXPR)
996     {
997       int cmp1, cmp2;
998
999       /* If VR0 is completely to the left or completely to the right
1000          of VR1, they are always different.  Notice that we need to
1001          make sure that both comparisons yield similar results to
1002          avoid comparing values that cannot be compared at
1003          compile-time.  */
1004       cmp1 = compare_values (vr0->max, vr1->min);
1005       cmp2 = compare_values (vr0->min, vr1->max);
1006       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1007         return boolean_true_node;
1008
1009       /* If VR0 and VR1 represent a single value and are identical,
1010          return false.  */
1011       else if (compare_values (vr0->min, vr0->max) == 0
1012                && compare_values (vr1->min, vr1->max) == 0
1013                && compare_values (vr0->min, vr1->min) == 0
1014                && compare_values (vr0->max, vr1->max) == 0)
1015         return boolean_false_node;
1016
1017       /* Otherwise, they may or may not be different.  */
1018       else
1019         return NULL_TREE;
1020     }
1021   else if (comp == LT_EXPR || comp == LE_EXPR)
1022     {
1023       int tst;
1024
1025       /* If VR0 is to the left of VR1, return true.  */
1026       tst = compare_values (vr0->max, vr1->min);
1027       if ((comp == LT_EXPR && tst == -1)
1028           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1029         return boolean_true_node;
1030
1031       /* If VR0 is to the right of VR1, return false.  */
1032       tst = compare_values (vr0->min, vr1->max);
1033       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1034           || (comp == LE_EXPR && tst == 1))
1035         return boolean_false_node;
1036
1037       /* Otherwise, we don't know.  */
1038       return NULL_TREE;
1039     }
1040     
1041   gcc_unreachable ();
1042 }
1043
1044
1045 /* Given a value range VR, a value VAL and a comparison code COMP, return
1046    BOOLEAN_TRUE_NODE if VR COMP VR1 always returns true for all the
1047    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
1048    always returns false.  Return NULL_TREE if it is not always
1049    possible to determine the value of the comparison.  */
1050
1051 static tree
1052 compare_range_with_value (enum tree_code comp, value_range *vr, tree val)
1053 {
1054   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
1055     return NULL_TREE;
1056
1057   /* Anti-ranges need to be handled separately.  */
1058   if (vr->type == VR_ANTI_RANGE)
1059     {
1060       /* For anti-ranges, the only predicates that we can compute at
1061          compile time are equality and inequality.  */
1062       if (comp == GT_EXPR
1063           || comp == GE_EXPR
1064           || comp == LT_EXPR
1065           || comp == LE_EXPR)
1066         return NULL_TREE;
1067
1068       /* ~[VAL, VAL] == VAL is always false.  */
1069       if (compare_values (vr->min, val) == 0
1070           && compare_values (vr->max, val) == 0)
1071         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1072
1073       return NULL_TREE;
1074     }
1075
1076   if (comp == EQ_EXPR)
1077     {
1078       /* EQ_EXPR may only be computed if VR represents exactly
1079          one value.  */
1080       if (compare_values (vr->min, vr->max) == 0)
1081         {
1082           int cmp = compare_values (vr->min, val);
1083           if (cmp == 0)
1084             return boolean_true_node;
1085           else if (cmp == -1 || cmp == 1 || cmp == 2)
1086             return boolean_false_node;
1087         }
1088
1089       return NULL_TREE;
1090     }
1091   else if (comp == NE_EXPR)
1092     {
1093       /* If VAL is not inside VR, then they are always different.  */
1094       if (compare_values (vr->max, val) == -1
1095           || compare_values (vr->min, val) == 1)
1096         return boolean_true_node;
1097
1098       /* If VR represents exactly one value equal to VAL, then return
1099          false.  */
1100       if (compare_values (vr->min, vr->max) == 0
1101           && compare_values (vr->min, val) == 0)
1102         return boolean_false_node;
1103
1104       /* Otherwise, they may or may not be different.  */
1105       return NULL_TREE;
1106     }
1107   else if (comp == LT_EXPR || comp == LE_EXPR)
1108     {
1109       int tst;
1110
1111       /* If VR is to the left of VAL, return true.  */
1112       tst = compare_values (vr->max, val);
1113       if ((comp == LT_EXPR && tst == -1)
1114           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1115         return boolean_true_node;
1116
1117       /* If VR is to the right of VAL, return false.  */
1118       tst = compare_values (vr->min, val);
1119       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1120           || (comp == LE_EXPR && tst == 1))
1121         return boolean_false_node;
1122
1123       /* Otherwise, we don't know.  */
1124       return NULL_TREE;
1125     }
1126   else if (comp == GT_EXPR || comp == GE_EXPR)
1127     {
1128       int tst;
1129
1130       /* If VR is to the right of VAL, return true.  */
1131       tst = compare_values (vr->min, val);
1132       if ((comp == GT_EXPR && tst == 1)
1133           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1134         return boolean_true_node;
1135
1136       /* If VR is to the left of VAL, return false.  */
1137       tst = compare_values (vr->max, val);
1138       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1139           || (comp == GE_EXPR && tst == -1))
1140         return boolean_false_node;
1141
1142       /* Otherwise, we don't know.  */
1143       return NULL_TREE;
1144     }
1145
1146   gcc_unreachable ();
1147 }
1148
1149
1150 /* Debugging dumps.  */
1151
1152 void
1153 dump_value_range (FILE *file, value_range *vr)
1154 {
1155   if (vr == NULL)
1156     fprintf (file, "[]");
1157   else if (vr->type == VR_UNDEFINED)
1158     fprintf (file, "UNDEFINED");
1159   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1160     {
1161       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1162       print_generic_expr (file, vr->min, 0);
1163       fprintf (file, ", ");
1164       print_generic_expr (file, vr->max, 0);
1165       fprintf (file, "]");
1166     }
1167   else if (vr->type == VR_VARYING)
1168     fprintf (file, "VARYING");
1169   else
1170     fprintf (file, "INVALID RANGE");
1171 }
1172
1173
1174 /* Dump value range VR to stderr.  */
1175
1176 void
1177 debug_value_range (value_range *vr)
1178 {
1179   dump_value_range (stderr, vr);
1180 }
1181
1182
1183 /* Dump value ranges of all SSA_NAMEs to FILE.  */
1184
1185 void
1186 dump_all_value_ranges (FILE *file)
1187 {
1188   size_t i;
1189
1190   for (i = 0; i < num_ssa_names; i++)
1191     {
1192       tree var = ssa_name (i);
1193       if (var && SSA_NAME_VALUE_RANGE (var))
1194         {
1195           print_generic_expr (file, var, 0);
1196           fprintf (file, ": ");
1197           dump_value_range (file, SSA_NAME_VALUE_RANGE (var));
1198           fprintf (file, "\n");
1199         }
1200     }
1201
1202   fprintf (file, "\n");
1203 }
1204
1205
1206 /* Dump all value ranges to stderr.  */
1207
1208 void
1209 debug_all_value_ranges (void)
1210 {
1211   dump_all_value_ranges (stderr);
1212 }
1213
1214
1215 /*---------------------------------------------------------------------------
1216                             Value Range Propagation
1217 ---------------------------------------------------------------------------*/
1218
1219 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1220    create a new SSA name N and return the assertion assignment
1221    'V = ASSERT_EXPR <V, V OP W>'.  */
1222
1223 static tree
1224 build_assert_expr_for (tree cond, tree v)
1225 {
1226   tree n, assertion;
1227
1228   gcc_assert (TREE_CODE (v) == SSA_NAME);
1229   n = duplicate_ssa_name (v, NULL_TREE);
1230
1231   if (TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison)
1232     {
1233       /* Build N = ASSERT_EXPR <V, COND>.  As a special case, if the
1234          conditional is an EQ_EXPR (V == Z), just build the assignment
1235          N = Z.  */
1236       if (TREE_CODE (cond) == EQ_EXPR)
1237         {
1238           tree other = get_opposite_operand (cond, v);
1239           assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, other);
1240         }
1241       else
1242         assertion = build (MODIFY_EXPR, TREE_TYPE (v), n,
1243                            build (ASSERT_EXPR, TREE_TYPE (v), v, cond));
1244     }
1245   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1246     {
1247       /* Given !V, build the assignment N = false.  */
1248       tree op0 = TREE_OPERAND (cond, 0);
1249       gcc_assert (op0 == v);
1250       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_false_node);
1251     }
1252   else if (TREE_CODE (cond) == SSA_NAME)
1253     {
1254       /* Given V, build the assignment N = true.  */
1255       gcc_assert (v == cond);
1256       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_true_node);
1257     }
1258   else
1259     gcc_unreachable ();
1260
1261   SSA_NAME_DEF_STMT (n) = assertion;
1262
1263   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1264      operand of the ASSERT_EXPR. Register the new name and the old one
1265      in the replacement table so that we can fix the SSA web after
1266      adding all the ASSERT_EXPRs.  */
1267   register_new_name_mapping (n, v);
1268
1269   return assertion;
1270 }
1271
1272
1273 /* Return false if EXPR is a predicate expression involving floating
1274    point values.  */
1275
1276 static inline bool
1277 fp_predicate (tree expr)
1278 {
1279   return TREE_CODE_CLASS (TREE_CODE (expr)) == tcc_comparison
1280          && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
1281 }
1282
1283
1284 /* Return an expression predicate that represents the range of values
1285    that can be taken by operand OP after STMT executes.  */
1286
1287 static tree
1288 infer_value_range (tree stmt, tree op)
1289 {
1290   /* Do not attempt to infer anything in names that flow through
1291      abnormal edges.  */
1292   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1293     return NULL_TREE;
1294
1295   if (POINTER_TYPE_P (TREE_TYPE (op)))
1296     {
1297       bool is_store;
1298       unsigned num_uses, num_derefs;
1299
1300       count_uses_and_derefs (op, stmt, &num_uses, &num_derefs, &is_store);
1301       if (num_derefs > 0 && flag_delete_null_pointer_checks)
1302         {
1303           /* We can only assume that a pointer dereference will yield
1304              non-NULL if -fdelete-null-pointer-checks is enabled.  */
1305           tree null = build_int_cst (TREE_TYPE (op), 0);
1306           tree t = build (NE_EXPR, boolean_type_node, op, null);
1307           return t;
1308         }
1309     }
1310
1311   return NULL_TREE;
1312 }
1313
1314
1315 /* Return true if OP is the result of an ASSERT_EXPR that tests the
1316    same condition as COND.  */
1317
1318 static bool
1319 has_assert_expr (tree op, tree cond)
1320 {
1321   tree def_stmt = SSA_NAME_DEF_STMT (op);
1322   tree assert_expr, other_cond, other_op;
1323
1324   /* If OP was not generated by an ASSERT_EXPR, return false.  */
1325   if (TREE_CODE (def_stmt) != MODIFY_EXPR
1326       || TREE_CODE (TREE_OPERAND (def_stmt, 1)) != ASSERT_EXPR)
1327     return false;
1328
1329   assert_expr = TREE_OPERAND (def_stmt, 1);
1330   other_cond = ASSERT_EXPR_COND (assert_expr);
1331   other_op = ASSERT_EXPR_VAR (assert_expr);
1332
1333   if (TREE_CODE (cond) == TREE_CODE (other_cond))
1334     {
1335       tree t1, t2;
1336
1337       /* If COND is not a comparison predicate, something is wrong.  */
1338       gcc_assert (TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
1339
1340       /* Note that we only need to compare against one of the operands
1341          of OTHER_COND.  
1342          
1343          Suppose that we are about to insert the assertion ASSERT_EXPR
1344          <x_4, x_4 != 0> and the defining statement for x_4 is x_4 =
1345          ASSERT_EXPR <x_3, x_3 != 0>.
1346
1347          In this case, we don't really want to insert a new
1348          ASSERT_EXPR for x_4 because that would be redundant.  We
1349          already know that x_4 is not 0.  So, when comparing the
1350          conditionals 'x_3 != 0' and 'x_4 != 0', we don't want to
1351          compare x_3 and x_4, we just want to compare the predicate's
1352          code (!=) and the other operand (0).  */
1353       if (TREE_OPERAND (cond, 0) == op)
1354         t1 = TREE_OPERAND (cond, 1);
1355       else
1356         t1 = TREE_OPERAND (cond, 0);
1357
1358       if (TREE_OPERAND (other_cond, 0) == other_op)
1359         t2 = TREE_OPERAND (other_cond, 1);
1360       else
1361         t2 = TREE_OPERAND (other_cond, 0);
1362
1363       return (t1 == t2 || operand_equal_p (t1, t2, 0));
1364     }
1365
1366   return false;
1367 }
1368
1369
1370 /* Traverse all the statements in block BB looking for used variables.
1371    Variables used in BB are added to bitmap FOUND.  The algorithm
1372    works in three main parts:
1373
1374    1- For every statement S in BB, all the variables used by S are
1375       added to bitmap FOUND.
1376
1377    2- If statement S uses an operand N in a way that exposes a known
1378       value range for N, then if N was not already generated by an
1379       ASSERT_EXPR, create a new ASSERT_EXPR for N.  For instance, if N
1380       is a pointer and the statement dereferences it, we can assume
1381       that N is not NULL.
1382
1383    3- COND_EXPRs are a special case of #2.  We can derive range
1384       information from the predicate but need to insert different
1385       ASSERT_EXPRs for each of the sub-graphs rooted at the
1386       conditional block.  If the last statement of BB is a conditional
1387       expression of the form 'X op Y', then
1388
1389       a) Remove X and Y from the set FOUND.
1390
1391       b) If the conditional dominates its THEN_CLAUSE sub-graph,
1392          recurse into it.  On return, if X and/or Y are marked in
1393          FOUND, then an ASSERT_EXPR is added for the corresponding
1394          variable.
1395
1396       c) Repeat step (b) on the ELSE_CLAUSE.
1397
1398       d) Mark X and Y in FOUND.
1399
1400    4- If BB does not end in a conditional expression, then we recurse
1401       into BB's dominator children.
1402    
1403    At the end of the recursive traversal, ASSERT_EXPRs will have been
1404    added to the edges of COND_EXPR blocks that have sub-graphs using
1405    one or both predicate operands.  For instance,
1406
1407         if (a == 9)
1408           b = a;
1409         else
1410           b = c + 1;
1411
1412    In this case, an assertion on the THEN clause is useful to
1413    determine that 'a' is always 9 on that edge.  However, an assertion
1414    on the ELSE clause would be unnecessary.
1415
1416    On exit from this function, all the names created by the newly
1417    inserted ASSERT_EXPRs need to be added to the SSA web by rewriting
1418    the SSA names that they replace.
1419    
1420    TODO.  Handle SWITCH_EXPR.  */
1421
1422 static bool
1423 maybe_add_assert_expr (basic_block bb)
1424 {
1425   block_stmt_iterator si;
1426   tree last;
1427   bool added;
1428   use_optype uses;
1429
1430   /* Step 1.  Mark all the SSA names used in BB in bitmap FOUND.  */
1431   added = false;
1432   last = NULL_TREE;
1433   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1434     {
1435       tree stmt, op;
1436       ssa_op_iter i;
1437       
1438       stmt = bsi_stmt (si);
1439
1440       /* Mark all the SSA names used by STMT in bitmap FOUND.  If STMT
1441          is inside the sub-graph of a conditional block, when we
1442          return from this recursive walk, our parent will use the
1443          FOUND bitset to determine if one of the operands it was
1444          looking for was present in the sub-graph.  */
1445       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
1446         {
1447           tree cond;
1448
1449           /* If OP is used only once, namely in this STMT, don't
1450              bother inserting an ASSERT_EXPR for it.  Such an
1451              ASSERT_EXPR would do nothing but increase compile time.
1452              Experiments show that with this simple check, we can save
1453              more than 20% of ASSERT_EXPRs.  */
1454           if (has_single_use (op))
1455             continue;
1456
1457           SET_BIT (found, SSA_NAME_VERSION (op));
1458
1459           cond = infer_value_range (stmt, op);
1460           if (!cond)
1461             continue;
1462
1463           /* Step 2.  If OP is used in such a way that we can infer a
1464              value range for it, create a new ASSERT_EXPR for OP
1465              (unless OP already has an ASSERT_EXPR).  */
1466           gcc_assert (!is_ctrl_stmt (stmt));
1467
1468           if (has_assert_expr (op, cond))
1469             continue;
1470
1471           if (!stmt_ends_bb_p (stmt))
1472             {
1473               /* If STMT does not end the block, we can insert the new
1474                  assertion right after it.  */
1475               tree t = build_assert_expr_for (cond, op);
1476               bsi_insert_after (&si, t, BSI_NEW_STMT);
1477               added = true;
1478             }
1479           else
1480             {
1481               /* STMT must be the last statement in BB.  We can only
1482                  insert new assertions on the non-abnormal edge out of
1483                  BB.  Note that since STMT is not control flow, there
1484                  may only be one non-abnormal edge out of BB.  */
1485               edge_iterator ei;
1486               edge e;
1487
1488               FOR_EACH_EDGE (e, ei, bb->succs)
1489                 if (!(e->flags & EDGE_ABNORMAL))
1490                   {
1491                     tree t = build_assert_expr_for (cond, op);
1492                     bsi_insert_on_edge (e, t);
1493                     added = true;
1494                     break;
1495                   }
1496             }
1497         }
1498
1499       /* Remember the last statement of the block.  */
1500       last = stmt;
1501     }
1502
1503   /* Step 3.  If BB's last statement is a conditional expression
1504      involving integer operands, recurse into each of the sub-graphs
1505      rooted at BB to determine if we need to add ASSERT_EXPRs.
1506      Notice that we only care about the first operand of the
1507      conditional.  Adding assertions for both operands may actually 
1508      hinder VRP.  FIXME, add example.  */
1509   if (last
1510       && TREE_CODE (last) == COND_EXPR
1511       && !fp_predicate (COND_EXPR_COND (last))
1512       && NUM_USES (uses = STMT_USE_OPS (last)) > 0)
1513     {
1514       edge e;
1515       edge_iterator ei;
1516       tree op, cond;
1517       basic_block son;
1518       
1519       cond = COND_EXPR_COND (last);
1520
1521       op = USE_OP (uses, 0);
1522
1523       /* Do not attempt to infer anything in names that flow through
1524          abnormal edges.  */
1525       if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1526         return false;
1527
1528       /* Remove the COND_EXPR operand from the FOUND bitmap.
1529          Otherwise, when we finish traversing each of the sub-graphs,
1530          we won't know whether the variables were found in the
1531          sub-graphs or if they had been found in a block upstream from
1532          BB.  */
1533       RESET_BIT (found, SSA_NAME_VERSION (op));
1534
1535       /* Look for uses of the operands in each of the sub-graphs
1536          rooted at BB.  We need to check each of the outgoing edges
1537          separately, so that we know what kind of ASSERT_EXPR to
1538          insert.  */
1539       FOR_EACH_EDGE (e, ei, bb->succs)
1540         {
1541           /* If BB strictly dominates the sub-graph at E->DEST,
1542              recurse into it.  */
1543           if (e->dest != bb
1544               && dominated_by_p (CDI_DOMINATORS, e->dest, bb))
1545             added |= maybe_add_assert_expr (e->dest);
1546
1547           /* Once we traversed the sub-graph, check if any block inside
1548              used either of the predicate's operands.  If so, add the
1549              appropriate ASSERT_EXPR.  */
1550           if (TEST_BIT (found, SSA_NAME_VERSION (op)))
1551             {
1552               /* We found a use of OP in the sub-graph rooted at
1553                  E->DEST.  Add an ASSERT_EXPR according to whether
1554                  E goes to THEN_CLAUSE or ELSE_CLAUSE.  */
1555               tree c, t;
1556
1557               if (e->flags & EDGE_TRUE_VALUE)
1558                 c = unshare_expr (cond);
1559               else if (e->flags & EDGE_FALSE_VALUE)
1560                 c = invert_truthvalue (cond);
1561               else
1562                 gcc_unreachable ();
1563
1564               t = build_assert_expr_for (c, op);
1565               bsi_insert_on_edge (e, t);
1566               added = true;
1567             }
1568         }
1569
1570       /* Finally, mark all the COND_EXPR operands as found.  */
1571       SET_BIT (found, SSA_NAME_VERSION (op));
1572
1573       /* Recurse into the dominator children of BB that are not BB's
1574          immediate successors.  Note that we have already visited BB's
1575          other dominator children above.  */
1576       for (son = first_dom_son (CDI_DOMINATORS, bb);
1577            son;
1578            son = next_dom_son (CDI_DOMINATORS, son))
1579         {
1580           if (find_edge (bb, son) == NULL)
1581             added |= maybe_add_assert_expr (son);
1582         }
1583     }
1584   else
1585     {
1586       /* Step 4.  Recurse into the dominator children of BB.  */
1587       basic_block son;
1588
1589       for (son = first_dom_son (CDI_DOMINATORS, bb);
1590            son;
1591            son = next_dom_son (CDI_DOMINATORS, son))
1592         added |= maybe_add_assert_expr (son);
1593     }
1594
1595   return added;
1596 }
1597
1598
1599 /* Traverse the flowgraph looking for conditional jumps to insert range
1600    expressions.  These range expressions are meant to provide information
1601    to optimizations that need to reason in terms of value ranges.  They
1602    will not be expanded into RTL.  For instance, given:
1603
1604    x = ...
1605    y = ...
1606    if (x < y)
1607      y = x - 2;
1608    else
1609      x = y + 3;
1610
1611    this pass will transform the code into:
1612
1613    x = ...
1614    y = ...
1615    if (x < y)
1616     {
1617       x = ASSERT_EXPR <x, x < y>
1618       y = x - 2
1619     }
1620    else
1621     {
1622       y = ASSERT_EXPR <y, x <= y>
1623       x = y + 3
1624     }
1625
1626    The idea is that once copy and constant propagation have run, other
1627    optimizations will be able to determine what ranges of values can 'x'
1628    take in different paths of the code, simply by checking the reaching
1629    definition of 'x'.  */
1630
1631 static void
1632 insert_range_assertions (void)
1633 {
1634   edge e;
1635   edge_iterator ei;
1636   bool update_ssa_p;
1637   
1638   found = sbitmap_alloc (num_ssa_names);
1639   sbitmap_zero (found);
1640
1641   calculate_dominance_info (CDI_DOMINATORS);
1642
1643   update_ssa_p = false;
1644   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
1645     if (maybe_add_assert_expr (e->dest))
1646       update_ssa_p = true;
1647
1648   if (update_ssa_p)
1649     {
1650       bsi_commit_edge_inserts ();
1651       update_ssa (TODO_update_ssa_no_phi);
1652     }
1653
1654   if (dump_file && (dump_flags & TDF_DETAILS))
1655     {
1656       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
1657       dump_function_to_file (current_function_decl, dump_file, dump_flags);
1658     }
1659
1660   sbitmap_free (found);
1661 }
1662
1663
1664 /* Convert range assertion expressions into copies.  FIXME, explain why.  */
1665
1666 static void
1667 remove_range_assertions (void)
1668 {
1669   basic_block bb;
1670   block_stmt_iterator si;
1671
1672   FOR_EACH_BB (bb)
1673     for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1674       {
1675         tree stmt = bsi_stmt (si);
1676
1677         if (TREE_CODE (stmt) == MODIFY_EXPR
1678             && TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
1679           {
1680             tree rhs = TREE_OPERAND (stmt, 1);
1681             tree cond = fold (ASSERT_EXPR_COND (rhs));
1682             gcc_assert (cond != boolean_false_node);
1683             TREE_OPERAND (stmt, 1) = ASSERT_EXPR_VAR (rhs);
1684             update_stmt (stmt);
1685           }
1686       }
1687 }
1688
1689
1690 /* Return true if STMT is interesting for VRP.  */
1691
1692 static bool
1693 stmt_interesting_for_vrp (tree stmt)
1694 {
1695   if (TREE_CODE (stmt) == PHI_NODE
1696       && is_gimple_reg (PHI_RESULT (stmt))
1697       && (INTEGRAL_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))
1698           || POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))))
1699     return true;
1700   else if (TREE_CODE (stmt) == MODIFY_EXPR)
1701     {
1702       tree lhs = TREE_OPERAND (stmt, 0);
1703       stmt_ann_t ann = stmt_ann (stmt);
1704
1705       if (TREE_CODE (lhs) == SSA_NAME
1706           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1707               || POINTER_TYPE_P (TREE_TYPE (lhs)))
1708           && NUM_V_MAY_DEFS (V_MAY_DEF_OPS (ann)) == 0
1709           && NUM_VUSES (VUSE_OPS (ann)) == 0
1710           && NUM_V_MUST_DEFS (V_MUST_DEF_OPS (ann)) == 0)
1711         return true;
1712     }
1713   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
1714     return true;
1715
1716   return false;
1717 }
1718
1719
1720 /* Initialize local data structures for VRP.  Return true if VRP
1721    is worth running (i.e. if we found any statements that could
1722    benefit from range information).  */
1723
1724 static bool
1725 vrp_initialize (void)
1726 {
1727   basic_block bb;
1728   bool do_vrp;
1729
1730   /* If we don't find any ASSERT_EXPRs in the code, there's no point
1731      running VRP.  */
1732   do_vrp = false;
1733
1734   FOR_EACH_BB (bb)
1735     {
1736       block_stmt_iterator si;
1737       tree phi;
1738
1739       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1740         {
1741           if (!stmt_interesting_for_vrp (phi))
1742             {
1743               tree lhs = PHI_RESULT (phi);
1744               set_value_range (get_value_range (lhs), VR_VARYING, 0, 0);
1745               DONT_SIMULATE_AGAIN (phi) = true;
1746             }
1747           else
1748             DONT_SIMULATE_AGAIN (phi) = false;
1749         }
1750
1751       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1752         {
1753           tree stmt = bsi_stmt (si);
1754
1755           if (!stmt_interesting_for_vrp (stmt))
1756             {
1757               ssa_op_iter i;
1758               tree def;
1759               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
1760                 set_value_range (get_value_range (def), VR_VARYING, 0, 0);
1761               DONT_SIMULATE_AGAIN (stmt) = true;
1762             }
1763           else
1764             {
1765               if (TREE_CODE (stmt) == MODIFY_EXPR
1766                    && TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
1767                 do_vrp = true;
1768
1769               DONT_SIMULATE_AGAIN (stmt) = false;
1770             }
1771         }
1772     }
1773
1774   return do_vrp;
1775 }
1776
1777
1778 /* Visit assignment STMT.  If it produces an interesting range, record
1779    the SSA name in *OUTPUT_P.  */
1780
1781 static enum ssa_prop_result
1782 vrp_visit_assignment (tree stmt, tree *output_p)
1783 {
1784   tree lhs, rhs, def;
1785   ssa_op_iter iter;
1786
1787   lhs = TREE_OPERAND (stmt, 0);
1788   rhs = TREE_OPERAND (stmt, 1);
1789
1790   /* We only keep track of ranges in integral and pointer types.  */
1791   if (TREE_CODE (lhs) == SSA_NAME
1792       && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1793           || POINTER_TYPE_P (TREE_TYPE (lhs))))
1794     {
1795       value_range *vr, new_vr;
1796       struct loop *l;
1797       
1798       vr = get_value_range (lhs);
1799       extract_range_from_expr (&new_vr, rhs);
1800
1801       /* If STMT is inside a loop, we may be able to know something
1802          else about the range of LHS by examining scalar evolution
1803          information.  */
1804       if (cfg_loops && (l = loop_containing_stmt (stmt)))
1805         adjust_range_with_scev (&new_vr, l, lhs);
1806
1807       if (update_value_range (vr, new_vr.type, new_vr.min, new_vr.max))
1808         {
1809           *output_p = lhs;
1810
1811           if (dump_file && (dump_flags & TDF_DETAILS))
1812             {
1813               fprintf (dump_file, "Found new range ");
1814               dump_value_range (dump_file, &new_vr);
1815               fprintf (dump_file, " for ");
1816               print_generic_expr (dump_file, lhs, 0);
1817               fprintf (dump_file, "\n\n");
1818             }
1819
1820           if (new_vr.type == VR_VARYING)
1821             return SSA_PROP_VARYING;
1822
1823           return SSA_PROP_INTERESTING;
1824         }
1825
1826       return SSA_PROP_NOT_INTERESTING;
1827     }
1828   
1829   /* Every other statements produces no useful ranges.  */
1830   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1831     set_value_range (get_value_range (def), VR_VARYING, 0, 0);
1832
1833   return SSA_PROP_VARYING;
1834 }
1835
1836
1837 /* Given a conditional predicate COND, try to determine if COND yields
1838    true or false based on the value ranges of its operands.  */
1839
1840 static tree
1841 vrp_evaluate_conditional (tree cond)
1842 {
1843   gcc_assert (TREE_CODE (cond) == SSA_NAME
1844               || TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
1845
1846   if (TREE_CODE (cond) == SSA_NAME)
1847     {
1848       /* For SSA names, only return a truth value if the range is
1849          known and contains exactly one value.  */
1850       value_range *vr = SSA_NAME_VALUE_RANGE (cond);
1851       if (vr && vr->type == VR_RANGE && vr->min == vr->max)
1852         return vr->min;
1853     }
1854   else
1855     {
1856       /* For comparisons, evaluate each operand and compare their
1857          ranges.  */
1858       tree op0, op1;
1859       value_range *vr0, *vr1;
1860
1861       op0 = TREE_OPERAND (cond, 0);
1862       vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
1863
1864       op1 = TREE_OPERAND (cond, 1);
1865       vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
1866
1867       if (vr0 && vr1)
1868         return compare_ranges (TREE_CODE (cond), vr0, vr1);
1869       else if (vr0 && vr1 == NULL)
1870         return compare_range_with_value (TREE_CODE (cond), vr0, op1);
1871       else if (vr0 == NULL && vr1)
1872         return compare_range_with_value (opposite_comparison (TREE_CODE (cond)),
1873                                          vr1, op0);
1874     }
1875
1876   /* Anything else cannot be computed statically.  */
1877   return NULL_TREE;
1878 }
1879
1880
1881 /* Visit conditional statement STMT.  If we can determine which edge
1882    will be taken out of STMT's basic block, record it in
1883    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
1884    SSA_PROP_VARYING.  */
1885
1886 static enum ssa_prop_result
1887 vrp_visit_cond_stmt (tree stmt, edge *taken_edge_p)
1888 {
1889   tree cond, val;
1890
1891   *taken_edge_p = NULL;
1892
1893   /* FIXME.  Handle SWITCH_EXPRs.  But first, the assert pass needs to
1894      add ASSERT_EXPRs for them.  */
1895   if (TREE_CODE (stmt) == SWITCH_EXPR)
1896     return SSA_PROP_VARYING;
1897
1898   cond = COND_EXPR_COND (stmt);
1899
1900   if (dump_file && (dump_flags & TDF_DETAILS))
1901     {
1902       tree use;
1903       ssa_op_iter i;
1904
1905       fprintf (dump_file, "\nVisiting conditional with predicate: ");
1906       print_generic_expr (dump_file, cond, 0);
1907       fprintf (dump_file, "\nWith known ranges\n");
1908       
1909       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
1910         {
1911           fprintf (dump_file, "\t");
1912           print_generic_expr (dump_file, use, 0);
1913           fprintf (dump_file, ": ");
1914           dump_value_range (dump_file, SSA_NAME_VALUE_RANGE (use));
1915         }
1916
1917       fprintf (dump_file, "\n");
1918     }
1919
1920   /* Compute the value of the predicate COND by checking the known
1921      ranges of each of its operands.  */
1922   val = vrp_evaluate_conditional (cond);
1923   if (val)
1924     *taken_edge_p = find_taken_edge (bb_for_stmt (stmt), val);
1925
1926   if (dump_file && (dump_flags & TDF_DETAILS))
1927     {
1928       fprintf (dump_file, "\nPredicate evaluates to: ");
1929       if (val == NULL_TREE)
1930         fprintf (dump_file, "DON'T KNOW\n");
1931       else
1932         print_generic_stmt (dump_file, val, 0);
1933     }
1934
1935   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
1936 }
1937
1938
1939 /* Evaluate statement STMT.  If the statement produces a useful range,
1940    return SSA_PROP_INTERESTING and record the SSA name with the
1941    interesting range into *OUTPUT_P.
1942
1943    If STMT is a conditional branch and we can determine its truth
1944    value, the taken edge is recorded in *TAKEN_EDGE_P.
1945
1946    If STMT produces a varying value, return SSA_PROP_VARYING.  */
1947
1948 static enum ssa_prop_result
1949 vrp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
1950 {
1951   tree def;
1952   ssa_op_iter iter;
1953   stmt_ann_t ann;
1954
1955   if (dump_file && (dump_flags & TDF_DETAILS))
1956     {
1957       fprintf (dump_file, "\nVisiting statement:\n");
1958       print_generic_stmt (dump_file, stmt, dump_flags);
1959       fprintf (dump_file, "\n");
1960     }
1961
1962   ann = stmt_ann (stmt);
1963   if (TREE_CODE (stmt) == MODIFY_EXPR
1964       && NUM_V_MAY_DEFS (V_MAY_DEF_OPS (ann)) == 0
1965       && NUM_VUSES (VUSE_OPS (ann)) == 0
1966       && NUM_V_MUST_DEFS (V_MUST_DEF_OPS (ann)) == 0)
1967     return vrp_visit_assignment (stmt, output_p);
1968   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
1969     return vrp_visit_cond_stmt (stmt, taken_edge_p);
1970
1971   /* All other statements produce nothing of interest for VRP, so mark
1972      their outputs varying and prevent further simulation.  */
1973   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1974     set_value_range (get_value_range (def), VR_VARYING, 0, 0);
1975
1976   return SSA_PROP_VARYING;
1977 }
1978
1979
1980 /* Meet operation for value ranges.  Given two value ranges VR0 and
1981    VR1, store in VR0 the result of meeting VR0 and VR1.
1982    
1983    The meeting rules are as follows:
1984
1985    1- If VR0 and VR1 have an empty intersection, set VR0 to VR_VARYING.
1986
1987    2- If VR0 and VR1 have a non-empty intersection, set VR0 to the
1988       union of VR0 and VR1.  */
1989
1990 static void
1991 vrp_meet (value_range *vr0, value_range *vr1)
1992 {
1993   if (vr0->type == VR_UNDEFINED)
1994     {
1995       *vr0 = *vr1;
1996       return;
1997     }
1998
1999   if (vr1->type == VR_UNDEFINED)
2000     {
2001       /* Nothing to do.  VR0 already has the resulting range.  */
2002       return;
2003     }
2004
2005   if (vr0->type == VR_VARYING)
2006     {
2007       /* Nothing to do.  VR0 already has the resulting range.  */
2008       return;
2009     }
2010
2011   if (vr1->type == VR_VARYING)
2012     {
2013       *vr0 = *vr1;
2014       return;
2015     }
2016
2017   /* If either is a symbolic range, drop to VARYING.  */
2018   if (symbolic_range_p (vr0) || symbolic_range_p (vr1))
2019     {
2020       set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2021       return;
2022     }
2023
2024   if (vr0->type == VR_RANGE && vr1->type == VR_RANGE)
2025     {
2026       /* If VR0 and VR1 have a non-empty intersection, compute the
2027          union of both ranges.  */
2028       if (value_ranges_intersect_p (vr0, vr1))
2029         {
2030           tree min, max;
2031
2032           min = vr0->min;
2033           max = vr0->max;
2034
2035           /* The lower limit of the new range is the minimum of the
2036              two ranges.  */
2037           if (compare_values (vr0->min, vr1->min) == 1)
2038             min = vr1->min;
2039
2040           /* The upper limit of the new range is the maximum of the
2041              two ranges.  */
2042           if (compare_values (vr0->max, vr1->max) == -1)
2043             max = vr1->max;
2044
2045           set_value_range (vr0, vr0->type, min, max);
2046         }
2047       else
2048         {
2049           /* The two ranges don't intersect, set the result to VR_VARYING.  */
2050           set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2051         }
2052     }
2053   else if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
2054     {
2055       /* Two anti-ranges meet only if they are both identical.  */
2056       if (compare_values (vr0->min, vr1->min) == 0
2057           && compare_values (vr0->max, vr1->max) == 0
2058           && compare_values (vr0->min, vr0->max) == 0)
2059         /* Nothing to do.  */ ;
2060       else
2061         set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2062     }
2063   else if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
2064     {
2065       /* A range [VAL1, VAL2] and an anti-range ~[VAL3, VAL4] meet
2066          only if the ranges have an empty intersection.  The result of
2067          the meet operation is the anti-range.  */
2068       if (!value_ranges_intersect_p (vr0, vr1))
2069         {
2070           if (vr1->type == VR_ANTI_RANGE)
2071             *vr0 = *vr1;
2072         }
2073       else
2074         set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2075     }
2076   else
2077     gcc_unreachable ();
2078 }
2079
2080       
2081 /* Visit all arguments for PHI node PHI that flow through executable
2082    edges.  If a valid value range can be derived from all the incoming
2083    value ranges, set a new range for the LHS of PHI.  */
2084
2085 static enum ssa_prop_result
2086 vrp_visit_phi_node (tree phi)
2087 {
2088   int i;
2089   tree lhs = PHI_RESULT (phi);
2090   value_range *lhs_vr = get_value_range (lhs);
2091   value_range vr_result = *lhs_vr;
2092
2093   if (dump_file && (dump_flags & TDF_DETAILS))
2094     {
2095       fprintf (dump_file, "\nVisiting PHI node: ");
2096       print_generic_expr (dump_file, phi, dump_flags);
2097     }
2098
2099   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
2100     {
2101       edge e = PHI_ARG_EDGE (phi, i);
2102
2103       if (dump_file && (dump_flags & TDF_DETAILS))
2104         {
2105           fprintf (dump_file,
2106               "\n    Argument #%d (%d -> %d %sexecutable)\n",
2107               i, e->src->index, e->dest->index,
2108               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
2109         }
2110
2111       if (e->flags & EDGE_EXECUTABLE)
2112         {
2113           tree arg = PHI_ARG_DEF (phi, i);
2114           value_range vr_arg;
2115
2116           if (TREE_CODE (arg) == SSA_NAME)
2117             vr_arg = *(get_value_range (arg));
2118           else
2119             {
2120               vr_arg.type = VR_RANGE;
2121               vr_arg.min = arg;
2122               vr_arg.max = arg;
2123             }
2124
2125           if (dump_file && (dump_flags & TDF_DETAILS))
2126             {
2127               fprintf (dump_file, "\t");
2128               print_generic_expr (dump_file, arg, dump_flags);
2129               fprintf (dump_file, "\n\tValue: ");
2130               dump_value_range (dump_file, &vr_arg);
2131               fprintf (dump_file, "\n");
2132             }
2133
2134           vrp_meet (&vr_result, &vr_arg);
2135
2136           if (vr_result.type == VR_VARYING)
2137             break;
2138         }
2139     }
2140
2141   if (vr_result.type == VR_VARYING)
2142     {
2143       set_value_range (lhs_vr, VR_VARYING, 0, 0);
2144       return SSA_PROP_VARYING;
2145     }
2146
2147   /* To prevent infinite iterations in the algorithm, derive ranges
2148      when the new value is slightly bigger or smaller than the
2149      previous one.  */
2150   if (lhs_vr->type == VR_RANGE)
2151     {
2152       if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
2153         {
2154           int cmp_min = compare_values (lhs_vr->min, vr_result.min);
2155           int cmp_max = compare_values (lhs_vr->max, vr_result.max);
2156
2157           /* If the new minimum is smaller or larger than the previous
2158              one, go all the way to -INF.  In the first case, to avoid
2159              iterating millions of times to reach -INF, and in the
2160              other case to avoid infinite bouncing between different
2161              minimums.  */
2162           if (cmp_min > 0 || cmp_min < 0)
2163             vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
2164
2165           /* Similarly, if the new maximum is smaller or larger than
2166              the previous one, go all the way to +INF.  */
2167           if (cmp_max < 0 || cmp_max > 0)
2168             vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
2169
2170           /* If we ended up with a (-INF, +INF) range, set it to
2171              VARYING.  */
2172           if (vr_result.min == TYPE_MIN_VALUE (TREE_TYPE (vr_result.min))
2173               && vr_result.max == TYPE_MAX_VALUE (TREE_TYPE (vr_result.max)))
2174             {
2175               set_value_range (lhs_vr, VR_VARYING, 0, 0);
2176               return SSA_PROP_VARYING;
2177             }
2178         }
2179     }
2180
2181   /* If the new range is different than the previous value, keep
2182      iterating.  */
2183   if (update_value_range (lhs_vr, vr_result.type, vr_result.min, vr_result.max))
2184     return SSA_PROP_INTERESTING;
2185
2186   /* Nothing changed, don't add outgoing edges.  */
2187   return SSA_PROP_NOT_INTERESTING;
2188 }
2189
2190
2191 /* Traverse all the blocks folding conditionals with known ranges.  */
2192
2193 static void
2194 vrp_finalize (void)
2195 {
2196   basic_block bb;
2197   int num_pred_folded = 0;
2198
2199   if (dump_file)
2200     {
2201       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
2202       dump_all_value_ranges (dump_file);
2203       fprintf (dump_file, "\n");
2204     }
2205
2206   FOR_EACH_BB (bb)
2207     {
2208       tree last = last_stmt (bb);
2209       if (last && TREE_CODE (last) == COND_EXPR)
2210         {
2211           tree val = vrp_evaluate_conditional (COND_EXPR_COND (last));
2212           if (val)
2213             {
2214               if (dump_file)
2215                 {
2216                   fprintf (dump_file, "Folding predicate ");
2217                   print_generic_expr (dump_file, COND_EXPR_COND (last), 0);
2218                   fprintf (dump_file, " to ");
2219                   print_generic_expr (dump_file, val, 0);
2220                   fprintf (dump_file, "\n");
2221                 }
2222
2223               num_pred_folded++;
2224               COND_EXPR_COND (last) = val;
2225               update_stmt (last);
2226             }
2227         }
2228     }
2229
2230   if (dump_file && (dump_flags & TDF_STATS))
2231     fprintf (dump_file, "\nNumber of predicates folded: %d\n\n",
2232              num_pred_folded);
2233 }
2234
2235
2236 /* Main entry point to VRP (Value Range Propagation).  This pass is
2237    loosely based on J. R. C. Patterson, ``Accurate Static Branch
2238    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
2239    Programming Language Design and Implementation, pp. 67-78, 1995.
2240    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
2241
2242    This is essentially an SSA-CCP pass modified to deal with ranges
2243    instead of constants.
2244
2245    TODO, the main difference between this pass and Patterson's is that
2246    we do not propagate edge probabilities.  We only compute whether
2247    edges can be taken or not.  That is, instead of having a spectrum
2248    of jump probabilities between 0 and 1, we only deal with 0, 1 and
2249    DON'T KNOW.  In the future, it may be worthwhile to propagate
2250    probabilities to aid branch prediction.  */
2251
2252 static void
2253 execute_vrp (void)
2254 {
2255   insert_range_assertions ();
2256
2257   cfg_loops = loop_optimizer_init (NULL);
2258   if (cfg_loops)
2259     scev_initialize (cfg_loops);
2260
2261   if (vrp_initialize ())
2262     {
2263       ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
2264       vrp_finalize ();
2265     }
2266
2267   if (cfg_loops)
2268     {
2269       scev_finalize ();
2270       loop_optimizer_finalize (cfg_loops, NULL);
2271       current_loops = NULL;
2272     }
2273
2274   remove_range_assertions ();
2275 }
2276
2277 static bool
2278 gate_vrp (void)
2279 {
2280   return flag_tree_vrp != 0;
2281 }
2282
2283 struct tree_opt_pass pass_vrp =
2284 {
2285   "vrp",                                /* name */
2286   gate_vrp,                             /* gate */
2287   execute_vrp,                          /* execute */
2288   NULL,                                 /* sub */
2289   NULL,                                 /* next */
2290   0,                                    /* static_pass_number */
2291   TV_TREE_VRP,                          /* tv_id */
2292   PROP_ssa | PROP_alias,                /* properties_required */
2293   0,                                    /* properties_provided */
2294   0,                                    /* properties_destroyed */
2295   0,                                    /* todo_flags_start */
2296   TODO_cleanup_cfg
2297     | TODO_ggc_collect
2298     | TODO_verify_ssa
2299     | TODO_dump_func
2300     | TODO_update_ssa,                  /* todo_flags_finish */
2301   0                                     /* letter */
2302 };