gcc:
[official-gcc.git] / gcc / tree-vrp.c
blobe8eb92925060f1464e0d0544409a3e1f436c7917
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2018 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>.
5 This file is part of GCC.
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 3, or (at your option)
10 any later version.
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.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "insn-codes.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "tree-pass.h"
31 #include "ssa.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "diagnostic-core.h"
35 #include "flags.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "cfganal.h"
40 #include "gimple-fold.h"
41 #include "tree-eh.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
44 #include "tree-cfg.h"
45 #include "tree-dfa.h"
46 #include "tree-ssa-loop-manip.h"
47 #include "tree-ssa-loop-niter.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "tree-ssa.h"
51 #include "intl.h"
52 #include "cfgloop.h"
53 #include "tree-scalar-evolution.h"
54 #include "tree-ssa-propagate.h"
55 #include "tree-chrec.h"
56 #include "tree-ssa-threadupdate.h"
57 #include "tree-ssa-scopedtables.h"
58 #include "tree-ssa-threadedge.h"
59 #include "omp-general.h"
60 #include "target.h"
61 #include "case-cfn-macros.h"
62 #include "params.h"
63 #include "alloc-pool.h"
64 #include "domwalk.h"
65 #include "tree-cfgcleanup.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "vr-values.h"
69 #include "builtins.h"
70 #include "wide-int-range.h"
72 /* Set of SSA names found live during the RPO traversal of the function
73 for still active basic-blocks. */
74 static sbitmap *live;
76 /* Return true if the SSA name NAME is live on the edge E. */
78 static bool
79 live_on_edge (edge e, tree name)
81 return (live[e->dest->index]
82 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
85 /* Location information for ASSERT_EXPRs. Each instance of this
86 structure describes an ASSERT_EXPR for an SSA name. Since a single
87 SSA name may have more than one assertion associated with it, these
88 locations are kept in a linked list attached to the corresponding
89 SSA name. */
90 struct assert_locus
92 /* Basic block where the assertion would be inserted. */
93 basic_block bb;
95 /* Some assertions need to be inserted on an edge (e.g., assertions
96 generated by COND_EXPRs). In those cases, BB will be NULL. */
97 edge e;
99 /* Pointer to the statement that generated this assertion. */
100 gimple_stmt_iterator si;
102 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
103 enum tree_code comp_code;
105 /* Value being compared against. */
106 tree val;
108 /* Expression to compare. */
109 tree expr;
111 /* Next node in the linked list. */
112 assert_locus *next;
115 /* If bit I is present, it means that SSA name N_i has a list of
116 assertions that should be inserted in the IL. */
117 static bitmap need_assert_for;
119 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
120 holds a list of ASSERT_LOCUS_T nodes that describe where
121 ASSERT_EXPRs for SSA name N_I should be inserted. */
122 static assert_locus **asserts_for;
124 vec<edge> to_remove_edges;
125 vec<switch_update> to_update_switch_stmts;
128 /* Return the maximum value for TYPE. */
130 tree
131 vrp_val_max (const_tree type)
133 if (!INTEGRAL_TYPE_P (type))
134 return NULL_TREE;
136 return TYPE_MAX_VALUE (type);
139 /* Return the minimum value for TYPE. */
141 tree
142 vrp_val_min (const_tree type)
144 if (!INTEGRAL_TYPE_P (type))
145 return NULL_TREE;
147 return TYPE_MIN_VALUE (type);
150 /* Return whether VAL is equal to the maximum value of its type.
151 We can't do a simple equality comparison with TYPE_MAX_VALUE because
152 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
153 is not == to the integer constant with the same value in the type. */
155 bool
156 vrp_val_is_max (const_tree val)
158 tree type_max = vrp_val_max (TREE_TYPE (val));
159 return (val == type_max
160 || (type_max != NULL_TREE
161 && operand_equal_p (val, type_max, 0)));
164 /* Return whether VAL is equal to the minimum value of its type. */
166 bool
167 vrp_val_is_min (const_tree val)
169 tree type_min = vrp_val_min (TREE_TYPE (val));
170 return (val == type_min
171 || (type_min != NULL_TREE
172 && operand_equal_p (val, type_min, 0)));
175 /* VR_TYPE describes a range with mininum value *MIN and maximum
176 value *MAX. Restrict the range to the set of values that have
177 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
178 return the new range type.
180 SGN gives the sign of the values described by the range. */
182 enum value_range_type
183 intersect_range_with_nonzero_bits (enum value_range_type vr_type,
184 wide_int *min, wide_int *max,
185 const wide_int &nonzero_bits,
186 signop sgn)
188 if (vr_type == VR_ANTI_RANGE)
190 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
191 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
192 to create an inclusive upper bound for A and an inclusive lower
193 bound for B. */
194 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
195 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
197 /* If the calculation of A_MAX wrapped, A is effectively empty
198 and A_MAX is the highest value that satisfies NONZERO_BITS.
199 Likewise if the calculation of B_MIN wrapped, B is effectively
200 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
201 bool a_empty = wi::ge_p (a_max, *min, sgn);
202 bool b_empty = wi::le_p (b_min, *max, sgn);
204 /* If both A and B are empty, there are no valid values. */
205 if (a_empty && b_empty)
206 return VR_UNDEFINED;
208 /* If exactly one of A or B is empty, return a VR_RANGE for the
209 other one. */
210 if (a_empty || b_empty)
212 *min = b_min;
213 *max = a_max;
214 gcc_checking_assert (wi::le_p (*min, *max, sgn));
215 return VR_RANGE;
218 /* Update the VR_ANTI_RANGE bounds. */
219 *min = a_max + 1;
220 *max = b_min - 1;
221 gcc_checking_assert (wi::le_p (*min, *max, sgn));
223 /* Now check whether the excluded range includes any values that
224 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
225 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
227 unsigned int precision = min->get_precision ();
228 *min = wi::min_value (precision, sgn);
229 *max = wi::max_value (precision, sgn);
230 vr_type = VR_RANGE;
233 if (vr_type == VR_RANGE)
235 *max = wi::round_down_for_mask (*max, nonzero_bits);
237 /* Check that the range contains at least one valid value. */
238 if (wi::gt_p (*min, *max, sgn))
239 return VR_UNDEFINED;
241 *min = wi::round_up_for_mask (*min, nonzero_bits);
242 gcc_checking_assert (wi::le_p (*min, *max, sgn));
244 return vr_type;
247 /* Set value range VR to VR_UNDEFINED. */
249 static inline void
250 set_value_range_to_undefined (value_range *vr)
252 vr->type = VR_UNDEFINED;
253 vr->min = vr->max = NULL_TREE;
254 if (vr->equiv)
255 bitmap_clear (vr->equiv);
258 /* Set value range VR to VR_VARYING. */
260 void
261 set_value_range_to_varying (value_range *vr)
263 vr->type = VR_VARYING;
264 vr->min = vr->max = NULL_TREE;
265 if (vr->equiv)
266 bitmap_clear (vr->equiv);
269 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
271 void
272 set_value_range (value_range *vr, enum value_range_type t, tree min,
273 tree max, bitmap equiv)
275 /* Check the validity of the range. */
276 if (flag_checking
277 && (t == VR_RANGE || t == VR_ANTI_RANGE))
279 int cmp;
281 gcc_assert (min && max);
283 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
285 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
286 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
288 cmp = compare_values (min, max);
289 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
292 if (flag_checking
293 && (t == VR_UNDEFINED || t == VR_VARYING))
295 gcc_assert (min == NULL_TREE && max == NULL_TREE);
296 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
299 vr->type = t;
300 vr->min = min;
301 vr->max = max;
303 /* Since updating the equivalence set involves deep copying the
304 bitmaps, only do it if absolutely necessary.
306 All equivalence bitmaps are allocated from the same obstack. So
307 we can use the obstack associated with EQUIV to allocate vr->equiv. */
308 if (vr->equiv == NULL
309 && equiv != NULL)
310 vr->equiv = BITMAP_ALLOC (equiv->obstack);
312 if (equiv != vr->equiv)
314 if (equiv && !bitmap_empty_p (equiv))
315 bitmap_copy (vr->equiv, equiv);
316 else
317 bitmap_clear (vr->equiv);
322 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
323 This means adjusting T, MIN and MAX representing the case of a
324 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
325 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
326 In corner cases where MAX+1 or MIN-1 wraps this will fall back
327 to varying.
328 This routine exists to ease canonicalization in the case where we
329 extract ranges from var + CST op limit. */
331 void
332 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
333 tree min, tree max, bitmap equiv)
335 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
336 if (t == VR_UNDEFINED)
338 set_value_range_to_undefined (vr);
339 return;
341 else if (t == VR_VARYING)
343 set_value_range_to_varying (vr);
344 return;
347 /* Nothing to canonicalize for symbolic ranges. */
348 if (TREE_CODE (min) != INTEGER_CST
349 || TREE_CODE (max) != INTEGER_CST)
351 set_value_range (vr, t, min, max, equiv);
352 return;
355 /* Wrong order for min and max, to swap them and the VR type we need
356 to adjust them. */
357 if (tree_int_cst_lt (max, min))
359 tree one, tmp;
361 /* For one bit precision if max < min, then the swapped
362 range covers all values, so for VR_RANGE it is varying and
363 for VR_ANTI_RANGE empty range, so drop to varying as well. */
364 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
366 set_value_range_to_varying (vr);
367 return;
370 one = build_int_cst (TREE_TYPE (min), 1);
371 tmp = int_const_binop (PLUS_EXPR, max, one);
372 max = int_const_binop (MINUS_EXPR, min, one);
373 min = tmp;
375 /* There's one corner case, if we had [C+1, C] before we now have
376 that again. But this represents an empty value range, so drop
377 to varying in this case. */
378 if (tree_int_cst_lt (max, min))
380 set_value_range_to_varying (vr);
381 return;
384 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
387 /* Anti-ranges that can be represented as ranges should be so. */
388 if (t == VR_ANTI_RANGE)
390 /* For -fstrict-enums we may receive out-of-range ranges so consider
391 values < -INF and values > INF as -INF/INF as well. */
392 tree type = TREE_TYPE (min);
393 bool is_min = (INTEGRAL_TYPE_P (type)
394 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
395 bool is_max = (INTEGRAL_TYPE_P (type)
396 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
398 if (is_min && is_max)
400 /* We cannot deal with empty ranges, drop to varying.
401 ??? This could be VR_UNDEFINED instead. */
402 set_value_range_to_varying (vr);
403 return;
405 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
406 && (is_min || is_max))
408 /* Non-empty boolean ranges can always be represented
409 as a singleton range. */
410 if (is_min)
411 min = max = vrp_val_max (TREE_TYPE (min));
412 else
413 min = max = vrp_val_min (TREE_TYPE (min));
414 t = VR_RANGE;
416 else if (is_min
417 /* As a special exception preserve non-null ranges. */
418 && !(TYPE_UNSIGNED (TREE_TYPE (min))
419 && integer_zerop (max)))
421 tree one = build_int_cst (TREE_TYPE (max), 1);
422 min = int_const_binop (PLUS_EXPR, max, one);
423 max = vrp_val_max (TREE_TYPE (max));
424 t = VR_RANGE;
426 else if (is_max)
428 tree one = build_int_cst (TREE_TYPE (min), 1);
429 max = int_const_binop (MINUS_EXPR, min, one);
430 min = vrp_val_min (TREE_TYPE (min));
431 t = VR_RANGE;
435 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
436 to make sure VRP iteration terminates, otherwise we can get into
437 oscillations. */
439 set_value_range (vr, t, min, max, equiv);
442 /* Copy value range FROM into value range TO. */
444 void
445 copy_value_range (value_range *to, value_range *from)
447 set_value_range (to, from->type, from->min, from->max, from->equiv);
450 /* Set value range VR to a single value. This function is only called
451 with values we get from statements, and exists to clear the
452 TREE_OVERFLOW flag. */
454 void
455 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
457 gcc_assert (is_gimple_min_invariant (val));
458 if (TREE_OVERFLOW_P (val))
459 val = drop_tree_overflow (val);
460 set_value_range (vr, VR_RANGE, val, val, equiv);
463 /* Set value range VR to a non-NULL range of type TYPE. */
465 void
466 set_value_range_to_nonnull (value_range *vr, tree type)
468 tree zero = build_int_cst (type, 0);
469 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
473 /* Set value range VR to a NULL range of type TYPE. */
475 void
476 set_value_range_to_null (value_range *vr, tree type)
478 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
481 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
483 bool
484 vrp_operand_equal_p (const_tree val1, const_tree val2)
486 if (val1 == val2)
487 return true;
488 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
489 return false;
490 return true;
493 /* Return true, if the bitmaps B1 and B2 are equal. */
495 bool
496 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
498 return (b1 == b2
499 || ((!b1 || bitmap_empty_p (b1))
500 && (!b2 || bitmap_empty_p (b2)))
501 || (b1 && b2
502 && bitmap_equal_p (b1, b2)));
505 /* Return true if VR is [0, 0]. */
507 static inline bool
508 range_is_null (value_range *vr)
510 return vr->type == VR_RANGE
511 && integer_zerop (vr->min)
512 && integer_zerop (vr->max);
515 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
516 a singleton. */
518 bool
519 range_int_cst_p (value_range *vr)
521 return (vr->type == VR_RANGE
522 && TREE_CODE (vr->max) == INTEGER_CST
523 && TREE_CODE (vr->min) == INTEGER_CST);
526 /* Return true if VR is a INTEGER_CST singleton. */
528 bool
529 range_int_cst_singleton_p (value_range *vr)
531 return (range_int_cst_p (vr)
532 && tree_int_cst_equal (vr->min, vr->max));
535 /* Return true if value range VR involves at least one symbol. */
537 bool
538 symbolic_range_p (value_range *vr)
540 return (!is_gimple_min_invariant (vr->min)
541 || !is_gimple_min_invariant (vr->max));
544 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
545 otherwise. We only handle additive operations and set NEG to true if the
546 symbol is negated and INV to the invariant part, if any. */
548 tree
549 get_single_symbol (tree t, bool *neg, tree *inv)
551 bool neg_;
552 tree inv_;
554 *inv = NULL_TREE;
555 *neg = false;
557 if (TREE_CODE (t) == PLUS_EXPR
558 || TREE_CODE (t) == POINTER_PLUS_EXPR
559 || TREE_CODE (t) == MINUS_EXPR)
561 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
563 neg_ = (TREE_CODE (t) == MINUS_EXPR);
564 inv_ = TREE_OPERAND (t, 0);
565 t = TREE_OPERAND (t, 1);
567 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
569 neg_ = false;
570 inv_ = TREE_OPERAND (t, 1);
571 t = TREE_OPERAND (t, 0);
573 else
574 return NULL_TREE;
576 else
578 neg_ = false;
579 inv_ = NULL_TREE;
582 if (TREE_CODE (t) == NEGATE_EXPR)
584 t = TREE_OPERAND (t, 0);
585 neg_ = !neg_;
588 if (TREE_CODE (t) != SSA_NAME)
589 return NULL_TREE;
591 if (inv_ && TREE_OVERFLOW_P (inv_))
592 inv_ = drop_tree_overflow (inv_);
594 *neg = neg_;
595 *inv = inv_;
596 return t;
599 /* The reverse operation: build a symbolic expression with TYPE
600 from symbol SYM, negated according to NEG, and invariant INV. */
602 static tree
603 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
605 const bool pointer_p = POINTER_TYPE_P (type);
606 tree t = sym;
608 if (neg)
609 t = build1 (NEGATE_EXPR, type, t);
611 if (integer_zerop (inv))
612 return t;
614 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
617 /* Return
618 1 if VAL < VAL2
619 0 if !(VAL < VAL2)
620 -2 if those are incomparable. */
622 operand_less_p (tree val, tree val2)
624 /* LT is folded faster than GE and others. Inline the common case. */
625 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
626 return tree_int_cst_lt (val, val2);
627 else
629 tree tcmp;
631 fold_defer_overflow_warnings ();
633 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
635 fold_undefer_and_ignore_overflow_warnings ();
637 if (!tcmp
638 || TREE_CODE (tcmp) != INTEGER_CST)
639 return -2;
641 if (!integer_zerop (tcmp))
642 return 1;
645 return 0;
648 /* Compare two values VAL1 and VAL2. Return
650 -2 if VAL1 and VAL2 cannot be compared at compile-time,
651 -1 if VAL1 < VAL2,
652 0 if VAL1 == VAL2,
653 +1 if VAL1 > VAL2, and
654 +2 if VAL1 != VAL2
656 This is similar to tree_int_cst_compare but supports pointer values
657 and values that cannot be compared at compile time.
659 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
660 true if the return value is only valid if we assume that signed
661 overflow is undefined. */
664 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
666 if (val1 == val2)
667 return 0;
669 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
670 both integers. */
671 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
672 == POINTER_TYPE_P (TREE_TYPE (val2)));
674 /* Convert the two values into the same type. This is needed because
675 sizetype causes sign extension even for unsigned types. */
676 val2 = fold_convert (TREE_TYPE (val1), val2);
677 STRIP_USELESS_TYPE_CONVERSION (val2);
679 const bool overflow_undefined
680 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
681 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
682 tree inv1, inv2;
683 bool neg1, neg2;
684 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
685 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
687 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
688 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
689 if (sym1 && sym2)
691 /* Both values must use the same name with the same sign. */
692 if (sym1 != sym2 || neg1 != neg2)
693 return -2;
695 /* [-]NAME + CST == [-]NAME + CST. */
696 if (inv1 == inv2)
697 return 0;
699 /* If overflow is defined we cannot simplify more. */
700 if (!overflow_undefined)
701 return -2;
703 if (strict_overflow_p != NULL
704 /* Symbolic range building sets TREE_NO_WARNING to declare
705 that overflow doesn't happen. */
706 && (!inv1 || !TREE_NO_WARNING (val1))
707 && (!inv2 || !TREE_NO_WARNING (val2)))
708 *strict_overflow_p = true;
710 if (!inv1)
711 inv1 = build_int_cst (TREE_TYPE (val1), 0);
712 if (!inv2)
713 inv2 = build_int_cst (TREE_TYPE (val2), 0);
715 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
716 TYPE_SIGN (TREE_TYPE (val1)));
719 const bool cst1 = is_gimple_min_invariant (val1);
720 const bool cst2 = is_gimple_min_invariant (val2);
722 /* If one is of the form '[-]NAME + CST' and the other is constant, then
723 it might be possible to say something depending on the constants. */
724 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
726 if (!overflow_undefined)
727 return -2;
729 if (strict_overflow_p != NULL
730 /* Symbolic range building sets TREE_NO_WARNING to declare
731 that overflow doesn't happen. */
732 && (!sym1 || !TREE_NO_WARNING (val1))
733 && (!sym2 || !TREE_NO_WARNING (val2)))
734 *strict_overflow_p = true;
736 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
737 tree cst = cst1 ? val1 : val2;
738 tree inv = cst1 ? inv2 : inv1;
740 /* Compute the difference between the constants. If it overflows or
741 underflows, this means that we can trivially compare the NAME with
742 it and, consequently, the two values with each other. */
743 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
744 if (wi::cmp (0, wi::to_wide (inv), sgn)
745 != wi::cmp (diff, wi::to_wide (cst), sgn))
747 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
748 return cst1 ? res : -res;
751 return -2;
754 /* We cannot say anything more for non-constants. */
755 if (!cst1 || !cst2)
756 return -2;
758 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
760 /* We cannot compare overflowed values. */
761 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
762 return -2;
764 if (TREE_CODE (val1) == INTEGER_CST
765 && TREE_CODE (val2) == INTEGER_CST)
766 return tree_int_cst_compare (val1, val2);
768 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
770 if (known_eq (wi::to_poly_widest (val1),
771 wi::to_poly_widest (val2)))
772 return 0;
773 if (known_lt (wi::to_poly_widest (val1),
774 wi::to_poly_widest (val2)))
775 return -1;
776 if (known_gt (wi::to_poly_widest (val1),
777 wi::to_poly_widest (val2)))
778 return 1;
781 return -2;
783 else
785 tree t;
787 /* First see if VAL1 and VAL2 are not the same. */
788 if (val1 == val2 || operand_equal_p (val1, val2, 0))
789 return 0;
791 /* If VAL1 is a lower address than VAL2, return -1. */
792 if (operand_less_p (val1, val2) == 1)
793 return -1;
795 /* If VAL1 is a higher address than VAL2, return +1. */
796 if (operand_less_p (val2, val1) == 1)
797 return 1;
799 /* If VAL1 is different than VAL2, return +2.
800 For integer constants we either have already returned -1 or 1
801 or they are equivalent. We still might succeed in proving
802 something about non-trivial operands. */
803 if (TREE_CODE (val1) != INTEGER_CST
804 || TREE_CODE (val2) != INTEGER_CST)
806 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
807 if (t && integer_onep (t))
808 return 2;
811 return -2;
815 /* Compare values like compare_values_warnv. */
818 compare_values (tree val1, tree val2)
820 bool sop;
821 return compare_values_warnv (val1, val2, &sop);
825 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
826 0 if VAL is not inside [MIN, MAX],
827 -2 if we cannot tell either way.
829 Benchmark compile/20001226-1.c compilation time after changing this
830 function. */
833 value_inside_range (tree val, tree min, tree max)
835 int cmp1, cmp2;
837 cmp1 = operand_less_p (val, min);
838 if (cmp1 == -2)
839 return -2;
840 if (cmp1 == 1)
841 return 0;
843 cmp2 = operand_less_p (max, val);
844 if (cmp2 == -2)
845 return -2;
847 return !cmp2;
851 /* Return true if value ranges VR0 and VR1 have a non-empty
852 intersection.
854 Benchmark compile/20001226-1.c compilation time after changing this
855 function.
858 static inline bool
859 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
861 /* The value ranges do not intersect if the maximum of the first range is
862 less than the minimum of the second range or vice versa.
863 When those relations are unknown, we can't do any better. */
864 if (operand_less_p (vr0->max, vr1->min) != 0)
865 return false;
866 if (operand_less_p (vr1->max, vr0->min) != 0)
867 return false;
868 return true;
872 /* Return TRUE if *VR includes the value zero. */
874 bool
875 range_includes_zero_p (const value_range *vr)
877 if (vr->type == VR_VARYING)
878 return true;
880 /* Ughh, we don't know. We choose not to optimize. */
881 if (vr->type == VR_UNDEFINED)
882 return true;
884 tree zero = build_int_cst (TREE_TYPE (vr->min), 0);
885 if (vr->type == VR_ANTI_RANGE)
887 int res = value_inside_range (zero, vr->min, vr->max);
888 return res == 0 || res == -2;
890 return value_inside_range (zero, vr->min, vr->max) != 0;
893 /* Return true if *VR is know to only contain nonnegative values. */
895 static inline bool
896 value_range_nonnegative_p (value_range *vr)
898 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
899 which would return a useful value should be encoded as a
900 VR_RANGE. */
901 if (vr->type == VR_RANGE)
903 int result = compare_values (vr->min, integer_zero_node);
904 return (result == 0 || result == 1);
907 return false;
910 /* If *VR has a value rante that is a single constant value return that,
911 otherwise return NULL_TREE. */
913 tree
914 value_range_constant_singleton (value_range *vr)
916 if (vr->type == VR_RANGE
917 && vrp_operand_equal_p (vr->min, vr->max)
918 && is_gimple_min_invariant (vr->min))
919 return vr->min;
921 return NULL_TREE;
924 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
926 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
928 Return TRUE if VR was a constant range and we were able to compute
929 the bit masks. */
931 bool
932 vrp_set_zero_nonzero_bits (const tree expr_type,
933 value_range *vr,
934 wide_int *may_be_nonzero,
935 wide_int *must_be_nonzero)
937 if (!range_int_cst_p (vr))
939 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
940 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
941 return false;
943 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
944 wi::to_wide (vr->min),
945 wi::to_wide (vr->max),
946 *may_be_nonzero, *must_be_nonzero);
947 return true;
950 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
951 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
952 false otherwise. If *AR can be represented with a single range
953 *VR1 will be VR_UNDEFINED. */
955 static bool
956 ranges_from_anti_range (value_range *ar,
957 value_range *vr0, value_range *vr1)
959 tree type = TREE_TYPE (ar->min);
961 vr0->type = VR_UNDEFINED;
962 vr1->type = VR_UNDEFINED;
964 /* As a future improvement, we could handle ~[0, A] as: [-INF, -1] U
965 [A+1, +INF]. Not sure if this helps in practice, though. */
967 if (ar->type != VR_ANTI_RANGE
968 || TREE_CODE (ar->min) != INTEGER_CST
969 || TREE_CODE (ar->max) != INTEGER_CST
970 || !vrp_val_min (type)
971 || !vrp_val_max (type))
972 return false;
974 if (!vrp_val_is_min (ar->min))
976 vr0->type = VR_RANGE;
977 vr0->min = vrp_val_min (type);
978 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
980 if (!vrp_val_is_max (ar->max))
982 vr1->type = VR_RANGE;
983 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
984 vr1->max = vrp_val_max (type);
986 if (vr0->type == VR_UNDEFINED)
988 *vr0 = *vr1;
989 vr1->type = VR_UNDEFINED;
992 return vr0->type != VR_UNDEFINED;
995 /* Extract the components of a value range into a pair of wide ints in
996 [WMIN, WMAX].
998 If the value range is anything but a VR_RANGE of constants, the
999 resulting wide ints are set to [-MIN, +MAX] for the type. */
1001 static void inline
1002 extract_range_into_wide_ints (value_range *vr,
1003 signop sign, unsigned prec,
1004 wide_int &wmin, wide_int &wmax)
1006 if (range_int_cst_p (vr))
1008 wmin = wi::to_wide (vr->min);
1009 wmax = wi::to_wide (vr->max);
1011 else
1013 wmin = wi::min_value (prec, sign);
1014 wmax = wi::max_value (prec, sign);
1018 /* Value range wrapper for wide_int_range_shift_undefined_p. */
1020 static inline bool
1021 vrp_shift_undefined_p (const value_range &shifter, unsigned prec)
1023 tree type = TREE_TYPE (shifter.min);
1024 return wide_int_range_shift_undefined_p (TYPE_SIGN (type), prec,
1025 wi::to_wide (shifter.min),
1026 wi::to_wide (shifter.max));
1029 /* Value range wrapper for wide_int_range_multiplicative_op:
1031 *VR = *VR0 .CODE. *VR1. */
1033 static void
1034 extract_range_from_multiplicative_op (value_range *vr,
1035 enum tree_code code,
1036 value_range *vr0, value_range *vr1)
1038 gcc_assert (code == MULT_EXPR
1039 || code == TRUNC_DIV_EXPR
1040 || code == FLOOR_DIV_EXPR
1041 || code == CEIL_DIV_EXPR
1042 || code == EXACT_DIV_EXPR
1043 || code == ROUND_DIV_EXPR
1044 || code == RSHIFT_EXPR
1045 || code == LSHIFT_EXPR);
1046 gcc_assert (vr0->type == VR_RANGE && vr0->type == vr1->type);
1048 tree type = TREE_TYPE (vr0->min);
1049 wide_int res_lb, res_ub;
1050 wide_int vr0_lb = wi::to_wide (vr0->min);
1051 wide_int vr0_ub = wi::to_wide (vr0->max);
1052 wide_int vr1_lb = wi::to_wide (vr1->min);
1053 wide_int vr1_ub = wi::to_wide (vr1->max);
1054 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1055 bool overflow_wraps = TYPE_OVERFLOW_WRAPS (type);
1056 unsigned prec = TYPE_PRECISION (type);
1058 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1059 code, TYPE_SIGN (type), prec,
1060 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1061 overflow_undefined, overflow_wraps))
1062 set_and_canonicalize_value_range (vr, VR_RANGE,
1063 wide_int_to_tree (type, res_lb),
1064 wide_int_to_tree (type, res_ub), NULL);
1065 else
1066 set_value_range_to_varying (vr);
1069 /* Value range wrapper for wide_int_range_can_optimize_bit_op.
1071 If a bit operation on two ranges can be easily optimized in terms
1072 of a mask, store the optimized new range in VR and return TRUE. */
1074 static bool
1075 vrp_can_optimize_bit_op (value_range *vr, enum tree_code code,
1076 value_range *vr0, value_range *vr1)
1078 tree lower_bound, upper_bound, mask;
1079 if (code != BIT_AND_EXPR && code != BIT_IOR_EXPR)
1080 return false;
1081 if (range_int_cst_singleton_p (vr1))
1083 if (!range_int_cst_p (vr0))
1084 return false;
1085 mask = vr1->min;
1086 lower_bound = vr0->min;
1087 upper_bound = vr0->max;
1089 else if (range_int_cst_singleton_p (vr0))
1091 if (!range_int_cst_p (vr1))
1092 return false;
1093 mask = vr0->min;
1094 lower_bound = vr1->min;
1095 upper_bound = vr1->max;
1097 else
1098 return false;
1099 if (wide_int_range_can_optimize_bit_op (code,
1100 wi::to_wide (lower_bound),
1101 wi::to_wide (upper_bound),
1102 wi::to_wide (mask)))
1104 tree min = int_const_binop (code, lower_bound, mask);
1105 tree max = int_const_binop (code, upper_bound, mask);
1106 set_value_range (vr, VR_RANGE, min, max, NULL);
1107 return true;
1109 return false;
1112 /* If BOUND will include a symbolic bound, adjust it accordingly,
1113 otherwise leave it as is.
1115 CODE is the original operation that combined the bounds (PLUS_EXPR
1116 or MINUS_EXPR).
1118 TYPE is the type of the original operation.
1120 SYM_OPn is the symbolic for OPn if it has a symbolic.
1122 NEG_OPn is TRUE if the OPn was negated. */
1124 static void
1125 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1126 tree sym_op0, tree sym_op1,
1127 bool neg_op0, bool neg_op1)
1129 bool minus_p = (code == MINUS_EXPR);
1130 /* If the result bound is constant, we're done; otherwise, build the
1131 symbolic lower bound. */
1132 if (sym_op0 == sym_op1)
1134 else if (sym_op0)
1135 bound = build_symbolic_expr (type, sym_op0,
1136 neg_op0, bound);
1137 else if (sym_op1)
1139 /* We may not negate if that might introduce
1140 undefined overflow. */
1141 if (!minus_p
1142 || neg_op1
1143 || TYPE_OVERFLOW_WRAPS (type))
1144 bound = build_symbolic_expr (type, sym_op1,
1145 neg_op1 ^ minus_p, bound);
1146 else
1147 bound = NULL_TREE;
1151 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1152 int bound according to CODE. CODE is the operation combining the
1153 bound (either a PLUS_EXPR or a MINUS_EXPR).
1155 TYPE is the type of the combine operation.
1157 WI is the wide int to store the result.
1159 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1160 if over/underflow occurred. */
1162 static void
1163 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1164 tree type, tree op0, tree op1)
1166 bool minus_p = (code == MINUS_EXPR);
1167 const signop sgn = TYPE_SIGN (type);
1168 const unsigned int prec = TYPE_PRECISION (type);
1170 /* Combine the bounds, if any. */
1171 if (op0 && op1)
1173 if (minus_p)
1174 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1175 else
1176 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1178 else if (op0)
1179 wi = wi::to_wide (op0);
1180 else if (op1)
1182 if (minus_p)
1183 wi = wi::neg (wi::to_wide (op1), &ovf);
1184 else
1185 wi = wi::to_wide (op1);
1187 else
1188 wi = wi::shwi (0, prec);
1191 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1192 put the result in VR.
1194 TYPE is the type of the range.
1196 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1197 occurred while originally calculating WMIN or WMAX. -1 indicates
1198 underflow. +1 indicates overflow. 0 indicates neither. */
1200 static void
1201 set_value_range_with_overflow (value_range &vr,
1202 tree type,
1203 const wide_int &wmin, const wide_int &wmax,
1204 wi::overflow_type min_ovf,
1205 wi::overflow_type max_ovf)
1207 const signop sgn = TYPE_SIGN (type);
1208 const unsigned int prec = TYPE_PRECISION (type);
1209 vr.type = VR_RANGE;
1210 vr.equiv = NULL;
1211 if (TYPE_OVERFLOW_WRAPS (type))
1213 /* If overflow wraps, truncate the values and adjust the
1214 range kind and bounds appropriately. */
1215 wide_int tmin = wide_int::from (wmin, prec, sgn);
1216 wide_int tmax = wide_int::from (wmax, prec, sgn);
1217 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1219 /* No overflow or both overflow or underflow. The
1220 range kind stays VR_RANGE. */
1221 vr.min = wide_int_to_tree (type, tmin);
1222 vr.max = wide_int_to_tree (type, tmax);
1224 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1225 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1227 /* Min underflow or max overflow. The range kind
1228 changes to VR_ANTI_RANGE. */
1229 bool covers = false;
1230 wide_int tem = tmin;
1231 vr.type = VR_ANTI_RANGE;
1232 tmin = tmax + 1;
1233 if (wi::cmp (tmin, tmax, sgn) < 0)
1234 covers = true;
1235 tmax = tem - 1;
1236 if (wi::cmp (tmax, tem, sgn) > 0)
1237 covers = true;
1238 /* If the anti-range would cover nothing, drop to varying.
1239 Likewise if the anti-range bounds are outside of the
1240 types values. */
1241 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1243 set_value_range_to_varying (&vr);
1244 return;
1246 vr.min = wide_int_to_tree (type, tmin);
1247 vr.max = wide_int_to_tree (type, tmax);
1249 else
1251 /* Other underflow and/or overflow, drop to VR_VARYING. */
1252 set_value_range_to_varying (&vr);
1253 return;
1256 else
1258 /* If overflow does not wrap, saturate to the types min/max
1259 value. */
1260 wide_int type_min = wi::min_value (prec, sgn);
1261 wide_int type_max = wi::max_value (prec, sgn);
1262 if (min_ovf == wi::OVF_UNDERFLOW)
1263 vr.min = wide_int_to_tree (type, type_min);
1264 else if (min_ovf == wi::OVF_OVERFLOW)
1265 vr.min = wide_int_to_tree (type, type_max);
1266 else
1267 vr.min = wide_int_to_tree (type, wmin);
1269 if (max_ovf == wi::OVF_UNDERFLOW)
1270 vr.max = wide_int_to_tree (type, type_min);
1271 else if (max_ovf == wi::OVF_OVERFLOW)
1272 vr.max = wide_int_to_tree (type, type_max);
1273 else
1274 vr.max = wide_int_to_tree (type, wmax);
1278 /* Extract range information from a binary operation CODE based on
1279 the ranges of each of its operands *VR0 and *VR1 with resulting
1280 type EXPR_TYPE. The resulting range is stored in *VR. */
1282 void
1283 extract_range_from_binary_expr_1 (value_range *vr,
1284 enum tree_code code, tree expr_type,
1285 value_range *vr0_, value_range *vr1_)
1287 signop sign = TYPE_SIGN (expr_type);
1288 unsigned int prec = TYPE_PRECISION (expr_type);
1289 value_range vr0 = *vr0_, vr1 = *vr1_;
1290 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1291 enum value_range_type type;
1292 tree min = NULL_TREE, max = NULL_TREE;
1293 int cmp;
1295 if (!INTEGRAL_TYPE_P (expr_type)
1296 && !POINTER_TYPE_P (expr_type))
1298 set_value_range_to_varying (vr);
1299 return;
1302 /* Not all binary expressions can be applied to ranges in a
1303 meaningful way. Handle only arithmetic operations. */
1304 if (code != PLUS_EXPR
1305 && code != MINUS_EXPR
1306 && code != POINTER_PLUS_EXPR
1307 && code != MULT_EXPR
1308 && code != TRUNC_DIV_EXPR
1309 && code != FLOOR_DIV_EXPR
1310 && code != CEIL_DIV_EXPR
1311 && code != EXACT_DIV_EXPR
1312 && code != ROUND_DIV_EXPR
1313 && code != TRUNC_MOD_EXPR
1314 && code != RSHIFT_EXPR
1315 && code != LSHIFT_EXPR
1316 && code != MIN_EXPR
1317 && code != MAX_EXPR
1318 && code != BIT_AND_EXPR
1319 && code != BIT_IOR_EXPR
1320 && code != BIT_XOR_EXPR)
1322 set_value_range_to_varying (vr);
1323 return;
1326 /* If both ranges are UNDEFINED, so is the result. */
1327 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1329 set_value_range_to_undefined (vr);
1330 return;
1332 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1333 code. At some point we may want to special-case operations that
1334 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1335 operand. */
1336 else if (vr0.type == VR_UNDEFINED)
1337 set_value_range_to_varying (&vr0);
1338 else if (vr1.type == VR_UNDEFINED)
1339 set_value_range_to_varying (&vr1);
1341 /* We get imprecise results from ranges_from_anti_range when
1342 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1343 range, but then we also need to hack up vrp_meet. It's just
1344 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1345 if (code == EXACT_DIV_EXPR
1346 && vr0.type == VR_ANTI_RANGE
1347 && vr0.min == vr0.max
1348 && integer_zerop (vr0.min))
1350 set_value_range_to_nonnull (vr, expr_type);
1351 return;
1354 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1355 and express ~[] op X as ([]' op X) U ([]'' op X). */
1356 if (vr0.type == VR_ANTI_RANGE
1357 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1359 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1360 if (vrtem1.type != VR_UNDEFINED)
1362 value_range vrres = VR_INITIALIZER;
1363 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1364 &vrtem1, vr1_);
1365 vrp_meet (vr, &vrres);
1367 return;
1369 /* Likewise for X op ~[]. */
1370 if (vr1.type == VR_ANTI_RANGE
1371 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1373 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1374 if (vrtem1.type != VR_UNDEFINED)
1376 value_range vrres = VR_INITIALIZER;
1377 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1378 vr0_, &vrtem1);
1379 vrp_meet (vr, &vrres);
1381 return;
1384 /* The type of the resulting value range defaults to VR0.TYPE. */
1385 type = vr0.type;
1387 /* Refuse to operate on VARYING ranges, ranges of different kinds
1388 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1389 because we may be able to derive a useful range even if one of
1390 the operands is VR_VARYING or symbolic range. Similarly for
1391 divisions, MIN/MAX and PLUS/MINUS.
1393 TODO, we may be able to derive anti-ranges in some cases. */
1394 if (code != BIT_AND_EXPR
1395 && code != BIT_IOR_EXPR
1396 && code != TRUNC_DIV_EXPR
1397 && code != FLOOR_DIV_EXPR
1398 && code != CEIL_DIV_EXPR
1399 && code != EXACT_DIV_EXPR
1400 && code != ROUND_DIV_EXPR
1401 && code != TRUNC_MOD_EXPR
1402 && code != MIN_EXPR
1403 && code != MAX_EXPR
1404 && code != PLUS_EXPR
1405 && code != MINUS_EXPR
1406 && code != RSHIFT_EXPR
1407 && code != POINTER_PLUS_EXPR
1408 && (vr0.type == VR_VARYING
1409 || vr1.type == VR_VARYING
1410 || vr0.type != vr1.type
1411 || symbolic_range_p (&vr0)
1412 || symbolic_range_p (&vr1)))
1414 set_value_range_to_varying (vr);
1415 return;
1418 /* Now evaluate the expression to determine the new range. */
1419 if (POINTER_TYPE_P (expr_type))
1421 if (code == MIN_EXPR || code == MAX_EXPR)
1423 /* For MIN/MAX expressions with pointers, we only care about
1424 nullness, if both are non null, then the result is nonnull.
1425 If both are null, then the result is null. Otherwise they
1426 are varying. */
1427 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1428 set_value_range_to_nonnull (vr, expr_type);
1429 else if (range_is_null (&vr0) && range_is_null (&vr1))
1430 set_value_range_to_null (vr, expr_type);
1431 else
1432 set_value_range_to_varying (vr);
1434 else if (code == POINTER_PLUS_EXPR)
1436 /* For pointer types, we are really only interested in asserting
1437 whether the expression evaluates to non-NULL. */
1438 if (!range_includes_zero_p (&vr0)
1439 || !range_includes_zero_p (&vr1))
1440 set_value_range_to_nonnull (vr, expr_type);
1441 else if (range_is_null (&vr0) && range_is_null (&vr1))
1442 set_value_range_to_null (vr, expr_type);
1443 else
1444 set_value_range_to_varying (vr);
1446 else if (code == BIT_AND_EXPR)
1448 /* For pointer types, we are really only interested in asserting
1449 whether the expression evaluates to non-NULL. */
1450 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1451 set_value_range_to_nonnull (vr, expr_type);
1452 else if (range_is_null (&vr0) || range_is_null (&vr1))
1453 set_value_range_to_null (vr, expr_type);
1454 else
1455 set_value_range_to_varying (vr);
1457 else
1458 set_value_range_to_varying (vr);
1460 return;
1463 /* For integer ranges, apply the operation to each end of the
1464 range and see what we end up with. */
1465 if (code == PLUS_EXPR || code == MINUS_EXPR)
1467 const bool minus_p = (code == MINUS_EXPR);
1468 tree min_op0 = vr0.min;
1469 tree min_op1 = minus_p ? vr1.max : vr1.min;
1470 tree max_op0 = vr0.max;
1471 tree max_op1 = minus_p ? vr1.min : vr1.max;
1472 tree sym_min_op0 = NULL_TREE;
1473 tree sym_min_op1 = NULL_TREE;
1474 tree sym_max_op0 = NULL_TREE;
1475 tree sym_max_op1 = NULL_TREE;
1476 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1478 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1480 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1481 single-symbolic ranges, try to compute the precise resulting range,
1482 but only if we know that this resulting range will also be constant
1483 or single-symbolic. */
1484 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1485 && (TREE_CODE (min_op0) == INTEGER_CST
1486 || (sym_min_op0
1487 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1488 && (TREE_CODE (min_op1) == INTEGER_CST
1489 || (sym_min_op1
1490 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1491 && (!(sym_min_op0 && sym_min_op1)
1492 || (sym_min_op0 == sym_min_op1
1493 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1494 && (TREE_CODE (max_op0) == INTEGER_CST
1495 || (sym_max_op0
1496 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1497 && (TREE_CODE (max_op1) == INTEGER_CST
1498 || (sym_max_op1
1499 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1500 && (!(sym_max_op0 && sym_max_op1)
1501 || (sym_max_op0 == sym_max_op1
1502 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1504 wide_int wmin, wmax;
1505 wi::overflow_type min_ovf = wi::OVF_NONE;
1506 wi::overflow_type max_ovf = wi::OVF_NONE;
1508 /* Build the bounds. */
1509 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1510 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1512 /* If we have overflow for the constant part and the resulting
1513 range will be symbolic, drop to VR_VARYING. */
1514 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1515 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1517 set_value_range_to_varying (vr);
1518 return;
1521 /* Adjust the range for possible overflow. */
1522 set_value_range_with_overflow (*vr, expr_type,
1523 wmin, wmax, min_ovf, max_ovf);
1524 if (vr->type == VR_VARYING)
1525 return;
1527 /* Build the symbolic bounds if needed. */
1528 adjust_symbolic_bound (vr->min, code, expr_type,
1529 sym_min_op0, sym_min_op1,
1530 neg_min_op0, neg_min_op1);
1531 adjust_symbolic_bound (vr->max, code, expr_type,
1532 sym_max_op0, sym_max_op1,
1533 neg_max_op0, neg_max_op1);
1534 /* ?? It would probably be cleaner to eliminate min/max/type
1535 entirely and hold these values in VR directly. */
1536 min = vr->min;
1537 max = vr->max;
1538 type = vr->type;
1540 else
1542 /* For other cases, for example if we have a PLUS_EXPR with two
1543 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1544 to compute a precise range for such a case.
1545 ??? General even mixed range kind operations can be expressed
1546 by for example transforming ~[3, 5] + [1, 2] to range-only
1547 operations and a union primitive:
1548 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1549 [-INF+1, 4] U [6, +INF(OVF)]
1550 though usually the union is not exactly representable with
1551 a single range or anti-range as the above is
1552 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1553 but one could use a scheme similar to equivalences for this. */
1554 set_value_range_to_varying (vr);
1555 return;
1558 else if (code == MIN_EXPR
1559 || code == MAX_EXPR)
1561 wide_int wmin, wmax;
1562 wide_int vr0_min, vr0_max;
1563 wide_int vr1_min, vr1_max;
1564 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1565 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1566 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1567 vr0_min, vr0_max, vr1_min, vr1_max))
1568 set_value_range (vr, VR_RANGE,
1569 wide_int_to_tree (expr_type, wmin),
1570 wide_int_to_tree (expr_type, wmax), NULL);
1571 else
1572 set_value_range_to_varying (vr);
1573 return;
1575 else if (code == MULT_EXPR)
1577 if (!range_int_cst_p (&vr0)
1578 || !range_int_cst_p (&vr1))
1580 set_value_range_to_varying (vr);
1581 return;
1583 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1584 return;
1586 else if (code == RSHIFT_EXPR
1587 || code == LSHIFT_EXPR)
1589 if (range_int_cst_p (&vr1)
1590 && !vrp_shift_undefined_p (vr1, prec))
1592 if (code == RSHIFT_EXPR)
1594 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1595 useful ranges just from the shift count. E.g.
1596 x >> 63 for signed 64-bit x is always [-1, 0]. */
1597 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1599 vr0.type = type = VR_RANGE;
1600 vr0.min = vrp_val_min (expr_type);
1601 vr0.max = vrp_val_max (expr_type);
1603 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1604 return;
1606 else if (code == LSHIFT_EXPR
1607 && range_int_cst_p (&vr0))
1609 wide_int res_lb, res_ub;
1610 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1611 wi::to_wide (vr0.min),
1612 wi::to_wide (vr0.max),
1613 wi::to_wide (vr1.min),
1614 wi::to_wide (vr1.max),
1615 TYPE_OVERFLOW_UNDEFINED (expr_type),
1616 TYPE_OVERFLOW_WRAPS (expr_type)))
1618 min = wide_int_to_tree (expr_type, res_lb);
1619 max = wide_int_to_tree (expr_type, res_ub);
1620 set_and_canonicalize_value_range (vr, VR_RANGE,
1621 min, max, NULL);
1622 return;
1626 set_value_range_to_varying (vr);
1627 return;
1629 else if (code == TRUNC_DIV_EXPR
1630 || code == FLOOR_DIV_EXPR
1631 || code == CEIL_DIV_EXPR
1632 || code == EXACT_DIV_EXPR
1633 || code == ROUND_DIV_EXPR)
1635 wide_int dividend_min, dividend_max, divisor_min, divisor_max;
1636 wide_int wmin, wmax, extra_min, extra_max;
1637 bool extra_range_p;
1639 /* Special case explicit division by zero as undefined. */
1640 if (range_is_null (&vr1))
1642 /* However, we must not eliminate a division by zero if
1643 flag_non_call_exceptions. */
1644 if (cfun->can_throw_non_call_exceptions)
1645 set_value_range_to_varying (vr);
1646 else
1647 set_value_range_to_undefined (vr);
1648 return;
1651 /* First, normalize ranges into constants we can handle. Note
1652 that VR_ANTI_RANGE's of constants were already normalized
1653 before arriving here.
1655 NOTE: As a future improvement, we may be able to do better
1656 with mixed symbolic (anti-)ranges like [0, A]. See note in
1657 ranges_from_anti_range. */
1658 extract_range_into_wide_ints (&vr0, sign, prec,
1659 dividend_min, dividend_max);
1660 extract_range_into_wide_ints (&vr1, sign, prec,
1661 divisor_min, divisor_max);
1662 if (!wide_int_range_div (wmin, wmax, code, sign, prec,
1663 dividend_min, dividend_max,
1664 divisor_min, divisor_max,
1665 TYPE_OVERFLOW_UNDEFINED (expr_type),
1666 TYPE_OVERFLOW_WRAPS (expr_type),
1667 extra_range_p, extra_min, extra_max))
1669 set_value_range_to_varying (vr);
1670 return;
1672 set_value_range (vr, VR_RANGE,
1673 wide_int_to_tree (expr_type, wmin),
1674 wide_int_to_tree (expr_type, wmax), NULL);
1675 if (extra_range_p)
1677 value_range extra_range = VR_INITIALIZER;
1678 set_value_range (&extra_range, VR_RANGE,
1679 wide_int_to_tree (expr_type, extra_min),
1680 wide_int_to_tree (expr_type, extra_max), NULL);
1681 vrp_meet (vr, &extra_range);
1683 return;
1685 else if (code == TRUNC_MOD_EXPR)
1687 if (range_is_null (&vr1))
1689 set_value_range_to_undefined (vr);
1690 return;
1692 wide_int wmin, wmax, tmp;
1693 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1694 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1695 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1696 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1697 vr0_min, vr0_max, vr1_min, vr1_max);
1698 min = wide_int_to_tree (expr_type, wmin);
1699 max = wide_int_to_tree (expr_type, wmax);
1700 set_value_range (vr, VR_RANGE, min, max, NULL);
1701 return;
1703 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1705 if (vrp_can_optimize_bit_op (vr, code, &vr0, &vr1))
1706 return;
1708 wide_int may_be_nonzero0, may_be_nonzero1;
1709 wide_int must_be_nonzero0, must_be_nonzero1;
1710 wide_int wmin, wmax;
1711 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1712 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1713 &may_be_nonzero0, &must_be_nonzero0);
1714 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1715 &may_be_nonzero1, &must_be_nonzero1);
1716 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1717 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1718 if (code == BIT_AND_EXPR)
1720 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1721 vr0_min, vr0_max,
1722 vr1_min, vr1_max,
1723 must_be_nonzero0,
1724 may_be_nonzero0,
1725 must_be_nonzero1,
1726 may_be_nonzero1))
1728 min = wide_int_to_tree (expr_type, wmin);
1729 max = wide_int_to_tree (expr_type, wmax);
1730 set_value_range (vr, VR_RANGE, min, max, NULL);
1732 else
1733 set_value_range_to_varying (vr);
1734 return;
1736 else if (code == BIT_IOR_EXPR)
1738 if (wide_int_range_bit_ior (wmin, wmax, sign,
1739 vr0_min, vr0_max,
1740 vr1_min, vr1_max,
1741 must_be_nonzero0,
1742 may_be_nonzero0,
1743 must_be_nonzero1,
1744 may_be_nonzero1))
1746 min = wide_int_to_tree (expr_type, wmin);
1747 max = wide_int_to_tree (expr_type, wmax);
1748 set_value_range (vr, VR_RANGE, min, max, NULL);
1750 else
1751 set_value_range_to_varying (vr);
1752 return;
1754 else if (code == BIT_XOR_EXPR)
1756 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1757 must_be_nonzero0,
1758 may_be_nonzero0,
1759 must_be_nonzero1,
1760 may_be_nonzero1))
1762 min = wide_int_to_tree (expr_type, wmin);
1763 max = wide_int_to_tree (expr_type, wmax);
1764 set_value_range (vr, VR_RANGE, min, max, NULL);
1766 else
1767 set_value_range_to_varying (vr);
1768 return;
1771 else
1772 gcc_unreachable ();
1774 /* If either MIN or MAX overflowed, then set the resulting range to
1775 VARYING. */
1776 if (min == NULL_TREE
1777 || TREE_OVERFLOW_P (min)
1778 || max == NULL_TREE
1779 || TREE_OVERFLOW_P (max))
1781 set_value_range_to_varying (vr);
1782 return;
1785 /* We punt for [-INF, +INF].
1786 We learn nothing when we have INF on both sides.
1787 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1788 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1790 set_value_range_to_varying (vr);
1791 return;
1794 cmp = compare_values (min, max);
1795 if (cmp == -2 || cmp == 1)
1797 /* If the new range has its limits swapped around (MIN > MAX),
1798 then the operation caused one of them to wrap around, mark
1799 the new range VARYING. */
1800 set_value_range_to_varying (vr);
1802 else
1803 set_value_range (vr, type, min, max, NULL);
1806 /* Extract range information from a unary operation CODE based on
1807 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
1808 The resulting range is stored in *VR. */
1810 void
1811 extract_range_from_unary_expr (value_range *vr,
1812 enum tree_code code, tree type,
1813 value_range *vr0_, tree op0_type)
1815 signop sign = TYPE_SIGN (type);
1816 unsigned int prec = TYPE_PRECISION (type);
1817 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1819 /* VRP only operates on integral and pointer types. */
1820 if (!(INTEGRAL_TYPE_P (op0_type)
1821 || POINTER_TYPE_P (op0_type))
1822 || !(INTEGRAL_TYPE_P (type)
1823 || POINTER_TYPE_P (type)))
1825 set_value_range_to_varying (vr);
1826 return;
1829 /* If VR0 is UNDEFINED, so is the result. */
1830 if (vr0.type == VR_UNDEFINED)
1832 set_value_range_to_undefined (vr);
1833 return;
1836 /* Handle operations that we express in terms of others. */
1837 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
1839 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
1840 copy_value_range (vr, &vr0);
1841 return;
1843 else if (code == NEGATE_EXPR)
1845 /* -X is simply 0 - X, so re-use existing code that also handles
1846 anti-ranges fine. */
1847 value_range zero = VR_INITIALIZER;
1848 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
1849 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
1850 return;
1852 else if (code == BIT_NOT_EXPR)
1854 /* ~X is simply -1 - X, so re-use existing code that also handles
1855 anti-ranges fine. */
1856 value_range minusone = VR_INITIALIZER;
1857 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
1858 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
1859 type, &minusone, &vr0);
1860 return;
1863 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1864 and express op ~[] as (op []') U (op []''). */
1865 if (vr0.type == VR_ANTI_RANGE
1866 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1868 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
1869 if (vrtem1.type != VR_UNDEFINED)
1871 value_range vrres = VR_INITIALIZER;
1872 extract_range_from_unary_expr (&vrres, code, type,
1873 &vrtem1, op0_type);
1874 vrp_meet (vr, &vrres);
1876 return;
1879 if (CONVERT_EXPR_CODE_P (code))
1881 tree inner_type = op0_type;
1882 tree outer_type = type;
1884 /* If the expression evaluates to a pointer, we are only interested in
1885 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
1886 if (POINTER_TYPE_P (type))
1888 if (!range_includes_zero_p (&vr0))
1889 set_value_range_to_nonnull (vr, type);
1890 else if (range_is_null (&vr0))
1891 set_value_range_to_null (vr, type);
1892 else
1893 set_value_range_to_varying (vr);
1894 return;
1897 /* If VR0 is varying and we increase the type precision, assume
1898 a full range for the following transformation. */
1899 if (vr0.type == VR_VARYING
1900 && INTEGRAL_TYPE_P (inner_type)
1901 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
1903 vr0.type = VR_RANGE;
1904 vr0.min = TYPE_MIN_VALUE (inner_type);
1905 vr0.max = TYPE_MAX_VALUE (inner_type);
1908 /* If VR0 is a constant range or anti-range and the conversion is
1909 not truncating we can convert the min and max values and
1910 canonicalize the resulting range. Otherwise we can do the
1911 conversion if the size of the range is less than what the
1912 precision of the target type can represent and the range is
1913 not an anti-range. */
1914 if ((vr0.type == VR_RANGE
1915 || vr0.type == VR_ANTI_RANGE)
1916 && TREE_CODE (vr0.min) == INTEGER_CST
1917 && TREE_CODE (vr0.max) == INTEGER_CST
1918 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
1919 || (vr0.type == VR_RANGE
1920 && integer_zerop (int_const_binop (RSHIFT_EXPR,
1921 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
1922 size_int (TYPE_PRECISION (outer_type)))))))
1924 tree new_min, new_max;
1925 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
1926 0, false);
1927 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
1928 0, false);
1929 set_and_canonicalize_value_range (vr, vr0.type,
1930 new_min, new_max, NULL);
1931 return;
1934 set_value_range_to_varying (vr);
1935 return;
1937 else if (code == ABS_EXPR)
1939 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1941 set_value_range_to_varying (vr);
1942 return;
1944 wide_int wmin, wmax;
1945 wide_int vr0_min, vr0_max;
1946 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1947 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
1948 TYPE_OVERFLOW_UNDEFINED (type)))
1949 set_value_range (vr, VR_RANGE,
1950 wide_int_to_tree (type, wmin),
1951 wide_int_to_tree (type, wmax), NULL);
1952 else
1953 set_value_range_to_varying (vr);
1954 return;
1957 /* For unhandled operations fall back to varying. */
1958 set_value_range_to_varying (vr);
1959 return;
1962 /* Debugging dumps. */
1964 void dump_value_range (FILE *, const value_range *);
1965 void debug_value_range (value_range *);
1966 void dump_all_value_ranges (FILE *);
1967 void dump_vr_equiv (FILE *, bitmap);
1968 void debug_vr_equiv (bitmap);
1971 /* Dump value range VR to FILE. */
1973 void
1974 dump_value_range (FILE *file, const value_range *vr)
1976 if (vr == NULL)
1977 fprintf (file, "[]");
1978 else if (vr->type == VR_UNDEFINED)
1979 fprintf (file, "UNDEFINED");
1980 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1982 tree type = TREE_TYPE (vr->min);
1984 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1986 if (INTEGRAL_TYPE_P (type)
1987 && !TYPE_UNSIGNED (type)
1988 && vrp_val_is_min (vr->min))
1989 fprintf (file, "-INF");
1990 else
1991 print_generic_expr (file, vr->min);
1993 fprintf (file, ", ");
1995 if (INTEGRAL_TYPE_P (type)
1996 && vrp_val_is_max (vr->max))
1997 fprintf (file, "+INF");
1998 else
1999 print_generic_expr (file, vr->max);
2001 fprintf (file, "]");
2003 if (vr->equiv)
2005 bitmap_iterator bi;
2006 unsigned i, c = 0;
2008 fprintf (file, " EQUIVALENCES: { ");
2010 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2012 print_generic_expr (file, ssa_name (i));
2013 fprintf (file, " ");
2014 c++;
2017 fprintf (file, "} (%u elements)", c);
2020 else if (vr->type == VR_VARYING)
2021 fprintf (file, "VARYING");
2022 else
2023 fprintf (file, "INVALID RANGE");
2027 /* Dump value range VR to stderr. */
2029 DEBUG_FUNCTION void
2030 debug_value_range (value_range *vr)
2032 dump_value_range (stderr, vr);
2033 fprintf (stderr, "\n");
2036 void
2037 value_range::dump ()
2039 debug_value_range (this);
2043 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2044 create a new SSA name N and return the assertion assignment
2045 'N = ASSERT_EXPR <V, V OP W>'. */
2047 static gimple *
2048 build_assert_expr_for (tree cond, tree v)
2050 tree a;
2051 gassign *assertion;
2053 gcc_assert (TREE_CODE (v) == SSA_NAME
2054 && COMPARISON_CLASS_P (cond));
2056 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2057 assertion = gimple_build_assign (NULL_TREE, a);
2059 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2060 operand of the ASSERT_EXPR. Create it so the new name and the old one
2061 are registered in the replacement table so that we can fix the SSA web
2062 after adding all the ASSERT_EXPRs. */
2063 tree new_def = create_new_def_for (v, assertion, NULL);
2064 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2065 given we have to be able to fully propagate those out to re-create
2066 valid SSA when removing the asserts. */
2067 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2068 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2070 return assertion;
2074 /* Return false if EXPR is a predicate expression involving floating
2075 point values. */
2077 static inline bool
2078 fp_predicate (gimple *stmt)
2080 GIMPLE_CHECK (stmt, GIMPLE_COND);
2082 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2085 /* If the range of values taken by OP can be inferred after STMT executes,
2086 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2087 describes the inferred range. Return true if a range could be
2088 inferred. */
2090 bool
2091 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2093 *val_p = NULL_TREE;
2094 *comp_code_p = ERROR_MARK;
2096 /* Do not attempt to infer anything in names that flow through
2097 abnormal edges. */
2098 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2099 return false;
2101 /* If STMT is the last statement of a basic block with no normal
2102 successors, there is no point inferring anything about any of its
2103 operands. We would not be able to find a proper insertion point
2104 for the assertion, anyway. */
2105 if (stmt_ends_bb_p (stmt))
2107 edge_iterator ei;
2108 edge e;
2110 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2111 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2112 break;
2113 if (e == NULL)
2114 return false;
2117 if (infer_nonnull_range (stmt, op))
2119 *val_p = build_int_cst (TREE_TYPE (op), 0);
2120 *comp_code_p = NE_EXPR;
2121 return true;
2124 return false;
2128 void dump_asserts_for (FILE *, tree);
2129 void debug_asserts_for (tree);
2130 void dump_all_asserts (FILE *);
2131 void debug_all_asserts (void);
2133 /* Dump all the registered assertions for NAME to FILE. */
2135 void
2136 dump_asserts_for (FILE *file, tree name)
2138 assert_locus *loc;
2140 fprintf (file, "Assertions to be inserted for ");
2141 print_generic_expr (file, name);
2142 fprintf (file, "\n");
2144 loc = asserts_for[SSA_NAME_VERSION (name)];
2145 while (loc)
2147 fprintf (file, "\t");
2148 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2149 fprintf (file, "\n\tBB #%d", loc->bb->index);
2150 if (loc->e)
2152 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2153 loc->e->dest->index);
2154 dump_edge_info (file, loc->e, dump_flags, 0);
2156 fprintf (file, "\n\tPREDICATE: ");
2157 print_generic_expr (file, loc->expr);
2158 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2159 print_generic_expr (file, loc->val);
2160 fprintf (file, "\n\n");
2161 loc = loc->next;
2164 fprintf (file, "\n");
2168 /* Dump all the registered assertions for NAME to stderr. */
2170 DEBUG_FUNCTION void
2171 debug_asserts_for (tree name)
2173 dump_asserts_for (stderr, name);
2177 /* Dump all the registered assertions for all the names to FILE. */
2179 void
2180 dump_all_asserts (FILE *file)
2182 unsigned i;
2183 bitmap_iterator bi;
2185 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2186 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2187 dump_asserts_for (file, ssa_name (i));
2188 fprintf (file, "\n");
2192 /* Dump all the registered assertions for all the names to stderr. */
2194 DEBUG_FUNCTION void
2195 debug_all_asserts (void)
2197 dump_all_asserts (stderr);
2200 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2202 static void
2203 add_assert_info (vec<assert_info> &asserts,
2204 tree name, tree expr, enum tree_code comp_code, tree val)
2206 assert_info info;
2207 info.comp_code = comp_code;
2208 info.name = name;
2209 if (TREE_OVERFLOW_P (val))
2210 val = drop_tree_overflow (val);
2211 info.val = val;
2212 info.expr = expr;
2213 asserts.safe_push (info);
2216 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2217 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2218 E->DEST, then register this location as a possible insertion point
2219 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2221 BB, E and SI provide the exact insertion point for the new
2222 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2223 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2224 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2225 must not be NULL. */
2227 static void
2228 register_new_assert_for (tree name, tree expr,
2229 enum tree_code comp_code,
2230 tree val,
2231 basic_block bb,
2232 edge e,
2233 gimple_stmt_iterator si)
2235 assert_locus *n, *loc, *last_loc;
2236 basic_block dest_bb;
2238 gcc_checking_assert (bb == NULL || e == NULL);
2240 if (e == NULL)
2241 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2242 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2244 /* Never build an assert comparing against an integer constant with
2245 TREE_OVERFLOW set. This confuses our undefined overflow warning
2246 machinery. */
2247 if (TREE_OVERFLOW_P (val))
2248 val = drop_tree_overflow (val);
2250 /* The new assertion A will be inserted at BB or E. We need to
2251 determine if the new location is dominated by a previously
2252 registered location for A. If we are doing an edge insertion,
2253 assume that A will be inserted at E->DEST. Note that this is not
2254 necessarily true.
2256 If E is a critical edge, it will be split. But even if E is
2257 split, the new block will dominate the same set of blocks that
2258 E->DEST dominates.
2260 The reverse, however, is not true, blocks dominated by E->DEST
2261 will not be dominated by the new block created to split E. So,
2262 if the insertion location is on a critical edge, we will not use
2263 the new location to move another assertion previously registered
2264 at a block dominated by E->DEST. */
2265 dest_bb = (bb) ? bb : e->dest;
2267 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2268 VAL at a block dominating DEST_BB, then we don't need to insert a new
2269 one. Similarly, if the same assertion already exists at a block
2270 dominated by DEST_BB and the new location is not on a critical
2271 edge, then update the existing location for the assertion (i.e.,
2272 move the assertion up in the dominance tree).
2274 Note, this is implemented as a simple linked list because there
2275 should not be more than a handful of assertions registered per
2276 name. If this becomes a performance problem, a table hashed by
2277 COMP_CODE and VAL could be implemented. */
2278 loc = asserts_for[SSA_NAME_VERSION (name)];
2279 last_loc = loc;
2280 while (loc)
2282 if (loc->comp_code == comp_code
2283 && (loc->val == val
2284 || operand_equal_p (loc->val, val, 0))
2285 && (loc->expr == expr
2286 || operand_equal_p (loc->expr, expr, 0)))
2288 /* If E is not a critical edge and DEST_BB
2289 dominates the existing location for the assertion, move
2290 the assertion up in the dominance tree by updating its
2291 location information. */
2292 if ((e == NULL || !EDGE_CRITICAL_P (e))
2293 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2295 loc->bb = dest_bb;
2296 loc->e = e;
2297 loc->si = si;
2298 return;
2302 /* Update the last node of the list and move to the next one. */
2303 last_loc = loc;
2304 loc = loc->next;
2307 /* If we didn't find an assertion already registered for
2308 NAME COMP_CODE VAL, add a new one at the end of the list of
2309 assertions associated with NAME. */
2310 n = XNEW (struct assert_locus);
2311 n->bb = dest_bb;
2312 n->e = e;
2313 n->si = si;
2314 n->comp_code = comp_code;
2315 n->val = val;
2316 n->expr = expr;
2317 n->next = NULL;
2319 if (last_loc)
2320 last_loc->next = n;
2321 else
2322 asserts_for[SSA_NAME_VERSION (name)] = n;
2324 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2327 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2328 Extract a suitable test code and value and store them into *CODE_P and
2329 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2331 If no extraction was possible, return FALSE, otherwise return TRUE.
2333 If INVERT is true, then we invert the result stored into *CODE_P. */
2335 static bool
2336 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2337 tree cond_op0, tree cond_op1,
2338 bool invert, enum tree_code *code_p,
2339 tree *val_p)
2341 enum tree_code comp_code;
2342 tree val;
2344 /* Otherwise, we have a comparison of the form NAME COMP VAL
2345 or VAL COMP NAME. */
2346 if (name == cond_op1)
2348 /* If the predicate is of the form VAL COMP NAME, flip
2349 COMP around because we need to register NAME as the
2350 first operand in the predicate. */
2351 comp_code = swap_tree_comparison (cond_code);
2352 val = cond_op0;
2354 else if (name == cond_op0)
2356 /* The comparison is of the form NAME COMP VAL, so the
2357 comparison code remains unchanged. */
2358 comp_code = cond_code;
2359 val = cond_op1;
2361 else
2362 gcc_unreachable ();
2364 /* Invert the comparison code as necessary. */
2365 if (invert)
2366 comp_code = invert_tree_comparison (comp_code, 0);
2368 /* VRP only handles integral and pointer types. */
2369 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2370 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2371 return false;
2373 /* Do not register always-false predicates.
2374 FIXME: this works around a limitation in fold() when dealing with
2375 enumerations. Given 'enum { N1, N2 } x;', fold will not
2376 fold 'if (x > N2)' to 'if (0)'. */
2377 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2378 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2380 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2381 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2383 if (comp_code == GT_EXPR
2384 && (!max
2385 || compare_values (val, max) == 0))
2386 return false;
2388 if (comp_code == LT_EXPR
2389 && (!min
2390 || compare_values (val, min) == 0))
2391 return false;
2393 *code_p = comp_code;
2394 *val_p = val;
2395 return true;
2398 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2399 (otherwise return VAL). VAL and MASK must be zero-extended for
2400 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2401 (to transform signed values into unsigned) and at the end xor
2402 SGNBIT back. */
2404 static wide_int
2405 masked_increment (const wide_int &val_in, const wide_int &mask,
2406 const wide_int &sgnbit, unsigned int prec)
2408 wide_int bit = wi::one (prec), res;
2409 unsigned int i;
2411 wide_int val = val_in ^ sgnbit;
2412 for (i = 0; i < prec; i++, bit += bit)
2414 res = mask;
2415 if ((res & bit) == 0)
2416 continue;
2417 res = bit - 1;
2418 res = wi::bit_and_not (val + bit, res);
2419 res &= mask;
2420 if (wi::gtu_p (res, val))
2421 return res ^ sgnbit;
2423 return val ^ sgnbit;
2426 /* Helper for overflow_comparison_p
2428 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2429 OP1's defining statement to see if it ultimately has the form
2430 OP0 CODE (OP0 PLUS INTEGER_CST)
2432 If so, return TRUE indicating this is an overflow test and store into
2433 *NEW_CST an updated constant that can be used in a narrowed range test.
2435 REVERSED indicates if the comparison was originally:
2437 OP1 CODE' OP0.
2439 This affects how we build the updated constant. */
2441 static bool
2442 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2443 bool follow_assert_exprs, bool reversed, tree *new_cst)
2445 /* See if this is a relational operation between two SSA_NAMES with
2446 unsigned, overflow wrapping values. If so, check it more deeply. */
2447 if ((code == LT_EXPR || code == LE_EXPR
2448 || code == GE_EXPR || code == GT_EXPR)
2449 && TREE_CODE (op0) == SSA_NAME
2450 && TREE_CODE (op1) == SSA_NAME
2451 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2452 && TYPE_UNSIGNED (TREE_TYPE (op0))
2453 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2455 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2457 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2458 if (follow_assert_exprs)
2460 while (gimple_assign_single_p (op1_def)
2461 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2463 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2464 if (TREE_CODE (op1) != SSA_NAME)
2465 break;
2466 op1_def = SSA_NAME_DEF_STMT (op1);
2470 /* Now look at the defining statement of OP1 to see if it adds
2471 or subtracts a nonzero constant from another operand. */
2472 if (op1_def
2473 && is_gimple_assign (op1_def)
2474 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2475 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2476 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2478 tree target = gimple_assign_rhs1 (op1_def);
2480 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2481 for one where TARGET appears on the RHS. */
2482 if (follow_assert_exprs)
2484 /* Now see if that "other operand" is op0, following the chain
2485 of ASSERT_EXPRs if necessary. */
2486 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2487 while (op0 != target
2488 && gimple_assign_single_p (op0_def)
2489 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2491 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2492 if (TREE_CODE (op0) != SSA_NAME)
2493 break;
2494 op0_def = SSA_NAME_DEF_STMT (op0);
2498 /* If we did not find our target SSA_NAME, then this is not
2499 an overflow test. */
2500 if (op0 != target)
2501 return false;
2503 tree type = TREE_TYPE (op0);
2504 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2505 tree inc = gimple_assign_rhs2 (op1_def);
2506 if (reversed)
2507 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2508 else
2509 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2510 return true;
2513 return false;
2516 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2517 OP1's defining statement to see if it ultimately has the form
2518 OP0 CODE (OP0 PLUS INTEGER_CST)
2520 If so, return TRUE indicating this is an overflow test and store into
2521 *NEW_CST an updated constant that can be used in a narrowed range test.
2523 These statements are left as-is in the IL to facilitate discovery of
2524 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2525 the alternate range representation is often useful within VRP. */
2527 bool
2528 overflow_comparison_p (tree_code code, tree name, tree val,
2529 bool use_equiv_p, tree *new_cst)
2531 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2532 return true;
2533 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2534 use_equiv_p, true, new_cst);
2538 /* Try to register an edge assertion for SSA name NAME on edge E for
2539 the condition COND contributing to the conditional jump pointed to by BSI.
2540 Invert the condition COND if INVERT is true. */
2542 static void
2543 register_edge_assert_for_2 (tree name, edge e,
2544 enum tree_code cond_code,
2545 tree cond_op0, tree cond_op1, bool invert,
2546 vec<assert_info> &asserts)
2548 tree val;
2549 enum tree_code comp_code;
2551 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2552 cond_op0,
2553 cond_op1,
2554 invert, &comp_code, &val))
2555 return;
2557 /* Queue the assert. */
2558 tree x;
2559 if (overflow_comparison_p (comp_code, name, val, false, &x))
2561 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2562 ? GT_EXPR : LE_EXPR);
2563 add_assert_info (asserts, name, name, new_code, x);
2565 add_assert_info (asserts, name, name, comp_code, val);
2567 /* In the case of NAME <= CST and NAME being defined as
2568 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2569 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2570 This catches range and anti-range tests. */
2571 if ((comp_code == LE_EXPR
2572 || comp_code == GT_EXPR)
2573 && TREE_CODE (val) == INTEGER_CST
2574 && TYPE_UNSIGNED (TREE_TYPE (val)))
2576 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2577 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2579 /* Extract CST2 from the (optional) addition. */
2580 if (is_gimple_assign (def_stmt)
2581 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2583 name2 = gimple_assign_rhs1 (def_stmt);
2584 cst2 = gimple_assign_rhs2 (def_stmt);
2585 if (TREE_CODE (name2) == SSA_NAME
2586 && TREE_CODE (cst2) == INTEGER_CST)
2587 def_stmt = SSA_NAME_DEF_STMT (name2);
2590 /* Extract NAME2 from the (optional) sign-changing cast. */
2591 if (gimple_assign_cast_p (def_stmt))
2593 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2594 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2595 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2596 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2597 name3 = gimple_assign_rhs1 (def_stmt);
2600 /* If name3 is used later, create an ASSERT_EXPR for it. */
2601 if (name3 != NULL_TREE
2602 && TREE_CODE (name3) == SSA_NAME
2603 && (cst2 == NULL_TREE
2604 || TREE_CODE (cst2) == INTEGER_CST)
2605 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2607 tree tmp;
2609 /* Build an expression for the range test. */
2610 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2611 if (cst2 != NULL_TREE)
2612 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2614 if (dump_file)
2616 fprintf (dump_file, "Adding assert for ");
2617 print_generic_expr (dump_file, name3);
2618 fprintf (dump_file, " from ");
2619 print_generic_expr (dump_file, tmp);
2620 fprintf (dump_file, "\n");
2623 add_assert_info (asserts, name3, tmp, comp_code, val);
2626 /* If name2 is used later, create an ASSERT_EXPR for it. */
2627 if (name2 != NULL_TREE
2628 && TREE_CODE (name2) == SSA_NAME
2629 && TREE_CODE (cst2) == INTEGER_CST
2630 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2632 tree tmp;
2634 /* Build an expression for the range test. */
2635 tmp = name2;
2636 if (TREE_TYPE (name) != TREE_TYPE (name2))
2637 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2638 if (cst2 != NULL_TREE)
2639 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2641 if (dump_file)
2643 fprintf (dump_file, "Adding assert for ");
2644 print_generic_expr (dump_file, name2);
2645 fprintf (dump_file, " from ");
2646 print_generic_expr (dump_file, tmp);
2647 fprintf (dump_file, "\n");
2650 add_assert_info (asserts, name2, tmp, comp_code, val);
2654 /* In the case of post-in/decrement tests like if (i++) ... and uses
2655 of the in/decremented value on the edge the extra name we want to
2656 assert for is not on the def chain of the name compared. Instead
2657 it is in the set of use stmts.
2658 Similar cases happen for conversions that were simplified through
2659 fold_{sign_changed,widened}_comparison. */
2660 if ((comp_code == NE_EXPR
2661 || comp_code == EQ_EXPR)
2662 && TREE_CODE (val) == INTEGER_CST)
2664 imm_use_iterator ui;
2665 gimple *use_stmt;
2666 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2668 if (!is_gimple_assign (use_stmt))
2669 continue;
2671 /* Cut off to use-stmts that are dominating the predecessor. */
2672 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2673 continue;
2675 tree name2 = gimple_assign_lhs (use_stmt);
2676 if (TREE_CODE (name2) != SSA_NAME)
2677 continue;
2679 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2680 tree cst;
2681 if (code == PLUS_EXPR
2682 || code == MINUS_EXPR)
2684 cst = gimple_assign_rhs2 (use_stmt);
2685 if (TREE_CODE (cst) != INTEGER_CST)
2686 continue;
2687 cst = int_const_binop (code, val, cst);
2689 else if (CONVERT_EXPR_CODE_P (code))
2691 /* For truncating conversions we cannot record
2692 an inequality. */
2693 if (comp_code == NE_EXPR
2694 && (TYPE_PRECISION (TREE_TYPE (name2))
2695 < TYPE_PRECISION (TREE_TYPE (name))))
2696 continue;
2697 cst = fold_convert (TREE_TYPE (name2), val);
2699 else
2700 continue;
2702 if (TREE_OVERFLOW_P (cst))
2703 cst = drop_tree_overflow (cst);
2704 add_assert_info (asserts, name2, name2, comp_code, cst);
2708 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2709 && TREE_CODE (val) == INTEGER_CST)
2711 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2712 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2713 tree val2 = NULL_TREE;
2714 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2715 wide_int mask = wi::zero (prec);
2716 unsigned int nprec = prec;
2717 enum tree_code rhs_code = ERROR_MARK;
2719 if (is_gimple_assign (def_stmt))
2720 rhs_code = gimple_assign_rhs_code (def_stmt);
2722 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2723 assert that A != CST1 -+ CST2. */
2724 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2725 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2727 tree op0 = gimple_assign_rhs1 (def_stmt);
2728 tree op1 = gimple_assign_rhs2 (def_stmt);
2729 if (TREE_CODE (op0) == SSA_NAME
2730 && TREE_CODE (op1) == INTEGER_CST)
2732 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2733 ? MINUS_EXPR : PLUS_EXPR);
2734 op1 = int_const_binop (reverse_op, val, op1);
2735 if (TREE_OVERFLOW (op1))
2736 op1 = drop_tree_overflow (op1);
2737 add_assert_info (asserts, op0, op0, comp_code, op1);
2741 /* Add asserts for NAME cmp CST and NAME being defined
2742 as NAME = (int) NAME2. */
2743 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2744 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2745 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2746 && gimple_assign_cast_p (def_stmt))
2748 name2 = gimple_assign_rhs1 (def_stmt);
2749 if (CONVERT_EXPR_CODE_P (rhs_code)
2750 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2751 && TYPE_UNSIGNED (TREE_TYPE (name2))
2752 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2753 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2754 || !tree_int_cst_equal (val,
2755 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2757 tree tmp, cst;
2758 enum tree_code new_comp_code = comp_code;
2760 cst = fold_convert (TREE_TYPE (name2),
2761 TYPE_MIN_VALUE (TREE_TYPE (val)));
2762 /* Build an expression for the range test. */
2763 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2764 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2765 fold_convert (TREE_TYPE (name2), val));
2766 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2768 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2769 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2770 build_int_cst (TREE_TYPE (name2), 1));
2773 if (dump_file)
2775 fprintf (dump_file, "Adding assert for ");
2776 print_generic_expr (dump_file, name2);
2777 fprintf (dump_file, " from ");
2778 print_generic_expr (dump_file, tmp);
2779 fprintf (dump_file, "\n");
2782 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2786 /* Add asserts for NAME cmp CST and NAME being defined as
2787 NAME = NAME2 >> CST2.
2789 Extract CST2 from the right shift. */
2790 if (rhs_code == RSHIFT_EXPR)
2792 name2 = gimple_assign_rhs1 (def_stmt);
2793 cst2 = gimple_assign_rhs2 (def_stmt);
2794 if (TREE_CODE (name2) == SSA_NAME
2795 && tree_fits_uhwi_p (cst2)
2796 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2797 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2798 && type_has_mode_precision_p (TREE_TYPE (val)))
2800 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2801 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2804 if (val2 != NULL_TREE
2805 && TREE_CODE (val2) == INTEGER_CST
2806 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2807 TREE_TYPE (val),
2808 val2, cst2), val))
2810 enum tree_code new_comp_code = comp_code;
2811 tree tmp, new_val;
2813 tmp = name2;
2814 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2816 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2818 tree type = build_nonstandard_integer_type (prec, 1);
2819 tmp = build1 (NOP_EXPR, type, name2);
2820 val2 = fold_convert (type, val2);
2822 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2823 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2824 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2826 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2828 wide_int minval
2829 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2830 new_val = val2;
2831 if (minval == wi::to_wide (new_val))
2832 new_val = NULL_TREE;
2834 else
2836 wide_int maxval
2837 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2838 mask |= wi::to_wide (val2);
2839 if (wi::eq_p (mask, maxval))
2840 new_val = NULL_TREE;
2841 else
2842 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2845 if (new_val)
2847 if (dump_file)
2849 fprintf (dump_file, "Adding assert for ");
2850 print_generic_expr (dump_file, name2);
2851 fprintf (dump_file, " from ");
2852 print_generic_expr (dump_file, tmp);
2853 fprintf (dump_file, "\n");
2856 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2860 /* Add asserts for NAME cmp CST and NAME being defined as
2861 NAME = NAME2 & CST2.
2863 Extract CST2 from the and.
2865 Also handle
2866 NAME = (unsigned) NAME2;
2867 casts where NAME's type is unsigned and has smaller precision
2868 than NAME2's type as if it was NAME = NAME2 & MASK. */
2869 names[0] = NULL_TREE;
2870 names[1] = NULL_TREE;
2871 cst2 = NULL_TREE;
2872 if (rhs_code == BIT_AND_EXPR
2873 || (CONVERT_EXPR_CODE_P (rhs_code)
2874 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2875 && TYPE_UNSIGNED (TREE_TYPE (val))
2876 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2877 > prec))
2879 name2 = gimple_assign_rhs1 (def_stmt);
2880 if (rhs_code == BIT_AND_EXPR)
2881 cst2 = gimple_assign_rhs2 (def_stmt);
2882 else
2884 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
2885 nprec = TYPE_PRECISION (TREE_TYPE (name2));
2887 if (TREE_CODE (name2) == SSA_NAME
2888 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2889 && TREE_CODE (cst2) == INTEGER_CST
2890 && !integer_zerop (cst2)
2891 && (nprec > 1
2892 || TYPE_UNSIGNED (TREE_TYPE (val))))
2894 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
2895 if (gimple_assign_cast_p (def_stmt2))
2897 names[1] = gimple_assign_rhs1 (def_stmt2);
2898 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2899 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
2900 || (TYPE_PRECISION (TREE_TYPE (name2))
2901 != TYPE_PRECISION (TREE_TYPE (names[1]))))
2902 names[1] = NULL_TREE;
2904 names[0] = name2;
2907 if (names[0] || names[1])
2909 wide_int minv, maxv, valv, cst2v;
2910 wide_int tem, sgnbit;
2911 bool valid_p = false, valn, cst2n;
2912 enum tree_code ccode = comp_code;
2914 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
2915 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
2916 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
2917 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
2918 /* If CST2 doesn't have most significant bit set,
2919 but VAL is negative, we have comparison like
2920 if ((x & 0x123) > -4) (always true). Just give up. */
2921 if (!cst2n && valn)
2922 ccode = ERROR_MARK;
2923 if (cst2n)
2924 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2925 else
2926 sgnbit = wi::zero (nprec);
2927 minv = valv & cst2v;
2928 switch (ccode)
2930 case EQ_EXPR:
2931 /* Minimum unsigned value for equality is VAL & CST2
2932 (should be equal to VAL, otherwise we probably should
2933 have folded the comparison into false) and
2934 maximum unsigned value is VAL | ~CST2. */
2935 maxv = valv | ~cst2v;
2936 valid_p = true;
2937 break;
2939 case NE_EXPR:
2940 tem = valv | ~cst2v;
2941 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
2942 if (valv == 0)
2944 cst2n = false;
2945 sgnbit = wi::zero (nprec);
2946 goto gt_expr;
2948 /* If (VAL | ~CST2) is all ones, handle it as
2949 (X & CST2) < VAL. */
2950 if (tem == -1)
2952 cst2n = false;
2953 valn = false;
2954 sgnbit = wi::zero (nprec);
2955 goto lt_expr;
2957 if (!cst2n && wi::neg_p (cst2v))
2958 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2959 if (sgnbit != 0)
2961 if (valv == sgnbit)
2963 cst2n = true;
2964 valn = true;
2965 goto gt_expr;
2967 if (tem == wi::mask (nprec - 1, false, nprec))
2969 cst2n = true;
2970 goto lt_expr;
2972 if (!cst2n)
2973 sgnbit = wi::zero (nprec);
2975 break;
2977 case GE_EXPR:
2978 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
2979 is VAL and maximum unsigned value is ~0. For signed
2980 comparison, if CST2 doesn't have most significant bit
2981 set, handle it similarly. If CST2 has MSB set,
2982 the minimum is the same, and maximum is ~0U/2. */
2983 if (minv != valv)
2985 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
2986 VAL. */
2987 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2988 if (minv == valv)
2989 break;
2991 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2992 valid_p = true;
2993 break;
2995 case GT_EXPR:
2996 gt_expr:
2997 /* Find out smallest MINV where MINV > VAL
2998 && (MINV & CST2) == MINV, if any. If VAL is signed and
2999 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3000 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3001 if (minv == valv)
3002 break;
3003 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3004 valid_p = true;
3005 break;
3007 case LE_EXPR:
3008 /* Minimum unsigned value for <= is 0 and maximum
3009 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3010 Otherwise, find smallest VAL2 where VAL2 > VAL
3011 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3012 as maximum.
3013 For signed comparison, if CST2 doesn't have most
3014 significant bit set, handle it similarly. If CST2 has
3015 MSB set, the maximum is the same and minimum is INT_MIN. */
3016 if (minv == valv)
3017 maxv = valv;
3018 else
3020 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3021 if (maxv == valv)
3022 break;
3023 maxv -= 1;
3025 maxv |= ~cst2v;
3026 minv = sgnbit;
3027 valid_p = true;
3028 break;
3030 case LT_EXPR:
3031 lt_expr:
3032 /* Minimum unsigned value for < is 0 and maximum
3033 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3034 Otherwise, find smallest VAL2 where VAL2 > VAL
3035 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3036 as maximum.
3037 For signed comparison, if CST2 doesn't have most
3038 significant bit set, handle it similarly. If CST2 has
3039 MSB set, the maximum is the same and minimum is INT_MIN. */
3040 if (minv == valv)
3042 if (valv == sgnbit)
3043 break;
3044 maxv = valv;
3046 else
3048 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3049 if (maxv == valv)
3050 break;
3052 maxv -= 1;
3053 maxv |= ~cst2v;
3054 minv = sgnbit;
3055 valid_p = true;
3056 break;
3058 default:
3059 break;
3061 if (valid_p
3062 && (maxv - minv) != -1)
3064 tree tmp, new_val, type;
3065 int i;
3067 for (i = 0; i < 2; i++)
3068 if (names[i])
3070 wide_int maxv2 = maxv;
3071 tmp = names[i];
3072 type = TREE_TYPE (names[i]);
3073 if (!TYPE_UNSIGNED (type))
3075 type = build_nonstandard_integer_type (nprec, 1);
3076 tmp = build1 (NOP_EXPR, type, names[i]);
3078 if (minv != 0)
3080 tmp = build2 (PLUS_EXPR, type, tmp,
3081 wide_int_to_tree (type, -minv));
3082 maxv2 = maxv - minv;
3084 new_val = wide_int_to_tree (type, maxv2);
3086 if (dump_file)
3088 fprintf (dump_file, "Adding assert for ");
3089 print_generic_expr (dump_file, names[i]);
3090 fprintf (dump_file, " from ");
3091 print_generic_expr (dump_file, tmp);
3092 fprintf (dump_file, "\n");
3095 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3102 /* OP is an operand of a truth value expression which is known to have
3103 a particular value. Register any asserts for OP and for any
3104 operands in OP's defining statement.
3106 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3107 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3109 static void
3110 register_edge_assert_for_1 (tree op, enum tree_code code,
3111 edge e, vec<assert_info> &asserts)
3113 gimple *op_def;
3114 tree val;
3115 enum tree_code rhs_code;
3117 /* We only care about SSA_NAMEs. */
3118 if (TREE_CODE (op) != SSA_NAME)
3119 return;
3121 /* We know that OP will have a zero or nonzero value. */
3122 val = build_int_cst (TREE_TYPE (op), 0);
3123 add_assert_info (asserts, op, op, code, val);
3125 /* Now look at how OP is set. If it's set from a comparison,
3126 a truth operation or some bit operations, then we may be able
3127 to register information about the operands of that assignment. */
3128 op_def = SSA_NAME_DEF_STMT (op);
3129 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3130 return;
3132 rhs_code = gimple_assign_rhs_code (op_def);
3134 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3136 bool invert = (code == EQ_EXPR ? true : false);
3137 tree op0 = gimple_assign_rhs1 (op_def);
3138 tree op1 = gimple_assign_rhs2 (op_def);
3140 if (TREE_CODE (op0) == SSA_NAME)
3141 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3142 if (TREE_CODE (op1) == SSA_NAME)
3143 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3145 else if ((code == NE_EXPR
3146 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3147 || (code == EQ_EXPR
3148 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3150 /* Recurse on each operand. */
3151 tree op0 = gimple_assign_rhs1 (op_def);
3152 tree op1 = gimple_assign_rhs2 (op_def);
3153 if (TREE_CODE (op0) == SSA_NAME
3154 && has_single_use (op0))
3155 register_edge_assert_for_1 (op0, code, e, asserts);
3156 if (TREE_CODE (op1) == SSA_NAME
3157 && has_single_use (op1))
3158 register_edge_assert_for_1 (op1, code, e, asserts);
3160 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3161 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3163 /* Recurse, flipping CODE. */
3164 code = invert_tree_comparison (code, false);
3165 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3167 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3169 /* Recurse through the copy. */
3170 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3172 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3174 /* Recurse through the type conversion, unless it is a narrowing
3175 conversion or conversion from non-integral type. */
3176 tree rhs = gimple_assign_rhs1 (op_def);
3177 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3178 && (TYPE_PRECISION (TREE_TYPE (rhs))
3179 <= TYPE_PRECISION (TREE_TYPE (op))))
3180 register_edge_assert_for_1 (rhs, code, e, asserts);
3184 /* Check if comparison
3185 NAME COND_OP INTEGER_CST
3186 has a form of
3187 (X & 11...100..0) COND_OP XX...X00...0
3188 Such comparison can yield assertions like
3189 X >= XX...X00...0
3190 X <= XX...X11...1
3191 in case of COND_OP being EQ_EXPR or
3192 X < XX...X00...0
3193 X > XX...X11...1
3194 in case of NE_EXPR. */
3196 static bool
3197 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3198 tree *new_name, tree *low, enum tree_code *low_code,
3199 tree *high, enum tree_code *high_code)
3201 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3203 if (!is_gimple_assign (def_stmt)
3204 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3205 return false;
3207 tree t = gimple_assign_rhs1 (def_stmt);
3208 tree maskt = gimple_assign_rhs2 (def_stmt);
3209 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3210 return false;
3212 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3213 wide_int inv_mask = ~mask;
3214 /* Must have been removed by now so don't bother optimizing. */
3215 if (mask == 0 || inv_mask == 0)
3216 return false;
3218 /* Assume VALT is INTEGER_CST. */
3219 wi::tree_to_wide_ref val = wi::to_wide (valt);
3221 if ((inv_mask & (inv_mask + 1)) != 0
3222 || (val & mask) != val)
3223 return false;
3225 bool is_range = cond_code == EQ_EXPR;
3227 tree type = TREE_TYPE (t);
3228 wide_int min = wi::min_value (type),
3229 max = wi::max_value (type);
3231 if (is_range)
3233 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3234 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3236 else
3238 /* We can still generate assertion if one of alternatives
3239 is known to always be false. */
3240 if (val == min)
3242 *low_code = (enum tree_code) 0;
3243 *high_code = GT_EXPR;
3245 else if ((val | inv_mask) == max)
3247 *low_code = LT_EXPR;
3248 *high_code = (enum tree_code) 0;
3250 else
3251 return false;
3254 *new_name = t;
3255 *low = wide_int_to_tree (type, val);
3256 *high = wide_int_to_tree (type, val | inv_mask);
3258 return true;
3261 /* Try to register an edge assertion for SSA name NAME on edge E for
3262 the condition COND contributing to the conditional jump pointed to by
3263 SI. */
3265 void
3266 register_edge_assert_for (tree name, edge e,
3267 enum tree_code cond_code, tree cond_op0,
3268 tree cond_op1, vec<assert_info> &asserts)
3270 tree val;
3271 enum tree_code comp_code;
3272 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3274 /* Do not attempt to infer anything in names that flow through
3275 abnormal edges. */
3276 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3277 return;
3279 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3280 cond_op0, cond_op1,
3281 is_else_edge,
3282 &comp_code, &val))
3283 return;
3285 /* Register ASSERT_EXPRs for name. */
3286 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3287 cond_op1, is_else_edge, asserts);
3290 /* If COND is effectively an equality test of an SSA_NAME against
3291 the value zero or one, then we may be able to assert values
3292 for SSA_NAMEs which flow into COND. */
3294 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3295 statement of NAME we can assert both operands of the BIT_AND_EXPR
3296 have nonzero value. */
3297 if (((comp_code == EQ_EXPR && integer_onep (val))
3298 || (comp_code == NE_EXPR && integer_zerop (val))))
3300 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3302 if (is_gimple_assign (def_stmt)
3303 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3305 tree op0 = gimple_assign_rhs1 (def_stmt);
3306 tree op1 = gimple_assign_rhs2 (def_stmt);
3307 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3308 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3312 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3313 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3314 have zero value. */
3315 if (((comp_code == EQ_EXPR && integer_zerop (val))
3316 || (comp_code == NE_EXPR && integer_onep (val))))
3318 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3320 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3321 necessarily zero value, or if type-precision is one. */
3322 if (is_gimple_assign (def_stmt)
3323 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3324 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3325 || comp_code == EQ_EXPR)))
3327 tree op0 = gimple_assign_rhs1 (def_stmt);
3328 tree op1 = gimple_assign_rhs2 (def_stmt);
3329 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3330 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3334 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3335 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3336 && TREE_CODE (val) == INTEGER_CST)
3338 enum tree_code low_code, high_code;
3339 tree low, high;
3340 if (is_masked_range_test (name, val, comp_code, &name, &low,
3341 &low_code, &high, &high_code))
3343 if (low_code != ERROR_MARK)
3344 register_edge_assert_for_2 (name, e, low_code, name,
3345 low, /*invert*/false, asserts);
3346 if (high_code != ERROR_MARK)
3347 register_edge_assert_for_2 (name, e, high_code, name,
3348 high, /*invert*/false, asserts);
3353 /* Finish found ASSERTS for E and register them at GSI. */
3355 static void
3356 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3357 vec<assert_info> &asserts)
3359 for (unsigned i = 0; i < asserts.length (); ++i)
3360 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3361 reachable from E. */
3362 if (live_on_edge (e, asserts[i].name))
3363 register_new_assert_for (asserts[i].name, asserts[i].expr,
3364 asserts[i].comp_code, asserts[i].val,
3365 NULL, e, gsi);
3370 /* Determine whether the outgoing edges of BB should receive an
3371 ASSERT_EXPR for each of the operands of BB's LAST statement.
3372 The last statement of BB must be a COND_EXPR.
3374 If any of the sub-graphs rooted at BB have an interesting use of
3375 the predicate operands, an assert location node is added to the
3376 list of assertions for the corresponding operands. */
3378 static void
3379 find_conditional_asserts (basic_block bb, gcond *last)
3381 gimple_stmt_iterator bsi;
3382 tree op;
3383 edge_iterator ei;
3384 edge e;
3385 ssa_op_iter iter;
3387 bsi = gsi_for_stmt (last);
3389 /* Look for uses of the operands in each of the sub-graphs
3390 rooted at BB. We need to check each of the outgoing edges
3391 separately, so that we know what kind of ASSERT_EXPR to
3392 insert. */
3393 FOR_EACH_EDGE (e, ei, bb->succs)
3395 if (e->dest == bb)
3396 continue;
3398 /* Register the necessary assertions for each operand in the
3399 conditional predicate. */
3400 auto_vec<assert_info, 8> asserts;
3401 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3402 register_edge_assert_for (op, e,
3403 gimple_cond_code (last),
3404 gimple_cond_lhs (last),
3405 gimple_cond_rhs (last), asserts);
3406 finish_register_edge_assert_for (e, bsi, asserts);
3410 struct case_info
3412 tree expr;
3413 basic_block bb;
3416 /* Compare two case labels sorting first by the destination bb index
3417 and then by the case value. */
3419 static int
3420 compare_case_labels (const void *p1, const void *p2)
3422 const struct case_info *ci1 = (const struct case_info *) p1;
3423 const struct case_info *ci2 = (const struct case_info *) p2;
3424 int idx1 = ci1->bb->index;
3425 int idx2 = ci2->bb->index;
3427 if (idx1 < idx2)
3428 return -1;
3429 else if (idx1 == idx2)
3431 /* Make sure the default label is first in a group. */
3432 if (!CASE_LOW (ci1->expr))
3433 return -1;
3434 else if (!CASE_LOW (ci2->expr))
3435 return 1;
3436 else
3437 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3438 CASE_LOW (ci2->expr));
3440 else
3441 return 1;
3444 /* Determine whether the outgoing edges of BB should receive an
3445 ASSERT_EXPR for each of the operands of BB's LAST statement.
3446 The last statement of BB must be a SWITCH_EXPR.
3448 If any of the sub-graphs rooted at BB have an interesting use of
3449 the predicate operands, an assert location node is added to the
3450 list of assertions for the corresponding operands. */
3452 static void
3453 find_switch_asserts (basic_block bb, gswitch *last)
3455 gimple_stmt_iterator bsi;
3456 tree op;
3457 edge e;
3458 struct case_info *ci;
3459 size_t n = gimple_switch_num_labels (last);
3460 #if GCC_VERSION >= 4000
3461 unsigned int idx;
3462 #else
3463 /* Work around GCC 3.4 bug (PR 37086). */
3464 volatile unsigned int idx;
3465 #endif
3467 bsi = gsi_for_stmt (last);
3468 op = gimple_switch_index (last);
3469 if (TREE_CODE (op) != SSA_NAME)
3470 return;
3472 /* Build a vector of case labels sorted by destination label. */
3473 ci = XNEWVEC (struct case_info, n);
3474 for (idx = 0; idx < n; ++idx)
3476 ci[idx].expr = gimple_switch_label (last, idx);
3477 ci[idx].bb = label_to_block (cfun, CASE_LABEL (ci[idx].expr));
3479 edge default_edge = find_edge (bb, ci[0].bb);
3480 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3482 for (idx = 0; idx < n; ++idx)
3484 tree min, max;
3485 tree cl = ci[idx].expr;
3486 basic_block cbb = ci[idx].bb;
3488 min = CASE_LOW (cl);
3489 max = CASE_HIGH (cl);
3491 /* If there are multiple case labels with the same destination
3492 we need to combine them to a single value range for the edge. */
3493 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3495 /* Skip labels until the last of the group. */
3496 do {
3497 ++idx;
3498 } while (idx < n && cbb == ci[idx].bb);
3499 --idx;
3501 /* Pick up the maximum of the case label range. */
3502 if (CASE_HIGH (ci[idx].expr))
3503 max = CASE_HIGH (ci[idx].expr);
3504 else
3505 max = CASE_LOW (ci[idx].expr);
3508 /* Can't extract a useful assertion out of a range that includes the
3509 default label. */
3510 if (min == NULL_TREE)
3511 continue;
3513 /* Find the edge to register the assert expr on. */
3514 e = find_edge (bb, cbb);
3516 /* Register the necessary assertions for the operand in the
3517 SWITCH_EXPR. */
3518 auto_vec<assert_info, 8> asserts;
3519 register_edge_assert_for (op, e,
3520 max ? GE_EXPR : EQ_EXPR,
3521 op, fold_convert (TREE_TYPE (op), min),
3522 asserts);
3523 if (max)
3524 register_edge_assert_for (op, e, LE_EXPR, op,
3525 fold_convert (TREE_TYPE (op), max),
3526 asserts);
3527 finish_register_edge_assert_for (e, bsi, asserts);
3530 XDELETEVEC (ci);
3532 if (!live_on_edge (default_edge, op))
3533 return;
3535 /* Now register along the default label assertions that correspond to the
3536 anti-range of each label. */
3537 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3538 if (insertion_limit == 0)
3539 return;
3541 /* We can't do this if the default case shares a label with another case. */
3542 tree default_cl = gimple_switch_default_label (last);
3543 for (idx = 1; idx < n; idx++)
3545 tree min, max;
3546 tree cl = gimple_switch_label (last, idx);
3547 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3548 continue;
3550 min = CASE_LOW (cl);
3551 max = CASE_HIGH (cl);
3553 /* Combine contiguous case ranges to reduce the number of assertions
3554 to insert. */
3555 for (idx = idx + 1; idx < n; idx++)
3557 tree next_min, next_max;
3558 tree next_cl = gimple_switch_label (last, idx);
3559 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3560 break;
3562 next_min = CASE_LOW (next_cl);
3563 next_max = CASE_HIGH (next_cl);
3565 wide_int difference = (wi::to_wide (next_min)
3566 - wi::to_wide (max ? max : min));
3567 if (wi::eq_p (difference, 1))
3568 max = next_max ? next_max : next_min;
3569 else
3570 break;
3572 idx--;
3574 if (max == NULL_TREE)
3576 /* Register the assertion OP != MIN. */
3577 auto_vec<assert_info, 8> asserts;
3578 min = fold_convert (TREE_TYPE (op), min);
3579 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3580 asserts);
3581 finish_register_edge_assert_for (default_edge, bsi, asserts);
3583 else
3585 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3586 which will give OP the anti-range ~[MIN,MAX]. */
3587 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3588 min = fold_convert (TREE_TYPE (uop), min);
3589 max = fold_convert (TREE_TYPE (uop), max);
3591 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3592 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3593 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3594 NULL, default_edge, bsi);
3597 if (--insertion_limit == 0)
3598 break;
3603 /* Traverse all the statements in block BB looking for statements that
3604 may generate useful assertions for the SSA names in their operand.
3605 If a statement produces a useful assertion A for name N_i, then the
3606 list of assertions already generated for N_i is scanned to
3607 determine if A is actually needed.
3609 If N_i already had the assertion A at a location dominating the
3610 current location, then nothing needs to be done. Otherwise, the
3611 new location for A is recorded instead.
3613 1- For every statement S in BB, all the variables used by S are
3614 added to bitmap FOUND_IN_SUBGRAPH.
3616 2- If statement S uses an operand N in a way that exposes a known
3617 value range for N, then if N was not already generated by an
3618 ASSERT_EXPR, create a new assert location for N. For instance,
3619 if N is a pointer and the statement dereferences it, we can
3620 assume that N is not NULL.
3622 3- COND_EXPRs are a special case of #2. We can derive range
3623 information from the predicate but need to insert different
3624 ASSERT_EXPRs for each of the sub-graphs rooted at the
3625 conditional block. If the last statement of BB is a conditional
3626 expression of the form 'X op Y', then
3628 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3630 b) If the conditional is the only entry point to the sub-graph
3631 corresponding to the THEN_CLAUSE, recurse into it. On
3632 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3633 an ASSERT_EXPR is added for the corresponding variable.
3635 c) Repeat step (b) on the ELSE_CLAUSE.
3637 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3639 For instance,
3641 if (a == 9)
3642 b = a;
3643 else
3644 b = c + 1;
3646 In this case, an assertion on the THEN clause is useful to
3647 determine that 'a' is always 9 on that edge. However, an assertion
3648 on the ELSE clause would be unnecessary.
3650 4- If BB does not end in a conditional expression, then we recurse
3651 into BB's dominator children.
3653 At the end of the recursive traversal, every SSA name will have a
3654 list of locations where ASSERT_EXPRs should be added. When a new
3655 location for name N is found, it is registered by calling
3656 register_new_assert_for. That function keeps track of all the
3657 registered assertions to prevent adding unnecessary assertions.
3658 For instance, if a pointer P_4 is dereferenced more than once in a
3659 dominator tree, only the location dominating all the dereference of
3660 P_4 will receive an ASSERT_EXPR. */
3662 static void
3663 find_assert_locations_1 (basic_block bb, sbitmap live)
3665 gimple *last;
3667 last = last_stmt (bb);
3669 /* If BB's last statement is a conditional statement involving integer
3670 operands, determine if we need to add ASSERT_EXPRs. */
3671 if (last
3672 && gimple_code (last) == GIMPLE_COND
3673 && !fp_predicate (last)
3674 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3675 find_conditional_asserts (bb, as_a <gcond *> (last));
3677 /* If BB's last statement is a switch statement involving integer
3678 operands, determine if we need to add ASSERT_EXPRs. */
3679 if (last
3680 && gimple_code (last) == GIMPLE_SWITCH
3681 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3682 find_switch_asserts (bb, as_a <gswitch *> (last));
3684 /* Traverse all the statements in BB marking used names and looking
3685 for statements that may infer assertions for their used operands. */
3686 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3687 gsi_prev (&si))
3689 gimple *stmt;
3690 tree op;
3691 ssa_op_iter i;
3693 stmt = gsi_stmt (si);
3695 if (is_gimple_debug (stmt))
3696 continue;
3698 /* See if we can derive an assertion for any of STMT's operands. */
3699 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3701 tree value;
3702 enum tree_code comp_code;
3704 /* If op is not live beyond this stmt, do not bother to insert
3705 asserts for it. */
3706 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3707 continue;
3709 /* If OP is used in such a way that we can infer a value
3710 range for it, and we don't find a previous assertion for
3711 it, create a new assertion location node for OP. */
3712 if (infer_value_range (stmt, op, &comp_code, &value))
3714 /* If we are able to infer a nonzero value range for OP,
3715 then walk backwards through the use-def chain to see if OP
3716 was set via a typecast.
3718 If so, then we can also infer a nonzero value range
3719 for the operand of the NOP_EXPR. */
3720 if (comp_code == NE_EXPR && integer_zerop (value))
3722 tree t = op;
3723 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3725 while (is_gimple_assign (def_stmt)
3726 && CONVERT_EXPR_CODE_P
3727 (gimple_assign_rhs_code (def_stmt))
3728 && TREE_CODE
3729 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3730 && POINTER_TYPE_P
3731 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3733 t = gimple_assign_rhs1 (def_stmt);
3734 def_stmt = SSA_NAME_DEF_STMT (t);
3736 /* Note we want to register the assert for the
3737 operand of the NOP_EXPR after SI, not after the
3738 conversion. */
3739 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3740 register_new_assert_for (t, t, comp_code, value,
3741 bb, NULL, si);
3745 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3749 /* Update live. */
3750 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3751 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3752 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3753 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3756 /* Traverse all PHI nodes in BB, updating live. */
3757 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3758 gsi_next (&si))
3760 use_operand_p arg_p;
3761 ssa_op_iter i;
3762 gphi *phi = si.phi ();
3763 tree res = gimple_phi_result (phi);
3765 if (virtual_operand_p (res))
3766 continue;
3768 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3770 tree arg = USE_FROM_PTR (arg_p);
3771 if (TREE_CODE (arg) == SSA_NAME)
3772 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3775 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3779 /* Do an RPO walk over the function computing SSA name liveness
3780 on-the-fly and deciding on assert expressions to insert. */
3782 static void
3783 find_assert_locations (void)
3785 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3786 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3787 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3788 int rpo_cnt, i;
3790 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3791 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3792 for (i = 0; i < rpo_cnt; ++i)
3793 bb_rpo[rpo[i]] = i;
3795 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3796 the order we compute liveness and insert asserts we otherwise
3797 fail to insert asserts into the loop latch. */
3798 loop_p loop;
3799 FOR_EACH_LOOP (loop, 0)
3801 i = loop->latch->index;
3802 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3803 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3804 !gsi_end_p (gsi); gsi_next (&gsi))
3806 gphi *phi = gsi.phi ();
3807 if (virtual_operand_p (gimple_phi_result (phi)))
3808 continue;
3809 tree arg = gimple_phi_arg_def (phi, j);
3810 if (TREE_CODE (arg) == SSA_NAME)
3812 if (live[i] == NULL)
3814 live[i] = sbitmap_alloc (num_ssa_names);
3815 bitmap_clear (live[i]);
3817 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3822 for (i = rpo_cnt - 1; i >= 0; --i)
3824 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3825 edge e;
3826 edge_iterator ei;
3828 if (!live[rpo[i]])
3830 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
3831 bitmap_clear (live[rpo[i]]);
3834 /* Process BB and update the live information with uses in
3835 this block. */
3836 find_assert_locations_1 (bb, live[rpo[i]]);
3838 /* Merge liveness into the predecessor blocks and free it. */
3839 if (!bitmap_empty_p (live[rpo[i]]))
3841 int pred_rpo = i;
3842 FOR_EACH_EDGE (e, ei, bb->preds)
3844 int pred = e->src->index;
3845 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3846 continue;
3848 if (!live[pred])
3850 live[pred] = sbitmap_alloc (num_ssa_names);
3851 bitmap_clear (live[pred]);
3853 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
3855 if (bb_rpo[pred] < pred_rpo)
3856 pred_rpo = bb_rpo[pred];
3859 /* Record the RPO number of the last visited block that needs
3860 live information from this block. */
3861 last_rpo[rpo[i]] = pred_rpo;
3863 else
3865 sbitmap_free (live[rpo[i]]);
3866 live[rpo[i]] = NULL;
3869 /* We can free all successors live bitmaps if all their
3870 predecessors have been visited already. */
3871 FOR_EACH_EDGE (e, ei, bb->succs)
3872 if (last_rpo[e->dest->index] == i
3873 && live[e->dest->index])
3875 sbitmap_free (live[e->dest->index]);
3876 live[e->dest->index] = NULL;
3880 XDELETEVEC (rpo);
3881 XDELETEVEC (bb_rpo);
3882 XDELETEVEC (last_rpo);
3883 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
3884 if (live[i])
3885 sbitmap_free (live[i]);
3886 XDELETEVEC (live);
3889 /* Create an ASSERT_EXPR for NAME and insert it in the location
3890 indicated by LOC. Return true if we made any edge insertions. */
3892 static bool
3893 process_assert_insertions_for (tree name, assert_locus *loc)
3895 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3896 gimple *stmt;
3897 tree cond;
3898 gimple *assert_stmt;
3899 edge_iterator ei;
3900 edge e;
3902 /* If we have X <=> X do not insert an assert expr for that. */
3903 if (loc->expr == loc->val)
3904 return false;
3906 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3907 assert_stmt = build_assert_expr_for (cond, name);
3908 if (loc->e)
3910 /* We have been asked to insert the assertion on an edge. This
3911 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3912 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
3913 || (gimple_code (gsi_stmt (loc->si))
3914 == GIMPLE_SWITCH));
3916 gsi_insert_on_edge (loc->e, assert_stmt);
3917 return true;
3920 /* If the stmt iterator points at the end then this is an insertion
3921 at the beginning of a block. */
3922 if (gsi_end_p (loc->si))
3924 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
3925 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
3926 return false;
3929 /* Otherwise, we can insert right after LOC->SI iff the
3930 statement must not be the last statement in the block. */
3931 stmt = gsi_stmt (loc->si);
3932 if (!stmt_ends_bb_p (stmt))
3934 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
3935 return false;
3938 /* If STMT must be the last statement in BB, we can only insert new
3939 assertions on the non-abnormal edge out of BB. Note that since
3940 STMT is not control flow, there may only be one non-abnormal/eh edge
3941 out of BB. */
3942 FOR_EACH_EDGE (e, ei, loc->bb->succs)
3943 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
3945 gsi_insert_on_edge (e, assert_stmt);
3946 return true;
3949 gcc_unreachable ();
3952 /* Qsort helper for sorting assert locations. If stable is true, don't
3953 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3954 on the other side some pointers might be NULL. */
3956 template <bool stable>
3957 static int
3958 compare_assert_loc (const void *pa, const void *pb)
3960 assert_locus * const a = *(assert_locus * const *)pa;
3961 assert_locus * const b = *(assert_locus * const *)pb;
3963 /* If stable, some asserts might be optimized away already, sort
3964 them last. */
3965 if (stable)
3967 if (a == NULL)
3968 return b != NULL;
3969 else if (b == NULL)
3970 return -1;
3973 if (a->e == NULL && b->e != NULL)
3974 return 1;
3975 else if (a->e != NULL && b->e == NULL)
3976 return -1;
3978 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3979 no need to test both a->e and b->e. */
3981 /* Sort after destination index. */
3982 if (a->e == NULL)
3984 else if (a->e->dest->index > b->e->dest->index)
3985 return 1;
3986 else if (a->e->dest->index < b->e->dest->index)
3987 return -1;
3989 /* Sort after comp_code. */
3990 if (a->comp_code > b->comp_code)
3991 return 1;
3992 else if (a->comp_code < b->comp_code)
3993 return -1;
3995 hashval_t ha, hb;
3997 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
3998 uses DECL_UID of the VAR_DECL, so sorting might differ between
3999 -g and -g0. When doing the removal of redundant assert exprs
4000 and commonization to successors, this does not matter, but for
4001 the final sort needs to be stable. */
4002 if (stable)
4004 ha = 0;
4005 hb = 0;
4007 else
4009 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4010 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4013 /* Break the tie using hashing and source/bb index. */
4014 if (ha == hb)
4015 return (a->e != NULL
4016 ? a->e->src->index - b->e->src->index
4017 : a->bb->index - b->bb->index);
4018 return ha > hb ? 1 : -1;
4021 /* Process all the insertions registered for every name N_i registered
4022 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4023 found in ASSERTS_FOR[i]. */
4025 static void
4026 process_assert_insertions (void)
4028 unsigned i;
4029 bitmap_iterator bi;
4030 bool update_edges_p = false;
4031 int num_asserts = 0;
4033 if (dump_file && (dump_flags & TDF_DETAILS))
4034 dump_all_asserts (dump_file);
4036 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4038 assert_locus *loc = asserts_for[i];
4039 gcc_assert (loc);
4041 auto_vec<assert_locus *, 16> asserts;
4042 for (; loc; loc = loc->next)
4043 asserts.safe_push (loc);
4044 asserts.qsort (compare_assert_loc<false>);
4046 /* Push down common asserts to successors and remove redundant ones. */
4047 unsigned ecnt = 0;
4048 assert_locus *common = NULL;
4049 unsigned commonj = 0;
4050 for (unsigned j = 0; j < asserts.length (); ++j)
4052 loc = asserts[j];
4053 if (! loc->e)
4054 common = NULL;
4055 else if (! common
4056 || loc->e->dest != common->e->dest
4057 || loc->comp_code != common->comp_code
4058 || ! operand_equal_p (loc->val, common->val, 0)
4059 || ! operand_equal_p (loc->expr, common->expr, 0))
4061 commonj = j;
4062 common = loc;
4063 ecnt = 1;
4065 else if (loc->e == asserts[j-1]->e)
4067 /* Remove duplicate asserts. */
4068 if (commonj == j - 1)
4070 commonj = j;
4071 common = loc;
4073 free (asserts[j-1]);
4074 asserts[j-1] = NULL;
4076 else
4078 ecnt++;
4079 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4081 /* We have the same assertion on all incoming edges of a BB.
4082 Insert it at the beginning of that block. */
4083 loc->bb = loc->e->dest;
4084 loc->e = NULL;
4085 loc->si = gsi_none ();
4086 common = NULL;
4087 /* Clear asserts commoned. */
4088 for (; commonj != j; ++commonj)
4089 if (asserts[commonj])
4091 free (asserts[commonj]);
4092 asserts[commonj] = NULL;
4098 /* The asserts vector sorting above might be unstable for
4099 -fcompare-debug, sort again to ensure a stable sort. */
4100 asserts.qsort (compare_assert_loc<true>);
4101 for (unsigned j = 0; j < asserts.length (); ++j)
4103 loc = asserts[j];
4104 if (! loc)
4105 break;
4106 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4107 num_asserts++;
4108 free (loc);
4112 if (update_edges_p)
4113 gsi_commit_edge_inserts ();
4115 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4116 num_asserts);
4120 /* Traverse the flowgraph looking for conditional jumps to insert range
4121 expressions. These range expressions are meant to provide information
4122 to optimizations that need to reason in terms of value ranges. They
4123 will not be expanded into RTL. For instance, given:
4125 x = ...
4126 y = ...
4127 if (x < y)
4128 y = x - 2;
4129 else
4130 x = y + 3;
4132 this pass will transform the code into:
4134 x = ...
4135 y = ...
4136 if (x < y)
4138 x = ASSERT_EXPR <x, x < y>
4139 y = x - 2
4141 else
4143 y = ASSERT_EXPR <y, x >= y>
4144 x = y + 3
4147 The idea is that once copy and constant propagation have run, other
4148 optimizations will be able to determine what ranges of values can 'x'
4149 take in different paths of the code, simply by checking the reaching
4150 definition of 'x'. */
4152 static void
4153 insert_range_assertions (void)
4155 need_assert_for = BITMAP_ALLOC (NULL);
4156 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4158 calculate_dominance_info (CDI_DOMINATORS);
4160 find_assert_locations ();
4161 if (!bitmap_empty_p (need_assert_for))
4163 process_assert_insertions ();
4164 update_ssa (TODO_update_ssa_no_phi);
4167 if (dump_file && (dump_flags & TDF_DETAILS))
4169 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4170 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4173 free (asserts_for);
4174 BITMAP_FREE (need_assert_for);
4177 class vrp_prop : public ssa_propagation_engine
4179 public:
4180 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4181 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4183 void vrp_initialize (void);
4184 void vrp_finalize (bool);
4185 void check_all_array_refs (void);
4186 void check_array_ref (location_t, tree, bool);
4187 void check_mem_ref (location_t, tree, bool);
4188 void search_for_addr_array (tree, location_t);
4190 class vr_values vr_values;
4191 /* Temporary delegator to minimize code churn. */
4192 value_range *get_value_range (const_tree op)
4193 { return vr_values.get_value_range (op); }
4194 void set_defs_to_varying (gimple *stmt)
4195 { return vr_values.set_defs_to_varying (stmt); }
4196 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4197 tree *output_p, value_range *vr)
4198 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4199 bool update_value_range (const_tree op, value_range *vr)
4200 { return vr_values.update_value_range (op, vr); }
4201 void extract_range_basic (value_range *vr, gimple *stmt)
4202 { vr_values.extract_range_basic (vr, stmt); }
4203 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4204 { vr_values.extract_range_from_phi_node (phi, vr); }
4206 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4207 and "struct" hacks. If VRP can determine that the
4208 array subscript is a constant, check if it is outside valid
4209 range. If the array subscript is a RANGE, warn if it is
4210 non-overlapping with valid range.
4211 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4213 void
4214 vrp_prop::check_array_ref (location_t location, tree ref,
4215 bool ignore_off_by_one)
4217 value_range *vr = NULL;
4218 tree low_sub, up_sub;
4219 tree low_bound, up_bound, up_bound_p1;
4221 if (TREE_NO_WARNING (ref))
4222 return;
4224 low_sub = up_sub = TREE_OPERAND (ref, 1);
4225 up_bound = array_ref_up_bound (ref);
4227 if (!up_bound
4228 || TREE_CODE (up_bound) != INTEGER_CST
4229 || (warn_array_bounds < 2
4230 && array_at_struct_end_p (ref)))
4232 /* Accesses to trailing arrays via pointers may access storage
4233 beyond the types array bounds. For such arrays, or for flexible
4234 array members, as well as for other arrays of an unknown size,
4235 replace the upper bound with a more permissive one that assumes
4236 the size of the largest object is PTRDIFF_MAX. */
4237 tree eltsize = array_ref_element_size (ref);
4239 if (TREE_CODE (eltsize) != INTEGER_CST
4240 || integer_zerop (eltsize))
4242 up_bound = NULL_TREE;
4243 up_bound_p1 = NULL_TREE;
4245 else
4247 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4248 tree arg = TREE_OPERAND (ref, 0);
4249 poly_int64 off;
4251 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4252 maxbound = wide_int_to_tree (sizetype,
4253 wi::sub (wi::to_wide (maxbound),
4254 off));
4255 else
4256 maxbound = fold_convert (sizetype, maxbound);
4258 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4260 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4261 build_int_cst (ptrdiff_type_node, 1));
4264 else
4265 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4266 build_int_cst (TREE_TYPE (up_bound), 1));
4268 low_bound = array_ref_low_bound (ref);
4270 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4272 bool warned = false;
4274 /* Empty array. */
4275 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4276 warned = warning_at (location, OPT_Warray_bounds,
4277 "array subscript %E is above array bounds of %qT",
4278 low_bound, artype);
4280 if (TREE_CODE (low_sub) == SSA_NAME)
4282 vr = get_value_range (low_sub);
4283 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4285 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4286 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4290 if (vr && vr->type == VR_ANTI_RANGE)
4292 if (up_bound
4293 && TREE_CODE (up_sub) == INTEGER_CST
4294 && (ignore_off_by_one
4295 ? tree_int_cst_lt (up_bound, up_sub)
4296 : tree_int_cst_le (up_bound, up_sub))
4297 && TREE_CODE (low_sub) == INTEGER_CST
4298 && tree_int_cst_le (low_sub, low_bound))
4299 warned = warning_at (location, OPT_Warray_bounds,
4300 "array subscript [%E, %E] is outside "
4301 "array bounds of %qT",
4302 low_sub, up_sub, artype);
4304 else if (up_bound
4305 && TREE_CODE (up_sub) == INTEGER_CST
4306 && (ignore_off_by_one
4307 ? !tree_int_cst_le (up_sub, up_bound_p1)
4308 : !tree_int_cst_le (up_sub, up_bound)))
4310 if (dump_file && (dump_flags & TDF_DETAILS))
4312 fprintf (dump_file, "Array bound warning for ");
4313 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4314 fprintf (dump_file, "\n");
4316 warned = warning_at (location, OPT_Warray_bounds,
4317 "array subscript %E is above array bounds of %qT",
4318 up_sub, artype);
4320 else if (TREE_CODE (low_sub) == INTEGER_CST
4321 && tree_int_cst_lt (low_sub, low_bound))
4323 if (dump_file && (dump_flags & TDF_DETAILS))
4325 fprintf (dump_file, "Array bound warning for ");
4326 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4327 fprintf (dump_file, "\n");
4329 warned = warning_at (location, OPT_Warray_bounds,
4330 "array subscript %E is below array bounds of %qT",
4331 low_sub, artype);
4334 if (warned)
4336 ref = TREE_OPERAND (ref, 0);
4338 if (DECL_P (ref))
4339 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4341 TREE_NO_WARNING (ref) = 1;
4345 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4346 references to string constants. If VRP can determine that the array
4347 subscript is a constant, check if it is outside valid range.
4348 If the array subscript is a RANGE, warn if it is non-overlapping
4349 with valid range.
4350 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4351 (used to allow one-past-the-end indices for code that takes
4352 the address of the just-past-the-end element of an array). */
4354 void
4355 vrp_prop::check_mem_ref (location_t location, tree ref,
4356 bool ignore_off_by_one)
4358 if (TREE_NO_WARNING (ref))
4359 return;
4361 tree arg = TREE_OPERAND (ref, 0);
4362 /* The constant and variable offset of the reference. */
4363 tree cstoff = TREE_OPERAND (ref, 1);
4364 tree varoff = NULL_TREE;
4366 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4368 /* The array or string constant bounds in bytes. Initially set
4369 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4370 determined. */
4371 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4373 /* The minimum and maximum intermediate offset. For a reference
4374 to be valid, not only does the final offset/subscript must be
4375 in bounds but all intermediate offsets should be as well.
4376 GCC may be able to deal gracefully with such out-of-bounds
4377 offsets so the checking is only enbaled at -Warray-bounds=2
4378 where it may help detect bugs in uses of the intermediate
4379 offsets that could otherwise not be detectable. */
4380 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4381 offset_int extrema[2] = { 0, wi::abs (ioff) };
4383 /* The range of the byte offset into the reference. */
4384 offset_int offrange[2] = { 0, 0 };
4386 value_range *vr = NULL;
4388 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4389 The loop computes the the range of the final offset for expressions
4390 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4391 in some range. */
4392 while (TREE_CODE (arg) == SSA_NAME)
4394 gimple *def = SSA_NAME_DEF_STMT (arg);
4395 if (!is_gimple_assign (def))
4396 break;
4398 tree_code code = gimple_assign_rhs_code (def);
4399 if (code == POINTER_PLUS_EXPR)
4401 arg = gimple_assign_rhs1 (def);
4402 varoff = gimple_assign_rhs2 (def);
4404 else if (code == ASSERT_EXPR)
4406 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4407 continue;
4409 else
4410 return;
4412 /* VAROFF should always be a SSA_NAME here (and not even
4413 INTEGER_CST) but there's no point in taking chances. */
4414 if (TREE_CODE (varoff) != SSA_NAME)
4415 break;
4417 vr = get_value_range (varoff);
4418 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4419 break;
4421 if (TREE_CODE (vr->min) != INTEGER_CST
4422 || TREE_CODE (vr->max) != INTEGER_CST)
4423 break;
4425 if (vr->type == VR_RANGE)
4427 if (tree_int_cst_lt (vr->min, vr->max))
4429 offset_int min
4430 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4431 offset_int max
4432 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4433 if (min < max)
4435 offrange[0] += min;
4436 offrange[1] += max;
4438 else
4440 offrange[0] += max;
4441 offrange[1] += min;
4444 else
4446 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4447 to OFFRANGE. */
4448 offrange[0] += arrbounds[0];
4449 offrange[1] += arrbounds[1];
4452 else
4454 /* For an anti-range, analogously to the above, conservatively
4455 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4456 offrange[0] += arrbounds[0];
4457 offrange[1] += arrbounds[1];
4460 /* Keep track of the minimum and maximum offset. */
4461 if (offrange[1] < 0 && offrange[1] < extrema[0])
4462 extrema[0] = offrange[1];
4463 if (offrange[0] > 0 && offrange[0] > extrema[1])
4464 extrema[1] = offrange[0];
4466 if (offrange[0] < arrbounds[0])
4467 offrange[0] = arrbounds[0];
4469 if (offrange[1] > arrbounds[1])
4470 offrange[1] = arrbounds[1];
4473 if (TREE_CODE (arg) == ADDR_EXPR)
4475 arg = TREE_OPERAND (arg, 0);
4476 if (TREE_CODE (arg) != STRING_CST
4477 && TREE_CODE (arg) != VAR_DECL)
4478 return;
4480 else
4481 return;
4483 /* The type of the object being referred to. It can be an array,
4484 string literal, or a non-array type when the MEM_REF represents
4485 a reference/subscript via a pointer to an object that is not
4486 an element of an array. References to members of structs and
4487 unions are excluded because MEM_REF doesn't make it possible
4488 to identify the member where the reference originated.
4489 Incomplete types are excluded as well because their size is
4490 not known. */
4491 tree reftype = TREE_TYPE (arg);
4492 if (POINTER_TYPE_P (reftype)
4493 || !COMPLETE_TYPE_P (reftype)
4494 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4495 || RECORD_OR_UNION_TYPE_P (reftype))
4496 return;
4498 offset_int eltsize;
4499 if (TREE_CODE (reftype) == ARRAY_TYPE)
4501 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4503 if (tree dom = TYPE_DOMAIN (reftype))
4505 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4506 if (array_at_struct_end_p (arg)
4507 || !bnds[0] || !bnds[1])
4509 arrbounds[0] = 0;
4510 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4512 else
4514 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4515 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4518 else
4520 arrbounds[0] = 0;
4521 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4524 if (TREE_CODE (ref) == MEM_REF)
4526 /* For MEM_REF determine a tighter bound of the non-array
4527 element type. */
4528 tree eltype = TREE_TYPE (reftype);
4529 while (TREE_CODE (eltype) == ARRAY_TYPE)
4530 eltype = TREE_TYPE (eltype);
4531 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4534 else
4536 eltsize = 1;
4537 arrbounds[0] = 0;
4538 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4541 offrange[0] += ioff;
4542 offrange[1] += ioff;
4544 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4545 is set (when taking the address of the one-past-last element
4546 of an array) but always use the stricter bound in diagnostics. */
4547 offset_int ubound = arrbounds[1];
4548 if (ignore_off_by_one)
4549 ubound += 1;
4551 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4553 /* Treat a reference to a non-array object as one to an array
4554 of a single element. */
4555 if (TREE_CODE (reftype) != ARRAY_TYPE)
4556 reftype = build_array_type_nelts (reftype, 1);
4558 if (TREE_CODE (ref) == MEM_REF)
4560 /* Extract the element type out of MEM_REF and use its size
4561 to compute the index to print in the diagnostic; arrays
4562 in MEM_REF don't mean anything. */
4563 tree type = TREE_TYPE (ref);
4564 while (TREE_CODE (type) == ARRAY_TYPE)
4565 type = TREE_TYPE (type);
4566 tree size = TYPE_SIZE_UNIT (type);
4567 offrange[0] = offrange[0] / wi::to_offset (size);
4568 offrange[1] = offrange[1] / wi::to_offset (size);
4570 else
4572 /* For anything other than MEM_REF, compute the index to
4573 print in the diagnostic as the offset over element size. */
4574 offrange[0] = offrange[0] / eltsize;
4575 offrange[1] = offrange[1] / eltsize;
4578 bool warned;
4579 if (offrange[0] == offrange[1])
4580 warned = warning_at (location, OPT_Warray_bounds,
4581 "array subscript %wi is outside array bounds "
4582 "of %qT",
4583 offrange[0].to_shwi (), reftype);
4584 else
4585 warned = warning_at (location, OPT_Warray_bounds,
4586 "array subscript [%wi, %wi] is outside "
4587 "array bounds of %qT",
4588 offrange[0].to_shwi (),
4589 offrange[1].to_shwi (), reftype);
4590 if (warned && DECL_P (arg))
4591 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4593 TREE_NO_WARNING (ref) = 1;
4594 return;
4597 if (warn_array_bounds < 2)
4598 return;
4600 /* At level 2 check also intermediate offsets. */
4601 int i = 0;
4602 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4604 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4606 warning_at (location, OPT_Warray_bounds,
4607 "intermediate array offset %wi is outside array bounds "
4608 "of %qT",
4609 tmpidx, reftype);
4610 TREE_NO_WARNING (ref) = 1;
4614 /* Searches if the expr T, located at LOCATION computes
4615 address of an ARRAY_REF, and call check_array_ref on it. */
4617 void
4618 vrp_prop::search_for_addr_array (tree t, location_t location)
4620 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4623 if (TREE_CODE (t) == ARRAY_REF)
4624 check_array_ref (location, t, true /*ignore_off_by_one*/);
4625 else if (TREE_CODE (t) == MEM_REF)
4626 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4628 t = TREE_OPERAND (t, 0);
4630 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4632 if (TREE_CODE (t) != MEM_REF
4633 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4634 || TREE_NO_WARNING (t))
4635 return;
4637 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4638 tree low_bound, up_bound, el_sz;
4639 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4640 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4641 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4642 return;
4644 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4645 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4646 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4647 if (!low_bound
4648 || TREE_CODE (low_bound) != INTEGER_CST
4649 || !up_bound
4650 || TREE_CODE (up_bound) != INTEGER_CST
4651 || !el_sz
4652 || TREE_CODE (el_sz) != INTEGER_CST)
4653 return;
4655 offset_int idx;
4656 if (!mem_ref_offset (t).is_constant (&idx))
4657 return;
4659 bool warned = false;
4660 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4661 if (idx < 0)
4663 if (dump_file && (dump_flags & TDF_DETAILS))
4665 fprintf (dump_file, "Array bound warning for ");
4666 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4667 fprintf (dump_file, "\n");
4669 warned = warning_at (location, OPT_Warray_bounds,
4670 "array subscript %wi is below "
4671 "array bounds of %qT",
4672 idx.to_shwi (), TREE_TYPE (tem));
4674 else if (idx > (wi::to_offset (up_bound)
4675 - wi::to_offset (low_bound) + 1))
4677 if (dump_file && (dump_flags & TDF_DETAILS))
4679 fprintf (dump_file, "Array bound warning for ");
4680 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4681 fprintf (dump_file, "\n");
4683 warned = warning_at (location, OPT_Warray_bounds,
4684 "array subscript %wu is above "
4685 "array bounds of %qT",
4686 idx.to_uhwi (), TREE_TYPE (tem));
4689 if (warned)
4691 if (DECL_P (t))
4692 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4694 TREE_NO_WARNING (t) = 1;
4698 /* walk_tree() callback that checks if *TP is
4699 an ARRAY_REF inside an ADDR_EXPR (in which an array
4700 subscript one outside the valid range is allowed). Call
4701 check_array_ref for each ARRAY_REF found. The location is
4702 passed in DATA. */
4704 static tree
4705 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4707 tree t = *tp;
4708 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4709 location_t location;
4711 if (EXPR_HAS_LOCATION (t))
4712 location = EXPR_LOCATION (t);
4713 else
4714 location = gimple_location (wi->stmt);
4716 *walk_subtree = TRUE;
4718 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4719 if (TREE_CODE (t) == ARRAY_REF)
4720 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4721 else if (TREE_CODE (t) == MEM_REF)
4722 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4723 else if (TREE_CODE (t) == ADDR_EXPR)
4725 vrp_prop->search_for_addr_array (t, location);
4726 *walk_subtree = FALSE;
4729 return NULL_TREE;
4732 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4733 to walk over all statements of all reachable BBs and call
4734 check_array_bounds on them. */
4736 class check_array_bounds_dom_walker : public dom_walker
4738 public:
4739 check_array_bounds_dom_walker (vrp_prop *prop)
4740 : dom_walker (CDI_DOMINATORS,
4741 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4742 flags, so that we can merge in information on
4743 non-executable edges from vrp_folder . */
4744 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4745 m_prop (prop) {}
4746 ~check_array_bounds_dom_walker () {}
4748 edge before_dom_children (basic_block) FINAL OVERRIDE;
4750 private:
4751 vrp_prop *m_prop;
4754 /* Implementation of dom_walker::before_dom_children.
4756 Walk over all statements of BB and call check_array_bounds on them,
4757 and determine if there's a unique successor edge. */
4759 edge
4760 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4762 gimple_stmt_iterator si;
4763 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4765 gimple *stmt = gsi_stmt (si);
4766 struct walk_stmt_info wi;
4767 if (!gimple_has_location (stmt)
4768 || is_gimple_debug (stmt))
4769 continue;
4771 memset (&wi, 0, sizeof (wi));
4773 wi.info = m_prop;
4775 walk_gimple_op (stmt, check_array_bounds, &wi);
4778 /* Determine if there's a unique successor edge, and if so, return
4779 that back to dom_walker, ensuring that we don't visit blocks that
4780 became unreachable during the VRP propagation
4781 (PR tree-optimization/83312). */
4782 return find_taken_edge (bb, NULL_TREE);
4785 /* Walk over all statements of all reachable BBs and call check_array_bounds
4786 on them. */
4788 void
4789 vrp_prop::check_all_array_refs ()
4791 check_array_bounds_dom_walker w (this);
4792 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4795 /* Return true if all imm uses of VAR are either in STMT, or
4796 feed (optionally through a chain of single imm uses) GIMPLE_COND
4797 in basic block COND_BB. */
4799 static bool
4800 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4802 use_operand_p use_p, use2_p;
4803 imm_use_iterator iter;
4805 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4806 if (USE_STMT (use_p) != stmt)
4808 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4809 if (is_gimple_debug (use_stmt))
4810 continue;
4811 while (is_gimple_assign (use_stmt)
4812 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4813 && single_imm_use (gimple_assign_lhs (use_stmt),
4814 &use2_p, &use_stmt2))
4815 use_stmt = use_stmt2;
4816 if (gimple_code (use_stmt) != GIMPLE_COND
4817 || gimple_bb (use_stmt) != cond_bb)
4818 return false;
4820 return true;
4823 /* Handle
4824 _4 = x_3 & 31;
4825 if (_4 != 0)
4826 goto <bb 6>;
4827 else
4828 goto <bb 7>;
4829 <bb 6>:
4830 __builtin_unreachable ();
4831 <bb 7>:
4832 x_5 = ASSERT_EXPR <x_3, ...>;
4833 If x_3 has no other immediate uses (checked by caller),
4834 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4835 from the non-zero bitmask. */
4837 void
4838 maybe_set_nonzero_bits (edge e, tree var)
4840 basic_block cond_bb = e->src;
4841 gimple *stmt = last_stmt (cond_bb);
4842 tree cst;
4844 if (stmt == NULL
4845 || gimple_code (stmt) != GIMPLE_COND
4846 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
4847 ? EQ_EXPR : NE_EXPR)
4848 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
4849 || !integer_zerop (gimple_cond_rhs (stmt)))
4850 return;
4852 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
4853 if (!is_gimple_assign (stmt)
4854 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4855 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
4856 return;
4857 if (gimple_assign_rhs1 (stmt) != var)
4859 gimple *stmt2;
4861 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
4862 return;
4863 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
4864 if (!gimple_assign_cast_p (stmt2)
4865 || gimple_assign_rhs1 (stmt2) != var
4866 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
4867 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
4868 != TYPE_PRECISION (TREE_TYPE (var))))
4869 return;
4871 cst = gimple_assign_rhs2 (stmt);
4872 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
4873 wi::to_wide (cst)));
4876 /* Convert range assertion expressions into the implied copies and
4877 copy propagate away the copies. Doing the trivial copy propagation
4878 here avoids the need to run the full copy propagation pass after
4879 VRP.
4881 FIXME, this will eventually lead to copy propagation removing the
4882 names that had useful range information attached to them. For
4883 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4884 then N_i will have the range [3, +INF].
4886 However, by converting the assertion into the implied copy
4887 operation N_i = N_j, we will then copy-propagate N_j into the uses
4888 of N_i and lose the range information. We may want to hold on to
4889 ASSERT_EXPRs a little while longer as the ranges could be used in
4890 things like jump threading.
4892 The problem with keeping ASSERT_EXPRs around is that passes after
4893 VRP need to handle them appropriately.
4895 Another approach would be to make the range information a first
4896 class property of the SSA_NAME so that it can be queried from
4897 any pass. This is made somewhat more complex by the need for
4898 multiple ranges to be associated with one SSA_NAME. */
4900 static void
4901 remove_range_assertions (void)
4903 basic_block bb;
4904 gimple_stmt_iterator si;
4905 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
4906 a basic block preceeded by GIMPLE_COND branching to it and
4907 __builtin_trap, -1 if not yet checked, 0 otherwise. */
4908 int is_unreachable;
4910 /* Note that the BSI iterator bump happens at the bottom of the
4911 loop and no bump is necessary if we're removing the statement
4912 referenced by the current BSI. */
4913 FOR_EACH_BB_FN (bb, cfun)
4914 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
4916 gimple *stmt = gsi_stmt (si);
4918 if (is_gimple_assign (stmt)
4919 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
4921 tree lhs = gimple_assign_lhs (stmt);
4922 tree rhs = gimple_assign_rhs1 (stmt);
4923 tree var;
4925 var = ASSERT_EXPR_VAR (rhs);
4927 if (TREE_CODE (var) == SSA_NAME
4928 && !POINTER_TYPE_P (TREE_TYPE (lhs))
4929 && SSA_NAME_RANGE_INFO (lhs))
4931 if (is_unreachable == -1)
4933 is_unreachable = 0;
4934 if (single_pred_p (bb)
4935 && assert_unreachable_fallthru_edge_p
4936 (single_pred_edge (bb)))
4937 is_unreachable = 1;
4939 /* Handle
4940 if (x_7 >= 10 && x_7 < 20)
4941 __builtin_unreachable ();
4942 x_8 = ASSERT_EXPR <x_7, ...>;
4943 if the only uses of x_7 are in the ASSERT_EXPR and
4944 in the condition. In that case, we can copy the
4945 range info from x_8 computed in this pass also
4946 for x_7. */
4947 if (is_unreachable
4948 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
4949 single_pred (bb)))
4951 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
4952 SSA_NAME_RANGE_INFO (lhs)->get_min (),
4953 SSA_NAME_RANGE_INFO (lhs)->get_max ());
4954 maybe_set_nonzero_bits (single_pred_edge (bb), var);
4958 /* Propagate the RHS into every use of the LHS. For SSA names
4959 also propagate abnormals as it merely restores the original
4960 IL in this case (an replace_uses_by would assert). */
4961 if (TREE_CODE (var) == SSA_NAME)
4963 imm_use_iterator iter;
4964 use_operand_p use_p;
4965 gimple *use_stmt;
4966 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4967 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4968 SET_USE (use_p, var);
4970 else
4971 replace_uses_by (lhs, var);
4973 /* And finally, remove the copy, it is not needed. */
4974 gsi_remove (&si, true);
4975 release_defs (stmt);
4977 else
4979 if (!is_gimple_debug (gsi_stmt (si)))
4980 is_unreachable = 0;
4981 gsi_next (&si);
4986 /* Return true if STMT is interesting for VRP. */
4988 bool
4989 stmt_interesting_for_vrp (gimple *stmt)
4991 if (gimple_code (stmt) == GIMPLE_PHI)
4993 tree res = gimple_phi_result (stmt);
4994 return (!virtual_operand_p (res)
4995 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
4996 || POINTER_TYPE_P (TREE_TYPE (res))));
4998 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5000 tree lhs = gimple_get_lhs (stmt);
5002 /* In general, assignments with virtual operands are not useful
5003 for deriving ranges, with the obvious exception of calls to
5004 builtin functions. */
5005 if (lhs && TREE_CODE (lhs) == SSA_NAME
5006 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5007 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5008 && (is_gimple_call (stmt)
5009 || !gimple_vuse (stmt)))
5010 return true;
5011 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5012 switch (gimple_call_internal_fn (stmt))
5014 case IFN_ADD_OVERFLOW:
5015 case IFN_SUB_OVERFLOW:
5016 case IFN_MUL_OVERFLOW:
5017 case IFN_ATOMIC_COMPARE_EXCHANGE:
5018 /* These internal calls return _Complex integer type,
5019 but are interesting to VRP nevertheless. */
5020 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5021 return true;
5022 break;
5023 default:
5024 break;
5027 else if (gimple_code (stmt) == GIMPLE_COND
5028 || gimple_code (stmt) == GIMPLE_SWITCH)
5029 return true;
5031 return false;
5034 /* Initialization required by ssa_propagate engine. */
5036 void
5037 vrp_prop::vrp_initialize ()
5039 basic_block bb;
5041 FOR_EACH_BB_FN (bb, cfun)
5043 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5044 gsi_next (&si))
5046 gphi *phi = si.phi ();
5047 if (!stmt_interesting_for_vrp (phi))
5049 tree lhs = PHI_RESULT (phi);
5050 set_value_range_to_varying (get_value_range (lhs));
5051 prop_set_simulate_again (phi, false);
5053 else
5054 prop_set_simulate_again (phi, true);
5057 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5058 gsi_next (&si))
5060 gimple *stmt = gsi_stmt (si);
5062 /* If the statement is a control insn, then we do not
5063 want to avoid simulating the statement once. Failure
5064 to do so means that those edges will never get added. */
5065 if (stmt_ends_bb_p (stmt))
5066 prop_set_simulate_again (stmt, true);
5067 else if (!stmt_interesting_for_vrp (stmt))
5069 set_defs_to_varying (stmt);
5070 prop_set_simulate_again (stmt, false);
5072 else
5073 prop_set_simulate_again (stmt, true);
5078 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5079 that includes the value VAL. The search is restricted to the range
5080 [START_IDX, n - 1] where n is the size of VEC.
5082 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5083 returned.
5085 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5086 it is placed in IDX and false is returned.
5088 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5089 returned. */
5091 bool
5092 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5094 size_t n = gimple_switch_num_labels (stmt);
5095 size_t low, high;
5097 /* Find case label for minimum of the value range or the next one.
5098 At each iteration we are searching in [low, high - 1]. */
5100 for (low = start_idx, high = n; high != low; )
5102 tree t;
5103 int cmp;
5104 /* Note that i != high, so we never ask for n. */
5105 size_t i = (high + low) / 2;
5106 t = gimple_switch_label (stmt, i);
5108 /* Cache the result of comparing CASE_LOW and val. */
5109 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5111 if (cmp == 0)
5113 /* Ranges cannot be empty. */
5114 *idx = i;
5115 return true;
5117 else if (cmp > 0)
5118 high = i;
5119 else
5121 low = i + 1;
5122 if (CASE_HIGH (t) != NULL
5123 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5125 *idx = i;
5126 return true;
5131 *idx = high;
5132 return false;
5135 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5136 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5137 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5138 then MAX_IDX < MIN_IDX.
5139 Returns true if the default label is not needed. */
5141 bool
5142 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5143 size_t *max_idx)
5145 size_t i, j;
5146 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5147 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5149 if (i == j
5150 && min_take_default
5151 && max_take_default)
5153 /* Only the default case label reached.
5154 Return an empty range. */
5155 *min_idx = 1;
5156 *max_idx = 0;
5157 return false;
5159 else
5161 bool take_default = min_take_default || max_take_default;
5162 tree low, high;
5163 size_t k;
5165 if (max_take_default)
5166 j--;
5168 /* If the case label range is continuous, we do not need
5169 the default case label. Verify that. */
5170 high = CASE_LOW (gimple_switch_label (stmt, i));
5171 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5172 high = CASE_HIGH (gimple_switch_label (stmt, i));
5173 for (k = i + 1; k <= j; ++k)
5175 low = CASE_LOW (gimple_switch_label (stmt, k));
5176 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5178 take_default = true;
5179 break;
5181 high = low;
5182 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5183 high = CASE_HIGH (gimple_switch_label (stmt, k));
5186 *min_idx = i;
5187 *max_idx = j;
5188 return !take_default;
5192 /* Evaluate statement STMT. If the statement produces a useful range,
5193 return SSA_PROP_INTERESTING and record the SSA name with the
5194 interesting range into *OUTPUT_P.
5196 If STMT is a conditional branch and we can determine its truth
5197 value, the taken edge is recorded in *TAKEN_EDGE_P.
5199 If STMT produces a varying value, return SSA_PROP_VARYING. */
5201 enum ssa_prop_result
5202 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5204 value_range vr = VR_INITIALIZER;
5205 tree lhs = gimple_get_lhs (stmt);
5206 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5208 if (*output_p)
5210 if (update_value_range (*output_p, &vr))
5212 if (dump_file && (dump_flags & TDF_DETAILS))
5214 fprintf (dump_file, "Found new range for ");
5215 print_generic_expr (dump_file, *output_p);
5216 fprintf (dump_file, ": ");
5217 dump_value_range (dump_file, &vr);
5218 fprintf (dump_file, "\n");
5221 if (vr.type == VR_VARYING)
5222 return SSA_PROP_VARYING;
5224 return SSA_PROP_INTERESTING;
5226 return SSA_PROP_NOT_INTERESTING;
5229 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5230 switch (gimple_call_internal_fn (stmt))
5232 case IFN_ADD_OVERFLOW:
5233 case IFN_SUB_OVERFLOW:
5234 case IFN_MUL_OVERFLOW:
5235 case IFN_ATOMIC_COMPARE_EXCHANGE:
5236 /* These internal calls return _Complex integer type,
5237 which VRP does not track, but the immediate uses
5238 thereof might be interesting. */
5239 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5241 imm_use_iterator iter;
5242 use_operand_p use_p;
5243 enum ssa_prop_result res = SSA_PROP_VARYING;
5245 set_value_range_to_varying (get_value_range (lhs));
5247 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5249 gimple *use_stmt = USE_STMT (use_p);
5250 if (!is_gimple_assign (use_stmt))
5251 continue;
5252 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5253 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5254 continue;
5255 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5256 tree use_lhs = gimple_assign_lhs (use_stmt);
5257 if (TREE_CODE (rhs1) != rhs_code
5258 || TREE_OPERAND (rhs1, 0) != lhs
5259 || TREE_CODE (use_lhs) != SSA_NAME
5260 || !stmt_interesting_for_vrp (use_stmt)
5261 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5262 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5263 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5264 continue;
5266 /* If there is a change in the value range for any of the
5267 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5268 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5269 or IMAGPART_EXPR immediate uses, but none of them have
5270 a change in their value ranges, return
5271 SSA_PROP_NOT_INTERESTING. If there are no
5272 {REAL,IMAG}PART_EXPR uses at all,
5273 return SSA_PROP_VARYING. */
5274 value_range new_vr = VR_INITIALIZER;
5275 extract_range_basic (&new_vr, use_stmt);
5276 value_range *old_vr = get_value_range (use_lhs);
5277 if (old_vr->type != new_vr.type
5278 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5279 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5280 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5281 res = SSA_PROP_INTERESTING;
5282 else
5283 res = SSA_PROP_NOT_INTERESTING;
5284 BITMAP_FREE (new_vr.equiv);
5285 if (res == SSA_PROP_INTERESTING)
5287 *output_p = lhs;
5288 return res;
5292 return res;
5294 break;
5295 default:
5296 break;
5299 /* All other statements produce nothing of interest for VRP, so mark
5300 their outputs varying and prevent further simulation. */
5301 set_defs_to_varying (stmt);
5303 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5306 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5307 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5308 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5309 possible such range. The resulting range is not canonicalized. */
5311 static void
5312 union_ranges (enum value_range_type *vr0type,
5313 tree *vr0min, tree *vr0max,
5314 enum value_range_type vr1type,
5315 tree vr1min, tree vr1max)
5317 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5318 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5320 /* [] is vr0, () is vr1 in the following classification comments. */
5321 if (mineq && maxeq)
5323 /* [( )] */
5324 if (*vr0type == vr1type)
5325 /* Nothing to do for equal ranges. */
5327 else if ((*vr0type == VR_RANGE
5328 && vr1type == VR_ANTI_RANGE)
5329 || (*vr0type == VR_ANTI_RANGE
5330 && vr1type == VR_RANGE))
5332 /* For anti-range with range union the result is varying. */
5333 goto give_up;
5335 else
5336 gcc_unreachable ();
5338 else if (operand_less_p (*vr0max, vr1min) == 1
5339 || operand_less_p (vr1max, *vr0min) == 1)
5341 /* [ ] ( ) or ( ) [ ]
5342 If the ranges have an empty intersection, result of the union
5343 operation is the anti-range or if both are anti-ranges
5344 it covers all. */
5345 if (*vr0type == VR_ANTI_RANGE
5346 && vr1type == VR_ANTI_RANGE)
5347 goto give_up;
5348 else if (*vr0type == VR_ANTI_RANGE
5349 && vr1type == VR_RANGE)
5351 else if (*vr0type == VR_RANGE
5352 && vr1type == VR_ANTI_RANGE)
5354 *vr0type = vr1type;
5355 *vr0min = vr1min;
5356 *vr0max = vr1max;
5358 else if (*vr0type == VR_RANGE
5359 && vr1type == VR_RANGE)
5361 /* The result is the convex hull of both ranges. */
5362 if (operand_less_p (*vr0max, vr1min) == 1)
5364 /* If the result can be an anti-range, create one. */
5365 if (TREE_CODE (*vr0max) == INTEGER_CST
5366 && TREE_CODE (vr1min) == INTEGER_CST
5367 && vrp_val_is_min (*vr0min)
5368 && vrp_val_is_max (vr1max))
5370 tree min = int_const_binop (PLUS_EXPR,
5371 *vr0max,
5372 build_int_cst (TREE_TYPE (*vr0max), 1));
5373 tree max = int_const_binop (MINUS_EXPR,
5374 vr1min,
5375 build_int_cst (TREE_TYPE (vr1min), 1));
5376 if (!operand_less_p (max, min))
5378 *vr0type = VR_ANTI_RANGE;
5379 *vr0min = min;
5380 *vr0max = max;
5382 else
5383 *vr0max = vr1max;
5385 else
5386 *vr0max = vr1max;
5388 else
5390 /* If the result can be an anti-range, create one. */
5391 if (TREE_CODE (vr1max) == INTEGER_CST
5392 && TREE_CODE (*vr0min) == INTEGER_CST
5393 && vrp_val_is_min (vr1min)
5394 && vrp_val_is_max (*vr0max))
5396 tree min = int_const_binop (PLUS_EXPR,
5397 vr1max,
5398 build_int_cst (TREE_TYPE (vr1max), 1));
5399 tree max = int_const_binop (MINUS_EXPR,
5400 *vr0min,
5401 build_int_cst (TREE_TYPE (*vr0min), 1));
5402 if (!operand_less_p (max, min))
5404 *vr0type = VR_ANTI_RANGE;
5405 *vr0min = min;
5406 *vr0max = max;
5408 else
5409 *vr0min = vr1min;
5411 else
5412 *vr0min = vr1min;
5415 else
5416 gcc_unreachable ();
5418 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5419 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5421 /* [ ( ) ] or [( ) ] or [ ( )] */
5422 if (*vr0type == VR_RANGE
5423 && vr1type == VR_RANGE)
5425 else if (*vr0type == VR_ANTI_RANGE
5426 && vr1type == VR_ANTI_RANGE)
5428 *vr0type = vr1type;
5429 *vr0min = vr1min;
5430 *vr0max = vr1max;
5432 else if (*vr0type == VR_ANTI_RANGE
5433 && vr1type == VR_RANGE)
5435 /* Arbitrarily choose the right or left gap. */
5436 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5437 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5438 build_int_cst (TREE_TYPE (vr1min), 1));
5439 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5440 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5441 build_int_cst (TREE_TYPE (vr1max), 1));
5442 else
5443 goto give_up;
5445 else if (*vr0type == VR_RANGE
5446 && vr1type == VR_ANTI_RANGE)
5447 /* The result covers everything. */
5448 goto give_up;
5449 else
5450 gcc_unreachable ();
5452 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5453 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5455 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5456 if (*vr0type == VR_RANGE
5457 && vr1type == VR_RANGE)
5459 *vr0type = vr1type;
5460 *vr0min = vr1min;
5461 *vr0max = vr1max;
5463 else if (*vr0type == VR_ANTI_RANGE
5464 && vr1type == VR_ANTI_RANGE)
5466 else if (*vr0type == VR_RANGE
5467 && vr1type == VR_ANTI_RANGE)
5469 *vr0type = VR_ANTI_RANGE;
5470 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5472 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5473 build_int_cst (TREE_TYPE (*vr0min), 1));
5474 *vr0min = vr1min;
5476 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5478 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5479 build_int_cst (TREE_TYPE (*vr0max), 1));
5480 *vr0max = vr1max;
5482 else
5483 goto give_up;
5485 else if (*vr0type == VR_ANTI_RANGE
5486 && vr1type == VR_RANGE)
5487 /* The result covers everything. */
5488 goto give_up;
5489 else
5490 gcc_unreachable ();
5492 else if ((operand_less_p (vr1min, *vr0max) == 1
5493 || operand_equal_p (vr1min, *vr0max, 0))
5494 && operand_less_p (*vr0min, vr1min) == 1
5495 && operand_less_p (*vr0max, vr1max) == 1)
5497 /* [ ( ] ) or [ ]( ) */
5498 if (*vr0type == VR_RANGE
5499 && vr1type == VR_RANGE)
5500 *vr0max = vr1max;
5501 else if (*vr0type == VR_ANTI_RANGE
5502 && vr1type == VR_ANTI_RANGE)
5503 *vr0min = vr1min;
5504 else if (*vr0type == VR_ANTI_RANGE
5505 && vr1type == VR_RANGE)
5507 if (TREE_CODE (vr1min) == INTEGER_CST)
5508 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5509 build_int_cst (TREE_TYPE (vr1min), 1));
5510 else
5511 goto give_up;
5513 else if (*vr0type == VR_RANGE
5514 && vr1type == VR_ANTI_RANGE)
5516 if (TREE_CODE (*vr0max) == INTEGER_CST)
5518 *vr0type = vr1type;
5519 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5520 build_int_cst (TREE_TYPE (*vr0max), 1));
5521 *vr0max = vr1max;
5523 else
5524 goto give_up;
5526 else
5527 gcc_unreachable ();
5529 else if ((operand_less_p (*vr0min, vr1max) == 1
5530 || operand_equal_p (*vr0min, vr1max, 0))
5531 && operand_less_p (vr1min, *vr0min) == 1
5532 && operand_less_p (vr1max, *vr0max) == 1)
5534 /* ( [ ) ] or ( )[ ] */
5535 if (*vr0type == VR_RANGE
5536 && vr1type == VR_RANGE)
5537 *vr0min = vr1min;
5538 else if (*vr0type == VR_ANTI_RANGE
5539 && vr1type == VR_ANTI_RANGE)
5540 *vr0max = vr1max;
5541 else if (*vr0type == VR_ANTI_RANGE
5542 && vr1type == VR_RANGE)
5544 if (TREE_CODE (vr1max) == INTEGER_CST)
5545 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5546 build_int_cst (TREE_TYPE (vr1max), 1));
5547 else
5548 goto give_up;
5550 else if (*vr0type == VR_RANGE
5551 && vr1type == VR_ANTI_RANGE)
5553 if (TREE_CODE (*vr0min) == INTEGER_CST)
5555 *vr0type = vr1type;
5556 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5557 build_int_cst (TREE_TYPE (*vr0min), 1));
5558 *vr0min = vr1min;
5560 else
5561 goto give_up;
5563 else
5564 gcc_unreachable ();
5566 else
5567 goto give_up;
5569 return;
5571 give_up:
5572 *vr0type = VR_VARYING;
5573 *vr0min = NULL_TREE;
5574 *vr0max = NULL_TREE;
5577 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5578 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5579 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5580 possible such range. The resulting range is not canonicalized. */
5582 static void
5583 intersect_ranges (enum value_range_type *vr0type,
5584 tree *vr0min, tree *vr0max,
5585 enum value_range_type vr1type,
5586 tree vr1min, tree vr1max)
5588 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5589 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5591 /* [] is vr0, () is vr1 in the following classification comments. */
5592 if (mineq && maxeq)
5594 /* [( )] */
5595 if (*vr0type == vr1type)
5596 /* Nothing to do for equal ranges. */
5598 else if ((*vr0type == VR_RANGE
5599 && vr1type == VR_ANTI_RANGE)
5600 || (*vr0type == VR_ANTI_RANGE
5601 && vr1type == VR_RANGE))
5603 /* For anti-range with range intersection the result is empty. */
5604 *vr0type = VR_UNDEFINED;
5605 *vr0min = NULL_TREE;
5606 *vr0max = NULL_TREE;
5608 else
5609 gcc_unreachable ();
5611 else if (operand_less_p (*vr0max, vr1min) == 1
5612 || operand_less_p (vr1max, *vr0min) == 1)
5614 /* [ ] ( ) or ( ) [ ]
5615 If the ranges have an empty intersection, the result of the
5616 intersect operation is the range for intersecting an
5617 anti-range with a range or empty when intersecting two ranges. */
5618 if (*vr0type == VR_RANGE
5619 && vr1type == VR_ANTI_RANGE)
5621 else if (*vr0type == VR_ANTI_RANGE
5622 && vr1type == VR_RANGE)
5624 *vr0type = vr1type;
5625 *vr0min = vr1min;
5626 *vr0max = vr1max;
5628 else if (*vr0type == VR_RANGE
5629 && vr1type == VR_RANGE)
5631 *vr0type = VR_UNDEFINED;
5632 *vr0min = NULL_TREE;
5633 *vr0max = NULL_TREE;
5635 else if (*vr0type == VR_ANTI_RANGE
5636 && vr1type == VR_ANTI_RANGE)
5638 /* If the anti-ranges are adjacent to each other merge them. */
5639 if (TREE_CODE (*vr0max) == INTEGER_CST
5640 && TREE_CODE (vr1min) == INTEGER_CST
5641 && operand_less_p (*vr0max, vr1min) == 1
5642 && integer_onep (int_const_binop (MINUS_EXPR,
5643 vr1min, *vr0max)))
5644 *vr0max = vr1max;
5645 else if (TREE_CODE (vr1max) == INTEGER_CST
5646 && TREE_CODE (*vr0min) == INTEGER_CST
5647 && operand_less_p (vr1max, *vr0min) == 1
5648 && integer_onep (int_const_binop (MINUS_EXPR,
5649 *vr0min, vr1max)))
5650 *vr0min = vr1min;
5651 /* Else arbitrarily take VR0. */
5654 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5655 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5657 /* [ ( ) ] or [( ) ] or [ ( )] */
5658 if (*vr0type == VR_RANGE
5659 && vr1type == VR_RANGE)
5661 /* If both are ranges the result is the inner one. */
5662 *vr0type = vr1type;
5663 *vr0min = vr1min;
5664 *vr0max = vr1max;
5666 else if (*vr0type == VR_RANGE
5667 && vr1type == VR_ANTI_RANGE)
5669 /* Choose the right gap if the left one is empty. */
5670 if (mineq)
5672 if (TREE_CODE (vr1max) != INTEGER_CST)
5673 *vr0min = vr1max;
5674 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5675 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5676 *vr0min
5677 = int_const_binop (MINUS_EXPR, vr1max,
5678 build_int_cst (TREE_TYPE (vr1max), -1));
5679 else
5680 *vr0min
5681 = int_const_binop (PLUS_EXPR, vr1max,
5682 build_int_cst (TREE_TYPE (vr1max), 1));
5684 /* Choose the left gap if the right one is empty. */
5685 else if (maxeq)
5687 if (TREE_CODE (vr1min) != INTEGER_CST)
5688 *vr0max = vr1min;
5689 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5690 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5691 *vr0max
5692 = int_const_binop (PLUS_EXPR, vr1min,
5693 build_int_cst (TREE_TYPE (vr1min), -1));
5694 else
5695 *vr0max
5696 = int_const_binop (MINUS_EXPR, vr1min,
5697 build_int_cst (TREE_TYPE (vr1min), 1));
5699 /* Choose the anti-range if the range is effectively varying. */
5700 else if (vrp_val_is_min (*vr0min)
5701 && vrp_val_is_max (*vr0max))
5703 *vr0type = vr1type;
5704 *vr0min = vr1min;
5705 *vr0max = vr1max;
5707 /* Else choose the range. */
5709 else if (*vr0type == VR_ANTI_RANGE
5710 && vr1type == VR_ANTI_RANGE)
5711 /* If both are anti-ranges the result is the outer one. */
5713 else if (*vr0type == VR_ANTI_RANGE
5714 && vr1type == VR_RANGE)
5716 /* The intersection is empty. */
5717 *vr0type = VR_UNDEFINED;
5718 *vr0min = NULL_TREE;
5719 *vr0max = NULL_TREE;
5721 else
5722 gcc_unreachable ();
5724 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5725 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5727 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5728 if (*vr0type == VR_RANGE
5729 && vr1type == VR_RANGE)
5730 /* Choose the inner range. */
5732 else if (*vr0type == VR_ANTI_RANGE
5733 && vr1type == VR_RANGE)
5735 /* Choose the right gap if the left is empty. */
5736 if (mineq)
5738 *vr0type = VR_RANGE;
5739 if (TREE_CODE (*vr0max) != INTEGER_CST)
5740 *vr0min = *vr0max;
5741 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5742 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5743 *vr0min
5744 = int_const_binop (MINUS_EXPR, *vr0max,
5745 build_int_cst (TREE_TYPE (*vr0max), -1));
5746 else
5747 *vr0min
5748 = int_const_binop (PLUS_EXPR, *vr0max,
5749 build_int_cst (TREE_TYPE (*vr0max), 1));
5750 *vr0max = vr1max;
5752 /* Choose the left gap if the right is empty. */
5753 else if (maxeq)
5755 *vr0type = VR_RANGE;
5756 if (TREE_CODE (*vr0min) != INTEGER_CST)
5757 *vr0max = *vr0min;
5758 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5759 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5760 *vr0max
5761 = int_const_binop (PLUS_EXPR, *vr0min,
5762 build_int_cst (TREE_TYPE (*vr0min), -1));
5763 else
5764 *vr0max
5765 = int_const_binop (MINUS_EXPR, *vr0min,
5766 build_int_cst (TREE_TYPE (*vr0min), 1));
5767 *vr0min = vr1min;
5769 /* Choose the anti-range if the range is effectively varying. */
5770 else if (vrp_val_is_min (vr1min)
5771 && vrp_val_is_max (vr1max))
5773 /* Choose the anti-range if it is ~[0,0], that range is special
5774 enough to special case when vr1's range is relatively wide.
5775 At least for types bigger than int - this covers pointers
5776 and arguments to functions like ctz. */
5777 else if (*vr0min == *vr0max
5778 && integer_zerop (*vr0min)
5779 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5780 >= TYPE_PRECISION (integer_type_node))
5781 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5782 && TREE_CODE (vr1max) == INTEGER_CST
5783 && TREE_CODE (vr1min) == INTEGER_CST
5784 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5785 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5787 /* Else choose the range. */
5788 else
5790 *vr0type = vr1type;
5791 *vr0min = vr1min;
5792 *vr0max = vr1max;
5795 else if (*vr0type == VR_ANTI_RANGE
5796 && vr1type == VR_ANTI_RANGE)
5798 /* If both are anti-ranges the result is the outer one. */
5799 *vr0type = vr1type;
5800 *vr0min = vr1min;
5801 *vr0max = vr1max;
5803 else if (vr1type == VR_ANTI_RANGE
5804 && *vr0type == VR_RANGE)
5806 /* The intersection is empty. */
5807 *vr0type = VR_UNDEFINED;
5808 *vr0min = NULL_TREE;
5809 *vr0max = NULL_TREE;
5811 else
5812 gcc_unreachable ();
5814 else if ((operand_less_p (vr1min, *vr0max) == 1
5815 || operand_equal_p (vr1min, *vr0max, 0))
5816 && operand_less_p (*vr0min, vr1min) == 1)
5818 /* [ ( ] ) or [ ]( ) */
5819 if (*vr0type == VR_ANTI_RANGE
5820 && vr1type == VR_ANTI_RANGE)
5821 *vr0max = vr1max;
5822 else if (*vr0type == VR_RANGE
5823 && vr1type == VR_RANGE)
5824 *vr0min = vr1min;
5825 else if (*vr0type == VR_RANGE
5826 && vr1type == VR_ANTI_RANGE)
5828 if (TREE_CODE (vr1min) == INTEGER_CST)
5829 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5830 build_int_cst (TREE_TYPE (vr1min), 1));
5831 else
5832 *vr0max = vr1min;
5834 else if (*vr0type == VR_ANTI_RANGE
5835 && vr1type == VR_RANGE)
5837 *vr0type = VR_RANGE;
5838 if (TREE_CODE (*vr0max) == INTEGER_CST)
5839 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5840 build_int_cst (TREE_TYPE (*vr0max), 1));
5841 else
5842 *vr0min = *vr0max;
5843 *vr0max = vr1max;
5845 else
5846 gcc_unreachable ();
5848 else if ((operand_less_p (*vr0min, vr1max) == 1
5849 || operand_equal_p (*vr0min, vr1max, 0))
5850 && operand_less_p (vr1min, *vr0min) == 1)
5852 /* ( [ ) ] or ( )[ ] */
5853 if (*vr0type == VR_ANTI_RANGE
5854 && vr1type == VR_ANTI_RANGE)
5855 *vr0min = vr1min;
5856 else if (*vr0type == VR_RANGE
5857 && vr1type == VR_RANGE)
5858 *vr0max = vr1max;
5859 else if (*vr0type == VR_RANGE
5860 && vr1type == VR_ANTI_RANGE)
5862 if (TREE_CODE (vr1max) == INTEGER_CST)
5863 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5864 build_int_cst (TREE_TYPE (vr1max), 1));
5865 else
5866 *vr0min = vr1max;
5868 else if (*vr0type == VR_ANTI_RANGE
5869 && vr1type == VR_RANGE)
5871 *vr0type = VR_RANGE;
5872 if (TREE_CODE (*vr0min) == INTEGER_CST)
5873 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5874 build_int_cst (TREE_TYPE (*vr0min), 1));
5875 else
5876 *vr0max = *vr0min;
5877 *vr0min = vr1min;
5879 else
5880 gcc_unreachable ();
5883 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
5884 result for the intersection. That's always a conservative
5885 correct estimate unless VR1 is a constant singleton range
5886 in which case we choose that. */
5887 if (vr1type == VR_RANGE
5888 && is_gimple_min_invariant (vr1min)
5889 && vrp_operand_equal_p (vr1min, vr1max))
5891 *vr0type = vr1type;
5892 *vr0min = vr1min;
5893 *vr0max = vr1max;
5896 return;
5900 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
5901 in *VR0. This may not be the smallest possible such range. */
5903 static void
5904 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
5906 value_range saved;
5908 /* If either range is VR_VARYING the other one wins. */
5909 if (vr1->type == VR_VARYING)
5910 return;
5911 if (vr0->type == VR_VARYING)
5913 copy_value_range (vr0, vr1);
5914 return;
5917 /* When either range is VR_UNDEFINED the resulting range is
5918 VR_UNDEFINED, too. */
5919 if (vr0->type == VR_UNDEFINED)
5920 return;
5921 if (vr1->type == VR_UNDEFINED)
5923 set_value_range_to_undefined (vr0);
5924 return;
5927 /* Save the original vr0 so we can return it as conservative intersection
5928 result when our worker turns things to varying. */
5929 saved = *vr0;
5930 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
5931 vr1->type, vr1->min, vr1->max);
5932 /* Make sure to canonicalize the result though as the inversion of a
5933 VR_RANGE can still be a VR_RANGE. */
5934 set_and_canonicalize_value_range (vr0, vr0->type,
5935 vr0->min, vr0->max, vr0->equiv);
5936 /* If that failed, use the saved original VR0. */
5937 if (vr0->type == VR_VARYING)
5939 *vr0 = saved;
5940 return;
5942 /* If the result is VR_UNDEFINED there is no need to mess with
5943 the equivalencies. */
5944 if (vr0->type == VR_UNDEFINED)
5945 return;
5947 /* The resulting set of equivalences for range intersection is the union of
5948 the two sets. */
5949 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5950 bitmap_ior_into (vr0->equiv, vr1->equiv);
5951 else if (vr1->equiv && !vr0->equiv)
5953 /* All equivalence bitmaps are allocated from the same obstack. So
5954 we can use the obstack associated with VR to allocate vr0->equiv. */
5955 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
5956 bitmap_copy (vr0->equiv, vr1->equiv);
5960 void
5961 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
5963 if (dump_file && (dump_flags & TDF_DETAILS))
5965 fprintf (dump_file, "Intersecting\n ");
5966 dump_value_range (dump_file, vr0);
5967 fprintf (dump_file, "\nand\n ");
5968 dump_value_range (dump_file, vr1);
5969 fprintf (dump_file, "\n");
5971 vrp_intersect_ranges_1 (vr0, vr1);
5972 if (dump_file && (dump_flags & TDF_DETAILS))
5974 fprintf (dump_file, "to\n ");
5975 dump_value_range (dump_file, vr0);
5976 fprintf (dump_file, "\n");
5980 /* Meet operation for value ranges. Given two value ranges VR0 and
5981 VR1, store in VR0 a range that contains both VR0 and VR1. This
5982 may not be the smallest possible such range. */
5984 static void
5985 vrp_meet_1 (value_range *vr0, const value_range *vr1)
5987 value_range saved;
5989 if (vr0->type == VR_UNDEFINED)
5991 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
5992 return;
5995 if (vr1->type == VR_UNDEFINED)
5997 /* VR0 already has the resulting range. */
5998 return;
6001 if (vr0->type == VR_VARYING)
6003 /* Nothing to do. VR0 already has the resulting range. */
6004 return;
6007 if (vr1->type == VR_VARYING)
6009 set_value_range_to_varying (vr0);
6010 return;
6013 saved = *vr0;
6014 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6015 vr1->type, vr1->min, vr1->max);
6016 if (vr0->type == VR_VARYING)
6018 /* Failed to find an efficient meet. Before giving up and setting
6019 the result to VARYING, see if we can at least derive a useful
6020 anti-range. */
6021 if (range_includes_zero_p (&saved) == 0
6022 && range_includes_zero_p (vr1) == 0)
6024 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6026 /* Since this meet operation did not result from the meeting of
6027 two equivalent names, VR0 cannot have any equivalences. */
6028 if (vr0->equiv)
6029 bitmap_clear (vr0->equiv);
6030 return;
6033 set_value_range_to_varying (vr0);
6034 return;
6036 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6037 vr0->equiv);
6038 if (vr0->type == VR_VARYING)
6039 return;
6041 /* The resulting set of equivalences is always the intersection of
6042 the two sets. */
6043 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6044 bitmap_and_into (vr0->equiv, vr1->equiv);
6045 else if (vr0->equiv && !vr1->equiv)
6046 bitmap_clear (vr0->equiv);
6049 void
6050 vrp_meet (value_range *vr0, const value_range *vr1)
6052 if (dump_file && (dump_flags & TDF_DETAILS))
6054 fprintf (dump_file, "Meeting\n ");
6055 dump_value_range (dump_file, vr0);
6056 fprintf (dump_file, "\nand\n ");
6057 dump_value_range (dump_file, vr1);
6058 fprintf (dump_file, "\n");
6060 vrp_meet_1 (vr0, vr1);
6061 if (dump_file && (dump_flags & TDF_DETAILS))
6063 fprintf (dump_file, "to\n ");
6064 dump_value_range (dump_file, vr0);
6065 fprintf (dump_file, "\n");
6070 /* Visit all arguments for PHI node PHI that flow through executable
6071 edges. If a valid value range can be derived from all the incoming
6072 value ranges, set a new range for the LHS of PHI. */
6074 enum ssa_prop_result
6075 vrp_prop::visit_phi (gphi *phi)
6077 tree lhs = PHI_RESULT (phi);
6078 value_range vr_result = VR_INITIALIZER;
6079 extract_range_from_phi_node (phi, &vr_result);
6080 if (update_value_range (lhs, &vr_result))
6082 if (dump_file && (dump_flags & TDF_DETAILS))
6084 fprintf (dump_file, "Found new range for ");
6085 print_generic_expr (dump_file, lhs);
6086 fprintf (dump_file, ": ");
6087 dump_value_range (dump_file, &vr_result);
6088 fprintf (dump_file, "\n");
6091 if (vr_result.type == VR_VARYING)
6092 return SSA_PROP_VARYING;
6094 return SSA_PROP_INTERESTING;
6097 /* Nothing changed, don't add outgoing edges. */
6098 return SSA_PROP_NOT_INTERESTING;
6101 class vrp_folder : public substitute_and_fold_engine
6103 public:
6104 tree get_value (tree) FINAL OVERRIDE;
6105 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6106 bool fold_predicate_in (gimple_stmt_iterator *);
6108 class vr_values *vr_values;
6110 /* Delegators. */
6111 tree vrp_evaluate_conditional (tree_code code, tree op0,
6112 tree op1, gimple *stmt)
6113 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6114 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6115 { return vr_values->simplify_stmt_using_ranges (gsi); }
6116 tree op_with_constant_singleton_value_range (tree op)
6117 { return vr_values->op_with_constant_singleton_value_range (op); }
6120 /* If the statement pointed by SI has a predicate whose value can be
6121 computed using the value range information computed by VRP, compute
6122 its value and return true. Otherwise, return false. */
6124 bool
6125 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6127 bool assignment_p = false;
6128 tree val;
6129 gimple *stmt = gsi_stmt (*si);
6131 if (is_gimple_assign (stmt)
6132 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6134 assignment_p = true;
6135 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6136 gimple_assign_rhs1 (stmt),
6137 gimple_assign_rhs2 (stmt),
6138 stmt);
6140 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6141 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6142 gimple_cond_lhs (cond_stmt),
6143 gimple_cond_rhs (cond_stmt),
6144 stmt);
6145 else
6146 return false;
6148 if (val)
6150 if (assignment_p)
6151 val = fold_convert (gimple_expr_type (stmt), val);
6153 if (dump_file)
6155 fprintf (dump_file, "Folding predicate ");
6156 print_gimple_expr (dump_file, stmt, 0);
6157 fprintf (dump_file, " to ");
6158 print_generic_expr (dump_file, val);
6159 fprintf (dump_file, "\n");
6162 if (is_gimple_assign (stmt))
6163 gimple_assign_set_rhs_from_tree (si, val);
6164 else
6166 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6167 gcond *cond_stmt = as_a <gcond *> (stmt);
6168 if (integer_zerop (val))
6169 gimple_cond_make_false (cond_stmt);
6170 else if (integer_onep (val))
6171 gimple_cond_make_true (cond_stmt);
6172 else
6173 gcc_unreachable ();
6176 return true;
6179 return false;
6182 /* Callback for substitute_and_fold folding the stmt at *SI. */
6184 bool
6185 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6187 if (fold_predicate_in (si))
6188 return true;
6190 return simplify_stmt_using_ranges (si);
6193 /* If OP has a value range with a single constant value return that,
6194 otherwise return NULL_TREE. This returns OP itself if OP is a
6195 constant.
6197 Implemented as a pure wrapper right now, but this will change. */
6199 tree
6200 vrp_folder::get_value (tree op)
6202 return op_with_constant_singleton_value_range (op);
6205 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6206 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6207 BB. If no such ASSERT_EXPR is found, return OP. */
6209 static tree
6210 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6212 imm_use_iterator imm_iter;
6213 gimple *use_stmt;
6214 use_operand_p use_p;
6216 if (TREE_CODE (op) == SSA_NAME)
6218 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6220 use_stmt = USE_STMT (use_p);
6221 if (use_stmt != stmt
6222 && gimple_assign_single_p (use_stmt)
6223 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6224 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6225 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6226 return gimple_assign_lhs (use_stmt);
6229 return op;
6232 /* A hack. */
6233 static class vr_values *x_vr_values;
6235 /* A trivial wrapper so that we can present the generic jump threading
6236 code with a simple API for simplifying statements. STMT is the
6237 statement we want to simplify, WITHIN_STMT provides the location
6238 for any overflow warnings. */
6240 static tree
6241 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6242 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6243 basic_block bb)
6245 /* First see if the conditional is in the hash table. */
6246 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6247 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6248 return cached_lhs;
6250 vr_values *vr_values = x_vr_values;
6251 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6253 tree op0 = gimple_cond_lhs (cond_stmt);
6254 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6256 tree op1 = gimple_cond_rhs (cond_stmt);
6257 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6259 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6260 op0, op1, within_stmt);
6263 /* We simplify a switch statement by trying to determine which case label
6264 will be taken. If we are successful then we return the corresponding
6265 CASE_LABEL_EXPR. */
6266 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6268 tree op = gimple_switch_index (switch_stmt);
6269 if (TREE_CODE (op) != SSA_NAME)
6270 return NULL_TREE;
6272 op = lhs_of_dominating_assert (op, bb, stmt);
6274 value_range *vr = vr_values->get_value_range (op);
6275 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6276 || symbolic_range_p (vr))
6277 return NULL_TREE;
6279 if (vr->type == VR_RANGE)
6281 size_t i, j;
6282 /* Get the range of labels that contain a part of the operand's
6283 value range. */
6284 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6286 /* Is there only one such label? */
6287 if (i == j)
6289 tree label = gimple_switch_label (switch_stmt, i);
6291 /* The i'th label will be taken only if the value range of the
6292 operand is entirely within the bounds of this label. */
6293 if (CASE_HIGH (label) != NULL_TREE
6294 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6295 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6296 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6297 && tree_int_cst_equal (vr->min, vr->max)))
6298 return label;
6301 /* If there are no such labels then the default label will be
6302 taken. */
6303 if (i > j)
6304 return gimple_switch_label (switch_stmt, 0);
6307 if (vr->type == VR_ANTI_RANGE)
6309 unsigned n = gimple_switch_num_labels (switch_stmt);
6310 tree min_label = gimple_switch_label (switch_stmt, 1);
6311 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6313 /* The default label will be taken only if the anti-range of the
6314 operand is entirely outside the bounds of all the (non-default)
6315 case labels. */
6316 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6317 && (CASE_HIGH (max_label) != NULL_TREE
6318 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6319 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6320 return gimple_switch_label (switch_stmt, 0);
6323 return NULL_TREE;
6326 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6328 tree lhs = gimple_assign_lhs (assign_stmt);
6329 if (TREE_CODE (lhs) == SSA_NAME
6330 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6331 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6332 && stmt_interesting_for_vrp (stmt))
6334 edge dummy_e;
6335 tree dummy_tree;
6336 value_range new_vr = VR_INITIALIZER;
6337 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6338 &dummy_tree, &new_vr);
6339 if (range_int_cst_singleton_p (&new_vr))
6340 return new_vr.min;
6344 return NULL_TREE;
6347 class vrp_dom_walker : public dom_walker
6349 public:
6350 vrp_dom_walker (cdi_direction direction,
6351 class const_and_copies *const_and_copies,
6352 class avail_exprs_stack *avail_exprs_stack)
6353 : dom_walker (direction, REACHABLE_BLOCKS),
6354 m_const_and_copies (const_and_copies),
6355 m_avail_exprs_stack (avail_exprs_stack),
6356 m_dummy_cond (NULL) {}
6358 virtual edge before_dom_children (basic_block);
6359 virtual void after_dom_children (basic_block);
6361 class vr_values *vr_values;
6363 private:
6364 class const_and_copies *m_const_and_copies;
6365 class avail_exprs_stack *m_avail_exprs_stack;
6367 gcond *m_dummy_cond;
6371 /* Called before processing dominator children of BB. We want to look
6372 at ASSERT_EXPRs and record information from them in the appropriate
6373 tables.
6375 We could look at other statements here. It's not seen as likely
6376 to significantly increase the jump threads we discover. */
6378 edge
6379 vrp_dom_walker::before_dom_children (basic_block bb)
6381 gimple_stmt_iterator gsi;
6383 m_avail_exprs_stack->push_marker ();
6384 m_const_and_copies->push_marker ();
6385 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6387 gimple *stmt = gsi_stmt (gsi);
6388 if (gimple_assign_single_p (stmt)
6389 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6391 tree rhs1 = gimple_assign_rhs1 (stmt);
6392 tree cond = TREE_OPERAND (rhs1, 1);
6393 tree inverted = invert_truthvalue (cond);
6394 vec<cond_equivalence> p;
6395 p.create (3);
6396 record_conditions (&p, cond, inverted);
6397 for (unsigned int i = 0; i < p.length (); i++)
6398 m_avail_exprs_stack->record_cond (&p[i]);
6400 tree lhs = gimple_assign_lhs (stmt);
6401 m_const_and_copies->record_const_or_copy (lhs,
6402 TREE_OPERAND (rhs1, 0));
6403 p.release ();
6404 continue;
6406 break;
6408 return NULL;
6411 /* Called after processing dominator children of BB. This is where we
6412 actually call into the threader. */
6413 void
6414 vrp_dom_walker::after_dom_children (basic_block bb)
6416 if (!m_dummy_cond)
6417 m_dummy_cond = gimple_build_cond (NE_EXPR,
6418 integer_zero_node, integer_zero_node,
6419 NULL, NULL);
6421 x_vr_values = vr_values;
6422 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6423 m_avail_exprs_stack, NULL,
6424 simplify_stmt_for_jump_threading);
6425 x_vr_values = NULL;
6427 m_avail_exprs_stack->pop_to_marker ();
6428 m_const_and_copies->pop_to_marker ();
6431 /* Blocks which have more than one predecessor and more than
6432 one successor present jump threading opportunities, i.e.,
6433 when the block is reached from a specific predecessor, we
6434 may be able to determine which of the outgoing edges will
6435 be traversed. When this optimization applies, we are able
6436 to avoid conditionals at runtime and we may expose secondary
6437 optimization opportunities.
6439 This routine is effectively a driver for the generic jump
6440 threading code. It basically just presents the generic code
6441 with edges that may be suitable for jump threading.
6443 Unlike DOM, we do not iterate VRP if jump threading was successful.
6444 While iterating may expose new opportunities for VRP, it is expected
6445 those opportunities would be very limited and the compile time cost
6446 to expose those opportunities would be significant.
6448 As jump threading opportunities are discovered, they are registered
6449 for later realization. */
6451 static void
6452 identify_jump_threads (class vr_values *vr_values)
6454 int i;
6455 edge e;
6457 /* Ugh. When substituting values earlier in this pass we can
6458 wipe the dominance information. So rebuild the dominator
6459 information as we need it within the jump threading code. */
6460 calculate_dominance_info (CDI_DOMINATORS);
6462 /* We do not allow VRP information to be used for jump threading
6463 across a back edge in the CFG. Otherwise it becomes too
6464 difficult to avoid eliminating loop exit tests. Of course
6465 EDGE_DFS_BACK is not accurate at this time so we have to
6466 recompute it. */
6467 mark_dfs_back_edges ();
6469 /* Do not thread across edges we are about to remove. Just marking
6470 them as EDGE_IGNORE will do. */
6471 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6472 e->flags |= EDGE_IGNORE;
6474 /* Allocate our unwinder stack to unwind any temporary equivalences
6475 that might be recorded. */
6476 const_and_copies *equiv_stack = new const_and_copies ();
6478 hash_table<expr_elt_hasher> *avail_exprs
6479 = new hash_table<expr_elt_hasher> (1024);
6480 avail_exprs_stack *avail_exprs_stack
6481 = new class avail_exprs_stack (avail_exprs);
6483 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6484 walker.vr_values = vr_values;
6485 walker.walk (cfun->cfg->x_entry_block_ptr);
6487 /* Clear EDGE_IGNORE. */
6488 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6489 e->flags &= ~EDGE_IGNORE;
6491 /* We do not actually update the CFG or SSA graphs at this point as
6492 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6493 handle ASSERT_EXPRs gracefully. */
6494 delete equiv_stack;
6495 delete avail_exprs;
6496 delete avail_exprs_stack;
6499 /* Traverse all the blocks folding conditionals with known ranges. */
6501 void
6502 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6504 size_t i;
6506 /* We have completed propagating through the lattice. */
6507 vr_values.set_lattice_propagation_complete ();
6509 if (dump_file)
6511 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6512 vr_values.dump_all_value_ranges (dump_file);
6513 fprintf (dump_file, "\n");
6516 /* Set value range to non pointer SSA_NAMEs. */
6517 for (i = 0; i < num_ssa_names; i++)
6519 tree name = ssa_name (i);
6520 if (!name)
6521 continue;
6523 value_range *vr = get_value_range (name);
6524 if (!name
6525 || (vr->type == VR_VARYING)
6526 || (vr->type == VR_UNDEFINED)
6527 || (TREE_CODE (vr->min) != INTEGER_CST)
6528 || (TREE_CODE (vr->max) != INTEGER_CST))
6529 continue;
6531 if (POINTER_TYPE_P (TREE_TYPE (name))
6532 && range_includes_zero_p (vr) == 0)
6533 set_ptr_nonnull (name);
6534 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6535 set_range_info (name, vr->type,
6536 wi::to_wide (vr->min),
6537 wi::to_wide (vr->max));
6540 /* If we're checking array refs, we want to merge information on
6541 the executability of each edge between vrp_folder and the
6542 check_array_bounds_dom_walker: each can clear the
6543 EDGE_EXECUTABLE flag on edges, in different ways.
6545 Hence, if we're going to call check_all_array_refs, set
6546 the flag on every edge now, rather than in
6547 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6548 it from some edges. */
6549 if (warn_array_bounds && warn_array_bounds_p)
6550 set_all_edges_as_executable (cfun);
6552 class vrp_folder vrp_folder;
6553 vrp_folder.vr_values = &vr_values;
6554 vrp_folder.substitute_and_fold ();
6556 if (warn_array_bounds && warn_array_bounds_p)
6557 check_all_array_refs ();
6560 /* Main entry point to VRP (Value Range Propagation). This pass is
6561 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6562 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6563 Programming Language Design and Implementation, pp. 67-78, 1995.
6564 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6566 This is essentially an SSA-CCP pass modified to deal with ranges
6567 instead of constants.
6569 While propagating ranges, we may find that two or more SSA name
6570 have equivalent, though distinct ranges. For instance,
6572 1 x_9 = p_3->a;
6573 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6574 3 if (p_4 == q_2)
6575 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6576 5 endif
6577 6 if (q_2)
6579 In the code above, pointer p_5 has range [q_2, q_2], but from the
6580 code we can also determine that p_5 cannot be NULL and, if q_2 had
6581 a non-varying range, p_5's range should also be compatible with it.
6583 These equivalences are created by two expressions: ASSERT_EXPR and
6584 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6585 result of another assertion, then we can use the fact that p_5 and
6586 p_4 are equivalent when evaluating p_5's range.
6588 Together with value ranges, we also propagate these equivalences
6589 between names so that we can take advantage of information from
6590 multiple ranges when doing final replacement. Note that this
6591 equivalency relation is transitive but not symmetric.
6593 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6594 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6595 in contexts where that assertion does not hold (e.g., in line 6).
6597 TODO, the main difference between this pass and Patterson's is that
6598 we do not propagate edge probabilities. We only compute whether
6599 edges can be taken or not. That is, instead of having a spectrum
6600 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6601 DON'T KNOW. In the future, it may be worthwhile to propagate
6602 probabilities to aid branch prediction. */
6604 static unsigned int
6605 execute_vrp (bool warn_array_bounds_p)
6607 int i;
6608 edge e;
6609 switch_update *su;
6611 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6612 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6613 scev_initialize ();
6615 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6616 Inserting assertions may split edges which will invalidate
6617 EDGE_DFS_BACK. */
6618 insert_range_assertions ();
6620 to_remove_edges.create (10);
6621 to_update_switch_stmts.create (5);
6622 threadedge_initialize_values ();
6624 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6625 mark_dfs_back_edges ();
6627 class vrp_prop vrp_prop;
6628 vrp_prop.vrp_initialize ();
6629 vrp_prop.ssa_propagate ();
6630 vrp_prop.vrp_finalize (warn_array_bounds_p);
6632 /* We must identify jump threading opportunities before we release
6633 the datastructures built by VRP. */
6634 identify_jump_threads (&vrp_prop.vr_values);
6636 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6637 was set by a type conversion can often be rewritten to use the
6638 RHS of the type conversion.
6640 However, doing so inhibits jump threading through the comparison.
6641 So that transformation is not performed until after jump threading
6642 is complete. */
6643 basic_block bb;
6644 FOR_EACH_BB_FN (bb, cfun)
6646 gimple *last = last_stmt (bb);
6647 if (last && gimple_code (last) == GIMPLE_COND)
6648 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6651 free_numbers_of_iterations_estimates (cfun);
6653 /* ASSERT_EXPRs must be removed before finalizing jump threads
6654 as finalizing jump threads calls the CFG cleanup code which
6655 does not properly handle ASSERT_EXPRs. */
6656 remove_range_assertions ();
6658 /* If we exposed any new variables, go ahead and put them into
6659 SSA form now, before we handle jump threading. This simplifies
6660 interactions between rewriting of _DECL nodes into SSA form
6661 and rewriting SSA_NAME nodes into SSA form after block
6662 duplication and CFG manipulation. */
6663 update_ssa (TODO_update_ssa);
6665 /* We identified all the jump threading opportunities earlier, but could
6666 not transform the CFG at that time. This routine transforms the
6667 CFG and arranges for the dominator tree to be rebuilt if necessary.
6669 Note the SSA graph update will occur during the normal TODO
6670 processing by the pass manager. */
6671 thread_through_all_blocks (false);
6673 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6674 CFG in a broken state and requires a cfg_cleanup run. */
6675 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6676 remove_edge (e);
6677 /* Update SWITCH_EXPR case label vector. */
6678 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6680 size_t j;
6681 size_t n = TREE_VEC_LENGTH (su->vec);
6682 tree label;
6683 gimple_switch_set_num_labels (su->stmt, n);
6684 for (j = 0; j < n; j++)
6685 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
6686 /* As we may have replaced the default label with a regular one
6687 make sure to make it a real default label again. This ensures
6688 optimal expansion. */
6689 label = gimple_switch_label (su->stmt, 0);
6690 CASE_LOW (label) = NULL_TREE;
6691 CASE_HIGH (label) = NULL_TREE;
6694 if (to_remove_edges.length () > 0)
6696 free_dominance_info (CDI_DOMINATORS);
6697 loops_state_set (LOOPS_NEED_FIXUP);
6700 to_remove_edges.release ();
6701 to_update_switch_stmts.release ();
6702 threadedge_finalize_values ();
6704 scev_finalize ();
6705 loop_optimizer_finalize ();
6706 return 0;
6709 namespace {
6711 const pass_data pass_data_vrp =
6713 GIMPLE_PASS, /* type */
6714 "vrp", /* name */
6715 OPTGROUP_NONE, /* optinfo_flags */
6716 TV_TREE_VRP, /* tv_id */
6717 PROP_ssa, /* properties_required */
6718 0, /* properties_provided */
6719 0, /* properties_destroyed */
6720 0, /* todo_flags_start */
6721 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6724 class pass_vrp : public gimple_opt_pass
6726 public:
6727 pass_vrp (gcc::context *ctxt)
6728 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6731 /* opt_pass methods: */
6732 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6733 void set_pass_param (unsigned int n, bool param)
6735 gcc_assert (n == 0);
6736 warn_array_bounds_p = param;
6738 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6739 virtual unsigned int execute (function *)
6740 { return execute_vrp (warn_array_bounds_p); }
6742 private:
6743 bool warn_array_bounds_p;
6744 }; // class pass_vrp
6746 } // anon namespace
6748 gimple_opt_pass *
6749 make_pass_vrp (gcc::context *ctxt)
6751 return new pass_vrp (ctxt);
6755 /* Worker for determine_value_range. */
6757 static void
6758 determine_value_range_1 (value_range *vr, tree expr)
6760 if (BINARY_CLASS_P (expr))
6762 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6763 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6764 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6765 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6766 &vr0, &vr1);
6768 else if (UNARY_CLASS_P (expr))
6770 value_range vr0 = VR_INITIALIZER;
6771 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6772 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6773 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6775 else if (TREE_CODE (expr) == INTEGER_CST)
6776 set_value_range_to_value (vr, expr, NULL);
6777 else
6779 value_range_type kind;
6780 wide_int min, max;
6781 /* For SSA names try to extract range info computed by VRP. Otherwise
6782 fall back to varying. */
6783 if (TREE_CODE (expr) == SSA_NAME
6784 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6785 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6786 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6787 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6788 else
6789 set_value_range_to_varying (vr);
6793 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6794 the determined range type. */
6796 value_range_type
6797 determine_value_range (tree expr, wide_int *min, wide_int *max)
6799 value_range vr = VR_INITIALIZER;
6800 determine_value_range_1 (&vr, expr);
6801 if ((vr.type == VR_RANGE
6802 || vr.type == VR_ANTI_RANGE)
6803 && !symbolic_range_p (&vr))
6805 *min = wi::to_wide (vr.min);
6806 *max = wi::to_wide (vr.max);
6807 return vr.type;
6810 return VR_VARYING;