OSDN Git Service

e040f41bdfa21c9d7fdb0cb1360a69d698a83191
[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 /* Wrapper around int_const_binop.  If the operation overflows and we
973    are not using wrapping arithmetic, then adjust the result to be
974    -INF or +INF depending on CODE, VAL1 and VAL2.  */
975
976 static inline tree
977 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
978 {
979   tree res;
980
981   if (flag_wrapv)
982     return int_const_binop (code, val1, val2, 0);
983
984   /* If we are not using wrapping arithmetic, operate symbolically
985      on -INF and +INF.  */
986   res = int_const_binop (code, val1, val2, 0);
987
988   /* If the operation overflowed but neither VAL1 nor VAL2 are
989      overflown, return -INF or +INF depending on the operation
990      and the combination of signs of the operands.  */
991   if (TREE_OVERFLOW (res)
992       && !TREE_OVERFLOW (val1)
993       && !TREE_OVERFLOW (val2))
994     {
995       int sgn1 = tree_int_cst_sgn (val1);
996       int sgn2 = tree_int_cst_sgn (val2);
997
998       /* Notice that we only need to handle the restricted set of
999          operations handled by extract_range_from_binary_expr.
1000          Among them, only multiplication, addition and subtraction
1001          can yield overflow without overflown operands because we
1002          are working with integral types only... except in the
1003          case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1004          for division too.  */
1005
1006       /* For multiplication, the sign of the overflow is given
1007          by the comparison of the signs of the operands.  */
1008       if ((code == MULT_EXPR && sgn1 == sgn2)
1009           /* For addition, the operands must be of the same sign
1010              to yield an overflow.  Its sign is therefore that
1011              of one of the operands, for example the first.  */
1012           || (code == PLUS_EXPR && sgn1 > 0)
1013           /* For subtraction, the operands must be of different
1014              signs to yield an overflow.  Its sign is therefore
1015              that of the first operand or the opposite of that
1016              of the second operand.  */
1017           || (code == MINUS_EXPR && sgn1 > 0)
1018           /* For division, the only case is -INF / -1 = +INF.  */
1019           || code == TRUNC_DIV_EXPR
1020           || code == FLOOR_DIV_EXPR
1021           || code == CEIL_DIV_EXPR
1022           || code == EXACT_DIV_EXPR
1023           || code == ROUND_DIV_EXPR)
1024         return TYPE_MAX_VALUE (TREE_TYPE (res));
1025       else
1026         return TYPE_MIN_VALUE (TREE_TYPE (res));
1027     }
1028
1029   return res;
1030 }
1031
1032
1033 /* Extract range information from a binary expression EXPR based on
1034    the ranges of each of its operands and the expression code.  */
1035
1036 static void
1037 extract_range_from_binary_expr (value_range_t *vr, tree expr)
1038 {
1039   enum tree_code code = TREE_CODE (expr);
1040   tree op0, op1, min, max;
1041   int cmp;
1042   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
1043   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
1044
1045   /* Not all binary expressions can be applied to ranges in a
1046      meaningful way.  Handle only arithmetic operations.  */
1047   if (code != PLUS_EXPR
1048       && code != MINUS_EXPR
1049       && code != MULT_EXPR
1050       && code != TRUNC_DIV_EXPR
1051       && code != FLOOR_DIV_EXPR
1052       && code != CEIL_DIV_EXPR
1053       && code != EXACT_DIV_EXPR
1054       && code != ROUND_DIV_EXPR
1055       && code != MIN_EXPR
1056       && code != MAX_EXPR
1057       && code != TRUTH_ANDIF_EXPR
1058       && code != TRUTH_ORIF_EXPR
1059       && code != TRUTH_AND_EXPR
1060       && code != TRUTH_OR_EXPR
1061       && code != TRUTH_XOR_EXPR)
1062     {
1063       set_value_range_to_varying (vr);
1064       return;
1065     }
1066
1067   /* Get value ranges for each operand.  For constant operands, create
1068      a new value range with the operand to simplify processing.  */
1069   op0 = TREE_OPERAND (expr, 0);
1070   if (TREE_CODE (op0) == SSA_NAME)
1071     vr0 = *(get_value_range (op0));
1072   else if (is_gimple_min_invariant (op0))
1073     set_value_range (&vr0, VR_RANGE, op0, op0, NULL);
1074   else
1075     set_value_range_to_varying (&vr0);
1076
1077   op1 = TREE_OPERAND (expr, 1);
1078   if (TREE_CODE (op1) == SSA_NAME)
1079     vr1 = *(get_value_range (op1));
1080   else if (is_gimple_min_invariant (op1))
1081     set_value_range (&vr1, VR_RANGE, op1, op1, NULL);
1082   else
1083     set_value_range_to_varying (&vr1);
1084
1085   /* If either range is UNDEFINED, so is the result.  */
1086   if (vr0.type == VR_UNDEFINED || vr1.type == VR_UNDEFINED)
1087     {
1088       set_value_range_to_undefined (vr);
1089       return;
1090     }
1091
1092   /* Refuse to operate on VARYING ranges, ranges of different kinds
1093      and symbolic ranges.  TODO, we may be able to derive anti-ranges
1094      in some cases.  */
1095   if (vr0.type == VR_VARYING
1096       || vr1.type == VR_VARYING
1097       || vr0.type != vr1.type
1098       || symbolic_range_p (&vr0)
1099       || symbolic_range_p (&vr1))
1100     {
1101       set_value_range_to_varying (vr);
1102       return;
1103     }
1104
1105   /* Now evaluate the expression to determine the new range.  */
1106   if (POINTER_TYPE_P (TREE_TYPE (expr))
1107       || POINTER_TYPE_P (TREE_TYPE (op0))
1108       || POINTER_TYPE_P (TREE_TYPE (op1)))
1109     {
1110       /* For pointer types, we are really only interested in asserting
1111          whether the expression evaluates to non-NULL.  FIXME, we used
1112          to gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR), but
1113          ivopts is generating expressions with pointer multiplication
1114          in them.  */
1115       if (code == PLUS_EXPR)
1116         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1117       else
1118         {
1119           /* Subtracting from a pointer, may yield 0, so just drop the
1120              resulting range to varying.  */
1121           set_value_range_to_varying (vr);
1122         }
1123
1124       return;
1125     }
1126
1127   /* For integer ranges, apply the operation to each end of the
1128      range and see what we end up with.  */
1129   if (code == TRUTH_ANDIF_EXPR
1130       || code == TRUTH_ORIF_EXPR
1131       || code == TRUTH_AND_EXPR
1132       || code == TRUTH_OR_EXPR
1133       || code == TRUTH_XOR_EXPR)
1134     {
1135       /* Boolean expressions cannot be folded with int_const_binop.  */
1136       min = fold_binary (code, TREE_TYPE (expr), vr0.min, vr1.min);
1137       max = fold_binary (code, TREE_TYPE (expr), vr0.max, vr1.max);
1138     }
1139   else if (code == PLUS_EXPR
1140            || code == MIN_EXPR
1141            || code == MAX_EXPR)
1142     {
1143       /* For operations that make the resulting range directly
1144          proportional to the original ranges, apply the operation to
1145          the same end of each range.  */
1146       min = vrp_int_const_binop (code, vr0.min, vr1.min);
1147       max = vrp_int_const_binop (code, vr0.max, vr1.max);
1148     }
1149   else if (code == MULT_EXPR
1150            || code == TRUNC_DIV_EXPR
1151            || code == FLOOR_DIV_EXPR
1152            || code == CEIL_DIV_EXPR
1153            || code == EXACT_DIV_EXPR
1154            || code == ROUND_DIV_EXPR)
1155     {
1156       tree val[4];
1157       size_t i;
1158
1159       /* Multiplications and divisions are a bit tricky to handle,
1160          depending on the mix of signs we have in the two ranges, we
1161          need to operate on different values to get the minimum and
1162          maximum values for the new range.  One approach is to figure
1163          out all the variations of range combinations and do the
1164          operations.
1165
1166          However, this involves several calls to compare_values and it
1167          is pretty convoluted.  It's simpler to do the 4 operations
1168          (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1169          MAX1) and then figure the smallest and largest values to form
1170          the new range.  */
1171
1172       /* Divisions by zero result in a VARYING value.  */
1173       if (code != MULT_EXPR && range_includes_zero_p (&vr1))
1174         {
1175           set_value_range_to_varying (vr);
1176           return;
1177         }
1178
1179       /* Compute the 4 cross operations.  */
1180       val[0] = vrp_int_const_binop (code, vr0.min, vr1.min);
1181
1182       val[1] = (vr1.max != vr1.min)
1183                ? vrp_int_const_binop (code, vr0.min, vr1.max)
1184                : NULL_TREE;
1185
1186       val[2] = (vr0.max != vr0.min)
1187                ? vrp_int_const_binop (code, vr0.max, vr1.min)
1188                : NULL_TREE;
1189
1190       val[3] = (vr0.min != vr1.min && vr0.max != vr1.max)
1191                ? vrp_int_const_binop (code, vr0.max, vr1.max)
1192                : NULL_TREE;
1193
1194       /* Set MIN to the minimum of VAL[i] and MAX to the maximum
1195          of VAL[i].  */
1196       min = val[0];
1197       max = val[0];
1198       for (i = 1; i < 4; i++)
1199         {
1200           if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
1201             break;
1202
1203           if (val[i])
1204             {
1205               if (TREE_OVERFLOW (val[i]))
1206                 {
1207                   /* If we found an overflowed value, set MIN and MAX
1208                      to it so that we set the resulting range to
1209                      VARYING.  */
1210                   min = max = val[i];
1211                   break;
1212                 }
1213
1214               if (compare_values (val[i], min) == -1)
1215                 min = val[i];
1216
1217               if (compare_values (val[i], max) == 1)
1218                 max = val[i];
1219             }
1220         }
1221     }
1222   else if (code == MINUS_EXPR)
1223     {
1224       /* For MINUS_EXPR, apply the operation to the opposite ends of
1225          each range.  */
1226       min = vrp_int_const_binop (code, vr0.min, vr1.max);
1227       max = vrp_int_const_binop (code, vr0.max, vr1.min);
1228     }
1229   else
1230     gcc_unreachable ();
1231
1232   /* If either MIN or MAX overflowed, then set the resulting range to
1233      VARYING.  */
1234   if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
1235     {
1236       set_value_range_to_varying (vr);
1237       return;
1238     }
1239
1240   cmp = compare_values (min, max);
1241   if (cmp == -2 || cmp == 1)
1242     {
1243       /* If the new range has its limits swapped around (MIN > MAX),
1244          then the operation caused one of them to wrap around, mark
1245          the new range VARYING.  */
1246       set_value_range_to_varying (vr);
1247     }
1248   else
1249     set_value_range (vr, vr0.type, min, max, NULL);
1250 }
1251
1252
1253 /* Extract range information from a unary expression EXPR based on
1254    the range of its operand and the expression code.  */
1255
1256 static void
1257 extract_range_from_unary_expr (value_range_t *vr, tree expr)
1258 {
1259   enum tree_code code = TREE_CODE (expr);
1260   tree min, max, op0;
1261   int cmp;
1262   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
1263
1264   /* Refuse to operate on certain unary expressions for which we
1265      cannot easily determine a resulting range.  */
1266   if (code == FIX_TRUNC_EXPR
1267       || code == FIX_CEIL_EXPR
1268       || code == FIX_FLOOR_EXPR
1269       || code == FIX_ROUND_EXPR
1270       || code == FLOAT_EXPR
1271       || code == BIT_NOT_EXPR
1272       || code == NON_LVALUE_EXPR
1273       || code == CONJ_EXPR)
1274     {
1275       set_value_range_to_varying (vr);
1276       return;
1277     }
1278
1279   /* Get value ranges for the operand.  For constant operands, create
1280      a new value range with the operand to simplify processing.  */
1281   op0 = TREE_OPERAND (expr, 0);
1282   if (TREE_CODE (op0) == SSA_NAME)
1283     vr0 = *(get_value_range (op0));
1284   else if (is_gimple_min_invariant (op0))
1285     set_value_range (&vr0, VR_RANGE, op0, op0, NULL);
1286   else
1287     set_value_range_to_varying (&vr0);
1288
1289   /* If VR0 is UNDEFINED, so is the result.  */
1290   if (vr0.type == VR_UNDEFINED)
1291     {
1292       set_value_range_to_undefined (vr);
1293       return;
1294     }
1295
1296   /* Refuse to operate on varying and symbolic ranges.  Also, if the
1297      operand is neither a pointer nor an integral type, set the
1298      resulting range to VARYING.  TODO, in some cases we may be able
1299      to derive anti-ranges (like non-zero values).  */
1300   if (vr0.type == VR_VARYING
1301       || (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
1302           && !POINTER_TYPE_P (TREE_TYPE (op0)))
1303       || symbolic_range_p (&vr0))
1304     {
1305       set_value_range_to_varying (vr);
1306       return;
1307     }
1308
1309   /* If the expression involves pointers, we are only interested in
1310      determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
1311   if (POINTER_TYPE_P (TREE_TYPE (expr)) || POINTER_TYPE_P (TREE_TYPE (op0)))
1312     {
1313       if (range_is_nonnull (&vr0) || expr_computes_nonzero (expr))
1314         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1315       else if (range_is_null (&vr0))
1316         set_value_range_to_null (vr, TREE_TYPE (expr));
1317       else
1318         set_value_range_to_varying (vr);
1319
1320       return;
1321     }
1322
1323   /* Handle unary expressions on integer ranges.  */
1324   if (code == NOP_EXPR || code == CONVERT_EXPR)
1325     {
1326       tree inner_type = TREE_TYPE (op0);
1327       tree outer_type = TREE_TYPE (expr);
1328
1329       /* When converting types of different sizes, set the result to
1330          VARYING.  Things like sign extensions and precision loss may
1331          change the range.  For instance, if x_3 is of type 'long long
1332          int' and 'y_5 = (unsigned short) x_3', if x_3 is ~[0, 0], it
1333          is impossible to know at compile time whether y_5 will be
1334          ~[0, 0].  */
1335       if (TYPE_SIZE (inner_type) != TYPE_SIZE (outer_type)
1336           || TYPE_PRECISION (inner_type) != TYPE_PRECISION (outer_type))
1337         {
1338           set_value_range_to_varying (vr);
1339           return;
1340         }
1341     }
1342
1343   /* Apply the operation to each end of the range and see what we end
1344      up with.  */
1345   if (code == NEGATE_EXPR
1346       && !TYPE_UNSIGNED (TREE_TYPE (expr)))
1347     {
1348       /* Negating an anti-range doesn't really do anything to it.  The
1349          new range will also not take on the same range of values
1350          excluded by the original anti-range.  */
1351       if (vr0.type == VR_ANTI_RANGE)
1352         {
1353           copy_value_range (vr, &vr0);
1354           return;
1355         }
1356
1357       /* NEGATE_EXPR flips the range around.  */
1358       min = (vr0.max == TYPE_MAX_VALUE (TREE_TYPE (expr)))
1359             ? TYPE_MIN_VALUE (TREE_TYPE (expr))
1360             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1361
1362       max = (vr0.min == TYPE_MIN_VALUE (TREE_TYPE (expr)))
1363             ? TYPE_MAX_VALUE (TREE_TYPE (expr))
1364             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1365     }
1366   else if (code == ABS_EXPR
1367            && !TYPE_UNSIGNED (TREE_TYPE (expr)))
1368     {
1369       /* ABS_EXPR may flip the range around, if the original range
1370          included negative values.  */
1371       min = (vr0.min == TYPE_MIN_VALUE (TREE_TYPE (expr)))
1372             ? TYPE_MAX_VALUE (TREE_TYPE (expr))
1373             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1374
1375       max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1376
1377       /* If the range was reversed, swap MIN and MAX.  */
1378       if (compare_values (min, max) == 1)
1379         {
1380           tree t = min;
1381           min = max;
1382           max = t;
1383         }
1384     }
1385   else
1386     {
1387       /* Otherwise, operate on each end of the range.  */
1388       min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1389       max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1390     }
1391
1392   cmp = compare_values (min, max);
1393   if (cmp == -2 || cmp == 1)
1394     {
1395       /* If the new range has its limits swapped around (MIN > MAX),
1396          then the operation caused one of them to wrap around, mark
1397          the new range VARYING.  */
1398       set_value_range_to_varying (vr);
1399     }
1400   else
1401     set_value_range (vr, vr0.type, min, max, NULL);
1402 }
1403
1404
1405 /* Extract range information from a comparison expression EXPR based
1406    on the range of its operand and the expression code.  */
1407
1408 static void
1409 extract_range_from_comparison (value_range_t *vr, tree expr)
1410 {
1411   tree val = vrp_evaluate_conditional (expr, false);
1412   if (val)
1413     {
1414       /* Since this expression was found on the RHS of an assignment,
1415          its type may be different from _Bool.  Convert VAL to EXPR's
1416          type.  */
1417       val = fold_convert (TREE_TYPE (expr), val);
1418       set_value_range (vr, VR_RANGE, val, val, vr->equiv);
1419     }
1420   else
1421     set_value_range_to_varying (vr);
1422 }
1423
1424
1425 /* Try to compute a useful range out of expression EXPR and store it
1426    in *VR.  */
1427
1428 static void
1429 extract_range_from_expr (value_range_t *vr, tree expr)
1430 {
1431   enum tree_code code = TREE_CODE (expr);
1432
1433   if (code == ASSERT_EXPR)
1434     extract_range_from_assert (vr, expr);
1435   else if (code == SSA_NAME)
1436     extract_range_from_ssa_name (vr, expr);
1437   else if (TREE_CODE_CLASS (code) == tcc_binary
1438            || code == TRUTH_ANDIF_EXPR
1439            || code == TRUTH_ORIF_EXPR
1440            || code == TRUTH_AND_EXPR
1441            || code == TRUTH_OR_EXPR
1442            || code == TRUTH_XOR_EXPR)
1443     extract_range_from_binary_expr (vr, expr);
1444   else if (TREE_CODE_CLASS (code) == tcc_unary)
1445     extract_range_from_unary_expr (vr, expr);
1446   else if (TREE_CODE_CLASS (code) == tcc_comparison)
1447     extract_range_from_comparison (vr, expr);
1448   else if (vrp_expr_computes_nonzero (expr))
1449     set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1450   else if (is_gimple_min_invariant (expr))
1451     set_value_range (vr, VR_RANGE, expr, expr, NULL);
1452   else
1453     set_value_range_to_varying (vr);
1454 }
1455
1456 /* Given a range VR, a LOOP and a variable VAR, determine whether it
1457    would be profitable to adjust VR using scalar evolution information
1458    for VAR.  If so, update VR with the new limits.  */
1459
1460 static void
1461 adjust_range_with_scev (value_range_t *vr, struct loop *loop, tree stmt,
1462                         tree var)
1463 {
1464   tree init, step, chrec;
1465   bool init_is_max;
1466
1467   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
1468      better opportunities than a regular range, but I'm not sure.  */
1469   if (vr->type == VR_ANTI_RANGE)
1470     return;
1471
1472   chrec = analyze_scalar_evolution (loop, var);
1473   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
1474     return;
1475
1476   init = CHREC_LEFT (chrec);
1477   step = CHREC_RIGHT (chrec);
1478
1479   /* If STEP is symbolic, we can't know whether INIT will be the
1480      minimum or maximum value in the range.  */
1481   if (!is_gimple_min_invariant (step))
1482     return;
1483
1484   /* Do not adjust ranges when chrec may wrap.  */
1485   if (scev_probably_wraps_p (chrec_type (chrec), init, step, stmt,
1486                              cfg_loops->parray[CHREC_VARIABLE (chrec)],
1487                              &init_is_max))
1488     return;
1489
1490   if (!POINTER_TYPE_P (TREE_TYPE (init))
1491       && (vr->type == VR_VARYING || vr->type == VR_UNDEFINED))
1492     {
1493       /* For VARYING or UNDEFINED ranges, just about anything we get
1494          from scalar evolutions should be better.  */
1495       if (init_is_max)
1496         set_value_range (vr, VR_RANGE, TYPE_MIN_VALUE (TREE_TYPE (init)),
1497                          init, vr->equiv);
1498       else
1499         set_value_range (vr, VR_RANGE, init, TYPE_MAX_VALUE (TREE_TYPE (init)),
1500                          vr->equiv);
1501     }
1502   else if (vr->type == VR_RANGE)
1503     {
1504       tree min = vr->min;
1505       tree max = vr->max;
1506
1507       if (init_is_max)
1508         {
1509           /* INIT is the maximum value.  If INIT is lower than VR->MAX
1510              but no smaller than VR->MIN, set VR->MAX to INIT.  */
1511           if (compare_values (init, max) == -1)
1512             {
1513               max = init;
1514
1515               /* If we just created an invalid range with the minimum
1516                  greater than the maximum, take the minimum all the
1517                  way to -INF.  */
1518               if (compare_values (min, max) == 1)
1519                 min = TYPE_MIN_VALUE (TREE_TYPE (min));
1520             }
1521         }
1522       else
1523         {
1524           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
1525           if (compare_values (init, min) == 1)
1526             {
1527               min = init;
1528
1529               /* If we just created an invalid range with the minimum
1530                  greater than the maximum, take the maximum all the
1531                  way to +INF.  */
1532               if (compare_values (min, max) == 1)
1533                 max = TYPE_MAX_VALUE (TREE_TYPE (max));
1534             }
1535         }
1536
1537       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
1538     }
1539 }
1540
1541
1542 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
1543    
1544    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
1545      all the values in the ranges.
1546
1547    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
1548
1549    - Return NULL_TREE if it is not always possible to determine the
1550      value of the comparison.  */
1551
1552
1553 static tree
1554 compare_ranges (enum tree_code comp, value_range_t *vr0, value_range_t *vr1)
1555 {
1556   /* VARYING or UNDEFINED ranges cannot be compared.  */
1557   if (vr0->type == VR_VARYING
1558       || vr0->type == VR_UNDEFINED
1559       || vr1->type == VR_VARYING
1560       || vr1->type == VR_UNDEFINED)
1561     return NULL_TREE;
1562
1563   /* Anti-ranges need to be handled separately.  */
1564   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
1565     {
1566       /* If both are anti-ranges, then we cannot compute any
1567          comparison.  */
1568       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
1569         return NULL_TREE;
1570
1571       /* These comparisons are never statically computable.  */
1572       if (comp == GT_EXPR
1573           || comp == GE_EXPR
1574           || comp == LT_EXPR
1575           || comp == LE_EXPR)
1576         return NULL_TREE;
1577
1578       /* Equality can be computed only between a range and an
1579          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
1580       if (vr0->type == VR_RANGE)
1581         {
1582           /* To simplify processing, make VR0 the anti-range.  */
1583           value_range_t *tmp = vr0;
1584           vr0 = vr1;
1585           vr1 = tmp;
1586         }
1587
1588       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
1589
1590       if (compare_values (vr0->min, vr1->min) == 0
1591           && compare_values (vr0->max, vr1->max) == 0)
1592         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1593
1594       return NULL_TREE;
1595     }
1596
1597   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
1598      operands around and change the comparison code.  */
1599   if (comp == GT_EXPR || comp == GE_EXPR)
1600     {
1601       value_range_t *tmp;
1602       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
1603       tmp = vr0;
1604       vr0 = vr1;
1605       vr1 = tmp;
1606     }
1607
1608   if (comp == EQ_EXPR)
1609     {
1610       /* Equality may only be computed if both ranges represent
1611          exactly one value.  */
1612       if (compare_values (vr0->min, vr0->max) == 0
1613           && compare_values (vr1->min, vr1->max) == 0)
1614         {
1615           int cmp_min = compare_values (vr0->min, vr1->min);
1616           int cmp_max = compare_values (vr0->max, vr1->max);
1617           if (cmp_min == 0 && cmp_max == 0)
1618             return boolean_true_node;
1619           else if (cmp_min != -2 && cmp_max != -2)
1620             return boolean_false_node;
1621         }
1622
1623       return NULL_TREE;
1624     }
1625   else if (comp == NE_EXPR)
1626     {
1627       int cmp1, cmp2;
1628
1629       /* If VR0 is completely to the left or completely to the right
1630          of VR1, they are always different.  Notice that we need to
1631          make sure that both comparisons yield similar results to
1632          avoid comparing values that cannot be compared at
1633          compile-time.  */
1634       cmp1 = compare_values (vr0->max, vr1->min);
1635       cmp2 = compare_values (vr0->min, vr1->max);
1636       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1637         return boolean_true_node;
1638
1639       /* If VR0 and VR1 represent a single value and are identical,
1640          return false.  */
1641       else if (compare_values (vr0->min, vr0->max) == 0
1642                && compare_values (vr1->min, vr1->max) == 0
1643                && compare_values (vr0->min, vr1->min) == 0
1644                && compare_values (vr0->max, vr1->max) == 0)
1645         return boolean_false_node;
1646
1647       /* Otherwise, they may or may not be different.  */
1648       else
1649         return NULL_TREE;
1650     }
1651   else if (comp == LT_EXPR || comp == LE_EXPR)
1652     {
1653       int tst;
1654
1655       /* If VR0 is to the left of VR1, return true.  */
1656       tst = compare_values (vr0->max, vr1->min);
1657       if ((comp == LT_EXPR && tst == -1)
1658           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1659         return boolean_true_node;
1660
1661       /* If VR0 is to the right of VR1, return false.  */
1662       tst = compare_values (vr0->min, vr1->max);
1663       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1664           || (comp == LE_EXPR && tst == 1))
1665         return boolean_false_node;
1666
1667       /* Otherwise, we don't know.  */
1668       return NULL_TREE;
1669     }
1670     
1671   gcc_unreachable ();
1672 }
1673
1674
1675 /* Given a value range VR, a value VAL and a comparison code COMP, return
1676    BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
1677    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
1678    always returns false.  Return NULL_TREE if it is not always
1679    possible to determine the value of the comparison.  */
1680
1681 static tree
1682 compare_range_with_value (enum tree_code comp, value_range_t *vr, tree val)
1683 {
1684   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
1685     return NULL_TREE;
1686
1687   /* Anti-ranges need to be handled separately.  */
1688   if (vr->type == VR_ANTI_RANGE)
1689     {
1690       /* For anti-ranges, the only predicates that we can compute at
1691          compile time are equality and inequality.  */
1692       if (comp == GT_EXPR
1693           || comp == GE_EXPR
1694           || comp == LT_EXPR
1695           || comp == LE_EXPR)
1696         return NULL_TREE;
1697
1698       /* ~[VAL, VAL] == VAL is always false.  */
1699       if (compare_values (vr->min, val) == 0
1700           && compare_values (vr->max, val) == 0)
1701         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1702
1703       return NULL_TREE;
1704     }
1705
1706   if (comp == EQ_EXPR)
1707     {
1708       /* EQ_EXPR may only be computed if VR represents exactly
1709          one value.  */
1710       if (compare_values (vr->min, vr->max) == 0)
1711         {
1712           int cmp = compare_values (vr->min, val);
1713           if (cmp == 0)
1714             return boolean_true_node;
1715           else if (cmp == -1 || cmp == 1 || cmp == 2)
1716             return boolean_false_node;
1717         }
1718       else if (compare_values (val, vr->min) == -1
1719                || compare_values (vr->max, val) == -1)
1720         return boolean_false_node;
1721
1722       return NULL_TREE;
1723     }
1724   else if (comp == NE_EXPR)
1725     {
1726       /* If VAL is not inside VR, then they are always different.  */
1727       if (compare_values (vr->max, val) == -1
1728           || compare_values (vr->min, val) == 1)
1729         return boolean_true_node;
1730
1731       /* If VR represents exactly one value equal to VAL, then return
1732          false.  */
1733       if (compare_values (vr->min, vr->max) == 0
1734           && compare_values (vr->min, val) == 0)
1735         return boolean_false_node;
1736
1737       /* Otherwise, they may or may not be different.  */
1738       return NULL_TREE;
1739     }
1740   else if (comp == LT_EXPR || comp == LE_EXPR)
1741     {
1742       int tst;
1743
1744       /* If VR is to the left of VAL, return true.  */
1745       tst = compare_values (vr->max, val);
1746       if ((comp == LT_EXPR && tst == -1)
1747           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1748         return boolean_true_node;
1749
1750       /* If VR is to the right of VAL, return false.  */
1751       tst = compare_values (vr->min, val);
1752       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1753           || (comp == LE_EXPR && tst == 1))
1754         return boolean_false_node;
1755
1756       /* Otherwise, we don't know.  */
1757       return NULL_TREE;
1758     }
1759   else if (comp == GT_EXPR || comp == GE_EXPR)
1760     {
1761       int tst;
1762
1763       /* If VR is to the right of VAL, return true.  */
1764       tst = compare_values (vr->min, val);
1765       if ((comp == GT_EXPR && tst == 1)
1766           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1767         return boolean_true_node;
1768
1769       /* If VR is to the left of VAL, return false.  */
1770       tst = compare_values (vr->max, val);
1771       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1772           || (comp == GE_EXPR && tst == -1))
1773         return boolean_false_node;
1774
1775       /* Otherwise, we don't know.  */
1776       return NULL_TREE;
1777     }
1778
1779   gcc_unreachable ();
1780 }
1781
1782
1783 /* Debugging dumps.  */
1784
1785 void dump_value_range (FILE *, value_range_t *);
1786 void debug_value_range (value_range_t *);
1787 void dump_all_value_ranges (FILE *);
1788 void debug_all_value_ranges (void);
1789 void dump_vr_equiv (FILE *, bitmap);
1790 void debug_vr_equiv (bitmap);
1791
1792
1793 /* Dump value range VR to FILE.  */
1794
1795 void
1796 dump_value_range (FILE *file, value_range_t *vr)
1797 {
1798   if (vr == NULL)
1799     fprintf (file, "[]");
1800   else if (vr->type == VR_UNDEFINED)
1801     fprintf (file, "UNDEFINED");
1802   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1803     {
1804       tree type = TREE_TYPE (vr->min);
1805
1806       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1807
1808       if (INTEGRAL_TYPE_P (type)
1809           && !TYPE_UNSIGNED (type)
1810           && vr->min == TYPE_MIN_VALUE (type))
1811         fprintf (file, "-INF");
1812       else
1813         print_generic_expr (file, vr->min, 0);
1814
1815       fprintf (file, ", ");
1816
1817       if (INTEGRAL_TYPE_P (type)
1818           && vr->max == TYPE_MAX_VALUE (type))
1819         fprintf (file, "+INF");
1820       else
1821         print_generic_expr (file, vr->max, 0);
1822
1823       fprintf (file, "]");
1824
1825       if (vr->equiv)
1826         {
1827           bitmap_iterator bi;
1828           unsigned i, c = 0;
1829
1830           fprintf (file, "  EQUIVALENCES: { ");
1831
1832           EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
1833             {
1834               print_generic_expr (file, ssa_name (i), 0);
1835               fprintf (file, " ");
1836               c++;
1837             }
1838
1839           fprintf (file, "} (%u elements)", c);
1840         }
1841     }
1842   else if (vr->type == VR_VARYING)
1843     fprintf (file, "VARYING");
1844   else
1845     fprintf (file, "INVALID RANGE");
1846 }
1847
1848
1849 /* Dump value range VR to stderr.  */
1850
1851 void
1852 debug_value_range (value_range_t *vr)
1853 {
1854   dump_value_range (stderr, vr);
1855 }
1856
1857
1858 /* Dump value ranges of all SSA_NAMEs to FILE.  */
1859
1860 void
1861 dump_all_value_ranges (FILE *file)
1862 {
1863   size_t i;
1864
1865   for (i = 0; i < num_ssa_names; i++)
1866     {
1867       if (vr_value[i])
1868         {
1869           print_generic_expr (file, ssa_name (i), 0);
1870           fprintf (file, ": ");
1871           dump_value_range (file, vr_value[i]);
1872           fprintf (file, "\n");
1873         }
1874     }
1875
1876   fprintf (file, "\n");
1877 }
1878
1879
1880 /* Dump all value ranges to stderr.  */
1881
1882 void
1883 debug_all_value_ranges (void)
1884 {
1885   dump_all_value_ranges (stderr);
1886 }
1887
1888
1889 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1890    create a new SSA name N and return the assertion assignment
1891    'V = ASSERT_EXPR <V, V OP W>'.  */
1892
1893 static tree
1894 build_assert_expr_for (tree cond, tree v)
1895 {
1896   tree n, assertion;
1897
1898   gcc_assert (TREE_CODE (v) == SSA_NAME);
1899   n = duplicate_ssa_name (v, NULL_TREE);
1900
1901   if (COMPARISON_CLASS_P (cond))
1902     {
1903       tree a = build (ASSERT_EXPR, TREE_TYPE (v), v, cond); 
1904       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, a);
1905     }
1906   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1907     {
1908       /* Given !V, build the assignment N = false.  */
1909       tree op0 = TREE_OPERAND (cond, 0);
1910       gcc_assert (op0 == v);
1911       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_false_node);
1912     }
1913   else if (TREE_CODE (cond) == SSA_NAME)
1914     {
1915       /* Given V, build the assignment N = true.  */
1916       gcc_assert (v == cond);
1917       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_true_node);
1918     }
1919   else
1920     gcc_unreachable ();
1921
1922   SSA_NAME_DEF_STMT (n) = assertion;
1923
1924   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1925      operand of the ASSERT_EXPR. Register the new name and the old one
1926      in the replacement table so that we can fix the SSA web after
1927      adding all the ASSERT_EXPRs.  */
1928   register_new_name_mapping (n, v);
1929
1930   return assertion;
1931 }
1932
1933
1934 /* Return false if EXPR is a predicate expression involving floating
1935    point values.  */
1936
1937 static inline bool
1938 fp_predicate (tree expr)
1939 {
1940   return (COMPARISON_CLASS_P (expr)
1941           && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0))));
1942 }
1943
1944
1945 /* If the range of values taken by OP can be inferred after STMT executes,
1946    return the comparison code (COMP_CODE_P) and value (VAL_P) that
1947    describes the inferred range.  Return true if a range could be
1948    inferred.  */
1949
1950 static bool
1951 infer_value_range (tree stmt, tree op, enum tree_code *comp_code_p, tree *val_p)
1952 {
1953   *val_p = NULL_TREE;
1954   *comp_code_p = ERROR_MARK;
1955
1956   /* Do not attempt to infer anything in names that flow through
1957      abnormal edges.  */
1958   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1959     return false;
1960
1961   /* Similarly, don't infer anything from statements that may throw
1962      exceptions.  */
1963   if (tree_could_throw_p (stmt))
1964     return false;
1965
1966   if (POINTER_TYPE_P (TREE_TYPE (op)))
1967     {
1968       bool is_store;
1969       unsigned num_uses, num_derefs;
1970
1971       count_uses_and_derefs (op, stmt, &num_uses, &num_derefs, &is_store);
1972       if (num_derefs > 0 && flag_delete_null_pointer_checks)
1973         {
1974           /* We can only assume that a pointer dereference will yield
1975              non-NULL if -fdelete-null-pointer-checks is enabled.  */
1976           *val_p = build_int_cst (TREE_TYPE (op), 0);
1977           *comp_code_p = NE_EXPR;
1978           return true;
1979         }
1980     }
1981
1982   return false;
1983 }
1984
1985
1986 void dump_asserts_for (FILE *, tree);
1987 void debug_asserts_for (tree);
1988 void dump_all_asserts (FILE *);
1989 void debug_all_asserts (void);
1990
1991 /* Dump all the registered assertions for NAME to FILE.  */
1992
1993 void
1994 dump_asserts_for (FILE *file, tree name)
1995 {
1996   assert_locus_t loc;
1997
1998   fprintf (file, "Assertions to be inserted for ");
1999   print_generic_expr (file, name, 0);
2000   fprintf (file, "\n");
2001
2002   loc = asserts_for[SSA_NAME_VERSION (name)];
2003   while (loc)
2004     {
2005       fprintf (file, "\t");
2006       print_generic_expr (file, bsi_stmt (loc->si), 0);
2007       fprintf (file, "\n\tBB #%d", loc->bb->index);
2008       if (loc->e)
2009         {
2010           fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2011                    loc->e->dest->index);
2012           dump_edge_info (file, loc->e, 0);
2013         }
2014       fprintf (file, "\n\tPREDICATE: ");
2015       print_generic_expr (file, name, 0);
2016       fprintf (file, " %s ", tree_code_name[(int)loc->comp_code]);
2017       print_generic_expr (file, loc->val, 0);
2018       fprintf (file, "\n\n");
2019       loc = loc->next;
2020     }
2021
2022   fprintf (file, "\n");
2023 }
2024
2025
2026 /* Dump all the registered assertions for NAME to stderr.  */
2027
2028 void
2029 debug_asserts_for (tree name)
2030 {
2031   dump_asserts_for (stderr, name);
2032 }
2033
2034
2035 /* Dump all the registered assertions for all the names to FILE.  */
2036
2037 void
2038 dump_all_asserts (FILE *file)
2039 {
2040   unsigned i;
2041   bitmap_iterator bi;
2042
2043   fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2044   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2045     dump_asserts_for (file, ssa_name (i));
2046   fprintf (file, "\n");
2047 }
2048
2049
2050 /* Dump all the registered assertions for all the names to stderr.  */
2051
2052 void
2053 debug_all_asserts (void)
2054 {
2055   dump_all_asserts (stderr);
2056 }
2057
2058
2059 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2060    'NAME COMP_CODE VAL' at a location that dominates block BB or
2061    E->DEST, then register this location as a possible insertion point
2062    for ASSERT_EXPR <NAME, NAME COMP_CODE VAL>.
2063
2064    BB, E and SI provide the exact insertion point for the new
2065    ASSERT_EXPR.  If BB is NULL, then the ASSERT_EXPR is to be inserted
2066    on edge E.  Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2067    BB.  If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2068    must not be NULL.  */
2069
2070 static void
2071 register_new_assert_for (tree name,
2072                          enum tree_code comp_code,
2073                          tree val,
2074                          basic_block bb,
2075                          edge e,
2076                          block_stmt_iterator si)
2077 {
2078   assert_locus_t n, loc, last_loc;
2079   bool found;
2080   basic_block dest_bb;
2081
2082 #if defined ENABLE_CHECKING
2083   gcc_assert (bb == NULL || e == NULL);
2084
2085   if (e == NULL)
2086     gcc_assert (TREE_CODE (bsi_stmt (si)) != COND_EXPR
2087                 && TREE_CODE (bsi_stmt (si)) != SWITCH_EXPR);
2088 #endif
2089
2090   /* The new assertion A will be inserted at BB or E.  We need to
2091      determine if the new location is dominated by a previously
2092      registered location for A.  If we are doing an edge insertion,
2093      assume that A will be inserted at E->DEST.  Note that this is not
2094      necessarily true.
2095      
2096      If E is a critical edge, it will be split.  But even if E is
2097      split, the new block will dominate the same set of blocks that
2098      E->DEST dominates.
2099      
2100      The reverse, however, is not true, blocks dominated by E->DEST
2101      will not be dominated by the new block created to split E.  So,
2102      if the insertion location is on a critical edge, we will not use
2103      the new location to move another assertion previously registered
2104      at a block dominated by E->DEST.  */
2105   dest_bb = (bb) ? bb : e->dest;
2106
2107   /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2108      VAL at a block dominating DEST_BB, then we don't need to insert a new
2109      one.  Similarly, if the same assertion already exists at a block
2110      dominated by DEST_BB and the new location is not on a critical
2111      edge, then update the existing location for the assertion (i.e.,
2112      move the assertion up in the dominance tree).
2113
2114      Note, this is implemented as a simple linked list because there
2115      should not be more than a handful of assertions registered per
2116      name.  If this becomes a performance problem, a table hashed by
2117      COMP_CODE and VAL could be implemented.  */
2118   loc = asserts_for[SSA_NAME_VERSION (name)];
2119   last_loc = loc;
2120   found = false;
2121   while (loc)
2122     {
2123       if (loc->comp_code == comp_code
2124           && (loc->val == val
2125               || operand_equal_p (loc->val, val, 0)))
2126         {
2127           /* If the assertion NAME COMP_CODE VAL has already been
2128              registered at a basic block that dominates DEST_BB, then
2129              we don't need to insert the same assertion again.  Note
2130              that we don't check strict dominance here to avoid
2131              replicating the same assertion inside the same basic
2132              block more than once (e.g., when a pointer is
2133              dereferenced several times inside a block).
2134
2135              An exception to this rule are edge insertions.  If the
2136              new assertion is to be inserted on edge E, then it will
2137              dominate all the other insertions that we may want to
2138              insert in DEST_BB.  So, if we are doing an edge
2139              insertion, don't do this dominance check.  */
2140           if (e == NULL
2141               && dominated_by_p (CDI_DOMINATORS, dest_bb, loc->bb))
2142             return;
2143
2144           /* Otherwise, if E is not a critical edge and DEST_BB
2145              dominates the existing location for the assertion, move
2146              the assertion up in the dominance tree by updating its
2147              location information.  */
2148           if ((e == NULL || !EDGE_CRITICAL_P (e))
2149               && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2150             {
2151               loc->bb = dest_bb;
2152               loc->e = e;
2153               loc->si = si;
2154               return;
2155             }
2156         }
2157
2158       /* Update the last node of the list and move to the next one.  */
2159       last_loc = loc;
2160       loc = loc->next;
2161     }
2162
2163   /* If we didn't find an assertion already registered for
2164      NAME COMP_CODE VAL, add a new one at the end of the list of
2165      assertions associated with NAME.  */
2166   n = xmalloc (sizeof (*n));
2167   n->bb = dest_bb;
2168   n->e = e;
2169   n->si = si;
2170   n->comp_code = comp_code;
2171   n->val = val;
2172   n->next = NULL;
2173
2174   if (last_loc)
2175     last_loc->next = n;
2176   else
2177     asserts_for[SSA_NAME_VERSION (name)] = n;
2178
2179   bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2180 }
2181
2182
2183 /* Try to register an edge assertion for SSA name NAME on edge E for
2184    the conditional jump pointed by SI.  Return true if an assertion
2185    for NAME could be registered.  */
2186
2187 static bool
2188 register_edge_assert_for (tree name, edge e, block_stmt_iterator si)
2189 {
2190   tree val, stmt;
2191   enum tree_code comp_code;
2192
2193   stmt = bsi_stmt (si);
2194
2195   /* Do not attempt to infer anything in names that flow through
2196      abnormal edges.  */
2197   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
2198     return false;
2199
2200   /* If NAME was not found in the sub-graph reachable from E, then
2201      there's nothing to do.  */
2202   if (!TEST_BIT (found_in_subgraph, SSA_NAME_VERSION (name)))
2203     return false;
2204
2205   /* We found a use of NAME in the sub-graph rooted at E->DEST.
2206      Register an assertion for NAME according to the value that NAME
2207      takes on edge E.  */
2208   if (TREE_CODE (stmt) == COND_EXPR)
2209     {
2210       /* If BB ends in a COND_EXPR then NAME then we should insert
2211          the original predicate on EDGE_TRUE_VALUE and the
2212          opposite predicate on EDGE_FALSE_VALUE.  */
2213       tree cond = COND_EXPR_COND (stmt);
2214       bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
2215
2216       /* Predicates may be a single SSA name or NAME OP VAL.  */
2217       if (cond == name)
2218         {
2219           /* If the predicate is a name, it must be NAME, in which
2220              case we create the predicate NAME == true or
2221              NAME == false accordingly.  */
2222           comp_code = EQ_EXPR;
2223           val = (is_else_edge) ? boolean_false_node : boolean_true_node;
2224         }
2225       else
2226         {
2227           /* Otherwise, we have a comparison of the form NAME COMP VAL
2228              or VAL COMP NAME.  */
2229           if (name == TREE_OPERAND (cond, 1))
2230             {
2231               /* If the predicate is of the form VAL COMP NAME, flip
2232                  COMP around because we need to register NAME as the
2233                  first operand in the predicate.  */
2234               comp_code = opposite_comparison (TREE_CODE (cond));
2235               val = TREE_OPERAND (cond, 0);
2236             }
2237           else
2238             {
2239               /* The comparison is of the form NAME COMP VAL, so the
2240                  comparison code remains unchanged.  */
2241               comp_code = TREE_CODE (cond);
2242               val = TREE_OPERAND (cond, 1);
2243             }
2244
2245           /* If we are inserting the assertion on the ELSE edge, we
2246              need to invert the sign comparison.  */
2247           if (is_else_edge)
2248             comp_code = invert_tree_comparison (comp_code, 0);
2249         }
2250     }
2251   else
2252     {
2253       /* FIXME.  Handle SWITCH_EXPR.  */
2254       gcc_unreachable ();
2255     }
2256
2257   register_new_assert_for (name, comp_code, val, NULL, e, si);
2258   return true;
2259 }
2260
2261
2262 static bool find_assert_locations (basic_block bb);
2263
2264 /* Determine whether the outgoing edges of BB should receive an
2265    ASSERT_EXPR for each of the operands of BB's last statement.  The
2266    last statement of BB must be a COND_EXPR or a SWITCH_EXPR.
2267
2268    If any of the sub-graphs rooted at BB have an interesting use of
2269    the predicate operands, an assert location node is added to the
2270    list of assertions for the corresponding operands.  */
2271
2272 static bool
2273 find_conditional_asserts (basic_block bb)
2274 {
2275   bool need_assert;
2276   block_stmt_iterator last_si;
2277   tree op, last;
2278   edge_iterator ei;
2279   edge e;
2280   ssa_op_iter iter;
2281
2282   need_assert = false;
2283   last_si = bsi_last (bb);
2284   last = bsi_stmt (last_si);
2285
2286   /* Look for uses of the operands in each of the sub-graphs
2287      rooted at BB.  We need to check each of the outgoing edges
2288      separately, so that we know what kind of ASSERT_EXPR to
2289      insert.  */
2290   FOR_EACH_EDGE (e, ei, bb->succs)
2291     {
2292       if (e->dest == bb)
2293         continue;
2294
2295       /* Remove the COND_EXPR operands from the FOUND_IN_SUBGRAPH bitmap.
2296          Otherwise, when we finish traversing each of the sub-graphs, we
2297          won't know whether the variables were found in the sub-graphs or
2298          if they had been found in a block upstream from BB.  */
2299       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2300         RESET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2301
2302       /* Traverse the strictly dominated sub-graph rooted at E->DEST
2303          to determine if any of the operands in the conditional
2304          predicate are used.  */
2305       if (e->dest != bb)
2306         need_assert |= find_assert_locations (e->dest);
2307
2308       /* Register the necessary assertions for each operand in the
2309          conditional predicate.  */
2310       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2311         need_assert |= register_edge_assert_for (op, e, last_si);
2312     }
2313
2314   /* Finally, indicate that we have found the operands in the
2315      conditional.  */
2316   FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2317     SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2318
2319   return need_assert;
2320 }
2321
2322
2323 /* Traverse all the statements in block BB looking for statements that
2324    may generate useful assertions for the SSA names in their operand.
2325    If a statement produces a useful assertion A for name N_i, then the
2326    list of assertions already generated for N_i is scanned to
2327    determine if A is actually needed.
2328    
2329    If N_i already had the assertion A at a location dominating the
2330    current location, then nothing needs to be done.  Otherwise, the
2331    new location for A is recorded instead.
2332
2333    1- For every statement S in BB, all the variables used by S are
2334       added to bitmap FOUND_IN_SUBGRAPH.
2335
2336    2- If statement S uses an operand N in a way that exposes a known
2337       value range for N, then if N was not already generated by an
2338       ASSERT_EXPR, create a new assert location for N.  For instance,
2339       if N is a pointer and the statement dereferences it, we can
2340       assume that N is not NULL.
2341
2342    3- COND_EXPRs are a special case of #2.  We can derive range
2343       information from the predicate but need to insert different
2344       ASSERT_EXPRs for each of the sub-graphs rooted at the
2345       conditional block.  If the last statement of BB is a conditional
2346       expression of the form 'X op Y', then
2347
2348       a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
2349
2350       b) If the conditional is the only entry point to the sub-graph
2351          corresponding to the THEN_CLAUSE, recurse into it.  On
2352          return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
2353          an ASSERT_EXPR is added for the corresponding variable.
2354
2355       c) Repeat step (b) on the ELSE_CLAUSE.
2356
2357       d) Mark X and Y in FOUND_IN_SUBGRAPH.
2358
2359       For instance,
2360
2361             if (a == 9)
2362               b = a;
2363             else
2364               b = c + 1;
2365
2366       In this case, an assertion on the THEN clause is useful to
2367       determine that 'a' is always 9 on that edge.  However, an assertion
2368       on the ELSE clause would be unnecessary.
2369
2370    4- If BB does not end in a conditional expression, then we recurse
2371       into BB's dominator children.
2372    
2373    At the end of the recursive traversal, every SSA name will have a
2374    list of locations where ASSERT_EXPRs should be added.  When a new
2375    location for name N is found, it is registered by calling
2376    register_new_assert_for.  That function keeps track of all the
2377    registered assertions to prevent adding unnecessary assertions.
2378    For instance, if a pointer P_4 is dereferenced more than once in a
2379    dominator tree, only the location dominating all the dereference of
2380    P_4 will receive an ASSERT_EXPR.
2381
2382    If this function returns true, then it means that there are names
2383    for which we need to generate ASSERT_EXPRs.  Those assertions are
2384    inserted by process_assert_insertions.
2385
2386    TODO.  Handle SWITCH_EXPR.  */
2387
2388 static bool
2389 find_assert_locations (basic_block bb)
2390 {
2391   block_stmt_iterator si;
2392   tree last, phi;
2393   bool need_assert;
2394   basic_block son;
2395
2396   if (TEST_BIT (blocks_visited, bb->index))
2397     return false;
2398
2399   SET_BIT (blocks_visited, bb->index);
2400
2401   need_assert = false;
2402
2403   /* Traverse all PHI nodes in BB marking used operands.  */
2404   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2405     {
2406       use_operand_p arg_p;
2407       ssa_op_iter i;
2408
2409       FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
2410         {
2411           tree arg = USE_FROM_PTR (arg_p);
2412           if (TREE_CODE (arg) == SSA_NAME)
2413             {
2414               gcc_assert (is_gimple_reg (PHI_RESULT (phi)));
2415               SET_BIT (found_in_subgraph, SSA_NAME_VERSION (arg));
2416             }
2417         }
2418     }
2419
2420   /* Traverse all the statements in BB marking used names and looking
2421      for statements that may infer assertions for their used operands.  */
2422   last = NULL_TREE;
2423   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2424     {
2425       tree stmt, op;
2426       ssa_op_iter i;
2427
2428       stmt = bsi_stmt (si);
2429
2430       /* See if we can derive an assertion for any of STMT's operands.  */
2431       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
2432         {
2433           tree value;
2434           enum tree_code comp_code;
2435
2436           /* Mark OP in bitmap FOUND_IN_SUBGRAPH.  If STMT is inside
2437              the sub-graph of a conditional block, when we return from
2438              this recursive walk, our parent will use the
2439              FOUND_IN_SUBGRAPH bitset to determine if one of the
2440              operands it was looking for was present in the sub-graph.  */
2441           SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2442
2443           /* If OP is used only once, namely in this STMT, don't
2444              bother creating an ASSERT_EXPR for it.  Such an
2445              ASSERT_EXPR would do nothing but increase compile time.
2446              Experiments show that with this simple check, we can save
2447              more than 20% of ASSERT_EXPRs.  */
2448           if (has_single_use (op))
2449             continue;
2450
2451           /* If OP is used in such a way that we can infer a value
2452              range for it, and we don't find a previous assertion for
2453              it, create a new assertion location node for OP.  */
2454           if (infer_value_range (stmt, op, &comp_code, &value))
2455             {
2456               register_new_assert_for (op, comp_code, value, bb, NULL, si);
2457               need_assert = true;
2458             }
2459         }
2460
2461       /* Remember the last statement of the block.  */
2462       last = stmt;
2463     }
2464
2465   /* If BB's last statement is a conditional expression
2466      involving integer operands, recurse into each of the sub-graphs
2467      rooted at BB to determine if we need to add ASSERT_EXPRs.  */
2468   if (last
2469       && TREE_CODE (last) == COND_EXPR
2470       && !fp_predicate (COND_EXPR_COND (last))
2471       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
2472     need_assert |= find_conditional_asserts (bb);
2473
2474   /* Recurse into the dominator children of BB.  */
2475   for (son = first_dom_son (CDI_DOMINATORS, bb);
2476        son;
2477        son = next_dom_son (CDI_DOMINATORS, son))
2478     need_assert |= find_assert_locations (son);
2479
2480   return need_assert;
2481 }
2482
2483
2484 /* Create an ASSERT_EXPR for NAME and insert it in the location
2485    indicated by LOC.  Return true if we made any edge insertions.  */
2486
2487 static bool
2488 process_assert_insertions_for (tree name, assert_locus_t loc)
2489 {
2490   /* Build the comparison expression NAME_i COMP_CODE VAL.  */
2491   tree stmt, cond, assert_expr;
2492   edge_iterator ei;
2493   edge e;
2494
2495   cond = build (loc->comp_code, boolean_type_node, name, loc->val);
2496   assert_expr = build_assert_expr_for (cond, name);
2497
2498   if (loc->e)
2499     {
2500       /* We have been asked to insert the assertion on an edge.  This
2501          is used only by COND_EXPR and SWITCH_EXPR assertions.  */
2502 #if defined ENABLE_CHECKING
2503       gcc_assert (TREE_CODE (bsi_stmt (loc->si)) == COND_EXPR
2504           || TREE_CODE (bsi_stmt (loc->si)) == SWITCH_EXPR);
2505 #endif
2506
2507       bsi_insert_on_edge (loc->e, assert_expr);
2508       return true;
2509     }
2510
2511   /* Otherwise, we can insert right after LOC->SI iff the
2512      statement must not be the last statement in the block.  */
2513   stmt = bsi_stmt (loc->si);
2514   if (!stmt_ends_bb_p (stmt))
2515     {
2516       bsi_insert_after (&loc->si, assert_expr, BSI_SAME_STMT);
2517       return false;
2518     }
2519
2520   /* If STMT must be the last statement in BB, we can only insert new
2521      assertions on the non-abnormal edge out of BB.  Note that since
2522      STMT is not control flow, there may only be one non-abnormal edge
2523      out of BB.  */
2524   FOR_EACH_EDGE (e, ei, loc->bb->succs)
2525     if (!(e->flags & EDGE_ABNORMAL))
2526       {
2527         bsi_insert_on_edge (e, assert_expr);
2528         return true;
2529       }
2530
2531   gcc_unreachable ();
2532 }
2533
2534
2535 /* Process all the insertions registered for every name N_i registered
2536    in NEED_ASSERT_FOR.  The list of assertions to be inserted are
2537    found in ASSERTS_FOR[i].  */
2538
2539 static void
2540 process_assert_insertions (void)
2541 {
2542   unsigned i;
2543   bitmap_iterator bi;
2544   bool update_edges_p = false;
2545   int num_asserts = 0;
2546
2547   if (dump_file && (dump_flags & TDF_DETAILS))
2548     dump_all_asserts (dump_file);
2549
2550   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2551     {
2552       assert_locus_t loc = asserts_for[i];
2553       gcc_assert (loc);
2554
2555       while (loc)
2556         {
2557           assert_locus_t next = loc->next;
2558           update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
2559           free (loc);
2560           loc = next;
2561           num_asserts++;
2562         }
2563     }
2564
2565   if (update_edges_p)
2566     bsi_commit_edge_inserts ();
2567
2568   if (dump_file && (dump_flags & TDF_STATS))
2569     fprintf (dump_file, "\nNumber of ASSERT_EXPR expressions inserted: %d\n\n",
2570              num_asserts);
2571 }
2572
2573
2574 /* Traverse the flowgraph looking for conditional jumps to insert range
2575    expressions.  These range expressions are meant to provide information
2576    to optimizations that need to reason in terms of value ranges.  They
2577    will not be expanded into RTL.  For instance, given:
2578
2579    x = ...
2580    y = ...
2581    if (x < y)
2582      y = x - 2;
2583    else
2584      x = y + 3;
2585
2586    this pass will transform the code into:
2587
2588    x = ...
2589    y = ...
2590    if (x < y)
2591     {
2592       x = ASSERT_EXPR <x, x < y>
2593       y = x - 2
2594     }
2595    else
2596     {
2597       y = ASSERT_EXPR <y, x <= y>
2598       x = y + 3
2599     }
2600
2601    The idea is that once copy and constant propagation have run, other
2602    optimizations will be able to determine what ranges of values can 'x'
2603    take in different paths of the code, simply by checking the reaching
2604    definition of 'x'.  */
2605
2606 static void
2607 insert_range_assertions (void)
2608 {
2609   edge e;
2610   edge_iterator ei;
2611   bool update_ssa_p;
2612   
2613   found_in_subgraph = sbitmap_alloc (num_ssa_names);
2614   sbitmap_zero (found_in_subgraph);
2615
2616   blocks_visited = sbitmap_alloc (last_basic_block);
2617   sbitmap_zero (blocks_visited);
2618
2619   need_assert_for = BITMAP_ALLOC (NULL);
2620   asserts_for = xmalloc (num_ssa_names * sizeof (assert_locus_t));
2621   memset (asserts_for, 0, num_ssa_names * sizeof (assert_locus_t));
2622
2623   calculate_dominance_info (CDI_DOMINATORS);
2624
2625   update_ssa_p = false;
2626   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2627     if (find_assert_locations (e->dest))
2628       update_ssa_p = true;
2629
2630   if (update_ssa_p)
2631     {
2632       process_assert_insertions ();
2633       update_ssa (TODO_update_ssa_no_phi);
2634     }
2635
2636   if (dump_file && (dump_flags & TDF_DETAILS))
2637     {
2638       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
2639       dump_function_to_file (current_function_decl, dump_file, dump_flags);
2640     }
2641
2642   sbitmap_free (found_in_subgraph);
2643   free (asserts_for);
2644   BITMAP_FREE (need_assert_for);
2645 }
2646
2647
2648 /* Convert range assertion expressions into the implied copies.
2649    
2650    FIXME, this will eventually lead to copy propagation removing the
2651    names that had useful range information attached to them.  For
2652    instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
2653    then N_i will have the range [3, +INF].
2654    
2655    However, by converting the assertion into the implied copy
2656    operation N_i = N_j, we will then copy-propagate N_j into the uses
2657    of N_i and lose the range information.  We may want to hold on to
2658    ASSERT_EXPRs a little while longer as the ranges could be used in
2659    things like jump threading.
2660    
2661    The problem with keeping ASSERT_EXPRs around is that passes after
2662    VRP need to handle them appropriately.  */
2663
2664 static void
2665 remove_range_assertions (void)
2666 {
2667   basic_block bb;
2668   block_stmt_iterator si;
2669
2670   FOR_EACH_BB (bb)
2671     for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2672       {
2673         tree stmt = bsi_stmt (si);
2674
2675         if (TREE_CODE (stmt) == MODIFY_EXPR
2676             && TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
2677           {
2678             tree rhs = TREE_OPERAND (stmt, 1);
2679             tree cond = fold (ASSERT_EXPR_COND (rhs));
2680             gcc_assert (cond != boolean_false_node);
2681             TREE_OPERAND (stmt, 1) = ASSERT_EXPR_VAR (rhs);
2682             update_stmt (stmt);
2683           }
2684       }
2685 }
2686
2687
2688 /* Return true if STMT is interesting for VRP.  */
2689
2690 static bool
2691 stmt_interesting_for_vrp (tree stmt)
2692 {
2693   if (TREE_CODE (stmt) == PHI_NODE
2694       && is_gimple_reg (PHI_RESULT (stmt))
2695       && (INTEGRAL_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))
2696           || POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))))
2697     return true;
2698   else if (TREE_CODE (stmt) == MODIFY_EXPR)
2699     {
2700       tree lhs = TREE_OPERAND (stmt, 0);
2701
2702       if (TREE_CODE (lhs) == SSA_NAME
2703           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2704               || POINTER_TYPE_P (TREE_TYPE (lhs)))
2705           && ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
2706         return true;
2707     }
2708   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
2709     return true;
2710
2711   return false;
2712 }
2713
2714
2715 /* Initialize local data structures for VRP.  Return true if VRP
2716    is worth running (i.e. if we found any statements that could
2717    benefit from range information).  */
2718
2719 static void
2720 vrp_initialize (void)
2721 {
2722   basic_block bb;
2723
2724   vr_value = xmalloc (num_ssa_names * sizeof (value_range_t *));
2725   memset (vr_value, 0, num_ssa_names * sizeof (value_range_t *));
2726
2727   FOR_EACH_BB (bb)
2728     {
2729       block_stmt_iterator si;
2730       tree phi;
2731
2732       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2733         {
2734           if (!stmt_interesting_for_vrp (phi))
2735             {
2736               tree lhs = PHI_RESULT (phi);
2737               set_value_range_to_varying (get_value_range (lhs));
2738               DONT_SIMULATE_AGAIN (phi) = true;
2739             }
2740           else
2741             DONT_SIMULATE_AGAIN (phi) = false;
2742         }
2743
2744       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2745         {
2746           tree stmt = bsi_stmt (si);
2747
2748           if (!stmt_interesting_for_vrp (stmt))
2749             {
2750               ssa_op_iter i;
2751               tree def;
2752               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
2753                 set_value_range_to_varying (get_value_range (def));
2754               DONT_SIMULATE_AGAIN (stmt) = true;
2755             }
2756           else
2757             {
2758               DONT_SIMULATE_AGAIN (stmt) = false;
2759             }
2760         }
2761     }
2762 }
2763
2764
2765 /* Visit assignment STMT.  If it produces an interesting range, record
2766    the SSA name in *OUTPUT_P.  */
2767
2768 static enum ssa_prop_result
2769 vrp_visit_assignment (tree stmt, tree *output_p)
2770 {
2771   tree lhs, rhs, def;
2772   ssa_op_iter iter;
2773
2774   lhs = TREE_OPERAND (stmt, 0);
2775   rhs = TREE_OPERAND (stmt, 1);
2776
2777   /* We only keep track of ranges in integral and pointer types.  */
2778   if (TREE_CODE (lhs) == SSA_NAME
2779       && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2780           || POINTER_TYPE_P (TREE_TYPE (lhs))))
2781     {
2782       struct loop *l;
2783       value_range_t new_vr = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2784
2785       extract_range_from_expr (&new_vr, rhs);
2786
2787       /* If STMT is inside a loop, we may be able to know something
2788          else about the range of LHS by examining scalar evolution
2789          information.  */
2790       if (cfg_loops && (l = loop_containing_stmt (stmt)))
2791         adjust_range_with_scev (&new_vr, l, stmt, lhs);
2792
2793       if (update_value_range (lhs, &new_vr))
2794         {
2795           *output_p = lhs;
2796
2797           if (dump_file && (dump_flags & TDF_DETAILS))
2798             {
2799               fprintf (dump_file, "Found new range for ");
2800               print_generic_expr (dump_file, lhs, 0);
2801               fprintf (dump_file, ": ");
2802               dump_value_range (dump_file, &new_vr);
2803               fprintf (dump_file, "\n\n");
2804             }
2805
2806           if (new_vr.type == VR_VARYING)
2807             return SSA_PROP_VARYING;
2808
2809           return SSA_PROP_INTERESTING;
2810         }
2811
2812       return SSA_PROP_NOT_INTERESTING;
2813     }
2814   
2815   /* Every other statement produces no useful ranges.  */
2816   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
2817     set_value_range_to_varying (get_value_range (def));
2818
2819   return SSA_PROP_VARYING;
2820 }
2821
2822
2823 /* Compare all the value ranges for names equivalent to VAR with VAL
2824    using comparison code COMP.  Return the same value returned by
2825    compare_range_with_value.  */
2826
2827 static tree
2828 compare_name_with_value (enum tree_code comp, tree var, tree val)
2829 {
2830   bitmap_iterator bi;
2831   unsigned i;
2832   bitmap e;
2833   tree retval, t;
2834   
2835   t = retval = NULL_TREE;
2836
2837   /* Get the set of equivalences for VAR.  */
2838   e = get_value_range (var)->equiv;
2839
2840   /* Add VAR to its own set of equivalences so that VAR's value range
2841      is processed by this loop (otherwise, we would have to replicate
2842      the body of the loop just to check VAR's value range).  */
2843   bitmap_set_bit (e, SSA_NAME_VERSION (var));
2844
2845   EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
2846     {
2847       value_range_t equiv_vr = *(vr_value[i]);
2848
2849       /* If name N_i does not have a valid range, use N_i as its own
2850          range.  This allows us to compare against names that may
2851          have N_i in their ranges.  */
2852       if (equiv_vr.type == VR_VARYING || equiv_vr.type == VR_UNDEFINED)
2853         {
2854           equiv_vr.type = VR_RANGE;
2855           equiv_vr.min = ssa_name (i);
2856           equiv_vr.max = ssa_name (i);
2857         }
2858
2859       t = compare_range_with_value (comp, &equiv_vr, val);
2860       if (t)
2861         {
2862           /* All the ranges should compare the same against VAL.  */
2863           gcc_assert (retval == NULL || t == retval);
2864           retval = t;
2865         }
2866     }
2867
2868   /* Remove VAR from its own equivalence set.  */
2869   bitmap_clear_bit (e, SSA_NAME_VERSION (var));
2870
2871   if (retval)
2872     return retval;
2873
2874   /* We couldn't find a non-NULL value for the predicate.  */
2875   return NULL_TREE;
2876 }
2877
2878
2879 /* Given a comparison code COMP and names N1 and N2, compare all the
2880    ranges equivalent to N1 against all the ranges equivalent to N2
2881    to determine the value of N1 COMP N2.  Return the same value
2882    returned by compare_ranges.  */
2883
2884 static tree
2885 compare_names (enum tree_code comp, tree n1, tree n2)
2886 {
2887   tree t, retval;
2888   bitmap e1, e2;
2889   bitmap_iterator bi1, bi2;
2890   unsigned i1, i2;
2891
2892   /* Compare the ranges of every name equivalent to N1 against the
2893      ranges of every name equivalent to N2.  */
2894   e1 = get_value_range (n1)->equiv;
2895   e2 = get_value_range (n2)->equiv;
2896
2897   /* Add N1 and N2 to their own set of equivalences to avoid
2898      duplicating the body of the loop just to check N1 and N2
2899      ranges.  */
2900   bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
2901   bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
2902
2903   /* If the equivalence sets have a common intersection, then the two
2904      names can be compared without checking their ranges.  */
2905   if (bitmap_intersect_p (e1, e2))
2906     {
2907       bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2908       bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2909
2910       return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
2911              ? boolean_true_node
2912              : boolean_false_node;
2913     }
2914
2915   /* Otherwise, compare all the equivalent ranges.  First, add N1 and
2916      N2 to their own set of equivalences to avoid duplicating the body
2917      of the loop just to check N1 and N2 ranges.  */
2918   EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
2919     {
2920       value_range_t vr1 = *(vr_value[i1]);
2921
2922       /* If the range is VARYING or UNDEFINED, use the name itself.  */
2923       if (vr1.type == VR_VARYING || vr1.type == VR_UNDEFINED)
2924         {
2925           vr1.type = VR_RANGE;
2926           vr1.min = ssa_name (i1);
2927           vr1.max = ssa_name (i1);
2928         }
2929
2930       t = retval = NULL_TREE;
2931       EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
2932         {
2933           value_range_t vr2 = *(vr_value[i2]);
2934
2935           if (vr2.type == VR_VARYING || vr2.type == VR_UNDEFINED)
2936             {
2937               vr2.type = VR_RANGE;
2938               vr2.min = ssa_name (i2);
2939               vr2.max = ssa_name (i2);
2940             }
2941
2942           t = compare_ranges (comp, &vr1, &vr2);
2943           if (t)
2944             {
2945               /* All the ranges in the equivalent sets should compare
2946                  the same.  */
2947               gcc_assert (retval == NULL || t == retval);
2948               retval = t;
2949             }
2950         }
2951
2952       if (retval)
2953         {
2954           bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2955           bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2956           return retval;
2957         }
2958     }
2959
2960   /* None of the equivalent ranges are useful in computing this
2961      comparison.  */
2962   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2963   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2964   return NULL_TREE;
2965 }
2966
2967
2968 /* Given a conditional predicate COND, try to determine if COND yields
2969    true or false based on the value ranges of its operands.  Return
2970    BOOLEAN_TRUE_NODE if the conditional always evaluates to true,
2971    BOOLEAN_FALSE_NODE if the conditional always evaluates to false, and,
2972    NULL if the conditional cannot be evaluated at compile time.
2973
2974    If USE_EQUIV_P is true, the ranges of all the names equivalent with
2975    the operands in COND are used when trying to compute its value.
2976    This is only used during final substitution.  During propagation,
2977    we only check the range of each variable and not its equivalents.  */
2978
2979 tree
2980 vrp_evaluate_conditional (tree cond, bool use_equiv_p)
2981 {
2982   gcc_assert (TREE_CODE (cond) == SSA_NAME
2983               || TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
2984
2985   if (TREE_CODE (cond) == SSA_NAME)
2986     {
2987       value_range_t *vr;
2988       tree retval;
2989
2990       if (use_equiv_p)
2991         retval = compare_name_with_value (NE_EXPR, cond, boolean_false_node);
2992       else
2993         {
2994           value_range_t *vr = get_value_range (cond);
2995           retval = compare_range_with_value (NE_EXPR, vr, boolean_false_node);
2996         }
2997
2998       /* If COND has a known boolean range, return it.  */
2999       if (retval)
3000         return retval;
3001
3002       /* Otherwise, if COND has a symbolic range of exactly one value,
3003          return it.  */
3004       vr = get_value_range (cond);
3005       if (vr->type == VR_RANGE && vr->min == vr->max)
3006         return vr->min;
3007     }
3008   else
3009     {
3010       tree op0 = TREE_OPERAND (cond, 0);
3011       tree op1 = TREE_OPERAND (cond, 1);
3012
3013       /* We only deal with integral and pointer types.  */
3014       if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
3015           && !POINTER_TYPE_P (TREE_TYPE (op0)))
3016         return NULL_TREE;
3017
3018       if (use_equiv_p)
3019         {
3020           if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME)
3021             return compare_names (TREE_CODE (cond), op0, op1);
3022           else if (TREE_CODE (op0) == SSA_NAME)
3023             return compare_name_with_value (TREE_CODE (cond), op0, op1);
3024           else if (TREE_CODE (op1) == SSA_NAME)
3025             return compare_name_with_value (
3026                     opposite_comparison (TREE_CODE (cond)), op1, op0);
3027         }
3028       else
3029         {
3030           value_range_t *vr0, *vr1;
3031
3032           vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
3033           vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
3034
3035           if (vr0 && vr1)
3036             return compare_ranges (TREE_CODE (cond), vr0, vr1);
3037           else if (vr0 && vr1 == NULL)
3038             return compare_range_with_value (TREE_CODE (cond), vr0, op1);
3039           else if (vr0 == NULL && vr1)
3040             return compare_range_with_value (
3041                     opposite_comparison (TREE_CODE (cond)), vr1, op0);
3042         }
3043     }
3044
3045   /* Anything else cannot be computed statically.  */
3046   return NULL_TREE;
3047 }
3048
3049
3050 /* Visit conditional statement STMT.  If we can determine which edge
3051    will be taken out of STMT's basic block, record it in
3052    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
3053    SSA_PROP_VARYING.  */
3054
3055 static enum ssa_prop_result
3056 vrp_visit_cond_stmt (tree stmt, edge *taken_edge_p)
3057 {
3058   tree cond, val;
3059
3060   *taken_edge_p = NULL;
3061
3062   /* FIXME.  Handle SWITCH_EXPRs.  But first, the assert pass needs to
3063      add ASSERT_EXPRs for them.  */
3064   if (TREE_CODE (stmt) == SWITCH_EXPR)
3065     return SSA_PROP_VARYING;
3066
3067   cond = COND_EXPR_COND (stmt);
3068
3069   if (dump_file && (dump_flags & TDF_DETAILS))
3070     {
3071       tree use;
3072       ssa_op_iter i;
3073
3074       fprintf (dump_file, "\nVisiting conditional with predicate: ");
3075       print_generic_expr (dump_file, cond, 0);
3076       fprintf (dump_file, "\nWith known ranges\n");
3077       
3078       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
3079         {
3080           fprintf (dump_file, "\t");
3081           print_generic_expr (dump_file, use, 0);
3082           fprintf (dump_file, ": ");
3083           dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
3084         }
3085
3086       fprintf (dump_file, "\n");
3087     }
3088
3089   /* Compute the value of the predicate COND by checking the known
3090      ranges of each of its operands.
3091      
3092      Note that we cannot evaluate all the equivalent ranges here
3093      because those ranges may not yet be final and with the current
3094      propagation strategy, we cannot determine when the value ranges
3095      of the names in the equivalence set have changed.
3096
3097      For instance, given the following code fragment
3098
3099         i_5 = PHI <8, i_13>
3100         ...
3101         i_14 = ASSERT_EXPR <i_5, i_5 != 0>
3102         if (i_14 == 1)
3103           ...
3104
3105      Assume that on the first visit to i_14, i_5 has the temporary
3106      range [8, 8] because the second argument to the PHI function is
3107      not yet executable.  We derive the range ~[0, 0] for i_14 and the
3108      equivalence set { i_5 }.  So, when we visit 'if (i_14 == 1)' for
3109      the first time, since i_14 is equivalent to the range [8, 8], we
3110      determine that the predicate is always false.
3111
3112      On the next round of propagation, i_13 is determined to be
3113      VARYING, which causes i_5 to drop down to VARYING.  So, another
3114      visit to i_14 is scheduled.  In this second visit, we compute the
3115      exact same range and equivalence set for i_14, namely ~[0, 0] and
3116      { i_5 }.  But we did not have the previous range for i_5
3117      registered, so vrp_visit_assignment thinks that the range for
3118      i_14 has not changed.  Therefore, the predicate 'if (i_14 == 1)'
3119      is not visited again, which stops propagation from visiting
3120      statements in the THEN clause of that if().
3121
3122      To properly fix this we would need to keep the previous range
3123      value for the names in the equivalence set.  This way we would've
3124      discovered that from one visit to the other i_5 changed from
3125      range [8, 8] to VR_VARYING.
3126
3127      However, fixing this apparent limitation may not be worth the
3128      additional checking.  Testing on several code bases (GCC, DLV,
3129      MICO, TRAMP3D and SPEC2000) showed that doing this results in
3130      4 more predicates folded in SPEC.  */
3131   val = vrp_evaluate_conditional (cond, false);
3132   if (val)
3133     *taken_edge_p = find_taken_edge (bb_for_stmt (stmt), val);
3134
3135   if (dump_file && (dump_flags & TDF_DETAILS))
3136     {
3137       fprintf (dump_file, "\nPredicate evaluates to: ");
3138       if (val == NULL_TREE)
3139         fprintf (dump_file, "DON'T KNOW\n");
3140       else
3141         print_generic_stmt (dump_file, val, 0);
3142     }
3143
3144   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
3145 }
3146
3147
3148 /* Evaluate statement STMT.  If the statement produces a useful range,
3149    return SSA_PROP_INTERESTING and record the SSA name with the
3150    interesting range into *OUTPUT_P.
3151
3152    If STMT is a conditional branch and we can determine its truth
3153    value, the taken edge is recorded in *TAKEN_EDGE_P.
3154
3155    If STMT produces a varying value, return SSA_PROP_VARYING.  */
3156
3157 static enum ssa_prop_result
3158 vrp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
3159 {
3160   tree def;
3161   ssa_op_iter iter;
3162   stmt_ann_t ann;
3163
3164   if (dump_file && (dump_flags & TDF_DETAILS))
3165     {
3166       fprintf (dump_file, "\nVisiting statement:\n");
3167       print_generic_stmt (dump_file, stmt, dump_flags);
3168       fprintf (dump_file, "\n");
3169     }
3170
3171   ann = stmt_ann (stmt);
3172   if (TREE_CODE (stmt) == MODIFY_EXPR
3173       && ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
3174     return vrp_visit_assignment (stmt, output_p);
3175   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
3176     return vrp_visit_cond_stmt (stmt, taken_edge_p);
3177
3178   /* All other statements produce nothing of interest for VRP, so mark
3179      their outputs varying and prevent further simulation.  */
3180   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
3181     set_value_range_to_varying (get_value_range (def));
3182
3183   return SSA_PROP_VARYING;
3184 }
3185
3186
3187 /* Meet operation for value ranges.  Given two value ranges VR0 and
3188    VR1, store in VR0 the result of meeting VR0 and VR1.
3189    
3190    The meeting rules are as follows:
3191
3192    1- If VR0 and VR1 have an empty intersection, set VR0 to VR_VARYING.
3193
3194    2- If VR0 and VR1 have a non-empty intersection, set VR0 to the
3195       union of VR0 and VR1.  */
3196
3197 static void
3198 vrp_meet (value_range_t *vr0, value_range_t *vr1)
3199 {
3200   if (vr0->type == VR_UNDEFINED)
3201     {
3202       copy_value_range (vr0, vr1);
3203       return;
3204     }
3205
3206   if (vr1->type == VR_UNDEFINED)
3207     {
3208       /* Nothing to do.  VR0 already has the resulting range.  */
3209       return;
3210     }
3211
3212   if (vr0->type == VR_VARYING)
3213     {
3214       /* Nothing to do.  VR0 already has the resulting range.  */
3215       return;
3216     }
3217
3218   if (vr1->type == VR_VARYING)
3219     {
3220       set_value_range_to_varying (vr0);
3221       return;
3222     }
3223
3224   if (vr0->type == VR_RANGE && vr1->type == VR_RANGE)
3225     {
3226       /* If VR0 and VR1 have a non-empty intersection, compute the
3227          union of both ranges.  */
3228       if (value_ranges_intersect_p (vr0, vr1))
3229         {
3230           int cmp;
3231           tree min, max;
3232
3233           /* The lower limit of the new range is the minimum of the
3234              two ranges.  If they cannot be compared, the result is
3235              VARYING.  */
3236           cmp = compare_values (vr0->min, vr1->min);
3237           if (cmp == 0 || cmp == 1)
3238             min = vr1->min;
3239           else if (cmp == -1)
3240             min = vr0->min;
3241           else
3242             {
3243               set_value_range_to_varying (vr0);
3244               return;
3245             }
3246
3247           /* Similarly, the upper limit of the new range is the
3248              maximum of the two ranges.  If they cannot be compared,
3249              the result is VARYING.  */
3250           cmp = compare_values (vr0->max, vr1->max);
3251           if (cmp == 0 || cmp == -1)
3252             max = vr1->max;
3253           else if (cmp == 1)
3254             max = vr0->max;
3255           else
3256             {
3257               set_value_range_to_varying (vr0);
3258               return;
3259             }
3260
3261           /* The resulting set of equivalences is the intersection of
3262              the two sets.  */
3263           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
3264             bitmap_and_into (vr0->equiv, vr1->equiv);
3265
3266           set_value_range (vr0, vr0->type, min, max, vr0->equiv);
3267         }
3268       else
3269         goto no_meet;
3270     }
3271   else if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
3272     {
3273       /* Two anti-ranges meet only if they are both identical.  */
3274       if (compare_values (vr0->min, vr1->min) == 0
3275           && compare_values (vr0->max, vr1->max) == 0
3276           && compare_values (vr0->min, vr0->max) == 0)
3277         {
3278           /* The resulting set of equivalences is the intersection of
3279              the two sets.  */
3280           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
3281             bitmap_and_into (vr0->equiv, vr1->equiv);
3282         }
3283       else
3284         goto no_meet;
3285     }
3286   else if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
3287     {
3288       /* A numeric range [VAL1, VAL2] and an anti-range ~[VAL3, VAL4]
3289          meet only if the ranges have an empty intersection.  The
3290          result of the meet operation is the anti-range.  */
3291       if (!symbolic_range_p (vr0)
3292           && !symbolic_range_p (vr1)
3293           && !value_ranges_intersect_p (vr0, vr1))
3294         {
3295           if (vr1->type == VR_ANTI_RANGE)
3296             copy_value_range (vr0, vr1);
3297         }
3298       else
3299         goto no_meet;
3300     }
3301   else
3302     gcc_unreachable ();
3303
3304   return;
3305
3306 no_meet:
3307   /* The two range VR0 and VR1 do not meet.  Before giving up and
3308      setting the result to VARYING, see if we can at least derive a
3309      useful anti-range.  */
3310   if (!symbolic_range_p (vr0)
3311       && !range_includes_zero_p (vr0)
3312       && !symbolic_range_p (vr1)
3313       && !range_includes_zero_p (vr1))
3314     set_value_range_to_nonnull (vr0, TREE_TYPE (vr0->min));
3315   else
3316     set_value_range_to_varying (vr0);
3317 }
3318
3319
3320 /* Visit all arguments for PHI node PHI that flow through executable
3321    edges.  If a valid value range can be derived from all the incoming
3322    value ranges, set a new range for the LHS of PHI.  */
3323
3324 static enum ssa_prop_result
3325 vrp_visit_phi_node (tree phi)
3326 {
3327   int i;
3328   tree lhs = PHI_RESULT (phi);
3329   value_range_t *lhs_vr = get_value_range (lhs);
3330   value_range_t vr_result = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
3331
3332   copy_value_range (&vr_result, lhs_vr);
3333
3334   if (dump_file && (dump_flags & TDF_DETAILS))
3335     {
3336       fprintf (dump_file, "\nVisiting PHI node: ");
3337       print_generic_expr (dump_file, phi, dump_flags);
3338     }
3339
3340   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
3341     {
3342       edge e = PHI_ARG_EDGE (phi, i);
3343
3344       if (dump_file && (dump_flags & TDF_DETAILS))
3345         {
3346           fprintf (dump_file,
3347               "\n    Argument #%d (%d -> %d %sexecutable)\n",
3348               i, e->src->index, e->dest->index,
3349               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
3350         }
3351
3352       if (e->flags & EDGE_EXECUTABLE)
3353         {
3354           tree arg = PHI_ARG_DEF (phi, i);
3355           value_range_t vr_arg;
3356
3357           if (TREE_CODE (arg) == SSA_NAME)
3358             vr_arg = *(get_value_range (arg));
3359           else
3360             {
3361               vr_arg.type = VR_RANGE;
3362               vr_arg.min = arg;
3363               vr_arg.max = arg;
3364               vr_arg.equiv = NULL;
3365             }
3366
3367           if (dump_file && (dump_flags & TDF_DETAILS))
3368             {
3369               fprintf (dump_file, "\t");
3370               print_generic_expr (dump_file, arg, dump_flags);
3371               fprintf (dump_file, "\n\tValue: ");
3372               dump_value_range (dump_file, &vr_arg);
3373               fprintf (dump_file, "\n");
3374             }
3375
3376           vrp_meet (&vr_result, &vr_arg);
3377
3378           if (vr_result.type == VR_VARYING)
3379             break;
3380         }
3381     }
3382
3383   if (vr_result.type == VR_VARYING)
3384     goto varying;
3385
3386   /* To prevent infinite iterations in the algorithm, derive ranges
3387      when the new value is slightly bigger or smaller than the
3388      previous one.  */
3389   if (lhs_vr->type == VR_RANGE)
3390     {
3391       if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
3392         {
3393           int cmp_min = compare_values (lhs_vr->min, vr_result.min);
3394           int cmp_max = compare_values (lhs_vr->max, vr_result.max);
3395
3396           /* If the new minimum is smaller or larger than the previous
3397              one, go all the way to -INF.  In the first case, to avoid
3398              iterating millions of times to reach -INF, and in the
3399              other case to avoid infinite bouncing between different
3400              minimums.  */
3401           if (cmp_min > 0 || cmp_min < 0)
3402             vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
3403
3404           /* Similarly, if the new maximum is smaller or larger than
3405              the previous one, go all the way to +INF.  */
3406           if (cmp_max < 0 || cmp_max > 0)
3407             vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
3408
3409           /* If we ended up with a (-INF, +INF) range, set it to
3410              VARYING.  */
3411           if (vr_result.min == TYPE_MIN_VALUE (TREE_TYPE (vr_result.min))
3412               && vr_result.max == TYPE_MAX_VALUE (TREE_TYPE (vr_result.max)))
3413             goto varying;
3414         }
3415     }
3416
3417   /* If the new range is different than the previous value, keep
3418      iterating.  */
3419   if (update_value_range (lhs, &vr_result))
3420     return SSA_PROP_INTERESTING;
3421
3422   /* Nothing changed, don't add outgoing edges.  */
3423   return SSA_PROP_NOT_INTERESTING;
3424
3425   /* No match found.  Set the LHS to VARYING.  */
3426 varying:
3427   set_value_range_to_varying (lhs_vr);
3428   return SSA_PROP_VARYING;
3429 }
3430
3431 /* Walk through the IL simplifying expressions using knowledge
3432    gathered by VRP.  */
3433
3434 static void
3435 simplify_using_ranges (void)
3436 {
3437   basic_block bb;
3438
3439   FOR_EACH_BB (bb)
3440     {
3441       block_stmt_iterator bsi;
3442
3443       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3444         {
3445           tree stmt = bsi_stmt (bsi);
3446
3447           if (TREE_CODE (stmt) == MODIFY_EXPR)
3448             {
3449               tree rhs = TREE_OPERAND (stmt, 1);
3450               enum tree_code rhs_code = TREE_CODE (rhs);
3451
3452               /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
3453                  and BIT_AND_EXPR respectively if the first operand is greater
3454                  than zero and the second operand is an exact power of two.  */
3455               if ((rhs_code == TRUNC_DIV_EXPR || rhs_code == TRUNC_MOD_EXPR)
3456                   && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0)))
3457                   && integer_pow2p (TREE_OPERAND (rhs, 1)))
3458                 {
3459                   tree val = NULL;
3460                   tree op = TREE_OPERAND (rhs, 0);
3461                   value_range_t *vr = get_value_range (TREE_OPERAND (rhs, 0));
3462
3463                   if (TYPE_UNSIGNED (TREE_TYPE (op)))
3464                     {
3465                       val = integer_one_node;
3466                     }
3467                   else
3468                     {
3469                       val = compare_range_with_value (GT_EXPR, vr,
3470                                                       integer_zero_node);
3471                     }
3472
3473                   if (val && integer_onep (val))
3474                     {
3475                       tree t;
3476                       tree op0 = TREE_OPERAND (rhs, 0);
3477                       tree op1 = TREE_OPERAND (rhs, 1);
3478
3479                       if (rhs_code == TRUNC_DIV_EXPR)
3480                         {
3481                           t = build_int_cst (NULL_TREE, tree_log2 (op1));
3482                           t = build (RSHIFT_EXPR, TREE_TYPE (op0), op0, t);
3483                         }
3484                       else
3485                         {
3486                           t = build_int_cst (TREE_TYPE (op1), 1);
3487                           t = int_const_binop (MINUS_EXPR, op1, t, 0);
3488                           t = fold_convert (TREE_TYPE (op0), t);
3489                           t = build2 (BIT_AND_EXPR, TREE_TYPE (op0), op0, t);
3490                         }
3491
3492                       TREE_OPERAND (stmt, 1) = t;
3493                       update_stmt (stmt);
3494                     }
3495
3496                 }
3497
3498               /* Transform ABS (X) into X or -X as appropriate.  */
3499               if (rhs_code == ABS_EXPR
3500                   && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME
3501                   && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0))))
3502                 {
3503                   tree val = NULL;
3504                   tree op = TREE_OPERAND (rhs, 0);
3505                   tree type = TREE_TYPE (op);
3506                   value_range_t *vr = get_value_range (TREE_OPERAND (rhs, 0));
3507
3508                   if (TYPE_UNSIGNED (type))
3509                     {
3510                       val = integer_zero_node;
3511                     }
3512                   else if (vr)
3513                     {
3514                       val = compare_range_with_value (LE_EXPR, vr,
3515                                                       integer_zero_node);
3516                       if (!val)
3517                         {
3518                           val = compare_range_with_value (GE_EXPR, vr,
3519                                                           integer_zero_node);
3520
3521                           if (val)
3522                             {
3523                               if (integer_zerop (val))
3524                                 val = integer_one_node;
3525                               else if (integer_onep (val))
3526                                 val = integer_zero_node;
3527                             }
3528                         }
3529
3530                       if (val
3531                           && (integer_onep (val) || integer_zerop (val)))
3532                         {
3533                           tree t;
3534
3535                           if (integer_onep (val))
3536                             t = build1 (NEGATE_EXPR, TREE_TYPE (op), op);
3537                           else
3538                             t = op;
3539
3540                           TREE_OPERAND (stmt, 1) = t;
3541                           update_stmt (stmt);
3542                         }
3543                     }
3544                 }
3545             }
3546
3547           /* TODO.  Simplify conditionals.   */
3548         }
3549     }
3550 }
3551
3552
3553 /* Traverse all the blocks folding conditionals with known ranges.  */
3554
3555 static void
3556 vrp_finalize (void)
3557 {
3558   size_t i;
3559   prop_value_t *single_val_range;
3560   bool do_value_subst_p;
3561
3562   if (dump_file)
3563     {
3564       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
3565       dump_all_value_ranges (dump_file);
3566       fprintf (dump_file, "\n");
3567     }
3568
3569   /* We may have ended with ranges that have exactly one value.  Those
3570      values can be substituted as any other copy/const propagated
3571      value using substitute_and_fold.  */
3572   single_val_range = xmalloc (num_ssa_names * sizeof (*single_val_range));
3573   memset (single_val_range, 0, num_ssa_names * sizeof (*single_val_range));
3574
3575   do_value_subst_p = false;
3576   for (i = 0; i < num_ssa_names; i++)
3577     if (vr_value[i]
3578         && vr_value[i]->type == VR_RANGE
3579         && vr_value[i]->min == vr_value[i]->max)
3580       {
3581         single_val_range[i].value = vr_value[i]->min;
3582         do_value_subst_p = true;
3583       }
3584
3585   if (!do_value_subst_p)
3586     {
3587       /* We found no single-valued ranges, don't waste time trying to
3588          do single value substitution in substitute_and_fold.  */
3589       free (single_val_range);
3590       single_val_range = NULL;
3591     }
3592
3593   substitute_and_fold (single_val_range, true);
3594
3595   /* One could argue all simplifications should be done here
3596      rather than using substitute_and_fold since this code
3597      is going to have to perform a complete walk through the
3598      IL anyway.  */
3599   simplify_using_ranges ();
3600
3601   /* Free allocated memory.  */
3602   for (i = 0; i < num_ssa_names; i++)
3603     if (vr_value[i])
3604       {
3605         BITMAP_FREE (vr_value[i]->equiv);
3606         free (vr_value[i]);
3607       }
3608
3609   free (single_val_range);
3610   free (vr_value);
3611 }
3612
3613
3614 /* Main entry point to VRP (Value Range Propagation).  This pass is
3615    loosely based on J. R. C. Patterson, ``Accurate Static Branch
3616    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
3617    Programming Language Design and Implementation, pp. 67-78, 1995.
3618    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
3619
3620    This is essentially an SSA-CCP pass modified to deal with ranges
3621    instead of constants.
3622
3623    While propagating ranges, we may find that two or more SSA name
3624    have equivalent, though distinct ranges.  For instance,
3625
3626      1  x_9 = p_3->a;
3627      2  p_4 = ASSERT_EXPR <p_3, p_3 != 0>
3628      3  if (p_4 == q_2)
3629      4    p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
3630      5  endif
3631      6  if (q_2)
3632         
3633    In the code above, pointer p_5 has range [q_2, q_2], but from the
3634    code we can also determine that p_5 cannot be NULL and, if q_2 had
3635    a non-varying range, p_5's range should also be compatible with it.
3636
3637    These equivalences are created by two expressions: ASSERT_EXPR and
3638    copy operations.  Since p_5 is an assertion on p_4, and p_4 was the
3639    result of another assertion, then we can use the fact that p_5 and
3640    p_4 are equivalent when evaluating p_5's range.
3641
3642    Together with value ranges, we also propagate these equivalences
3643    between names so that we can take advantage of information from
3644    multiple ranges when doing final replacement.  Note that this
3645    equivalency relation is transitive but not symmetric.
3646    
3647    In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
3648    cannot assert that q_2 is equivalent to p_5 because q_2 may be used
3649    in contexts where that assertion does not hold (e.g., in line 6).
3650
3651    TODO, the main difference between this pass and Patterson's is that
3652    we do not propagate edge probabilities.  We only compute whether
3653    edges can be taken or not.  That is, instead of having a spectrum
3654    of jump probabilities between 0 and 1, we only deal with 0, 1 and
3655    DON'T KNOW.  In the future, it may be worthwhile to propagate
3656    probabilities to aid branch prediction.  */
3657
3658 static void
3659 execute_vrp (void)
3660 {
3661   insert_range_assertions ();
3662
3663   cfg_loops = loop_optimizer_init (NULL);
3664   if (cfg_loops)
3665     scev_initialize (cfg_loops);
3666
3667   vrp_initialize ();
3668   ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
3669   vrp_finalize ();
3670
3671   if (cfg_loops)
3672     {
3673       scev_finalize ();
3674       loop_optimizer_finalize (cfg_loops, NULL);
3675       current_loops = NULL;
3676     }
3677
3678   remove_range_assertions ();
3679 }
3680
3681 static bool
3682 gate_vrp (void)
3683 {
3684   return flag_tree_vrp != 0;
3685 }
3686
3687 struct tree_opt_pass pass_vrp =
3688 {
3689   "vrp",                                /* name */
3690   gate_vrp,                             /* gate */
3691   execute_vrp,                          /* execute */
3692   NULL,                                 /* sub */
3693   NULL,                                 /* next */
3694   0,                                    /* static_pass_number */
3695   TV_TREE_VRP,                          /* tv_id */
3696   PROP_ssa | PROP_alias,                /* properties_required */
3697   0,                                    /* properties_provided */
3698   0,                                    /* properties_destroyed */
3699   0,                                    /* todo_flags_start */
3700   TODO_cleanup_cfg
3701     | TODO_ggc_collect
3702     | TODO_verify_ssa
3703     | TODO_dump_func
3704     | TODO_update_ssa,                  /* todo_flags_finish */
3705   0                                     /* letter */
3706 };