PR c++/86728 - C variadic generic lambda.
[official-gcc.git] / gcc / tree-vrp.c
blobe1875d8d46e75f9747fbebbd47e099f8e498b538
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);
482 /* If abs (min) < abs (max), set VR to [-max, max], if
483 abs (min) >= abs (max), set VR to [-min, min]. */
485 static void
486 abs_extent_range (value_range *vr, tree min, tree max)
488 int cmp;
490 gcc_assert (TREE_CODE (min) == INTEGER_CST);
491 gcc_assert (TREE_CODE (max) == INTEGER_CST);
492 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
493 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
494 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
495 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
496 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
498 set_value_range_to_varying (vr);
499 return;
501 cmp = compare_values (min, max);
502 if (cmp == -1)
503 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
504 else if (cmp == 0 || cmp == 1)
506 max = min;
507 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
509 else
511 set_value_range_to_varying (vr);
512 return;
514 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
517 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
519 bool
520 vrp_operand_equal_p (const_tree val1, const_tree val2)
522 if (val1 == val2)
523 return true;
524 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
525 return false;
526 return true;
529 /* Return true, if the bitmaps B1 and B2 are equal. */
531 bool
532 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
534 return (b1 == b2
535 || ((!b1 || bitmap_empty_p (b1))
536 && (!b2 || bitmap_empty_p (b2)))
537 || (b1 && b2
538 && bitmap_equal_p (b1, b2)));
541 /* Return true if VR is ~[0, 0]. */
543 bool
544 range_is_nonnull (value_range *vr)
546 return vr->type == VR_ANTI_RANGE
547 && integer_zerop (vr->min)
548 && integer_zerop (vr->max);
552 /* Return true if VR is [0, 0]. */
554 static inline bool
555 range_is_null (value_range *vr)
557 return vr->type == VR_RANGE
558 && integer_zerop (vr->min)
559 && integer_zerop (vr->max);
562 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
563 a singleton. */
565 bool
566 range_int_cst_p (value_range *vr)
568 return (vr->type == VR_RANGE
569 && TREE_CODE (vr->max) == INTEGER_CST
570 && TREE_CODE (vr->min) == INTEGER_CST);
573 /* Return true if VR is a INTEGER_CST singleton. */
575 bool
576 range_int_cst_singleton_p (value_range *vr)
578 return (range_int_cst_p (vr)
579 && tree_int_cst_equal (vr->min, vr->max));
582 /* Return true if value range VR involves at least one symbol. */
584 bool
585 symbolic_range_p (value_range *vr)
587 return (!is_gimple_min_invariant (vr->min)
588 || !is_gimple_min_invariant (vr->max));
591 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
592 otherwise. We only handle additive operations and set NEG to true if the
593 symbol is negated and INV to the invariant part, if any. */
595 tree
596 get_single_symbol (tree t, bool *neg, tree *inv)
598 bool neg_;
599 tree inv_;
601 *inv = NULL_TREE;
602 *neg = false;
604 if (TREE_CODE (t) == PLUS_EXPR
605 || TREE_CODE (t) == POINTER_PLUS_EXPR
606 || TREE_CODE (t) == MINUS_EXPR)
608 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
610 neg_ = (TREE_CODE (t) == MINUS_EXPR);
611 inv_ = TREE_OPERAND (t, 0);
612 t = TREE_OPERAND (t, 1);
614 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
616 neg_ = false;
617 inv_ = TREE_OPERAND (t, 1);
618 t = TREE_OPERAND (t, 0);
620 else
621 return NULL_TREE;
623 else
625 neg_ = false;
626 inv_ = NULL_TREE;
629 if (TREE_CODE (t) == NEGATE_EXPR)
631 t = TREE_OPERAND (t, 0);
632 neg_ = !neg_;
635 if (TREE_CODE (t) != SSA_NAME)
636 return NULL_TREE;
638 if (inv_ && TREE_OVERFLOW_P (inv_))
639 inv_ = drop_tree_overflow (inv_);
641 *neg = neg_;
642 *inv = inv_;
643 return t;
646 /* The reverse operation: build a symbolic expression with TYPE
647 from symbol SYM, negated according to NEG, and invariant INV. */
649 static tree
650 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
652 const bool pointer_p = POINTER_TYPE_P (type);
653 tree t = sym;
655 if (neg)
656 t = build1 (NEGATE_EXPR, type, t);
658 if (integer_zerop (inv))
659 return t;
661 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
664 /* Return
665 1 if VAL < VAL2
666 0 if !(VAL < VAL2)
667 -2 if those are incomparable. */
669 operand_less_p (tree val, tree val2)
671 /* LT is folded faster than GE and others. Inline the common case. */
672 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
673 return tree_int_cst_lt (val, val2);
674 else
676 tree tcmp;
678 fold_defer_overflow_warnings ();
680 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
682 fold_undefer_and_ignore_overflow_warnings ();
684 if (!tcmp
685 || TREE_CODE (tcmp) != INTEGER_CST)
686 return -2;
688 if (!integer_zerop (tcmp))
689 return 1;
692 return 0;
695 /* Compare two values VAL1 and VAL2. Return
697 -2 if VAL1 and VAL2 cannot be compared at compile-time,
698 -1 if VAL1 < VAL2,
699 0 if VAL1 == VAL2,
700 +1 if VAL1 > VAL2, and
701 +2 if VAL1 != VAL2
703 This is similar to tree_int_cst_compare but supports pointer values
704 and values that cannot be compared at compile time.
706 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
707 true if the return value is only valid if we assume that signed
708 overflow is undefined. */
711 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
713 if (val1 == val2)
714 return 0;
716 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
717 both integers. */
718 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
719 == POINTER_TYPE_P (TREE_TYPE (val2)));
721 /* Convert the two values into the same type. This is needed because
722 sizetype causes sign extension even for unsigned types. */
723 val2 = fold_convert (TREE_TYPE (val1), val2);
724 STRIP_USELESS_TYPE_CONVERSION (val2);
726 const bool overflow_undefined
727 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
728 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
729 tree inv1, inv2;
730 bool neg1, neg2;
731 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
732 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
734 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
735 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
736 if (sym1 && sym2)
738 /* Both values must use the same name with the same sign. */
739 if (sym1 != sym2 || neg1 != neg2)
740 return -2;
742 /* [-]NAME + CST == [-]NAME + CST. */
743 if (inv1 == inv2)
744 return 0;
746 /* If overflow is defined we cannot simplify more. */
747 if (!overflow_undefined)
748 return -2;
750 if (strict_overflow_p != NULL
751 /* Symbolic range building sets TREE_NO_WARNING to declare
752 that overflow doesn't happen. */
753 && (!inv1 || !TREE_NO_WARNING (val1))
754 && (!inv2 || !TREE_NO_WARNING (val2)))
755 *strict_overflow_p = true;
757 if (!inv1)
758 inv1 = build_int_cst (TREE_TYPE (val1), 0);
759 if (!inv2)
760 inv2 = build_int_cst (TREE_TYPE (val2), 0);
762 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
763 TYPE_SIGN (TREE_TYPE (val1)));
766 const bool cst1 = is_gimple_min_invariant (val1);
767 const bool cst2 = is_gimple_min_invariant (val2);
769 /* If one is of the form '[-]NAME + CST' and the other is constant, then
770 it might be possible to say something depending on the constants. */
771 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
773 if (!overflow_undefined)
774 return -2;
776 if (strict_overflow_p != NULL
777 /* Symbolic range building sets TREE_NO_WARNING to declare
778 that overflow doesn't happen. */
779 && (!sym1 || !TREE_NO_WARNING (val1))
780 && (!sym2 || !TREE_NO_WARNING (val2)))
781 *strict_overflow_p = true;
783 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
784 tree cst = cst1 ? val1 : val2;
785 tree inv = cst1 ? inv2 : inv1;
787 /* Compute the difference between the constants. If it overflows or
788 underflows, this means that we can trivially compare the NAME with
789 it and, consequently, the two values with each other. */
790 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
791 if (wi::cmp (0, wi::to_wide (inv), sgn)
792 != wi::cmp (diff, wi::to_wide (cst), sgn))
794 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
795 return cst1 ? res : -res;
798 return -2;
801 /* We cannot say anything more for non-constants. */
802 if (!cst1 || !cst2)
803 return -2;
805 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
807 /* We cannot compare overflowed values. */
808 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
809 return -2;
811 if (TREE_CODE (val1) == INTEGER_CST
812 && TREE_CODE (val2) == INTEGER_CST)
813 return tree_int_cst_compare (val1, val2);
815 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
817 if (known_eq (wi::to_poly_widest (val1),
818 wi::to_poly_widest (val2)))
819 return 0;
820 if (known_lt (wi::to_poly_widest (val1),
821 wi::to_poly_widest (val2)))
822 return -1;
823 if (known_gt (wi::to_poly_widest (val1),
824 wi::to_poly_widest (val2)))
825 return 1;
828 return -2;
830 else
832 tree t;
834 /* First see if VAL1 and VAL2 are not the same. */
835 if (val1 == val2 || operand_equal_p (val1, val2, 0))
836 return 0;
838 /* If VAL1 is a lower address than VAL2, return -1. */
839 if (operand_less_p (val1, val2) == 1)
840 return -1;
842 /* If VAL1 is a higher address than VAL2, return +1. */
843 if (operand_less_p (val2, val1) == 1)
844 return 1;
846 /* If VAL1 is different than VAL2, return +2.
847 For integer constants we either have already returned -1 or 1
848 or they are equivalent. We still might succeed in proving
849 something about non-trivial operands. */
850 if (TREE_CODE (val1) != INTEGER_CST
851 || TREE_CODE (val2) != INTEGER_CST)
853 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
854 if (t && integer_onep (t))
855 return 2;
858 return -2;
862 /* Compare values like compare_values_warnv. */
865 compare_values (tree val1, tree val2)
867 bool sop;
868 return compare_values_warnv (val1, val2, &sop);
872 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
873 0 if VAL is not inside [MIN, MAX],
874 -2 if we cannot tell either way.
876 Benchmark compile/20001226-1.c compilation time after changing this
877 function. */
880 value_inside_range (tree val, tree min, tree max)
882 int cmp1, cmp2;
884 cmp1 = operand_less_p (val, min);
885 if (cmp1 == -2)
886 return -2;
887 if (cmp1 == 1)
888 return 0;
890 cmp2 = operand_less_p (max, val);
891 if (cmp2 == -2)
892 return -2;
894 return !cmp2;
898 /* Return true if value ranges VR0 and VR1 have a non-empty
899 intersection.
901 Benchmark compile/20001226-1.c compilation time after changing this
902 function.
905 static inline bool
906 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
908 /* The value ranges do not intersect if the maximum of the first range is
909 less than the minimum of the second range or vice versa.
910 When those relations are unknown, we can't do any better. */
911 if (operand_less_p (vr0->max, vr1->min) != 0)
912 return false;
913 if (operand_less_p (vr1->max, vr0->min) != 0)
914 return false;
915 return true;
919 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
920 include the value zero, -2 if we cannot tell. */
923 range_includes_zero_p (tree min, tree max)
925 tree zero = build_int_cst (TREE_TYPE (min), 0);
926 return value_inside_range (zero, min, max);
929 /* Return true if *VR is know to only contain nonnegative values. */
931 static inline bool
932 value_range_nonnegative_p (value_range *vr)
934 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
935 which would return a useful value should be encoded as a
936 VR_RANGE. */
937 if (vr->type == VR_RANGE)
939 int result = compare_values (vr->min, integer_zero_node);
940 return (result == 0 || result == 1);
943 return false;
946 /* If *VR has a value rante that is a single constant value return that,
947 otherwise return NULL_TREE. */
949 tree
950 value_range_constant_singleton (value_range *vr)
952 if (vr->type == VR_RANGE
953 && vrp_operand_equal_p (vr->min, vr->max)
954 && is_gimple_min_invariant (vr->min))
955 return vr->min;
957 return NULL_TREE;
960 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
962 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
964 Return TRUE if VR was a constant range and we were able to compute
965 the bit masks. */
967 bool
968 vrp_set_zero_nonzero_bits (const tree expr_type,
969 value_range *vr,
970 wide_int *may_be_nonzero,
971 wide_int *must_be_nonzero)
973 if (!range_int_cst_p (vr))
975 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
976 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
977 return false;
979 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
980 wi::to_wide (vr->min),
981 wi::to_wide (vr->max),
982 *may_be_nonzero, *must_be_nonzero);
983 return true;
986 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
987 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
988 false otherwise. If *AR can be represented with a single range
989 *VR1 will be VR_UNDEFINED. */
991 static bool
992 ranges_from_anti_range (value_range *ar,
993 value_range *vr0, value_range *vr1)
995 tree type = TREE_TYPE (ar->min);
997 vr0->type = VR_UNDEFINED;
998 vr1->type = VR_UNDEFINED;
1000 if (ar->type != VR_ANTI_RANGE
1001 || TREE_CODE (ar->min) != INTEGER_CST
1002 || TREE_CODE (ar->max) != INTEGER_CST
1003 || !vrp_val_min (type)
1004 || !vrp_val_max (type))
1005 return false;
1007 if (!vrp_val_is_min (ar->min))
1009 vr0->type = VR_RANGE;
1010 vr0->min = vrp_val_min (type);
1011 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1013 if (!vrp_val_is_max (ar->max))
1015 vr1->type = VR_RANGE;
1016 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1017 vr1->max = vrp_val_max (type);
1019 if (vr0->type == VR_UNDEFINED)
1021 *vr0 = *vr1;
1022 vr1->type = VR_UNDEFINED;
1025 return vr0->type != VR_UNDEFINED;
1028 /* Extract the components of a value range into a pair of wide ints in
1029 [WMIN, WMAX].
1031 If the value range is anything but a VR_RANGE of constants, the
1032 resulting wide ints are set to [-MIN, +MAX] for the type. */
1034 static void inline
1035 extract_range_into_wide_ints (value_range *vr,
1036 signop sign, unsigned prec,
1037 wide_int *wmin, wide_int *wmax)
1039 if (range_int_cst_p (vr))
1041 *wmin = wi::to_wide (vr->min);
1042 *wmax = wi::to_wide (vr->max);
1044 else
1046 *wmin = wi::min_value (prec, sign);
1047 *wmax = wi::max_value (prec, sign);
1051 /* Value range wrapper for wide_int_range_shift_undefined_p. */
1053 static inline bool
1054 vrp_shift_undefined_p (const value_range &shifter, unsigned prec)
1056 tree type = TREE_TYPE (shifter.min);
1057 return wide_int_range_shift_undefined_p (TYPE_SIGN (type), prec,
1058 wi::to_wide (shifter.min),
1059 wi::to_wide (shifter.max));
1062 /* Value range wrapper for wide_int_range_multiplicative_op:
1064 *VR = *VR0 .CODE. *VR1. */
1066 static void
1067 extract_range_from_multiplicative_op (value_range *vr,
1068 enum tree_code code,
1069 value_range *vr0, value_range *vr1)
1071 gcc_assert (code == MULT_EXPR
1072 || code == TRUNC_DIV_EXPR
1073 || code == FLOOR_DIV_EXPR
1074 || code == CEIL_DIV_EXPR
1075 || code == EXACT_DIV_EXPR
1076 || code == ROUND_DIV_EXPR
1077 || code == RSHIFT_EXPR
1078 || code == LSHIFT_EXPR);
1079 gcc_assert (vr0->type == VR_RANGE && vr0->type == vr1->type);
1081 tree type = TREE_TYPE (vr0->min);
1082 wide_int res_lb, res_ub;
1083 wide_int vr0_lb = wi::to_wide (vr0->min);
1084 wide_int vr0_ub = wi::to_wide (vr0->max);
1085 wide_int vr1_lb = wi::to_wide (vr1->min);
1086 wide_int vr1_ub = wi::to_wide (vr1->max);
1087 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1088 bool overflow_wraps = TYPE_OVERFLOW_WRAPS (type);
1089 unsigned prec = TYPE_PRECISION (type);
1091 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1092 code, TYPE_SIGN (type), prec,
1093 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1094 overflow_undefined, overflow_wraps))
1095 set_and_canonicalize_value_range (vr, VR_RANGE,
1096 wide_int_to_tree (type, res_lb),
1097 wide_int_to_tree (type, res_ub), NULL);
1098 else
1099 set_value_range_to_varying (vr);
1102 /* Value range wrapper for wide_int_range_can_optimize_bit_op.
1104 If a bit operation on two ranges can be easily optimized in terms
1105 of a mask, store the optimized new range in VR and return TRUE. */
1107 static bool
1108 vrp_can_optimize_bit_op (value_range *vr, enum tree_code code,
1109 value_range *vr0, value_range *vr1)
1111 tree lower_bound, upper_bound, mask;
1112 if (code != BIT_AND_EXPR && code != BIT_IOR_EXPR)
1113 return false;
1114 if (range_int_cst_singleton_p (vr1))
1116 if (!range_int_cst_p (vr0))
1117 return false;
1118 mask = vr1->min;
1119 lower_bound = vr0->min;
1120 upper_bound = vr0->max;
1122 else if (range_int_cst_singleton_p (vr0))
1124 if (!range_int_cst_p (vr1))
1125 return false;
1126 mask = vr0->min;
1127 lower_bound = vr1->min;
1128 upper_bound = vr1->max;
1130 else
1131 return false;
1132 if (wide_int_range_can_optimize_bit_op (code,
1133 wi::to_wide (lower_bound),
1134 wi::to_wide (upper_bound),
1135 wi::to_wide (mask)))
1137 tree min = int_const_binop (code, lower_bound, mask);
1138 tree max = int_const_binop (code, upper_bound, mask);
1139 set_value_range (vr, VR_RANGE, min, max, NULL);
1140 return true;
1142 return false;
1145 /* If BOUND will include a symbolic bound, adjust it accordingly,
1146 otherwise leave it as is.
1148 CODE is the original operation that combined the bounds (PLUS_EXPR
1149 or MINUS_EXPR).
1151 TYPE is the type of the original operation.
1153 SYM_OPn is the symbolic for OPn if it has a symbolic.
1155 NEG_OPn is TRUE if the OPn was negated. */
1157 static void
1158 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1159 tree sym_op0, tree sym_op1,
1160 bool neg_op0, bool neg_op1)
1162 bool minus_p = (code == MINUS_EXPR);
1163 /* If the result bound is constant, we're done; otherwise, build the
1164 symbolic lower bound. */
1165 if (sym_op0 == sym_op1)
1167 else if (sym_op0)
1168 bound = build_symbolic_expr (type, sym_op0,
1169 neg_op0, bound);
1170 else if (sym_op1)
1172 /* We may not negate if that might introduce
1173 undefined overflow. */
1174 if (!minus_p
1175 || neg_op1
1176 || TYPE_OVERFLOW_WRAPS (type))
1177 bound = build_symbolic_expr (type, sym_op1,
1178 neg_op1 ^ minus_p, bound);
1179 else
1180 bound = NULL_TREE;
1184 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1185 int bound according to CODE. CODE is the operation combining the
1186 bound (either a PLUS_EXPR or a MINUS_EXPR).
1188 TYPE is the type of the combine operation.
1190 WI is the wide int to store the result.
1192 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1193 if over/underflow occurred. */
1195 static void
1196 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1197 tree type, tree op0, tree op1)
1199 bool minus_p = (code == MINUS_EXPR);
1200 const signop sgn = TYPE_SIGN (type);
1201 const unsigned int prec = TYPE_PRECISION (type);
1203 /* Combine the bounds, if any. */
1204 if (op0 && op1)
1206 if (minus_p)
1207 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1208 else
1209 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1211 else if (op0)
1212 wi = wi::to_wide (op0);
1213 else if (op1)
1215 if (minus_p)
1216 wi = wi::neg (wi::to_wide (op1), &ovf);
1217 else
1218 wi = wi::to_wide (op1);
1220 else
1221 wi = wi::shwi (0, prec);
1224 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1225 put the result in VR.
1227 TYPE is the type of the range.
1229 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1230 occurred while originally calculating WMIN or WMAX. -1 indicates
1231 underflow. +1 indicates overflow. 0 indicates neither. */
1233 static void
1234 set_value_range_with_overflow (value_range &vr,
1235 tree type,
1236 const wide_int &wmin, const wide_int &wmax,
1237 wi::overflow_type min_ovf,
1238 wi::overflow_type max_ovf)
1240 const signop sgn = TYPE_SIGN (type);
1241 const unsigned int prec = TYPE_PRECISION (type);
1242 vr.type = VR_RANGE;
1243 vr.equiv = NULL;
1244 if (TYPE_OVERFLOW_WRAPS (type))
1246 /* If overflow wraps, truncate the values and adjust the
1247 range kind and bounds appropriately. */
1248 wide_int tmin = wide_int::from (wmin, prec, sgn);
1249 wide_int tmax = wide_int::from (wmax, prec, sgn);
1250 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1252 /* No overflow or both overflow or underflow. The
1253 range kind stays VR_RANGE. */
1254 vr.min = wide_int_to_tree (type, tmin);
1255 vr.max = wide_int_to_tree (type, tmax);
1257 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1258 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1260 /* Min underflow or max overflow. The range kind
1261 changes to VR_ANTI_RANGE. */
1262 bool covers = false;
1263 wide_int tem = tmin;
1264 vr.type = VR_ANTI_RANGE;
1265 tmin = tmax + 1;
1266 if (wi::cmp (tmin, tmax, sgn) < 0)
1267 covers = true;
1268 tmax = tem - 1;
1269 if (wi::cmp (tmax, tem, sgn) > 0)
1270 covers = true;
1271 /* If the anti-range would cover nothing, drop to varying.
1272 Likewise if the anti-range bounds are outside of the
1273 types values. */
1274 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1276 set_value_range_to_varying (&vr);
1277 return;
1279 vr.min = wide_int_to_tree (type, tmin);
1280 vr.max = wide_int_to_tree (type, tmax);
1282 else
1284 /* Other underflow and/or overflow, drop to VR_VARYING. */
1285 set_value_range_to_varying (&vr);
1286 return;
1289 else
1291 /* If overflow does not wrap, saturate to the types min/max
1292 value. */
1293 wide_int type_min = wi::min_value (prec, sgn);
1294 wide_int type_max = wi::max_value (prec, sgn);
1295 if (min_ovf == wi::OVF_UNDERFLOW)
1296 vr.min = wide_int_to_tree (type, type_min);
1297 else if (min_ovf == wi::OVF_OVERFLOW)
1298 vr.min = wide_int_to_tree (type, type_max);
1299 else
1300 vr.min = wide_int_to_tree (type, wmin);
1302 if (max_ovf == wi::OVF_UNDERFLOW)
1303 vr.max = wide_int_to_tree (type, type_min);
1304 else if (max_ovf == wi::OVF_OVERFLOW)
1305 vr.max = wide_int_to_tree (type, type_max);
1306 else
1307 vr.max = wide_int_to_tree (type, wmax);
1311 /* Extract range information from a binary operation CODE based on
1312 the ranges of each of its operands *VR0 and *VR1 with resulting
1313 type EXPR_TYPE. The resulting range is stored in *VR. */
1315 void
1316 extract_range_from_binary_expr_1 (value_range *vr,
1317 enum tree_code code, tree expr_type,
1318 value_range *vr0_, value_range *vr1_)
1320 signop sign = TYPE_SIGN (expr_type);
1321 unsigned int prec = TYPE_PRECISION (expr_type);
1322 value_range vr0 = *vr0_, vr1 = *vr1_;
1323 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1324 enum value_range_type type;
1325 tree min = NULL_TREE, max = NULL_TREE;
1326 int cmp;
1328 if (!INTEGRAL_TYPE_P (expr_type)
1329 && !POINTER_TYPE_P (expr_type))
1331 set_value_range_to_varying (vr);
1332 return;
1335 /* Not all binary expressions can be applied to ranges in a
1336 meaningful way. Handle only arithmetic operations. */
1337 if (code != PLUS_EXPR
1338 && code != MINUS_EXPR
1339 && code != POINTER_PLUS_EXPR
1340 && code != MULT_EXPR
1341 && code != TRUNC_DIV_EXPR
1342 && code != FLOOR_DIV_EXPR
1343 && code != CEIL_DIV_EXPR
1344 && code != EXACT_DIV_EXPR
1345 && code != ROUND_DIV_EXPR
1346 && code != TRUNC_MOD_EXPR
1347 && code != RSHIFT_EXPR
1348 && code != LSHIFT_EXPR
1349 && code != MIN_EXPR
1350 && code != MAX_EXPR
1351 && code != BIT_AND_EXPR
1352 && code != BIT_IOR_EXPR
1353 && code != BIT_XOR_EXPR)
1355 set_value_range_to_varying (vr);
1356 return;
1359 /* If both ranges are UNDEFINED, so is the result. */
1360 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1362 set_value_range_to_undefined (vr);
1363 return;
1365 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1366 code. At some point we may want to special-case operations that
1367 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1368 operand. */
1369 else if (vr0.type == VR_UNDEFINED)
1370 set_value_range_to_varying (&vr0);
1371 else if (vr1.type == VR_UNDEFINED)
1372 set_value_range_to_varying (&vr1);
1374 /* We get imprecise results from ranges_from_anti_range when
1375 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1376 range, but then we also need to hack up vrp_meet. It's just
1377 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1378 if (code == EXACT_DIV_EXPR
1379 && vr0.type == VR_ANTI_RANGE
1380 && vr0.min == vr0.max
1381 && integer_zerop (vr0.min))
1383 set_value_range_to_nonnull (vr, expr_type);
1384 return;
1387 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1388 and express ~[] op X as ([]' op X) U ([]'' op X). */
1389 if (vr0.type == VR_ANTI_RANGE
1390 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1392 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1393 if (vrtem1.type != VR_UNDEFINED)
1395 value_range vrres = VR_INITIALIZER;
1396 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1397 &vrtem1, vr1_);
1398 vrp_meet (vr, &vrres);
1400 return;
1402 /* Likewise for X op ~[]. */
1403 if (vr1.type == VR_ANTI_RANGE
1404 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1406 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1407 if (vrtem1.type != VR_UNDEFINED)
1409 value_range vrres = VR_INITIALIZER;
1410 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1411 vr0_, &vrtem1);
1412 vrp_meet (vr, &vrres);
1414 return;
1417 /* The type of the resulting value range defaults to VR0.TYPE. */
1418 type = vr0.type;
1420 /* Refuse to operate on VARYING ranges, ranges of different kinds
1421 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1422 because we may be able to derive a useful range even if one of
1423 the operands is VR_VARYING or symbolic range. Similarly for
1424 divisions, MIN/MAX and PLUS/MINUS.
1426 TODO, we may be able to derive anti-ranges in some cases. */
1427 if (code != BIT_AND_EXPR
1428 && code != BIT_IOR_EXPR
1429 && code != TRUNC_DIV_EXPR
1430 && code != FLOOR_DIV_EXPR
1431 && code != CEIL_DIV_EXPR
1432 && code != EXACT_DIV_EXPR
1433 && code != ROUND_DIV_EXPR
1434 && code != TRUNC_MOD_EXPR
1435 && code != MIN_EXPR
1436 && code != MAX_EXPR
1437 && code != PLUS_EXPR
1438 && code != MINUS_EXPR
1439 && code != RSHIFT_EXPR
1440 && (vr0.type == VR_VARYING
1441 || vr1.type == VR_VARYING
1442 || vr0.type != vr1.type
1443 || symbolic_range_p (&vr0)
1444 || symbolic_range_p (&vr1)))
1446 set_value_range_to_varying (vr);
1447 return;
1450 /* Now evaluate the expression to determine the new range. */
1451 if (POINTER_TYPE_P (expr_type))
1453 if (code == MIN_EXPR || code == MAX_EXPR)
1455 /* For MIN/MAX expressions with pointers, we only care about
1456 nullness, if both are non null, then the result is nonnull.
1457 If both are null, then the result is null. Otherwise they
1458 are varying. */
1459 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1460 set_value_range_to_nonnull (vr, expr_type);
1461 else if (range_is_null (&vr0) && range_is_null (&vr1))
1462 set_value_range_to_null (vr, expr_type);
1463 else
1464 set_value_range_to_varying (vr);
1466 else if (code == POINTER_PLUS_EXPR)
1468 /* For pointer types, we are really only interested in asserting
1469 whether the expression evaluates to non-NULL. */
1470 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
1471 set_value_range_to_nonnull (vr, expr_type);
1472 else if (range_is_null (&vr0) && range_is_null (&vr1))
1473 set_value_range_to_null (vr, expr_type);
1474 else
1475 set_value_range_to_varying (vr);
1477 else if (code == BIT_AND_EXPR)
1479 /* For pointer types, we are really only interested in asserting
1480 whether the expression evaluates to non-NULL. */
1481 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1482 set_value_range_to_nonnull (vr, expr_type);
1483 else if (range_is_null (&vr0) || range_is_null (&vr1))
1484 set_value_range_to_null (vr, expr_type);
1485 else
1486 set_value_range_to_varying (vr);
1488 else
1489 set_value_range_to_varying (vr);
1491 return;
1494 /* For integer ranges, apply the operation to each end of the
1495 range and see what we end up with. */
1496 if (code == PLUS_EXPR || code == MINUS_EXPR)
1498 const bool minus_p = (code == MINUS_EXPR);
1499 tree min_op0 = vr0.min;
1500 tree min_op1 = minus_p ? vr1.max : vr1.min;
1501 tree max_op0 = vr0.max;
1502 tree max_op1 = minus_p ? vr1.min : vr1.max;
1503 tree sym_min_op0 = NULL_TREE;
1504 tree sym_min_op1 = NULL_TREE;
1505 tree sym_max_op0 = NULL_TREE;
1506 tree sym_max_op1 = NULL_TREE;
1507 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1509 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1511 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1512 single-symbolic ranges, try to compute the precise resulting range,
1513 but only if we know that this resulting range will also be constant
1514 or single-symbolic. */
1515 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1516 && (TREE_CODE (min_op0) == INTEGER_CST
1517 || (sym_min_op0
1518 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1519 && (TREE_CODE (min_op1) == INTEGER_CST
1520 || (sym_min_op1
1521 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1522 && (!(sym_min_op0 && sym_min_op1)
1523 || (sym_min_op0 == sym_min_op1
1524 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1525 && (TREE_CODE (max_op0) == INTEGER_CST
1526 || (sym_max_op0
1527 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1528 && (TREE_CODE (max_op1) == INTEGER_CST
1529 || (sym_max_op1
1530 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1531 && (!(sym_max_op0 && sym_max_op1)
1532 || (sym_max_op0 == sym_max_op1
1533 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1535 wide_int wmin, wmax;
1536 wi::overflow_type min_ovf = wi::OVF_NONE;
1537 wi::overflow_type max_ovf = wi::OVF_NONE;
1539 /* Build the bounds. */
1540 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1541 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1543 /* If we have overflow for the constant part and the resulting
1544 range will be symbolic, drop to VR_VARYING. */
1545 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1546 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1548 set_value_range_to_varying (vr);
1549 return;
1552 /* Adjust the range for possible overflow. */
1553 set_value_range_with_overflow (*vr, expr_type,
1554 wmin, wmax, min_ovf, max_ovf);
1555 if (vr->type == VR_VARYING)
1556 return;
1558 /* Build the symbolic bounds if needed. */
1559 adjust_symbolic_bound (vr->min, code, expr_type,
1560 sym_min_op0, sym_min_op1,
1561 neg_min_op0, neg_min_op1);
1562 adjust_symbolic_bound (vr->max, code, expr_type,
1563 sym_max_op0, sym_max_op1,
1564 neg_max_op0, neg_max_op1);
1565 /* ?? It would probably be cleaner to eliminate min/max/type
1566 entirely and hold these values in VR directly. */
1567 min = vr->min;
1568 max = vr->max;
1569 type = vr->type;
1571 else
1573 /* For other cases, for example if we have a PLUS_EXPR with two
1574 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1575 to compute a precise range for such a case.
1576 ??? General even mixed range kind operations can be expressed
1577 by for example transforming ~[3, 5] + [1, 2] to range-only
1578 operations and a union primitive:
1579 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1580 [-INF+1, 4] U [6, +INF(OVF)]
1581 though usually the union is not exactly representable with
1582 a single range or anti-range as the above is
1583 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1584 but one could use a scheme similar to equivalences for this. */
1585 set_value_range_to_varying (vr);
1586 return;
1589 else if (code == MIN_EXPR
1590 || code == MAX_EXPR)
1592 if (vr0.type == VR_RANGE
1593 && !symbolic_range_p (&vr0))
1595 type = VR_RANGE;
1596 if (vr1.type == VR_RANGE
1597 && !symbolic_range_p (&vr1))
1599 /* For operations that make the resulting range directly
1600 proportional to the original ranges, apply the operation to
1601 the same end of each range. */
1602 min = int_const_binop (code, vr0.min, vr1.min);
1603 max = int_const_binop (code, vr0.max, vr1.max);
1605 else if (code == MIN_EXPR)
1607 min = vrp_val_min (expr_type);
1608 max = vr0.max;
1610 else if (code == MAX_EXPR)
1612 min = vr0.min;
1613 max = vrp_val_max (expr_type);
1616 else if (vr1.type == VR_RANGE
1617 && !symbolic_range_p (&vr1))
1619 type = VR_RANGE;
1620 if (code == MIN_EXPR)
1622 min = vrp_val_min (expr_type);
1623 max = vr1.max;
1625 else if (code == MAX_EXPR)
1627 min = vr1.min;
1628 max = vrp_val_max (expr_type);
1631 else
1633 set_value_range_to_varying (vr);
1634 return;
1637 else if (code == MULT_EXPR)
1639 if (!range_int_cst_p (&vr0)
1640 || !range_int_cst_p (&vr1))
1642 set_value_range_to_varying (vr);
1643 return;
1645 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1646 return;
1648 else if (code == RSHIFT_EXPR
1649 || code == LSHIFT_EXPR)
1651 if (range_int_cst_p (&vr1)
1652 && !vrp_shift_undefined_p (vr1, prec))
1654 if (code == RSHIFT_EXPR)
1656 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1657 useful ranges just from the shift count. E.g.
1658 x >> 63 for signed 64-bit x is always [-1, 0]. */
1659 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1661 vr0.type = type = VR_RANGE;
1662 vr0.min = vrp_val_min (expr_type);
1663 vr0.max = vrp_val_max (expr_type);
1665 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1666 return;
1668 else if (code == LSHIFT_EXPR
1669 && range_int_cst_p (&vr0))
1671 wide_int res_lb, res_ub;
1672 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1673 wi::to_wide (vr0.min),
1674 wi::to_wide (vr0.max),
1675 wi::to_wide (vr1.min),
1676 wi::to_wide (vr1.max),
1677 TYPE_OVERFLOW_UNDEFINED (expr_type),
1678 TYPE_OVERFLOW_WRAPS (expr_type)))
1680 min = wide_int_to_tree (expr_type, res_lb);
1681 max = wide_int_to_tree (expr_type, res_ub);
1682 set_and_canonicalize_value_range (vr, VR_RANGE,
1683 min, max, NULL);
1684 return;
1688 set_value_range_to_varying (vr);
1689 return;
1691 else if (code == TRUNC_DIV_EXPR
1692 || code == FLOOR_DIV_EXPR
1693 || code == CEIL_DIV_EXPR
1694 || code == EXACT_DIV_EXPR
1695 || code == ROUND_DIV_EXPR)
1697 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1699 /* For division, if op1 has VR_RANGE but op0 does not, something
1700 can be deduced just from that range. Say [min, max] / [4, max]
1701 gives [min / 4, max / 4] range. */
1702 if (vr1.type == VR_RANGE
1703 && !symbolic_range_p (&vr1)
1704 && range_includes_zero_p (vr1.min, vr1.max) == 0)
1706 vr0.type = type = VR_RANGE;
1707 vr0.min = vrp_val_min (expr_type);
1708 vr0.max = vrp_val_max (expr_type);
1710 else
1712 set_value_range_to_varying (vr);
1713 return;
1717 /* For divisions, if flag_non_call_exceptions is true, we must
1718 not eliminate a division by zero. */
1719 if (cfun->can_throw_non_call_exceptions
1720 && (vr1.type != VR_RANGE
1721 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1723 set_value_range_to_varying (vr);
1724 return;
1727 /* For divisions, if op0 is VR_RANGE, we can deduce a range
1728 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
1729 include 0. */
1730 if (vr0.type == VR_RANGE
1731 && (vr1.type != VR_RANGE
1732 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1734 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
1735 int cmp;
1737 min = NULL_TREE;
1738 max = NULL_TREE;
1739 if (TYPE_UNSIGNED (expr_type)
1740 || value_range_nonnegative_p (&vr1))
1742 /* For unsigned division or when divisor is known
1743 to be non-negative, the range has to cover
1744 all numbers from 0 to max for positive max
1745 and all numbers from min to 0 for negative min. */
1746 cmp = compare_values (vr0.max, zero);
1747 if (cmp == -1)
1749 /* When vr0.max < 0, vr1.min != 0 and value
1750 ranges for dividend and divisor are available. */
1751 if (vr1.type == VR_RANGE
1752 && !symbolic_range_p (&vr0)
1753 && !symbolic_range_p (&vr1)
1754 && compare_values (vr1.min, zero) != 0)
1755 max = int_const_binop (code, vr0.max, vr1.min);
1756 else
1757 max = zero;
1759 else if (cmp == 0 || cmp == 1)
1760 max = vr0.max;
1761 else
1762 type = VR_VARYING;
1763 cmp = compare_values (vr0.min, zero);
1764 if (cmp == 1)
1766 /* For unsigned division when value ranges for dividend
1767 and divisor are available. */
1768 if (vr1.type == VR_RANGE
1769 && !symbolic_range_p (&vr0)
1770 && !symbolic_range_p (&vr1)
1771 && compare_values (vr1.max, zero) != 0)
1772 min = int_const_binop (code, vr0.min, vr1.max);
1773 else
1774 min = zero;
1776 else if (cmp == 0 || cmp == -1)
1777 min = vr0.min;
1778 else
1779 type = VR_VARYING;
1781 else
1783 /* Otherwise the range is -max .. max or min .. -min
1784 depending on which bound is bigger in absolute value,
1785 as the division can change the sign. */
1786 abs_extent_range (vr, vr0.min, vr0.max);
1787 return;
1789 if (type == VR_VARYING)
1791 set_value_range_to_varying (vr);
1792 return;
1795 else if (range_int_cst_p (&vr0) && range_int_cst_p (&vr1))
1797 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1798 return;
1801 else if (code == TRUNC_MOD_EXPR)
1803 if (range_is_null (&vr1))
1805 set_value_range_to_undefined (vr);
1806 return;
1808 wide_int wmin, wmax, tmp;
1809 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1810 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1811 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1812 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1813 vr0_min, vr0_max, vr1_min, vr1_max);
1814 min = wide_int_to_tree (expr_type, wmin);
1815 max = wide_int_to_tree (expr_type, wmax);
1816 set_value_range (vr, VR_RANGE, min, max, NULL);
1817 return;
1819 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1821 if (vrp_can_optimize_bit_op (vr, code, &vr0, &vr1))
1822 return;
1824 wide_int may_be_nonzero0, may_be_nonzero1;
1825 wide_int must_be_nonzero0, must_be_nonzero1;
1826 wide_int wmin, wmax;
1827 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1828 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1829 &may_be_nonzero0, &must_be_nonzero0);
1830 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1831 &may_be_nonzero1, &must_be_nonzero1);
1832 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1833 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1834 if (code == BIT_AND_EXPR)
1836 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1837 vr0_min, vr0_max,
1838 vr1_min, vr1_max,
1839 must_be_nonzero0,
1840 may_be_nonzero0,
1841 must_be_nonzero1,
1842 may_be_nonzero1))
1844 min = wide_int_to_tree (expr_type, wmin);
1845 max = wide_int_to_tree (expr_type, wmax);
1846 set_value_range (vr, VR_RANGE, min, max, NULL);
1848 else
1849 set_value_range_to_varying (vr);
1850 return;
1852 else if (code == BIT_IOR_EXPR)
1854 if (wide_int_range_bit_ior (wmin, wmax, sign,
1855 vr0_min, vr0_max,
1856 vr1_min, vr1_max,
1857 must_be_nonzero0,
1858 may_be_nonzero0,
1859 must_be_nonzero1,
1860 may_be_nonzero1))
1862 min = wide_int_to_tree (expr_type, wmin);
1863 max = wide_int_to_tree (expr_type, wmax);
1864 set_value_range (vr, VR_RANGE, min, max, NULL);
1866 else
1867 set_value_range_to_varying (vr);
1868 return;
1870 else if (code == BIT_XOR_EXPR)
1872 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1873 must_be_nonzero0,
1874 may_be_nonzero0,
1875 must_be_nonzero1,
1876 may_be_nonzero1))
1878 min = wide_int_to_tree (expr_type, wmin);
1879 max = wide_int_to_tree (expr_type, wmax);
1880 set_value_range (vr, VR_RANGE, min, max, NULL);
1882 else
1883 set_value_range_to_varying (vr);
1884 return;
1887 else
1888 gcc_unreachable ();
1890 /* If either MIN or MAX overflowed, then set the resulting range to
1891 VARYING. */
1892 if (min == NULL_TREE
1893 || TREE_OVERFLOW_P (min)
1894 || max == NULL_TREE
1895 || TREE_OVERFLOW_P (max))
1897 set_value_range_to_varying (vr);
1898 return;
1901 /* We punt for [-INF, +INF].
1902 We learn nothing when we have INF on both sides.
1903 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1904 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1906 set_value_range_to_varying (vr);
1907 return;
1910 cmp = compare_values (min, max);
1911 if (cmp == -2 || cmp == 1)
1913 /* If the new range has its limits swapped around (MIN > MAX),
1914 then the operation caused one of them to wrap around, mark
1915 the new range VARYING. */
1916 set_value_range_to_varying (vr);
1918 else
1919 set_value_range (vr, type, min, max, NULL);
1922 /* Calculates the absolute value of a range and puts the result in VR.
1923 VR0 is the input range. TYPE is the type of the resulting
1924 range. */
1926 static void
1927 extract_range_from_abs_expr (value_range &vr, tree type, value_range &vr0)
1929 /* Pass through vr0 in the easy cases. */
1930 if (TYPE_UNSIGNED (type)
1931 || value_range_nonnegative_p (&vr0))
1933 copy_value_range (&vr, &vr0);
1934 return;
1937 /* For the remaining varying or symbolic ranges we can't do anything
1938 useful. */
1939 if (vr0.type == VR_VARYING
1940 || symbolic_range_p (&vr0))
1942 set_value_range_to_varying (&vr);
1943 return;
1946 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
1947 useful range. */
1948 if (!TYPE_OVERFLOW_UNDEFINED (type)
1949 && ((vr0.type == VR_RANGE
1950 && vrp_val_is_min (vr0.min))
1951 || (vr0.type == VR_ANTI_RANGE
1952 && !vrp_val_is_min (vr0.min))))
1954 set_value_range_to_varying (&vr);
1955 return;
1958 /* ABS_EXPR may flip the range around, if the original range
1959 included negative values. */
1960 tree min, max;
1961 if (!vrp_val_is_min (vr0.min))
1962 min = fold_unary_to_constant (ABS_EXPR, type, vr0.min);
1963 else
1964 min = TYPE_MAX_VALUE (type);
1966 if (!vrp_val_is_min (vr0.max))
1967 max = fold_unary_to_constant (ABS_EXPR, type, vr0.max);
1968 else
1969 max = TYPE_MAX_VALUE (type);
1971 int cmp = compare_values (min, max);
1972 gcc_assert (vr0.type != VR_ANTI_RANGE);
1974 /* If the range contains zero then we know that the minimum value in the
1975 range will be zero. */
1976 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
1978 if (cmp == 1)
1979 max = min;
1980 min = build_int_cst (type, 0);
1982 else
1984 /* If the range was reversed, swap MIN and MAX. */
1985 if (cmp == 1)
1986 std::swap (min, max);
1989 cmp = compare_values (min, max);
1990 if (cmp == -2 || cmp == 1)
1992 /* If the new range has its limits swapped around (MIN > MAX),
1993 then the operation caused one of them to wrap around, mark
1994 the new range VARYING. */
1995 set_value_range_to_varying (&vr);
1997 else
1998 set_value_range (&vr, vr0.type, min, max, NULL);
2001 /* Extract range information from a unary operation CODE based on
2002 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2003 The resulting range is stored in *VR. */
2005 void
2006 extract_range_from_unary_expr (value_range *vr,
2007 enum tree_code code, tree type,
2008 value_range *vr0_, tree op0_type)
2010 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2012 /* VRP only operates on integral and pointer types. */
2013 if (!(INTEGRAL_TYPE_P (op0_type)
2014 || POINTER_TYPE_P (op0_type))
2015 || !(INTEGRAL_TYPE_P (type)
2016 || POINTER_TYPE_P (type)))
2018 set_value_range_to_varying (vr);
2019 return;
2022 /* If VR0 is UNDEFINED, so is the result. */
2023 if (vr0.type == VR_UNDEFINED)
2025 set_value_range_to_undefined (vr);
2026 return;
2029 /* Handle operations that we express in terms of others. */
2030 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2032 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2033 copy_value_range (vr, &vr0);
2034 return;
2036 else if (code == NEGATE_EXPR)
2038 /* -X is simply 0 - X, so re-use existing code that also handles
2039 anti-ranges fine. */
2040 value_range zero = VR_INITIALIZER;
2041 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2042 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2043 return;
2045 else if (code == BIT_NOT_EXPR)
2047 /* ~X is simply -1 - X, so re-use existing code that also handles
2048 anti-ranges fine. */
2049 value_range minusone = VR_INITIALIZER;
2050 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2051 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2052 type, &minusone, &vr0);
2053 return;
2056 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2057 and express op ~[] as (op []') U (op []''). */
2058 if (vr0.type == VR_ANTI_RANGE
2059 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2061 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2062 if (vrtem1.type != VR_UNDEFINED)
2064 value_range vrres = VR_INITIALIZER;
2065 extract_range_from_unary_expr (&vrres, code, type,
2066 &vrtem1, op0_type);
2067 vrp_meet (vr, &vrres);
2069 return;
2072 if (CONVERT_EXPR_CODE_P (code))
2074 tree inner_type = op0_type;
2075 tree outer_type = type;
2077 /* If the expression evaluates to a pointer, we are only interested in
2078 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
2079 if (POINTER_TYPE_P (type))
2081 if (range_is_nonnull (&vr0))
2082 set_value_range_to_nonnull (vr, type);
2083 else if (range_is_null (&vr0))
2084 set_value_range_to_null (vr, type);
2085 else
2086 set_value_range_to_varying (vr);
2087 return;
2090 /* If VR0 is varying and we increase the type precision, assume
2091 a full range for the following transformation. */
2092 if (vr0.type == VR_VARYING
2093 && INTEGRAL_TYPE_P (inner_type)
2094 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2096 vr0.type = VR_RANGE;
2097 vr0.min = TYPE_MIN_VALUE (inner_type);
2098 vr0.max = TYPE_MAX_VALUE (inner_type);
2101 /* If VR0 is a constant range or anti-range and the conversion is
2102 not truncating we can convert the min and max values and
2103 canonicalize the resulting range. Otherwise we can do the
2104 conversion if the size of the range is less than what the
2105 precision of the target type can represent and the range is
2106 not an anti-range. */
2107 if ((vr0.type == VR_RANGE
2108 || vr0.type == VR_ANTI_RANGE)
2109 && TREE_CODE (vr0.min) == INTEGER_CST
2110 && TREE_CODE (vr0.max) == INTEGER_CST
2111 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2112 || (vr0.type == VR_RANGE
2113 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2114 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2115 size_int (TYPE_PRECISION (outer_type)))))))
2117 tree new_min, new_max;
2118 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2119 0, false);
2120 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2121 0, false);
2122 set_and_canonicalize_value_range (vr, vr0.type,
2123 new_min, new_max, NULL);
2124 return;
2127 set_value_range_to_varying (vr);
2128 return;
2130 else if (code == ABS_EXPR)
2131 return extract_range_from_abs_expr (*vr, type, vr0);
2133 /* For unhandled operations fall back to varying. */
2134 set_value_range_to_varying (vr);
2135 return;
2138 /* Debugging dumps. */
2140 void dump_value_range (FILE *, const value_range *);
2141 void debug_value_range (value_range *);
2142 void dump_all_value_ranges (FILE *);
2143 void dump_vr_equiv (FILE *, bitmap);
2144 void debug_vr_equiv (bitmap);
2147 /* Dump value range VR to FILE. */
2149 void
2150 dump_value_range (FILE *file, const value_range *vr)
2152 if (vr == NULL)
2153 fprintf (file, "[]");
2154 else if (vr->type == VR_UNDEFINED)
2155 fprintf (file, "UNDEFINED");
2156 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2158 tree type = TREE_TYPE (vr->min);
2160 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2162 if (INTEGRAL_TYPE_P (type)
2163 && !TYPE_UNSIGNED (type)
2164 && vrp_val_is_min (vr->min))
2165 fprintf (file, "-INF");
2166 else
2167 print_generic_expr (file, vr->min);
2169 fprintf (file, ", ");
2171 if (INTEGRAL_TYPE_P (type)
2172 && vrp_val_is_max (vr->max))
2173 fprintf (file, "+INF");
2174 else
2175 print_generic_expr (file, vr->max);
2177 fprintf (file, "]");
2179 if (vr->equiv)
2181 bitmap_iterator bi;
2182 unsigned i, c = 0;
2184 fprintf (file, " EQUIVALENCES: { ");
2186 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2188 print_generic_expr (file, ssa_name (i));
2189 fprintf (file, " ");
2190 c++;
2193 fprintf (file, "} (%u elements)", c);
2196 else if (vr->type == VR_VARYING)
2197 fprintf (file, "VARYING");
2198 else
2199 fprintf (file, "INVALID RANGE");
2203 /* Dump value range VR to stderr. */
2205 DEBUG_FUNCTION void
2206 debug_value_range (value_range *vr)
2208 dump_value_range (stderr, vr);
2209 fprintf (stderr, "\n");
2212 void
2213 value_range::dump ()
2215 debug_value_range (this);
2219 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2220 create a new SSA name N and return the assertion assignment
2221 'N = ASSERT_EXPR <V, V OP W>'. */
2223 static gimple *
2224 build_assert_expr_for (tree cond, tree v)
2226 tree a;
2227 gassign *assertion;
2229 gcc_assert (TREE_CODE (v) == SSA_NAME
2230 && COMPARISON_CLASS_P (cond));
2232 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2233 assertion = gimple_build_assign (NULL_TREE, a);
2235 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2236 operand of the ASSERT_EXPR. Create it so the new name and the old one
2237 are registered in the replacement table so that we can fix the SSA web
2238 after adding all the ASSERT_EXPRs. */
2239 tree new_def = create_new_def_for (v, assertion, NULL);
2240 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2241 given we have to be able to fully propagate those out to re-create
2242 valid SSA when removing the asserts. */
2243 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2244 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2246 return assertion;
2250 /* Return false if EXPR is a predicate expression involving floating
2251 point values. */
2253 static inline bool
2254 fp_predicate (gimple *stmt)
2256 GIMPLE_CHECK (stmt, GIMPLE_COND);
2258 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2261 /* If the range of values taken by OP can be inferred after STMT executes,
2262 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2263 describes the inferred range. Return true if a range could be
2264 inferred. */
2266 bool
2267 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2269 *val_p = NULL_TREE;
2270 *comp_code_p = ERROR_MARK;
2272 /* Do not attempt to infer anything in names that flow through
2273 abnormal edges. */
2274 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2275 return false;
2277 /* If STMT is the last statement of a basic block with no normal
2278 successors, there is no point inferring anything about any of its
2279 operands. We would not be able to find a proper insertion point
2280 for the assertion, anyway. */
2281 if (stmt_ends_bb_p (stmt))
2283 edge_iterator ei;
2284 edge e;
2286 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2287 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2288 break;
2289 if (e == NULL)
2290 return false;
2293 if (infer_nonnull_range (stmt, op))
2295 *val_p = build_int_cst (TREE_TYPE (op), 0);
2296 *comp_code_p = NE_EXPR;
2297 return true;
2300 return false;
2304 void dump_asserts_for (FILE *, tree);
2305 void debug_asserts_for (tree);
2306 void dump_all_asserts (FILE *);
2307 void debug_all_asserts (void);
2309 /* Dump all the registered assertions for NAME to FILE. */
2311 void
2312 dump_asserts_for (FILE *file, tree name)
2314 assert_locus *loc;
2316 fprintf (file, "Assertions to be inserted for ");
2317 print_generic_expr (file, name);
2318 fprintf (file, "\n");
2320 loc = asserts_for[SSA_NAME_VERSION (name)];
2321 while (loc)
2323 fprintf (file, "\t");
2324 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2325 fprintf (file, "\n\tBB #%d", loc->bb->index);
2326 if (loc->e)
2328 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2329 loc->e->dest->index);
2330 dump_edge_info (file, loc->e, dump_flags, 0);
2332 fprintf (file, "\n\tPREDICATE: ");
2333 print_generic_expr (file, loc->expr);
2334 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2335 print_generic_expr (file, loc->val);
2336 fprintf (file, "\n\n");
2337 loc = loc->next;
2340 fprintf (file, "\n");
2344 /* Dump all the registered assertions for NAME to stderr. */
2346 DEBUG_FUNCTION void
2347 debug_asserts_for (tree name)
2349 dump_asserts_for (stderr, name);
2353 /* Dump all the registered assertions for all the names to FILE. */
2355 void
2356 dump_all_asserts (FILE *file)
2358 unsigned i;
2359 bitmap_iterator bi;
2361 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2362 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2363 dump_asserts_for (file, ssa_name (i));
2364 fprintf (file, "\n");
2368 /* Dump all the registered assertions for all the names to stderr. */
2370 DEBUG_FUNCTION void
2371 debug_all_asserts (void)
2373 dump_all_asserts (stderr);
2376 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2378 static void
2379 add_assert_info (vec<assert_info> &asserts,
2380 tree name, tree expr, enum tree_code comp_code, tree val)
2382 assert_info info;
2383 info.comp_code = comp_code;
2384 info.name = name;
2385 if (TREE_OVERFLOW_P (val))
2386 val = drop_tree_overflow (val);
2387 info.val = val;
2388 info.expr = expr;
2389 asserts.safe_push (info);
2392 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2393 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2394 E->DEST, then register this location as a possible insertion point
2395 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2397 BB, E and SI provide the exact insertion point for the new
2398 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2399 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2400 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2401 must not be NULL. */
2403 static void
2404 register_new_assert_for (tree name, tree expr,
2405 enum tree_code comp_code,
2406 tree val,
2407 basic_block bb,
2408 edge e,
2409 gimple_stmt_iterator si)
2411 assert_locus *n, *loc, *last_loc;
2412 basic_block dest_bb;
2414 gcc_checking_assert (bb == NULL || e == NULL);
2416 if (e == NULL)
2417 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2418 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2420 /* Never build an assert comparing against an integer constant with
2421 TREE_OVERFLOW set. This confuses our undefined overflow warning
2422 machinery. */
2423 if (TREE_OVERFLOW_P (val))
2424 val = drop_tree_overflow (val);
2426 /* The new assertion A will be inserted at BB or E. We need to
2427 determine if the new location is dominated by a previously
2428 registered location for A. If we are doing an edge insertion,
2429 assume that A will be inserted at E->DEST. Note that this is not
2430 necessarily true.
2432 If E is a critical edge, it will be split. But even if E is
2433 split, the new block will dominate the same set of blocks that
2434 E->DEST dominates.
2436 The reverse, however, is not true, blocks dominated by E->DEST
2437 will not be dominated by the new block created to split E. So,
2438 if the insertion location is on a critical edge, we will not use
2439 the new location to move another assertion previously registered
2440 at a block dominated by E->DEST. */
2441 dest_bb = (bb) ? bb : e->dest;
2443 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2444 VAL at a block dominating DEST_BB, then we don't need to insert a new
2445 one. Similarly, if the same assertion already exists at a block
2446 dominated by DEST_BB and the new location is not on a critical
2447 edge, then update the existing location for the assertion (i.e.,
2448 move the assertion up in the dominance tree).
2450 Note, this is implemented as a simple linked list because there
2451 should not be more than a handful of assertions registered per
2452 name. If this becomes a performance problem, a table hashed by
2453 COMP_CODE and VAL could be implemented. */
2454 loc = asserts_for[SSA_NAME_VERSION (name)];
2455 last_loc = loc;
2456 while (loc)
2458 if (loc->comp_code == comp_code
2459 && (loc->val == val
2460 || operand_equal_p (loc->val, val, 0))
2461 && (loc->expr == expr
2462 || operand_equal_p (loc->expr, expr, 0)))
2464 /* If E is not a critical edge and DEST_BB
2465 dominates the existing location for the assertion, move
2466 the assertion up in the dominance tree by updating its
2467 location information. */
2468 if ((e == NULL || !EDGE_CRITICAL_P (e))
2469 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2471 loc->bb = dest_bb;
2472 loc->e = e;
2473 loc->si = si;
2474 return;
2478 /* Update the last node of the list and move to the next one. */
2479 last_loc = loc;
2480 loc = loc->next;
2483 /* If we didn't find an assertion already registered for
2484 NAME COMP_CODE VAL, add a new one at the end of the list of
2485 assertions associated with NAME. */
2486 n = XNEW (struct assert_locus);
2487 n->bb = dest_bb;
2488 n->e = e;
2489 n->si = si;
2490 n->comp_code = comp_code;
2491 n->val = val;
2492 n->expr = expr;
2493 n->next = NULL;
2495 if (last_loc)
2496 last_loc->next = n;
2497 else
2498 asserts_for[SSA_NAME_VERSION (name)] = n;
2500 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2503 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2504 Extract a suitable test code and value and store them into *CODE_P and
2505 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2507 If no extraction was possible, return FALSE, otherwise return TRUE.
2509 If INVERT is true, then we invert the result stored into *CODE_P. */
2511 static bool
2512 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2513 tree cond_op0, tree cond_op1,
2514 bool invert, enum tree_code *code_p,
2515 tree *val_p)
2517 enum tree_code comp_code;
2518 tree val;
2520 /* Otherwise, we have a comparison of the form NAME COMP VAL
2521 or VAL COMP NAME. */
2522 if (name == cond_op1)
2524 /* If the predicate is of the form VAL COMP NAME, flip
2525 COMP around because we need to register NAME as the
2526 first operand in the predicate. */
2527 comp_code = swap_tree_comparison (cond_code);
2528 val = cond_op0;
2530 else if (name == cond_op0)
2532 /* The comparison is of the form NAME COMP VAL, so the
2533 comparison code remains unchanged. */
2534 comp_code = cond_code;
2535 val = cond_op1;
2537 else
2538 gcc_unreachable ();
2540 /* Invert the comparison code as necessary. */
2541 if (invert)
2542 comp_code = invert_tree_comparison (comp_code, 0);
2544 /* VRP only handles integral and pointer types. */
2545 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2546 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2547 return false;
2549 /* Do not register always-false predicates.
2550 FIXME: this works around a limitation in fold() when dealing with
2551 enumerations. Given 'enum { N1, N2 } x;', fold will not
2552 fold 'if (x > N2)' to 'if (0)'. */
2553 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2554 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2556 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2557 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2559 if (comp_code == GT_EXPR
2560 && (!max
2561 || compare_values (val, max) == 0))
2562 return false;
2564 if (comp_code == LT_EXPR
2565 && (!min
2566 || compare_values (val, min) == 0))
2567 return false;
2569 *code_p = comp_code;
2570 *val_p = val;
2571 return true;
2574 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2575 (otherwise return VAL). VAL and MASK must be zero-extended for
2576 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2577 (to transform signed values into unsigned) and at the end xor
2578 SGNBIT back. */
2580 static wide_int
2581 masked_increment (const wide_int &val_in, const wide_int &mask,
2582 const wide_int &sgnbit, unsigned int prec)
2584 wide_int bit = wi::one (prec), res;
2585 unsigned int i;
2587 wide_int val = val_in ^ sgnbit;
2588 for (i = 0; i < prec; i++, bit += bit)
2590 res = mask;
2591 if ((res & bit) == 0)
2592 continue;
2593 res = bit - 1;
2594 res = wi::bit_and_not (val + bit, res);
2595 res &= mask;
2596 if (wi::gtu_p (res, val))
2597 return res ^ sgnbit;
2599 return val ^ sgnbit;
2602 /* Helper for overflow_comparison_p
2604 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2605 OP1's defining statement to see if it ultimately has the form
2606 OP0 CODE (OP0 PLUS INTEGER_CST)
2608 If so, return TRUE indicating this is an overflow test and store into
2609 *NEW_CST an updated constant that can be used in a narrowed range test.
2611 REVERSED indicates if the comparison was originally:
2613 OP1 CODE' OP0.
2615 This affects how we build the updated constant. */
2617 static bool
2618 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2619 bool follow_assert_exprs, bool reversed, tree *new_cst)
2621 /* See if this is a relational operation between two SSA_NAMES with
2622 unsigned, overflow wrapping values. If so, check it more deeply. */
2623 if ((code == LT_EXPR || code == LE_EXPR
2624 || code == GE_EXPR || code == GT_EXPR)
2625 && TREE_CODE (op0) == SSA_NAME
2626 && TREE_CODE (op1) == SSA_NAME
2627 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2628 && TYPE_UNSIGNED (TREE_TYPE (op0))
2629 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2631 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2633 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2634 if (follow_assert_exprs)
2636 while (gimple_assign_single_p (op1_def)
2637 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2639 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2640 if (TREE_CODE (op1) != SSA_NAME)
2641 break;
2642 op1_def = SSA_NAME_DEF_STMT (op1);
2646 /* Now look at the defining statement of OP1 to see if it adds
2647 or subtracts a nonzero constant from another operand. */
2648 if (op1_def
2649 && is_gimple_assign (op1_def)
2650 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2651 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2652 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2654 tree target = gimple_assign_rhs1 (op1_def);
2656 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2657 for one where TARGET appears on the RHS. */
2658 if (follow_assert_exprs)
2660 /* Now see if that "other operand" is op0, following the chain
2661 of ASSERT_EXPRs if necessary. */
2662 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2663 while (op0 != target
2664 && gimple_assign_single_p (op0_def)
2665 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2667 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2668 if (TREE_CODE (op0) != SSA_NAME)
2669 break;
2670 op0_def = SSA_NAME_DEF_STMT (op0);
2674 /* If we did not find our target SSA_NAME, then this is not
2675 an overflow test. */
2676 if (op0 != target)
2677 return false;
2679 tree type = TREE_TYPE (op0);
2680 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2681 tree inc = gimple_assign_rhs2 (op1_def);
2682 if (reversed)
2683 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2684 else
2685 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2686 return true;
2689 return false;
2692 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2693 OP1's defining statement to see if it ultimately has the form
2694 OP0 CODE (OP0 PLUS INTEGER_CST)
2696 If so, return TRUE indicating this is an overflow test and store into
2697 *NEW_CST an updated constant that can be used in a narrowed range test.
2699 These statements are left as-is in the IL to facilitate discovery of
2700 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2701 the alternate range representation is often useful within VRP. */
2703 bool
2704 overflow_comparison_p (tree_code code, tree name, tree val,
2705 bool use_equiv_p, tree *new_cst)
2707 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2708 return true;
2709 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2710 use_equiv_p, true, new_cst);
2714 /* Try to register an edge assertion for SSA name NAME on edge E for
2715 the condition COND contributing to the conditional jump pointed to by BSI.
2716 Invert the condition COND if INVERT is true. */
2718 static void
2719 register_edge_assert_for_2 (tree name, edge e,
2720 enum tree_code cond_code,
2721 tree cond_op0, tree cond_op1, bool invert,
2722 vec<assert_info> &asserts)
2724 tree val;
2725 enum tree_code comp_code;
2727 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2728 cond_op0,
2729 cond_op1,
2730 invert, &comp_code, &val))
2731 return;
2733 /* Queue the assert. */
2734 tree x;
2735 if (overflow_comparison_p (comp_code, name, val, false, &x))
2737 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2738 ? GT_EXPR : LE_EXPR);
2739 add_assert_info (asserts, name, name, new_code, x);
2741 add_assert_info (asserts, name, name, comp_code, val);
2743 /* In the case of NAME <= CST and NAME being defined as
2744 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2745 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2746 This catches range and anti-range tests. */
2747 if ((comp_code == LE_EXPR
2748 || comp_code == GT_EXPR)
2749 && TREE_CODE (val) == INTEGER_CST
2750 && TYPE_UNSIGNED (TREE_TYPE (val)))
2752 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2753 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2755 /* Extract CST2 from the (optional) addition. */
2756 if (is_gimple_assign (def_stmt)
2757 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2759 name2 = gimple_assign_rhs1 (def_stmt);
2760 cst2 = gimple_assign_rhs2 (def_stmt);
2761 if (TREE_CODE (name2) == SSA_NAME
2762 && TREE_CODE (cst2) == INTEGER_CST)
2763 def_stmt = SSA_NAME_DEF_STMT (name2);
2766 /* Extract NAME2 from the (optional) sign-changing cast. */
2767 if (gimple_assign_cast_p (def_stmt))
2769 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2770 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2771 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2772 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2773 name3 = gimple_assign_rhs1 (def_stmt);
2776 /* If name3 is used later, create an ASSERT_EXPR for it. */
2777 if (name3 != NULL_TREE
2778 && TREE_CODE (name3) == SSA_NAME
2779 && (cst2 == NULL_TREE
2780 || TREE_CODE (cst2) == INTEGER_CST)
2781 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2783 tree tmp;
2785 /* Build an expression for the range test. */
2786 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2787 if (cst2 != NULL_TREE)
2788 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2790 if (dump_file)
2792 fprintf (dump_file, "Adding assert for ");
2793 print_generic_expr (dump_file, name3);
2794 fprintf (dump_file, " from ");
2795 print_generic_expr (dump_file, tmp);
2796 fprintf (dump_file, "\n");
2799 add_assert_info (asserts, name3, tmp, comp_code, val);
2802 /* If name2 is used later, create an ASSERT_EXPR for it. */
2803 if (name2 != NULL_TREE
2804 && TREE_CODE (name2) == SSA_NAME
2805 && TREE_CODE (cst2) == INTEGER_CST
2806 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2808 tree tmp;
2810 /* Build an expression for the range test. */
2811 tmp = name2;
2812 if (TREE_TYPE (name) != TREE_TYPE (name2))
2813 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2814 if (cst2 != NULL_TREE)
2815 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2817 if (dump_file)
2819 fprintf (dump_file, "Adding assert for ");
2820 print_generic_expr (dump_file, name2);
2821 fprintf (dump_file, " from ");
2822 print_generic_expr (dump_file, tmp);
2823 fprintf (dump_file, "\n");
2826 add_assert_info (asserts, name2, tmp, comp_code, val);
2830 /* In the case of post-in/decrement tests like if (i++) ... and uses
2831 of the in/decremented value on the edge the extra name we want to
2832 assert for is not on the def chain of the name compared. Instead
2833 it is in the set of use stmts.
2834 Similar cases happen for conversions that were simplified through
2835 fold_{sign_changed,widened}_comparison. */
2836 if ((comp_code == NE_EXPR
2837 || comp_code == EQ_EXPR)
2838 && TREE_CODE (val) == INTEGER_CST)
2840 imm_use_iterator ui;
2841 gimple *use_stmt;
2842 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2844 if (!is_gimple_assign (use_stmt))
2845 continue;
2847 /* Cut off to use-stmts that are dominating the predecessor. */
2848 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2849 continue;
2851 tree name2 = gimple_assign_lhs (use_stmt);
2852 if (TREE_CODE (name2) != SSA_NAME)
2853 continue;
2855 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2856 tree cst;
2857 if (code == PLUS_EXPR
2858 || code == MINUS_EXPR)
2860 cst = gimple_assign_rhs2 (use_stmt);
2861 if (TREE_CODE (cst) != INTEGER_CST)
2862 continue;
2863 cst = int_const_binop (code, val, cst);
2865 else if (CONVERT_EXPR_CODE_P (code))
2867 /* For truncating conversions we cannot record
2868 an inequality. */
2869 if (comp_code == NE_EXPR
2870 && (TYPE_PRECISION (TREE_TYPE (name2))
2871 < TYPE_PRECISION (TREE_TYPE (name))))
2872 continue;
2873 cst = fold_convert (TREE_TYPE (name2), val);
2875 else
2876 continue;
2878 if (TREE_OVERFLOW_P (cst))
2879 cst = drop_tree_overflow (cst);
2880 add_assert_info (asserts, name2, name2, comp_code, cst);
2884 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2885 && TREE_CODE (val) == INTEGER_CST)
2887 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2888 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2889 tree val2 = NULL_TREE;
2890 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2891 wide_int mask = wi::zero (prec);
2892 unsigned int nprec = prec;
2893 enum tree_code rhs_code = ERROR_MARK;
2895 if (is_gimple_assign (def_stmt))
2896 rhs_code = gimple_assign_rhs_code (def_stmt);
2898 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2899 assert that A != CST1 -+ CST2. */
2900 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2901 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2903 tree op0 = gimple_assign_rhs1 (def_stmt);
2904 tree op1 = gimple_assign_rhs2 (def_stmt);
2905 if (TREE_CODE (op0) == SSA_NAME
2906 && TREE_CODE (op1) == INTEGER_CST)
2908 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2909 ? MINUS_EXPR : PLUS_EXPR);
2910 op1 = int_const_binop (reverse_op, val, op1);
2911 if (TREE_OVERFLOW (op1))
2912 op1 = drop_tree_overflow (op1);
2913 add_assert_info (asserts, op0, op0, comp_code, op1);
2917 /* Add asserts for NAME cmp CST and NAME being defined
2918 as NAME = (int) NAME2. */
2919 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2920 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2921 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2922 && gimple_assign_cast_p (def_stmt))
2924 name2 = gimple_assign_rhs1 (def_stmt);
2925 if (CONVERT_EXPR_CODE_P (rhs_code)
2926 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2927 && TYPE_UNSIGNED (TREE_TYPE (name2))
2928 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2929 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2930 || !tree_int_cst_equal (val,
2931 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2933 tree tmp, cst;
2934 enum tree_code new_comp_code = comp_code;
2936 cst = fold_convert (TREE_TYPE (name2),
2937 TYPE_MIN_VALUE (TREE_TYPE (val)));
2938 /* Build an expression for the range test. */
2939 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2940 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2941 fold_convert (TREE_TYPE (name2), val));
2942 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2944 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2945 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2946 build_int_cst (TREE_TYPE (name2), 1));
2949 if (dump_file)
2951 fprintf (dump_file, "Adding assert for ");
2952 print_generic_expr (dump_file, name2);
2953 fprintf (dump_file, " from ");
2954 print_generic_expr (dump_file, tmp);
2955 fprintf (dump_file, "\n");
2958 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2962 /* Add asserts for NAME cmp CST and NAME being defined as
2963 NAME = NAME2 >> CST2.
2965 Extract CST2 from the right shift. */
2966 if (rhs_code == RSHIFT_EXPR)
2968 name2 = gimple_assign_rhs1 (def_stmt);
2969 cst2 = gimple_assign_rhs2 (def_stmt);
2970 if (TREE_CODE (name2) == SSA_NAME
2971 && tree_fits_uhwi_p (cst2)
2972 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2973 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2974 && type_has_mode_precision_p (TREE_TYPE (val)))
2976 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2977 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2980 if (val2 != NULL_TREE
2981 && TREE_CODE (val2) == INTEGER_CST
2982 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2983 TREE_TYPE (val),
2984 val2, cst2), val))
2986 enum tree_code new_comp_code = comp_code;
2987 tree tmp, new_val;
2989 tmp = name2;
2990 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2992 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2994 tree type = build_nonstandard_integer_type (prec, 1);
2995 tmp = build1 (NOP_EXPR, type, name2);
2996 val2 = fold_convert (type, val2);
2998 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2999 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
3000 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
3002 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3004 wide_int minval
3005 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3006 new_val = val2;
3007 if (minval == wi::to_wide (new_val))
3008 new_val = NULL_TREE;
3010 else
3012 wide_int maxval
3013 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3014 mask |= wi::to_wide (val2);
3015 if (wi::eq_p (mask, maxval))
3016 new_val = NULL_TREE;
3017 else
3018 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3021 if (new_val)
3023 if (dump_file)
3025 fprintf (dump_file, "Adding assert for ");
3026 print_generic_expr (dump_file, name2);
3027 fprintf (dump_file, " from ");
3028 print_generic_expr (dump_file, tmp);
3029 fprintf (dump_file, "\n");
3032 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3036 /* Add asserts for NAME cmp CST and NAME being defined as
3037 NAME = NAME2 & CST2.
3039 Extract CST2 from the and.
3041 Also handle
3042 NAME = (unsigned) NAME2;
3043 casts where NAME's type is unsigned and has smaller precision
3044 than NAME2's type as if it was NAME = NAME2 & MASK. */
3045 names[0] = NULL_TREE;
3046 names[1] = NULL_TREE;
3047 cst2 = NULL_TREE;
3048 if (rhs_code == BIT_AND_EXPR
3049 || (CONVERT_EXPR_CODE_P (rhs_code)
3050 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3051 && TYPE_UNSIGNED (TREE_TYPE (val))
3052 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3053 > prec))
3055 name2 = gimple_assign_rhs1 (def_stmt);
3056 if (rhs_code == BIT_AND_EXPR)
3057 cst2 = gimple_assign_rhs2 (def_stmt);
3058 else
3060 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3061 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3063 if (TREE_CODE (name2) == SSA_NAME
3064 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3065 && TREE_CODE (cst2) == INTEGER_CST
3066 && !integer_zerop (cst2)
3067 && (nprec > 1
3068 || TYPE_UNSIGNED (TREE_TYPE (val))))
3070 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3071 if (gimple_assign_cast_p (def_stmt2))
3073 names[1] = gimple_assign_rhs1 (def_stmt2);
3074 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3075 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3076 || (TYPE_PRECISION (TREE_TYPE (name2))
3077 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3078 names[1] = NULL_TREE;
3080 names[0] = name2;
3083 if (names[0] || names[1])
3085 wide_int minv, maxv, valv, cst2v;
3086 wide_int tem, sgnbit;
3087 bool valid_p = false, valn, cst2n;
3088 enum tree_code ccode = comp_code;
3090 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3091 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3092 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3093 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3094 /* If CST2 doesn't have most significant bit set,
3095 but VAL is negative, we have comparison like
3096 if ((x & 0x123) > -4) (always true). Just give up. */
3097 if (!cst2n && valn)
3098 ccode = ERROR_MARK;
3099 if (cst2n)
3100 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3101 else
3102 sgnbit = wi::zero (nprec);
3103 minv = valv & cst2v;
3104 switch (ccode)
3106 case EQ_EXPR:
3107 /* Minimum unsigned value for equality is VAL & CST2
3108 (should be equal to VAL, otherwise we probably should
3109 have folded the comparison into false) and
3110 maximum unsigned value is VAL | ~CST2. */
3111 maxv = valv | ~cst2v;
3112 valid_p = true;
3113 break;
3115 case NE_EXPR:
3116 tem = valv | ~cst2v;
3117 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3118 if (valv == 0)
3120 cst2n = false;
3121 sgnbit = wi::zero (nprec);
3122 goto gt_expr;
3124 /* If (VAL | ~CST2) is all ones, handle it as
3125 (X & CST2) < VAL. */
3126 if (tem == -1)
3128 cst2n = false;
3129 valn = false;
3130 sgnbit = wi::zero (nprec);
3131 goto lt_expr;
3133 if (!cst2n && wi::neg_p (cst2v))
3134 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3135 if (sgnbit != 0)
3137 if (valv == sgnbit)
3139 cst2n = true;
3140 valn = true;
3141 goto gt_expr;
3143 if (tem == wi::mask (nprec - 1, false, nprec))
3145 cst2n = true;
3146 goto lt_expr;
3148 if (!cst2n)
3149 sgnbit = wi::zero (nprec);
3151 break;
3153 case GE_EXPR:
3154 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3155 is VAL and maximum unsigned value is ~0. For signed
3156 comparison, if CST2 doesn't have most significant bit
3157 set, handle it similarly. If CST2 has MSB set,
3158 the minimum is the same, and maximum is ~0U/2. */
3159 if (minv != valv)
3161 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3162 VAL. */
3163 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3164 if (minv == valv)
3165 break;
3167 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3168 valid_p = true;
3169 break;
3171 case GT_EXPR:
3172 gt_expr:
3173 /* Find out smallest MINV where MINV > VAL
3174 && (MINV & CST2) == MINV, if any. If VAL is signed and
3175 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3176 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3177 if (minv == valv)
3178 break;
3179 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3180 valid_p = true;
3181 break;
3183 case LE_EXPR:
3184 /* Minimum unsigned value for <= is 0 and maximum
3185 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3186 Otherwise, find smallest VAL2 where VAL2 > VAL
3187 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3188 as maximum.
3189 For signed comparison, if CST2 doesn't have most
3190 significant bit set, handle it similarly. If CST2 has
3191 MSB set, the maximum is the same and minimum is INT_MIN. */
3192 if (minv == valv)
3193 maxv = valv;
3194 else
3196 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3197 if (maxv == valv)
3198 break;
3199 maxv -= 1;
3201 maxv |= ~cst2v;
3202 minv = sgnbit;
3203 valid_p = true;
3204 break;
3206 case LT_EXPR:
3207 lt_expr:
3208 /* Minimum unsigned value for < is 0 and maximum
3209 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3210 Otherwise, find smallest VAL2 where VAL2 > VAL
3211 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3212 as maximum.
3213 For signed comparison, if CST2 doesn't have most
3214 significant bit set, handle it similarly. If CST2 has
3215 MSB set, the maximum is the same and minimum is INT_MIN. */
3216 if (minv == valv)
3218 if (valv == sgnbit)
3219 break;
3220 maxv = valv;
3222 else
3224 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3225 if (maxv == valv)
3226 break;
3228 maxv -= 1;
3229 maxv |= ~cst2v;
3230 minv = sgnbit;
3231 valid_p = true;
3232 break;
3234 default:
3235 break;
3237 if (valid_p
3238 && (maxv - minv) != -1)
3240 tree tmp, new_val, type;
3241 int i;
3243 for (i = 0; i < 2; i++)
3244 if (names[i])
3246 wide_int maxv2 = maxv;
3247 tmp = names[i];
3248 type = TREE_TYPE (names[i]);
3249 if (!TYPE_UNSIGNED (type))
3251 type = build_nonstandard_integer_type (nprec, 1);
3252 tmp = build1 (NOP_EXPR, type, names[i]);
3254 if (minv != 0)
3256 tmp = build2 (PLUS_EXPR, type, tmp,
3257 wide_int_to_tree (type, -minv));
3258 maxv2 = maxv - minv;
3260 new_val = wide_int_to_tree (type, maxv2);
3262 if (dump_file)
3264 fprintf (dump_file, "Adding assert for ");
3265 print_generic_expr (dump_file, names[i]);
3266 fprintf (dump_file, " from ");
3267 print_generic_expr (dump_file, tmp);
3268 fprintf (dump_file, "\n");
3271 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3278 /* OP is an operand of a truth value expression which is known to have
3279 a particular value. Register any asserts for OP and for any
3280 operands in OP's defining statement.
3282 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3283 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3285 static void
3286 register_edge_assert_for_1 (tree op, enum tree_code code,
3287 edge e, vec<assert_info> &asserts)
3289 gimple *op_def;
3290 tree val;
3291 enum tree_code rhs_code;
3293 /* We only care about SSA_NAMEs. */
3294 if (TREE_CODE (op) != SSA_NAME)
3295 return;
3297 /* We know that OP will have a zero or nonzero value. */
3298 val = build_int_cst (TREE_TYPE (op), 0);
3299 add_assert_info (asserts, op, op, code, val);
3301 /* Now look at how OP is set. If it's set from a comparison,
3302 a truth operation or some bit operations, then we may be able
3303 to register information about the operands of that assignment. */
3304 op_def = SSA_NAME_DEF_STMT (op);
3305 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3306 return;
3308 rhs_code = gimple_assign_rhs_code (op_def);
3310 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3312 bool invert = (code == EQ_EXPR ? true : false);
3313 tree op0 = gimple_assign_rhs1 (op_def);
3314 tree op1 = gimple_assign_rhs2 (op_def);
3316 if (TREE_CODE (op0) == SSA_NAME)
3317 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3318 if (TREE_CODE (op1) == SSA_NAME)
3319 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3321 else if ((code == NE_EXPR
3322 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3323 || (code == EQ_EXPR
3324 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3326 /* Recurse on each operand. */
3327 tree op0 = gimple_assign_rhs1 (op_def);
3328 tree op1 = gimple_assign_rhs2 (op_def);
3329 if (TREE_CODE (op0) == SSA_NAME
3330 && has_single_use (op0))
3331 register_edge_assert_for_1 (op0, code, e, asserts);
3332 if (TREE_CODE (op1) == SSA_NAME
3333 && has_single_use (op1))
3334 register_edge_assert_for_1 (op1, code, e, asserts);
3336 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3337 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3339 /* Recurse, flipping CODE. */
3340 code = invert_tree_comparison (code, false);
3341 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3343 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3345 /* Recurse through the copy. */
3346 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3348 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3350 /* Recurse through the type conversion, unless it is a narrowing
3351 conversion or conversion from non-integral type. */
3352 tree rhs = gimple_assign_rhs1 (op_def);
3353 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3354 && (TYPE_PRECISION (TREE_TYPE (rhs))
3355 <= TYPE_PRECISION (TREE_TYPE (op))))
3356 register_edge_assert_for_1 (rhs, code, e, asserts);
3360 /* Check if comparison
3361 NAME COND_OP INTEGER_CST
3362 has a form of
3363 (X & 11...100..0) COND_OP XX...X00...0
3364 Such comparison can yield assertions like
3365 X >= XX...X00...0
3366 X <= XX...X11...1
3367 in case of COND_OP being EQ_EXPR or
3368 X < XX...X00...0
3369 X > XX...X11...1
3370 in case of NE_EXPR. */
3372 static bool
3373 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3374 tree *new_name, tree *low, enum tree_code *low_code,
3375 tree *high, enum tree_code *high_code)
3377 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3379 if (!is_gimple_assign (def_stmt)
3380 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3381 return false;
3383 tree t = gimple_assign_rhs1 (def_stmt);
3384 tree maskt = gimple_assign_rhs2 (def_stmt);
3385 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3386 return false;
3388 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3389 wide_int inv_mask = ~mask;
3390 /* Must have been removed by now so don't bother optimizing. */
3391 if (mask == 0 || inv_mask == 0)
3392 return false;
3394 /* Assume VALT is INTEGER_CST. */
3395 wi::tree_to_wide_ref val = wi::to_wide (valt);
3397 if ((inv_mask & (inv_mask + 1)) != 0
3398 || (val & mask) != val)
3399 return false;
3401 bool is_range = cond_code == EQ_EXPR;
3403 tree type = TREE_TYPE (t);
3404 wide_int min = wi::min_value (type),
3405 max = wi::max_value (type);
3407 if (is_range)
3409 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3410 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3412 else
3414 /* We can still generate assertion if one of alternatives
3415 is known to always be false. */
3416 if (val == min)
3418 *low_code = (enum tree_code) 0;
3419 *high_code = GT_EXPR;
3421 else if ((val | inv_mask) == max)
3423 *low_code = LT_EXPR;
3424 *high_code = (enum tree_code) 0;
3426 else
3427 return false;
3430 *new_name = t;
3431 *low = wide_int_to_tree (type, val);
3432 *high = wide_int_to_tree (type, val | inv_mask);
3434 return true;
3437 /* Try to register an edge assertion for SSA name NAME on edge E for
3438 the condition COND contributing to the conditional jump pointed to by
3439 SI. */
3441 void
3442 register_edge_assert_for (tree name, edge e,
3443 enum tree_code cond_code, tree cond_op0,
3444 tree cond_op1, vec<assert_info> &asserts)
3446 tree val;
3447 enum tree_code comp_code;
3448 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3450 /* Do not attempt to infer anything in names that flow through
3451 abnormal edges. */
3452 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3453 return;
3455 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3456 cond_op0, cond_op1,
3457 is_else_edge,
3458 &comp_code, &val))
3459 return;
3461 /* Register ASSERT_EXPRs for name. */
3462 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3463 cond_op1, is_else_edge, asserts);
3466 /* If COND is effectively an equality test of an SSA_NAME against
3467 the value zero or one, then we may be able to assert values
3468 for SSA_NAMEs which flow into COND. */
3470 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3471 statement of NAME we can assert both operands of the BIT_AND_EXPR
3472 have nonzero value. */
3473 if (((comp_code == EQ_EXPR && integer_onep (val))
3474 || (comp_code == NE_EXPR && integer_zerop (val))))
3476 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3478 if (is_gimple_assign (def_stmt)
3479 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3481 tree op0 = gimple_assign_rhs1 (def_stmt);
3482 tree op1 = gimple_assign_rhs2 (def_stmt);
3483 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3484 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3488 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3489 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3490 have zero value. */
3491 if (((comp_code == EQ_EXPR && integer_zerop (val))
3492 || (comp_code == NE_EXPR && integer_onep (val))))
3494 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3496 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3497 necessarily zero value, or if type-precision is one. */
3498 if (is_gimple_assign (def_stmt)
3499 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3500 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3501 || comp_code == EQ_EXPR)))
3503 tree op0 = gimple_assign_rhs1 (def_stmt);
3504 tree op1 = gimple_assign_rhs2 (def_stmt);
3505 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3506 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3510 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3511 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3512 && TREE_CODE (val) == INTEGER_CST)
3514 enum tree_code low_code, high_code;
3515 tree low, high;
3516 if (is_masked_range_test (name, val, comp_code, &name, &low,
3517 &low_code, &high, &high_code))
3519 if (low_code != ERROR_MARK)
3520 register_edge_assert_for_2 (name, e, low_code, name,
3521 low, /*invert*/false, asserts);
3522 if (high_code != ERROR_MARK)
3523 register_edge_assert_for_2 (name, e, high_code, name,
3524 high, /*invert*/false, asserts);
3529 /* Finish found ASSERTS for E and register them at GSI. */
3531 static void
3532 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3533 vec<assert_info> &asserts)
3535 for (unsigned i = 0; i < asserts.length (); ++i)
3536 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3537 reachable from E. */
3538 if (live_on_edge (e, asserts[i].name))
3539 register_new_assert_for (asserts[i].name, asserts[i].expr,
3540 asserts[i].comp_code, asserts[i].val,
3541 NULL, e, gsi);
3546 /* Determine whether the outgoing edges of BB should receive an
3547 ASSERT_EXPR for each of the operands of BB's LAST statement.
3548 The last statement of BB must be a COND_EXPR.
3550 If any of the sub-graphs rooted at BB have an interesting use of
3551 the predicate operands, an assert location node is added to the
3552 list of assertions for the corresponding operands. */
3554 static void
3555 find_conditional_asserts (basic_block bb, gcond *last)
3557 gimple_stmt_iterator bsi;
3558 tree op;
3559 edge_iterator ei;
3560 edge e;
3561 ssa_op_iter iter;
3563 bsi = gsi_for_stmt (last);
3565 /* Look for uses of the operands in each of the sub-graphs
3566 rooted at BB. We need to check each of the outgoing edges
3567 separately, so that we know what kind of ASSERT_EXPR to
3568 insert. */
3569 FOR_EACH_EDGE (e, ei, bb->succs)
3571 if (e->dest == bb)
3572 continue;
3574 /* Register the necessary assertions for each operand in the
3575 conditional predicate. */
3576 auto_vec<assert_info, 8> asserts;
3577 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3578 register_edge_assert_for (op, e,
3579 gimple_cond_code (last),
3580 gimple_cond_lhs (last),
3581 gimple_cond_rhs (last), asserts);
3582 finish_register_edge_assert_for (e, bsi, asserts);
3586 struct case_info
3588 tree expr;
3589 basic_block bb;
3592 /* Compare two case labels sorting first by the destination bb index
3593 and then by the case value. */
3595 static int
3596 compare_case_labels (const void *p1, const void *p2)
3598 const struct case_info *ci1 = (const struct case_info *) p1;
3599 const struct case_info *ci2 = (const struct case_info *) p2;
3600 int idx1 = ci1->bb->index;
3601 int idx2 = ci2->bb->index;
3603 if (idx1 < idx2)
3604 return -1;
3605 else if (idx1 == idx2)
3607 /* Make sure the default label is first in a group. */
3608 if (!CASE_LOW (ci1->expr))
3609 return -1;
3610 else if (!CASE_LOW (ci2->expr))
3611 return 1;
3612 else
3613 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3614 CASE_LOW (ci2->expr));
3616 else
3617 return 1;
3620 /* Determine whether the outgoing edges of BB should receive an
3621 ASSERT_EXPR for each of the operands of BB's LAST statement.
3622 The last statement of BB must be a SWITCH_EXPR.
3624 If any of the sub-graphs rooted at BB have an interesting use of
3625 the predicate operands, an assert location node is added to the
3626 list of assertions for the corresponding operands. */
3628 static void
3629 find_switch_asserts (basic_block bb, gswitch *last)
3631 gimple_stmt_iterator bsi;
3632 tree op;
3633 edge e;
3634 struct case_info *ci;
3635 size_t n = gimple_switch_num_labels (last);
3636 #if GCC_VERSION >= 4000
3637 unsigned int idx;
3638 #else
3639 /* Work around GCC 3.4 bug (PR 37086). */
3640 volatile unsigned int idx;
3641 #endif
3643 bsi = gsi_for_stmt (last);
3644 op = gimple_switch_index (last);
3645 if (TREE_CODE (op) != SSA_NAME)
3646 return;
3648 /* Build a vector of case labels sorted by destination label. */
3649 ci = XNEWVEC (struct case_info, n);
3650 for (idx = 0; idx < n; ++idx)
3652 ci[idx].expr = gimple_switch_label (last, idx);
3653 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
3655 edge default_edge = find_edge (bb, ci[0].bb);
3656 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3658 for (idx = 0; idx < n; ++idx)
3660 tree min, max;
3661 tree cl = ci[idx].expr;
3662 basic_block cbb = ci[idx].bb;
3664 min = CASE_LOW (cl);
3665 max = CASE_HIGH (cl);
3667 /* If there are multiple case labels with the same destination
3668 we need to combine them to a single value range for the edge. */
3669 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3671 /* Skip labels until the last of the group. */
3672 do {
3673 ++idx;
3674 } while (idx < n && cbb == ci[idx].bb);
3675 --idx;
3677 /* Pick up the maximum of the case label range. */
3678 if (CASE_HIGH (ci[idx].expr))
3679 max = CASE_HIGH (ci[idx].expr);
3680 else
3681 max = CASE_LOW (ci[idx].expr);
3684 /* Can't extract a useful assertion out of a range that includes the
3685 default label. */
3686 if (min == NULL_TREE)
3687 continue;
3689 /* Find the edge to register the assert expr on. */
3690 e = find_edge (bb, cbb);
3692 /* Register the necessary assertions for the operand in the
3693 SWITCH_EXPR. */
3694 auto_vec<assert_info, 8> asserts;
3695 register_edge_assert_for (op, e,
3696 max ? GE_EXPR : EQ_EXPR,
3697 op, fold_convert (TREE_TYPE (op), min),
3698 asserts);
3699 if (max)
3700 register_edge_assert_for (op, e, LE_EXPR, op,
3701 fold_convert (TREE_TYPE (op), max),
3702 asserts);
3703 finish_register_edge_assert_for (e, bsi, asserts);
3706 XDELETEVEC (ci);
3708 if (!live_on_edge (default_edge, op))
3709 return;
3711 /* Now register along the default label assertions that correspond to the
3712 anti-range of each label. */
3713 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3714 if (insertion_limit == 0)
3715 return;
3717 /* We can't do this if the default case shares a label with another case. */
3718 tree default_cl = gimple_switch_default_label (last);
3719 for (idx = 1; idx < n; idx++)
3721 tree min, max;
3722 tree cl = gimple_switch_label (last, idx);
3723 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3724 continue;
3726 min = CASE_LOW (cl);
3727 max = CASE_HIGH (cl);
3729 /* Combine contiguous case ranges to reduce the number of assertions
3730 to insert. */
3731 for (idx = idx + 1; idx < n; idx++)
3733 tree next_min, next_max;
3734 tree next_cl = gimple_switch_label (last, idx);
3735 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3736 break;
3738 next_min = CASE_LOW (next_cl);
3739 next_max = CASE_HIGH (next_cl);
3741 wide_int difference = (wi::to_wide (next_min)
3742 - wi::to_wide (max ? max : min));
3743 if (wi::eq_p (difference, 1))
3744 max = next_max ? next_max : next_min;
3745 else
3746 break;
3748 idx--;
3750 if (max == NULL_TREE)
3752 /* Register the assertion OP != MIN. */
3753 auto_vec<assert_info, 8> asserts;
3754 min = fold_convert (TREE_TYPE (op), min);
3755 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3756 asserts);
3757 finish_register_edge_assert_for (default_edge, bsi, asserts);
3759 else
3761 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3762 which will give OP the anti-range ~[MIN,MAX]. */
3763 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3764 min = fold_convert (TREE_TYPE (uop), min);
3765 max = fold_convert (TREE_TYPE (uop), max);
3767 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3768 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3769 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3770 NULL, default_edge, bsi);
3773 if (--insertion_limit == 0)
3774 break;
3779 /* Traverse all the statements in block BB looking for statements that
3780 may generate useful assertions for the SSA names in their operand.
3781 If a statement produces a useful assertion A for name N_i, then the
3782 list of assertions already generated for N_i is scanned to
3783 determine if A is actually needed.
3785 If N_i already had the assertion A at a location dominating the
3786 current location, then nothing needs to be done. Otherwise, the
3787 new location for A is recorded instead.
3789 1- For every statement S in BB, all the variables used by S are
3790 added to bitmap FOUND_IN_SUBGRAPH.
3792 2- If statement S uses an operand N in a way that exposes a known
3793 value range for N, then if N was not already generated by an
3794 ASSERT_EXPR, create a new assert location for N. For instance,
3795 if N is a pointer and the statement dereferences it, we can
3796 assume that N is not NULL.
3798 3- COND_EXPRs are a special case of #2. We can derive range
3799 information from the predicate but need to insert different
3800 ASSERT_EXPRs for each of the sub-graphs rooted at the
3801 conditional block. If the last statement of BB is a conditional
3802 expression of the form 'X op Y', then
3804 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3806 b) If the conditional is the only entry point to the sub-graph
3807 corresponding to the THEN_CLAUSE, recurse into it. On
3808 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3809 an ASSERT_EXPR is added for the corresponding variable.
3811 c) Repeat step (b) on the ELSE_CLAUSE.
3813 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3815 For instance,
3817 if (a == 9)
3818 b = a;
3819 else
3820 b = c + 1;
3822 In this case, an assertion on the THEN clause is useful to
3823 determine that 'a' is always 9 on that edge. However, an assertion
3824 on the ELSE clause would be unnecessary.
3826 4- If BB does not end in a conditional expression, then we recurse
3827 into BB's dominator children.
3829 At the end of the recursive traversal, every SSA name will have a
3830 list of locations where ASSERT_EXPRs should be added. When a new
3831 location for name N is found, it is registered by calling
3832 register_new_assert_for. That function keeps track of all the
3833 registered assertions to prevent adding unnecessary assertions.
3834 For instance, if a pointer P_4 is dereferenced more than once in a
3835 dominator tree, only the location dominating all the dereference of
3836 P_4 will receive an ASSERT_EXPR. */
3838 static void
3839 find_assert_locations_1 (basic_block bb, sbitmap live)
3841 gimple *last;
3843 last = last_stmt (bb);
3845 /* If BB's last statement is a conditional statement involving integer
3846 operands, determine if we need to add ASSERT_EXPRs. */
3847 if (last
3848 && gimple_code (last) == GIMPLE_COND
3849 && !fp_predicate (last)
3850 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3851 find_conditional_asserts (bb, as_a <gcond *> (last));
3853 /* If BB's last statement is a switch statement involving integer
3854 operands, determine if we need to add ASSERT_EXPRs. */
3855 if (last
3856 && gimple_code (last) == GIMPLE_SWITCH
3857 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3858 find_switch_asserts (bb, as_a <gswitch *> (last));
3860 /* Traverse all the statements in BB marking used names and looking
3861 for statements that may infer assertions for their used operands. */
3862 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3863 gsi_prev (&si))
3865 gimple *stmt;
3866 tree op;
3867 ssa_op_iter i;
3869 stmt = gsi_stmt (si);
3871 if (is_gimple_debug (stmt))
3872 continue;
3874 /* See if we can derive an assertion for any of STMT's operands. */
3875 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3877 tree value;
3878 enum tree_code comp_code;
3880 /* If op is not live beyond this stmt, do not bother to insert
3881 asserts for it. */
3882 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3883 continue;
3885 /* If OP is used in such a way that we can infer a value
3886 range for it, and we don't find a previous assertion for
3887 it, create a new assertion location node for OP. */
3888 if (infer_value_range (stmt, op, &comp_code, &value))
3890 /* If we are able to infer a nonzero value range for OP,
3891 then walk backwards through the use-def chain to see if OP
3892 was set via a typecast.
3894 If so, then we can also infer a nonzero value range
3895 for the operand of the NOP_EXPR. */
3896 if (comp_code == NE_EXPR && integer_zerop (value))
3898 tree t = op;
3899 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3901 while (is_gimple_assign (def_stmt)
3902 && CONVERT_EXPR_CODE_P
3903 (gimple_assign_rhs_code (def_stmt))
3904 && TREE_CODE
3905 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3906 && POINTER_TYPE_P
3907 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3909 t = gimple_assign_rhs1 (def_stmt);
3910 def_stmt = SSA_NAME_DEF_STMT (t);
3912 /* Note we want to register the assert for the
3913 operand of the NOP_EXPR after SI, not after the
3914 conversion. */
3915 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3916 register_new_assert_for (t, t, comp_code, value,
3917 bb, NULL, si);
3921 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3925 /* Update live. */
3926 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3927 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3928 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3929 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3932 /* Traverse all PHI nodes in BB, updating live. */
3933 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3934 gsi_next (&si))
3936 use_operand_p arg_p;
3937 ssa_op_iter i;
3938 gphi *phi = si.phi ();
3939 tree res = gimple_phi_result (phi);
3941 if (virtual_operand_p (res))
3942 continue;
3944 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3946 tree arg = USE_FROM_PTR (arg_p);
3947 if (TREE_CODE (arg) == SSA_NAME)
3948 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3951 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3955 /* Do an RPO walk over the function computing SSA name liveness
3956 on-the-fly and deciding on assert expressions to insert. */
3958 static void
3959 find_assert_locations (void)
3961 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3962 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3963 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3964 int rpo_cnt, i;
3966 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3967 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3968 for (i = 0; i < rpo_cnt; ++i)
3969 bb_rpo[rpo[i]] = i;
3971 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3972 the order we compute liveness and insert asserts we otherwise
3973 fail to insert asserts into the loop latch. */
3974 loop_p loop;
3975 FOR_EACH_LOOP (loop, 0)
3977 i = loop->latch->index;
3978 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3979 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3980 !gsi_end_p (gsi); gsi_next (&gsi))
3982 gphi *phi = gsi.phi ();
3983 if (virtual_operand_p (gimple_phi_result (phi)))
3984 continue;
3985 tree arg = gimple_phi_arg_def (phi, j);
3986 if (TREE_CODE (arg) == SSA_NAME)
3988 if (live[i] == NULL)
3990 live[i] = sbitmap_alloc (num_ssa_names);
3991 bitmap_clear (live[i]);
3993 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3998 for (i = rpo_cnt - 1; i >= 0; --i)
4000 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
4001 edge e;
4002 edge_iterator ei;
4004 if (!live[rpo[i]])
4006 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4007 bitmap_clear (live[rpo[i]]);
4010 /* Process BB and update the live information with uses in
4011 this block. */
4012 find_assert_locations_1 (bb, live[rpo[i]]);
4014 /* Merge liveness into the predecessor blocks and free it. */
4015 if (!bitmap_empty_p (live[rpo[i]]))
4017 int pred_rpo = i;
4018 FOR_EACH_EDGE (e, ei, bb->preds)
4020 int pred = e->src->index;
4021 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4022 continue;
4024 if (!live[pred])
4026 live[pred] = sbitmap_alloc (num_ssa_names);
4027 bitmap_clear (live[pred]);
4029 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4031 if (bb_rpo[pred] < pred_rpo)
4032 pred_rpo = bb_rpo[pred];
4035 /* Record the RPO number of the last visited block that needs
4036 live information from this block. */
4037 last_rpo[rpo[i]] = pred_rpo;
4039 else
4041 sbitmap_free (live[rpo[i]]);
4042 live[rpo[i]] = NULL;
4045 /* We can free all successors live bitmaps if all their
4046 predecessors have been visited already. */
4047 FOR_EACH_EDGE (e, ei, bb->succs)
4048 if (last_rpo[e->dest->index] == i
4049 && live[e->dest->index])
4051 sbitmap_free (live[e->dest->index]);
4052 live[e->dest->index] = NULL;
4056 XDELETEVEC (rpo);
4057 XDELETEVEC (bb_rpo);
4058 XDELETEVEC (last_rpo);
4059 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4060 if (live[i])
4061 sbitmap_free (live[i]);
4062 XDELETEVEC (live);
4065 /* Create an ASSERT_EXPR for NAME and insert it in the location
4066 indicated by LOC. Return true if we made any edge insertions. */
4068 static bool
4069 process_assert_insertions_for (tree name, assert_locus *loc)
4071 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4072 gimple *stmt;
4073 tree cond;
4074 gimple *assert_stmt;
4075 edge_iterator ei;
4076 edge e;
4078 /* If we have X <=> X do not insert an assert expr for that. */
4079 if (loc->expr == loc->val)
4080 return false;
4082 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4083 assert_stmt = build_assert_expr_for (cond, name);
4084 if (loc->e)
4086 /* We have been asked to insert the assertion on an edge. This
4087 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4088 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4089 || (gimple_code (gsi_stmt (loc->si))
4090 == GIMPLE_SWITCH));
4092 gsi_insert_on_edge (loc->e, assert_stmt);
4093 return true;
4096 /* If the stmt iterator points at the end then this is an insertion
4097 at the beginning of a block. */
4098 if (gsi_end_p (loc->si))
4100 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4101 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4102 return false;
4105 /* Otherwise, we can insert right after LOC->SI iff the
4106 statement must not be the last statement in the block. */
4107 stmt = gsi_stmt (loc->si);
4108 if (!stmt_ends_bb_p (stmt))
4110 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4111 return false;
4114 /* If STMT must be the last statement in BB, we can only insert new
4115 assertions on the non-abnormal edge out of BB. Note that since
4116 STMT is not control flow, there may only be one non-abnormal/eh edge
4117 out of BB. */
4118 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4119 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4121 gsi_insert_on_edge (e, assert_stmt);
4122 return true;
4125 gcc_unreachable ();
4128 /* Qsort helper for sorting assert locations. If stable is true, don't
4129 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4130 on the other side some pointers might be NULL. */
4132 template <bool stable>
4133 static int
4134 compare_assert_loc (const void *pa, const void *pb)
4136 assert_locus * const a = *(assert_locus * const *)pa;
4137 assert_locus * const b = *(assert_locus * const *)pb;
4139 /* If stable, some asserts might be optimized away already, sort
4140 them last. */
4141 if (stable)
4143 if (a == NULL)
4144 return b != NULL;
4145 else if (b == NULL)
4146 return -1;
4149 if (a->e == NULL && b->e != NULL)
4150 return 1;
4151 else if (a->e != NULL && b->e == NULL)
4152 return -1;
4154 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4155 no need to test both a->e and b->e. */
4157 /* Sort after destination index. */
4158 if (a->e == NULL)
4160 else if (a->e->dest->index > b->e->dest->index)
4161 return 1;
4162 else if (a->e->dest->index < b->e->dest->index)
4163 return -1;
4165 /* Sort after comp_code. */
4166 if (a->comp_code > b->comp_code)
4167 return 1;
4168 else if (a->comp_code < b->comp_code)
4169 return -1;
4171 hashval_t ha, hb;
4173 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4174 uses DECL_UID of the VAR_DECL, so sorting might differ between
4175 -g and -g0. When doing the removal of redundant assert exprs
4176 and commonization to successors, this does not matter, but for
4177 the final sort needs to be stable. */
4178 if (stable)
4180 ha = 0;
4181 hb = 0;
4183 else
4185 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4186 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4189 /* Break the tie using hashing and source/bb index. */
4190 if (ha == hb)
4191 return (a->e != NULL
4192 ? a->e->src->index - b->e->src->index
4193 : a->bb->index - b->bb->index);
4194 return ha > hb ? 1 : -1;
4197 /* Process all the insertions registered for every name N_i registered
4198 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4199 found in ASSERTS_FOR[i]. */
4201 static void
4202 process_assert_insertions (void)
4204 unsigned i;
4205 bitmap_iterator bi;
4206 bool update_edges_p = false;
4207 int num_asserts = 0;
4209 if (dump_file && (dump_flags & TDF_DETAILS))
4210 dump_all_asserts (dump_file);
4212 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4214 assert_locus *loc = asserts_for[i];
4215 gcc_assert (loc);
4217 auto_vec<assert_locus *, 16> asserts;
4218 for (; loc; loc = loc->next)
4219 asserts.safe_push (loc);
4220 asserts.qsort (compare_assert_loc<false>);
4222 /* Push down common asserts to successors and remove redundant ones. */
4223 unsigned ecnt = 0;
4224 assert_locus *common = NULL;
4225 unsigned commonj = 0;
4226 for (unsigned j = 0; j < asserts.length (); ++j)
4228 loc = asserts[j];
4229 if (! loc->e)
4230 common = NULL;
4231 else if (! common
4232 || loc->e->dest != common->e->dest
4233 || loc->comp_code != common->comp_code
4234 || ! operand_equal_p (loc->val, common->val, 0)
4235 || ! operand_equal_p (loc->expr, common->expr, 0))
4237 commonj = j;
4238 common = loc;
4239 ecnt = 1;
4241 else if (loc->e == asserts[j-1]->e)
4243 /* Remove duplicate asserts. */
4244 if (commonj == j - 1)
4246 commonj = j;
4247 common = loc;
4249 free (asserts[j-1]);
4250 asserts[j-1] = NULL;
4252 else
4254 ecnt++;
4255 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4257 /* We have the same assertion on all incoming edges of a BB.
4258 Insert it at the beginning of that block. */
4259 loc->bb = loc->e->dest;
4260 loc->e = NULL;
4261 loc->si = gsi_none ();
4262 common = NULL;
4263 /* Clear asserts commoned. */
4264 for (; commonj != j; ++commonj)
4265 if (asserts[commonj])
4267 free (asserts[commonj]);
4268 asserts[commonj] = NULL;
4274 /* The asserts vector sorting above might be unstable for
4275 -fcompare-debug, sort again to ensure a stable sort. */
4276 asserts.qsort (compare_assert_loc<true>);
4277 for (unsigned j = 0; j < asserts.length (); ++j)
4279 loc = asserts[j];
4280 if (! loc)
4281 break;
4282 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4283 num_asserts++;
4284 free (loc);
4288 if (update_edges_p)
4289 gsi_commit_edge_inserts ();
4291 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4292 num_asserts);
4296 /* Traverse the flowgraph looking for conditional jumps to insert range
4297 expressions. These range expressions are meant to provide information
4298 to optimizations that need to reason in terms of value ranges. They
4299 will not be expanded into RTL. For instance, given:
4301 x = ...
4302 y = ...
4303 if (x < y)
4304 y = x - 2;
4305 else
4306 x = y + 3;
4308 this pass will transform the code into:
4310 x = ...
4311 y = ...
4312 if (x < y)
4314 x = ASSERT_EXPR <x, x < y>
4315 y = x - 2
4317 else
4319 y = ASSERT_EXPR <y, x >= y>
4320 x = y + 3
4323 The idea is that once copy and constant propagation have run, other
4324 optimizations will be able to determine what ranges of values can 'x'
4325 take in different paths of the code, simply by checking the reaching
4326 definition of 'x'. */
4328 static void
4329 insert_range_assertions (void)
4331 need_assert_for = BITMAP_ALLOC (NULL);
4332 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4334 calculate_dominance_info (CDI_DOMINATORS);
4336 find_assert_locations ();
4337 if (!bitmap_empty_p (need_assert_for))
4339 process_assert_insertions ();
4340 update_ssa (TODO_update_ssa_no_phi);
4343 if (dump_file && (dump_flags & TDF_DETAILS))
4345 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4346 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4349 free (asserts_for);
4350 BITMAP_FREE (need_assert_for);
4353 class vrp_prop : public ssa_propagation_engine
4355 public:
4356 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4357 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4359 void vrp_initialize (void);
4360 void vrp_finalize (bool);
4361 void check_all_array_refs (void);
4362 void check_array_ref (location_t, tree, bool);
4363 void check_mem_ref (location_t, tree, bool);
4364 void search_for_addr_array (tree, location_t);
4366 class vr_values vr_values;
4367 /* Temporary delegator to minimize code churn. */
4368 value_range *get_value_range (const_tree op)
4369 { return vr_values.get_value_range (op); }
4370 void set_defs_to_varying (gimple *stmt)
4371 { return vr_values.set_defs_to_varying (stmt); }
4372 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4373 tree *output_p, value_range *vr)
4374 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4375 bool update_value_range (const_tree op, value_range *vr)
4376 { return vr_values.update_value_range (op, vr); }
4377 void extract_range_basic (value_range *vr, gimple *stmt)
4378 { vr_values.extract_range_basic (vr, stmt); }
4379 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4380 { vr_values.extract_range_from_phi_node (phi, vr); }
4382 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4383 and "struct" hacks. If VRP can determine that the
4384 array subscript is a constant, check if it is outside valid
4385 range. If the array subscript is a RANGE, warn if it is
4386 non-overlapping with valid range.
4387 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4389 void
4390 vrp_prop::check_array_ref (location_t location, tree ref,
4391 bool ignore_off_by_one)
4393 value_range *vr = NULL;
4394 tree low_sub, up_sub;
4395 tree low_bound, up_bound, up_bound_p1;
4397 if (TREE_NO_WARNING (ref))
4398 return;
4400 low_sub = up_sub = TREE_OPERAND (ref, 1);
4401 up_bound = array_ref_up_bound (ref);
4403 if (!up_bound
4404 || TREE_CODE (up_bound) != INTEGER_CST
4405 || (warn_array_bounds < 2
4406 && array_at_struct_end_p (ref)))
4408 /* Accesses to trailing arrays via pointers may access storage
4409 beyond the types array bounds. For such arrays, or for flexible
4410 array members, as well as for other arrays of an unknown size,
4411 replace the upper bound with a more permissive one that assumes
4412 the size of the largest object is PTRDIFF_MAX. */
4413 tree eltsize = array_ref_element_size (ref);
4415 if (TREE_CODE (eltsize) != INTEGER_CST
4416 || integer_zerop (eltsize))
4418 up_bound = NULL_TREE;
4419 up_bound_p1 = NULL_TREE;
4421 else
4423 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4424 tree arg = TREE_OPERAND (ref, 0);
4425 poly_int64 off;
4427 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4428 maxbound = wide_int_to_tree (sizetype,
4429 wi::sub (wi::to_wide (maxbound),
4430 off));
4431 else
4432 maxbound = fold_convert (sizetype, maxbound);
4434 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4436 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4437 build_int_cst (ptrdiff_type_node, 1));
4440 else
4441 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4442 build_int_cst (TREE_TYPE (up_bound), 1));
4444 low_bound = array_ref_low_bound (ref);
4446 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4448 /* Empty array. */
4449 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4451 warning_at (location, OPT_Warray_bounds,
4452 "array subscript %E is above array bounds of %qT",
4453 low_bound, artype);
4454 TREE_NO_WARNING (ref) = 1;
4457 if (TREE_CODE (low_sub) == SSA_NAME)
4459 vr = get_value_range (low_sub);
4460 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4462 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4463 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4467 if (vr && vr->type == VR_ANTI_RANGE)
4469 if (up_bound
4470 && TREE_CODE (up_sub) == INTEGER_CST
4471 && (ignore_off_by_one
4472 ? tree_int_cst_lt (up_bound, up_sub)
4473 : tree_int_cst_le (up_bound, up_sub))
4474 && TREE_CODE (low_sub) == INTEGER_CST
4475 && tree_int_cst_le (low_sub, low_bound))
4477 warning_at (location, OPT_Warray_bounds,
4478 "array subscript [%E, %E] is outside array bounds of %qT",
4479 low_sub, up_sub, artype);
4480 TREE_NO_WARNING (ref) = 1;
4483 else if (up_bound
4484 && TREE_CODE (up_sub) == INTEGER_CST
4485 && (ignore_off_by_one
4486 ? !tree_int_cst_le (up_sub, up_bound_p1)
4487 : !tree_int_cst_le (up_sub, up_bound)))
4489 if (dump_file && (dump_flags & TDF_DETAILS))
4491 fprintf (dump_file, "Array bound warning for ");
4492 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4493 fprintf (dump_file, "\n");
4495 warning_at (location, OPT_Warray_bounds,
4496 "array subscript %E is above array bounds of %qT",
4497 up_sub, artype);
4498 TREE_NO_WARNING (ref) = 1;
4500 else if (TREE_CODE (low_sub) == INTEGER_CST
4501 && tree_int_cst_lt (low_sub, low_bound))
4503 if (dump_file && (dump_flags & TDF_DETAILS))
4505 fprintf (dump_file, "Array bound warning for ");
4506 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4507 fprintf (dump_file, "\n");
4509 warning_at (location, OPT_Warray_bounds,
4510 "array subscript %E is below array bounds of %qT",
4511 low_sub, artype);
4512 TREE_NO_WARNING (ref) = 1;
4516 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4517 references to string constants. If VRP can determine that the array
4518 subscript is a constant, check if it is outside valid range.
4519 If the array subscript is a RANGE, warn if it is non-overlapping
4520 with valid range.
4521 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4522 (used to allow one-past-the-end indices for code that takes
4523 the address of the just-past-the-end element of an array). */
4525 void
4526 vrp_prop::check_mem_ref (location_t location, tree ref, bool ignore_off_by_one)
4528 if (TREE_NO_WARNING (ref))
4529 return;
4531 tree arg = TREE_OPERAND (ref, 0);
4532 /* The constant and variable offset of the reference. */
4533 tree cstoff = TREE_OPERAND (ref, 1);
4534 tree varoff = NULL_TREE;
4536 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4538 /* The array or string constant bounds in bytes. Initially set
4539 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4540 determined. */
4541 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4543 /* The minimum and maximum intermediate offset. For a reference
4544 to be valid, not only does the final offset/subscript must be
4545 in bounds but all intermediate offsets should be as well.
4546 GCC may be able to deal gracefully with such out-of-bounds
4547 offsets so the checking is only enbaled at -Warray-bounds=2
4548 where it may help detect bugs in uses of the intermediate
4549 offsets that could otherwise not be detectable. */
4550 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4551 offset_int extrema[2] = { 0, wi::abs (ioff) };
4553 /* The range of the byte offset into the reference. */
4554 offset_int offrange[2] = { 0, 0 };
4556 value_range *vr = NULL;
4558 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4559 The loop computes the the range of the final offset for expressions
4560 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4561 in some range. */
4562 while (TREE_CODE (arg) == SSA_NAME)
4564 gimple *def = SSA_NAME_DEF_STMT (arg);
4565 if (!is_gimple_assign (def))
4566 break;
4568 tree_code code = gimple_assign_rhs_code (def);
4569 if (code == POINTER_PLUS_EXPR)
4571 arg = gimple_assign_rhs1 (def);
4572 varoff = gimple_assign_rhs2 (def);
4574 else if (code == ASSERT_EXPR)
4576 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4577 continue;
4579 else
4580 return;
4582 /* VAROFF should always be a SSA_NAME here (and not even
4583 INTEGER_CST) but there's no point in taking chances. */
4584 if (TREE_CODE (varoff) != SSA_NAME)
4585 break;
4587 vr = get_value_range (varoff);
4588 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4589 break;
4591 if (TREE_CODE (vr->min) != INTEGER_CST
4592 || TREE_CODE (vr->max) != INTEGER_CST)
4593 break;
4595 if (vr->type == VR_RANGE)
4597 if (tree_int_cst_lt (vr->min, vr->max))
4599 offset_int min
4600 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4601 offset_int max
4602 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4603 if (min < max)
4605 offrange[0] += min;
4606 offrange[1] += max;
4608 else
4610 offrange[0] += max;
4611 offrange[1] += min;
4614 else
4616 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4617 to OFFRANGE. */
4618 offrange[0] += arrbounds[0];
4619 offrange[1] += arrbounds[1];
4622 else
4624 /* For an anti-range, analogously to the above, conservatively
4625 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4626 offrange[0] += arrbounds[0];
4627 offrange[1] += arrbounds[1];
4630 /* Keep track of the minimum and maximum offset. */
4631 if (offrange[1] < 0 && offrange[1] < extrema[0])
4632 extrema[0] = offrange[1];
4633 if (offrange[0] > 0 && offrange[0] > extrema[1])
4634 extrema[1] = offrange[0];
4636 if (offrange[0] < arrbounds[0])
4637 offrange[0] = arrbounds[0];
4639 if (offrange[1] > arrbounds[1])
4640 offrange[1] = arrbounds[1];
4643 if (TREE_CODE (arg) == ADDR_EXPR)
4645 arg = TREE_OPERAND (arg, 0);
4646 if (TREE_CODE (arg) != STRING_CST
4647 && TREE_CODE (arg) != VAR_DECL)
4648 return;
4650 else
4651 return;
4653 /* The type of the object being referred to. It can be an array,
4654 string literal, or a non-array type when the MEM_REF represents
4655 a reference/subscript via a pointer to an object that is not
4656 an element of an array. References to members of structs and
4657 unions are excluded because MEM_REF doesn't make it possible
4658 to identify the member where the reference originated.
4659 Incomplete types are excluded as well because their size is
4660 not known. */
4661 tree reftype = TREE_TYPE (arg);
4662 if (POINTER_TYPE_P (reftype)
4663 || !COMPLETE_TYPE_P (reftype)
4664 || RECORD_OR_UNION_TYPE_P (reftype))
4665 return;
4667 offset_int eltsize;
4668 if (TREE_CODE (reftype) == ARRAY_TYPE)
4670 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4672 if (tree dom = TYPE_DOMAIN (reftype))
4674 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4675 if (array_at_struct_end_p (arg)
4676 || !bnds[0] || !bnds[1])
4678 arrbounds[0] = 0;
4679 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4681 else
4683 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4684 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4687 else
4689 arrbounds[0] = 0;
4690 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4693 if (TREE_CODE (ref) == MEM_REF)
4695 /* For MEM_REF determine a tighter bound of the non-array
4696 element type. */
4697 tree eltype = TREE_TYPE (reftype);
4698 while (TREE_CODE (eltype) == ARRAY_TYPE)
4699 eltype = TREE_TYPE (eltype);
4700 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4703 else
4705 eltsize = 1;
4706 arrbounds[0] = 0;
4707 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4710 offrange[0] += ioff;
4711 offrange[1] += ioff;
4713 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4714 is set (when taking the address of the one-past-last element
4715 of an array) but always use the stricter bound in diagnostics. */
4716 offset_int ubound = arrbounds[1];
4717 if (ignore_off_by_one)
4718 ubound += 1;
4720 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4722 /* Treat a reference to a non-array object as one to an array
4723 of a single element. */
4724 if (TREE_CODE (reftype) != ARRAY_TYPE)
4725 reftype = build_array_type_nelts (reftype, 1);
4727 if (TREE_CODE (ref) == MEM_REF)
4729 /* Extract the element type out of MEM_REF and use its size
4730 to compute the index to print in the diagnostic; arrays
4731 in MEM_REF don't mean anything. */
4732 tree type = TREE_TYPE (ref);
4733 while (TREE_CODE (type) == ARRAY_TYPE)
4734 type = TREE_TYPE (type);
4735 tree size = TYPE_SIZE_UNIT (type);
4736 offrange[0] = offrange[0] / wi::to_offset (size);
4737 offrange[1] = offrange[1] / wi::to_offset (size);
4739 else
4741 /* For anything other than MEM_REF, compute the index to
4742 print in the diagnostic as the offset over element size. */
4743 offrange[0] = offrange[0] / eltsize;
4744 offrange[1] = offrange[1] / eltsize;
4747 if (offrange[0] == offrange[1])
4748 warning_at (location, OPT_Warray_bounds,
4749 "array subscript %wi is outside array bounds "
4750 "of %qT",
4751 offrange[0].to_shwi (), reftype);
4752 else
4753 warning_at (location, OPT_Warray_bounds,
4754 "array subscript [%wi, %wi] is outside array bounds "
4755 "of %qT",
4756 offrange[0].to_shwi (), offrange[1].to_shwi (), reftype);
4757 TREE_NO_WARNING (ref) = 1;
4758 return;
4761 if (warn_array_bounds < 2)
4762 return;
4764 /* At level 2 check also intermediate offsets. */
4765 int i = 0;
4766 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4768 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4770 warning_at (location, OPT_Warray_bounds,
4771 "intermediate array offset %wi is outside array bounds "
4772 "of %qT",
4773 tmpidx, reftype);
4774 TREE_NO_WARNING (ref) = 1;
4778 /* Searches if the expr T, located at LOCATION computes
4779 address of an ARRAY_REF, and call check_array_ref on it. */
4781 void
4782 vrp_prop::search_for_addr_array (tree t, location_t location)
4784 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4787 if (TREE_CODE (t) == ARRAY_REF)
4788 check_array_ref (location, t, true /*ignore_off_by_one*/);
4789 else if (TREE_CODE (t) == MEM_REF)
4790 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4792 t = TREE_OPERAND (t, 0);
4794 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4796 if (TREE_CODE (t) == MEM_REF
4797 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
4798 && !TREE_NO_WARNING (t))
4800 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4801 tree low_bound, up_bound, el_sz;
4802 offset_int idx;
4803 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4804 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4805 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4806 return;
4808 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4809 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4810 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4811 if (!low_bound
4812 || TREE_CODE (low_bound) != INTEGER_CST
4813 || !up_bound
4814 || TREE_CODE (up_bound) != INTEGER_CST
4815 || !el_sz
4816 || TREE_CODE (el_sz) != INTEGER_CST)
4817 return;
4819 if (!mem_ref_offset (t).is_constant (&idx))
4820 return;
4822 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4823 if (idx < 0)
4825 if (dump_file && (dump_flags & TDF_DETAILS))
4827 fprintf (dump_file, "Array bound warning for ");
4828 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4829 fprintf (dump_file, "\n");
4831 warning_at (location, OPT_Warray_bounds,
4832 "array subscript %wi is below array bounds of %qT",
4833 idx.to_shwi (), TREE_TYPE (tem));
4834 TREE_NO_WARNING (t) = 1;
4836 else if (idx > (wi::to_offset (up_bound)
4837 - wi::to_offset (low_bound) + 1))
4839 if (dump_file && (dump_flags & TDF_DETAILS))
4841 fprintf (dump_file, "Array bound warning for ");
4842 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4843 fprintf (dump_file, "\n");
4845 warning_at (location, OPT_Warray_bounds,
4846 "array subscript %wu is above array bounds of %qT",
4847 idx.to_uhwi (), TREE_TYPE (tem));
4848 TREE_NO_WARNING (t) = 1;
4853 /* walk_tree() callback that checks if *TP is
4854 an ARRAY_REF inside an ADDR_EXPR (in which an array
4855 subscript one outside the valid range is allowed). Call
4856 check_array_ref for each ARRAY_REF found. The location is
4857 passed in DATA. */
4859 static tree
4860 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4862 tree t = *tp;
4863 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4864 location_t location;
4866 if (EXPR_HAS_LOCATION (t))
4867 location = EXPR_LOCATION (t);
4868 else
4869 location = gimple_location (wi->stmt);
4871 *walk_subtree = TRUE;
4873 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4874 if (TREE_CODE (t) == ARRAY_REF)
4875 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4876 else if (TREE_CODE (t) == MEM_REF)
4877 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4878 else if (TREE_CODE (t) == ADDR_EXPR)
4880 vrp_prop->search_for_addr_array (t, location);
4881 *walk_subtree = FALSE;
4884 return NULL_TREE;
4887 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4888 to walk over all statements of all reachable BBs and call
4889 check_array_bounds on them. */
4891 class check_array_bounds_dom_walker : public dom_walker
4893 public:
4894 check_array_bounds_dom_walker (vrp_prop *prop)
4895 : dom_walker (CDI_DOMINATORS,
4896 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4897 flags, so that we can merge in information on
4898 non-executable edges from vrp_folder . */
4899 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4900 m_prop (prop) {}
4901 ~check_array_bounds_dom_walker () {}
4903 edge before_dom_children (basic_block) FINAL OVERRIDE;
4905 private:
4906 vrp_prop *m_prop;
4909 /* Implementation of dom_walker::before_dom_children.
4911 Walk over all statements of BB and call check_array_bounds on them,
4912 and determine if there's a unique successor edge. */
4914 edge
4915 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4917 gimple_stmt_iterator si;
4918 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4920 gimple *stmt = gsi_stmt (si);
4921 struct walk_stmt_info wi;
4922 if (!gimple_has_location (stmt)
4923 || is_gimple_debug (stmt))
4924 continue;
4926 memset (&wi, 0, sizeof (wi));
4928 wi.info = m_prop;
4930 walk_gimple_op (stmt, check_array_bounds, &wi);
4933 /* Determine if there's a unique successor edge, and if so, return
4934 that back to dom_walker, ensuring that we don't visit blocks that
4935 became unreachable during the VRP propagation
4936 (PR tree-optimization/83312). */
4937 return find_taken_edge (bb, NULL_TREE);
4940 /* Walk over all statements of all reachable BBs and call check_array_bounds
4941 on them. */
4943 void
4944 vrp_prop::check_all_array_refs ()
4946 check_array_bounds_dom_walker w (this);
4947 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4950 /* Return true if all imm uses of VAR are either in STMT, or
4951 feed (optionally through a chain of single imm uses) GIMPLE_COND
4952 in basic block COND_BB. */
4954 static bool
4955 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4957 use_operand_p use_p, use2_p;
4958 imm_use_iterator iter;
4960 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4961 if (USE_STMT (use_p) != stmt)
4963 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4964 if (is_gimple_debug (use_stmt))
4965 continue;
4966 while (is_gimple_assign (use_stmt)
4967 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4968 && single_imm_use (gimple_assign_lhs (use_stmt),
4969 &use2_p, &use_stmt2))
4970 use_stmt = use_stmt2;
4971 if (gimple_code (use_stmt) != GIMPLE_COND
4972 || gimple_bb (use_stmt) != cond_bb)
4973 return false;
4975 return true;
4978 /* Handle
4979 _4 = x_3 & 31;
4980 if (_4 != 0)
4981 goto <bb 6>;
4982 else
4983 goto <bb 7>;
4984 <bb 6>:
4985 __builtin_unreachable ();
4986 <bb 7>:
4987 x_5 = ASSERT_EXPR <x_3, ...>;
4988 If x_3 has no other immediate uses (checked by caller),
4989 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4990 from the non-zero bitmask. */
4992 void
4993 maybe_set_nonzero_bits (edge e, tree var)
4995 basic_block cond_bb = e->src;
4996 gimple *stmt = last_stmt (cond_bb);
4997 tree cst;
4999 if (stmt == NULL
5000 || gimple_code (stmt) != GIMPLE_COND
5001 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5002 ? EQ_EXPR : NE_EXPR)
5003 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5004 || !integer_zerop (gimple_cond_rhs (stmt)))
5005 return;
5007 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5008 if (!is_gimple_assign (stmt)
5009 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5010 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5011 return;
5012 if (gimple_assign_rhs1 (stmt) != var)
5014 gimple *stmt2;
5016 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5017 return;
5018 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5019 if (!gimple_assign_cast_p (stmt2)
5020 || gimple_assign_rhs1 (stmt2) != var
5021 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5022 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5023 != TYPE_PRECISION (TREE_TYPE (var))))
5024 return;
5026 cst = gimple_assign_rhs2 (stmt);
5027 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5028 wi::to_wide (cst)));
5031 /* Convert range assertion expressions into the implied copies and
5032 copy propagate away the copies. Doing the trivial copy propagation
5033 here avoids the need to run the full copy propagation pass after
5034 VRP.
5036 FIXME, this will eventually lead to copy propagation removing the
5037 names that had useful range information attached to them. For
5038 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5039 then N_i will have the range [3, +INF].
5041 However, by converting the assertion into the implied copy
5042 operation N_i = N_j, we will then copy-propagate N_j into the uses
5043 of N_i and lose the range information. We may want to hold on to
5044 ASSERT_EXPRs a little while longer as the ranges could be used in
5045 things like jump threading.
5047 The problem with keeping ASSERT_EXPRs around is that passes after
5048 VRP need to handle them appropriately.
5050 Another approach would be to make the range information a first
5051 class property of the SSA_NAME so that it can be queried from
5052 any pass. This is made somewhat more complex by the need for
5053 multiple ranges to be associated with one SSA_NAME. */
5055 static void
5056 remove_range_assertions (void)
5058 basic_block bb;
5059 gimple_stmt_iterator si;
5060 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5061 a basic block preceeded by GIMPLE_COND branching to it and
5062 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5063 int is_unreachable;
5065 /* Note that the BSI iterator bump happens at the bottom of the
5066 loop and no bump is necessary if we're removing the statement
5067 referenced by the current BSI. */
5068 FOR_EACH_BB_FN (bb, cfun)
5069 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5071 gimple *stmt = gsi_stmt (si);
5073 if (is_gimple_assign (stmt)
5074 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5076 tree lhs = gimple_assign_lhs (stmt);
5077 tree rhs = gimple_assign_rhs1 (stmt);
5078 tree var;
5080 var = ASSERT_EXPR_VAR (rhs);
5082 if (TREE_CODE (var) == SSA_NAME
5083 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5084 && SSA_NAME_RANGE_INFO (lhs))
5086 if (is_unreachable == -1)
5088 is_unreachable = 0;
5089 if (single_pred_p (bb)
5090 && assert_unreachable_fallthru_edge_p
5091 (single_pred_edge (bb)))
5092 is_unreachable = 1;
5094 /* Handle
5095 if (x_7 >= 10 && x_7 < 20)
5096 __builtin_unreachable ();
5097 x_8 = ASSERT_EXPR <x_7, ...>;
5098 if the only uses of x_7 are in the ASSERT_EXPR and
5099 in the condition. In that case, we can copy the
5100 range info from x_8 computed in this pass also
5101 for x_7. */
5102 if (is_unreachable
5103 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5104 single_pred (bb)))
5106 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5107 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5108 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5109 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5113 /* Propagate the RHS into every use of the LHS. For SSA names
5114 also propagate abnormals as it merely restores the original
5115 IL in this case (an replace_uses_by would assert). */
5116 if (TREE_CODE (var) == SSA_NAME)
5118 imm_use_iterator iter;
5119 use_operand_p use_p;
5120 gimple *use_stmt;
5121 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5122 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5123 SET_USE (use_p, var);
5125 else
5126 replace_uses_by (lhs, var);
5128 /* And finally, remove the copy, it is not needed. */
5129 gsi_remove (&si, true);
5130 release_defs (stmt);
5132 else
5134 if (!is_gimple_debug (gsi_stmt (si)))
5135 is_unreachable = 0;
5136 gsi_next (&si);
5141 /* Return true if STMT is interesting for VRP. */
5143 bool
5144 stmt_interesting_for_vrp (gimple *stmt)
5146 if (gimple_code (stmt) == GIMPLE_PHI)
5148 tree res = gimple_phi_result (stmt);
5149 return (!virtual_operand_p (res)
5150 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5151 || POINTER_TYPE_P (TREE_TYPE (res))));
5153 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5155 tree lhs = gimple_get_lhs (stmt);
5157 /* In general, assignments with virtual operands are not useful
5158 for deriving ranges, with the obvious exception of calls to
5159 builtin functions. */
5160 if (lhs && TREE_CODE (lhs) == SSA_NAME
5161 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5162 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5163 && (is_gimple_call (stmt)
5164 || !gimple_vuse (stmt)))
5165 return true;
5166 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5167 switch (gimple_call_internal_fn (stmt))
5169 case IFN_ADD_OVERFLOW:
5170 case IFN_SUB_OVERFLOW:
5171 case IFN_MUL_OVERFLOW:
5172 case IFN_ATOMIC_COMPARE_EXCHANGE:
5173 /* These internal calls return _Complex integer type,
5174 but are interesting to VRP nevertheless. */
5175 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5176 return true;
5177 break;
5178 default:
5179 break;
5182 else if (gimple_code (stmt) == GIMPLE_COND
5183 || gimple_code (stmt) == GIMPLE_SWITCH)
5184 return true;
5186 return false;
5189 /* Initialization required by ssa_propagate engine. */
5191 void
5192 vrp_prop::vrp_initialize ()
5194 basic_block bb;
5196 FOR_EACH_BB_FN (bb, cfun)
5198 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5199 gsi_next (&si))
5201 gphi *phi = si.phi ();
5202 if (!stmt_interesting_for_vrp (phi))
5204 tree lhs = PHI_RESULT (phi);
5205 set_value_range_to_varying (get_value_range (lhs));
5206 prop_set_simulate_again (phi, false);
5208 else
5209 prop_set_simulate_again (phi, true);
5212 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5213 gsi_next (&si))
5215 gimple *stmt = gsi_stmt (si);
5217 /* If the statement is a control insn, then we do not
5218 want to avoid simulating the statement once. Failure
5219 to do so means that those edges will never get added. */
5220 if (stmt_ends_bb_p (stmt))
5221 prop_set_simulate_again (stmt, true);
5222 else if (!stmt_interesting_for_vrp (stmt))
5224 set_defs_to_varying (stmt);
5225 prop_set_simulate_again (stmt, false);
5227 else
5228 prop_set_simulate_again (stmt, true);
5233 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5234 that includes the value VAL. The search is restricted to the range
5235 [START_IDX, n - 1] where n is the size of VEC.
5237 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5238 returned.
5240 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5241 it is placed in IDX and false is returned.
5243 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5244 returned. */
5246 bool
5247 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5249 size_t n = gimple_switch_num_labels (stmt);
5250 size_t low, high;
5252 /* Find case label for minimum of the value range or the next one.
5253 At each iteration we are searching in [low, high - 1]. */
5255 for (low = start_idx, high = n; high != low; )
5257 tree t;
5258 int cmp;
5259 /* Note that i != high, so we never ask for n. */
5260 size_t i = (high + low) / 2;
5261 t = gimple_switch_label (stmt, i);
5263 /* Cache the result of comparing CASE_LOW and val. */
5264 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5266 if (cmp == 0)
5268 /* Ranges cannot be empty. */
5269 *idx = i;
5270 return true;
5272 else if (cmp > 0)
5273 high = i;
5274 else
5276 low = i + 1;
5277 if (CASE_HIGH (t) != NULL
5278 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5280 *idx = i;
5281 return true;
5286 *idx = high;
5287 return false;
5290 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5291 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5292 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5293 then MAX_IDX < MIN_IDX.
5294 Returns true if the default label is not needed. */
5296 bool
5297 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5298 size_t *max_idx)
5300 size_t i, j;
5301 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5302 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5304 if (i == j
5305 && min_take_default
5306 && max_take_default)
5308 /* Only the default case label reached.
5309 Return an empty range. */
5310 *min_idx = 1;
5311 *max_idx = 0;
5312 return false;
5314 else
5316 bool take_default = min_take_default || max_take_default;
5317 tree low, high;
5318 size_t k;
5320 if (max_take_default)
5321 j--;
5323 /* If the case label range is continuous, we do not need
5324 the default case label. Verify that. */
5325 high = CASE_LOW (gimple_switch_label (stmt, i));
5326 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5327 high = CASE_HIGH (gimple_switch_label (stmt, i));
5328 for (k = i + 1; k <= j; ++k)
5330 low = CASE_LOW (gimple_switch_label (stmt, k));
5331 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5333 take_default = true;
5334 break;
5336 high = low;
5337 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5338 high = CASE_HIGH (gimple_switch_label (stmt, k));
5341 *min_idx = i;
5342 *max_idx = j;
5343 return !take_default;
5347 /* Evaluate statement STMT. If the statement produces a useful range,
5348 return SSA_PROP_INTERESTING and record the SSA name with the
5349 interesting range into *OUTPUT_P.
5351 If STMT is a conditional branch and we can determine its truth
5352 value, the taken edge is recorded in *TAKEN_EDGE_P.
5354 If STMT produces a varying value, return SSA_PROP_VARYING. */
5356 enum ssa_prop_result
5357 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5359 value_range vr = VR_INITIALIZER;
5360 tree lhs = gimple_get_lhs (stmt);
5361 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5363 if (*output_p)
5365 if (update_value_range (*output_p, &vr))
5367 if (dump_file && (dump_flags & TDF_DETAILS))
5369 fprintf (dump_file, "Found new range for ");
5370 print_generic_expr (dump_file, *output_p);
5371 fprintf (dump_file, ": ");
5372 dump_value_range (dump_file, &vr);
5373 fprintf (dump_file, "\n");
5376 if (vr.type == VR_VARYING)
5377 return SSA_PROP_VARYING;
5379 return SSA_PROP_INTERESTING;
5381 return SSA_PROP_NOT_INTERESTING;
5384 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5385 switch (gimple_call_internal_fn (stmt))
5387 case IFN_ADD_OVERFLOW:
5388 case IFN_SUB_OVERFLOW:
5389 case IFN_MUL_OVERFLOW:
5390 case IFN_ATOMIC_COMPARE_EXCHANGE:
5391 /* These internal calls return _Complex integer type,
5392 which VRP does not track, but the immediate uses
5393 thereof might be interesting. */
5394 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5396 imm_use_iterator iter;
5397 use_operand_p use_p;
5398 enum ssa_prop_result res = SSA_PROP_VARYING;
5400 set_value_range_to_varying (get_value_range (lhs));
5402 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5404 gimple *use_stmt = USE_STMT (use_p);
5405 if (!is_gimple_assign (use_stmt))
5406 continue;
5407 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5408 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5409 continue;
5410 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5411 tree use_lhs = gimple_assign_lhs (use_stmt);
5412 if (TREE_CODE (rhs1) != rhs_code
5413 || TREE_OPERAND (rhs1, 0) != lhs
5414 || TREE_CODE (use_lhs) != SSA_NAME
5415 || !stmt_interesting_for_vrp (use_stmt)
5416 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5417 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5418 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5419 continue;
5421 /* If there is a change in the value range for any of the
5422 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5423 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5424 or IMAGPART_EXPR immediate uses, but none of them have
5425 a change in their value ranges, return
5426 SSA_PROP_NOT_INTERESTING. If there are no
5427 {REAL,IMAG}PART_EXPR uses at all,
5428 return SSA_PROP_VARYING. */
5429 value_range new_vr = VR_INITIALIZER;
5430 extract_range_basic (&new_vr, use_stmt);
5431 value_range *old_vr = get_value_range (use_lhs);
5432 if (old_vr->type != new_vr.type
5433 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5434 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5435 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5436 res = SSA_PROP_INTERESTING;
5437 else
5438 res = SSA_PROP_NOT_INTERESTING;
5439 BITMAP_FREE (new_vr.equiv);
5440 if (res == SSA_PROP_INTERESTING)
5442 *output_p = lhs;
5443 return res;
5447 return res;
5449 break;
5450 default:
5451 break;
5454 /* All other statements produce nothing of interest for VRP, so mark
5455 their outputs varying and prevent further simulation. */
5456 set_defs_to_varying (stmt);
5458 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5461 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5462 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5463 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5464 possible such range. The resulting range is not canonicalized. */
5466 static void
5467 union_ranges (enum value_range_type *vr0type,
5468 tree *vr0min, tree *vr0max,
5469 enum value_range_type vr1type,
5470 tree vr1min, tree vr1max)
5472 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5473 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5475 /* [] is vr0, () is vr1 in the following classification comments. */
5476 if (mineq && maxeq)
5478 /* [( )] */
5479 if (*vr0type == vr1type)
5480 /* Nothing to do for equal ranges. */
5482 else if ((*vr0type == VR_RANGE
5483 && vr1type == VR_ANTI_RANGE)
5484 || (*vr0type == VR_ANTI_RANGE
5485 && vr1type == VR_RANGE))
5487 /* For anti-range with range union the result is varying. */
5488 goto give_up;
5490 else
5491 gcc_unreachable ();
5493 else if (operand_less_p (*vr0max, vr1min) == 1
5494 || operand_less_p (vr1max, *vr0min) == 1)
5496 /* [ ] ( ) or ( ) [ ]
5497 If the ranges have an empty intersection, result of the union
5498 operation is the anti-range or if both are anti-ranges
5499 it covers all. */
5500 if (*vr0type == VR_ANTI_RANGE
5501 && vr1type == VR_ANTI_RANGE)
5502 goto give_up;
5503 else if (*vr0type == VR_ANTI_RANGE
5504 && vr1type == VR_RANGE)
5506 else if (*vr0type == VR_RANGE
5507 && vr1type == VR_ANTI_RANGE)
5509 *vr0type = vr1type;
5510 *vr0min = vr1min;
5511 *vr0max = vr1max;
5513 else if (*vr0type == VR_RANGE
5514 && vr1type == VR_RANGE)
5516 /* The result is the convex hull of both ranges. */
5517 if (operand_less_p (*vr0max, vr1min) == 1)
5519 /* If the result can be an anti-range, create one. */
5520 if (TREE_CODE (*vr0max) == INTEGER_CST
5521 && TREE_CODE (vr1min) == INTEGER_CST
5522 && vrp_val_is_min (*vr0min)
5523 && vrp_val_is_max (vr1max))
5525 tree min = int_const_binop (PLUS_EXPR,
5526 *vr0max,
5527 build_int_cst (TREE_TYPE (*vr0max), 1));
5528 tree max = int_const_binop (MINUS_EXPR,
5529 vr1min,
5530 build_int_cst (TREE_TYPE (vr1min), 1));
5531 if (!operand_less_p (max, min))
5533 *vr0type = VR_ANTI_RANGE;
5534 *vr0min = min;
5535 *vr0max = max;
5537 else
5538 *vr0max = vr1max;
5540 else
5541 *vr0max = vr1max;
5543 else
5545 /* If the result can be an anti-range, create one. */
5546 if (TREE_CODE (vr1max) == INTEGER_CST
5547 && TREE_CODE (*vr0min) == INTEGER_CST
5548 && vrp_val_is_min (vr1min)
5549 && vrp_val_is_max (*vr0max))
5551 tree min = int_const_binop (PLUS_EXPR,
5552 vr1max,
5553 build_int_cst (TREE_TYPE (vr1max), 1));
5554 tree max = int_const_binop (MINUS_EXPR,
5555 *vr0min,
5556 build_int_cst (TREE_TYPE (*vr0min), 1));
5557 if (!operand_less_p (max, min))
5559 *vr0type = VR_ANTI_RANGE;
5560 *vr0min = min;
5561 *vr0max = max;
5563 else
5564 *vr0min = vr1min;
5566 else
5567 *vr0min = vr1min;
5570 else
5571 gcc_unreachable ();
5573 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5574 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5576 /* [ ( ) ] or [( ) ] or [ ( )] */
5577 if (*vr0type == VR_RANGE
5578 && vr1type == VR_RANGE)
5580 else if (*vr0type == VR_ANTI_RANGE
5581 && vr1type == VR_ANTI_RANGE)
5583 *vr0type = vr1type;
5584 *vr0min = vr1min;
5585 *vr0max = vr1max;
5587 else if (*vr0type == VR_ANTI_RANGE
5588 && vr1type == VR_RANGE)
5590 /* Arbitrarily choose the right or left gap. */
5591 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5592 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5593 build_int_cst (TREE_TYPE (vr1min), 1));
5594 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5595 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5596 build_int_cst (TREE_TYPE (vr1max), 1));
5597 else
5598 goto give_up;
5600 else if (*vr0type == VR_RANGE
5601 && vr1type == VR_ANTI_RANGE)
5602 /* The result covers everything. */
5603 goto give_up;
5604 else
5605 gcc_unreachable ();
5607 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5608 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5610 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5611 if (*vr0type == VR_RANGE
5612 && vr1type == VR_RANGE)
5614 *vr0type = vr1type;
5615 *vr0min = vr1min;
5616 *vr0max = vr1max;
5618 else if (*vr0type == VR_ANTI_RANGE
5619 && vr1type == VR_ANTI_RANGE)
5621 else if (*vr0type == VR_RANGE
5622 && vr1type == VR_ANTI_RANGE)
5624 *vr0type = VR_ANTI_RANGE;
5625 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5627 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5628 build_int_cst (TREE_TYPE (*vr0min), 1));
5629 *vr0min = vr1min;
5631 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5633 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5634 build_int_cst (TREE_TYPE (*vr0max), 1));
5635 *vr0max = vr1max;
5637 else
5638 goto give_up;
5640 else if (*vr0type == VR_ANTI_RANGE
5641 && vr1type == VR_RANGE)
5642 /* The result covers everything. */
5643 goto give_up;
5644 else
5645 gcc_unreachable ();
5647 else if ((operand_less_p (vr1min, *vr0max) == 1
5648 || operand_equal_p (vr1min, *vr0max, 0))
5649 && operand_less_p (*vr0min, vr1min) == 1
5650 && operand_less_p (*vr0max, vr1max) == 1)
5652 /* [ ( ] ) or [ ]( ) */
5653 if (*vr0type == VR_RANGE
5654 && vr1type == VR_RANGE)
5655 *vr0max = vr1max;
5656 else if (*vr0type == VR_ANTI_RANGE
5657 && vr1type == VR_ANTI_RANGE)
5658 *vr0min = vr1min;
5659 else if (*vr0type == VR_ANTI_RANGE
5660 && vr1type == VR_RANGE)
5662 if (TREE_CODE (vr1min) == INTEGER_CST)
5663 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5664 build_int_cst (TREE_TYPE (vr1min), 1));
5665 else
5666 goto give_up;
5668 else if (*vr0type == VR_RANGE
5669 && vr1type == VR_ANTI_RANGE)
5671 if (TREE_CODE (*vr0max) == INTEGER_CST)
5673 *vr0type = vr1type;
5674 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5675 build_int_cst (TREE_TYPE (*vr0max), 1));
5676 *vr0max = vr1max;
5678 else
5679 goto give_up;
5681 else
5682 gcc_unreachable ();
5684 else if ((operand_less_p (*vr0min, vr1max) == 1
5685 || operand_equal_p (*vr0min, vr1max, 0))
5686 && operand_less_p (vr1min, *vr0min) == 1
5687 && operand_less_p (vr1max, *vr0max) == 1)
5689 /* ( [ ) ] or ( )[ ] */
5690 if (*vr0type == VR_RANGE
5691 && vr1type == VR_RANGE)
5692 *vr0min = vr1min;
5693 else if (*vr0type == VR_ANTI_RANGE
5694 && vr1type == VR_ANTI_RANGE)
5695 *vr0max = vr1max;
5696 else if (*vr0type == VR_ANTI_RANGE
5697 && vr1type == VR_RANGE)
5699 if (TREE_CODE (vr1max) == INTEGER_CST)
5700 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5701 build_int_cst (TREE_TYPE (vr1max), 1));
5702 else
5703 goto give_up;
5705 else if (*vr0type == VR_RANGE
5706 && vr1type == VR_ANTI_RANGE)
5708 if (TREE_CODE (*vr0min) == INTEGER_CST)
5710 *vr0type = vr1type;
5711 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5712 build_int_cst (TREE_TYPE (*vr0min), 1));
5713 *vr0min = vr1min;
5715 else
5716 goto give_up;
5718 else
5719 gcc_unreachable ();
5721 else
5722 goto give_up;
5724 return;
5726 give_up:
5727 *vr0type = VR_VARYING;
5728 *vr0min = NULL_TREE;
5729 *vr0max = NULL_TREE;
5732 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5733 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5734 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5735 possible such range. The resulting range is not canonicalized. */
5737 static void
5738 intersect_ranges (enum value_range_type *vr0type,
5739 tree *vr0min, tree *vr0max,
5740 enum value_range_type vr1type,
5741 tree vr1min, tree vr1max)
5743 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5744 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5746 /* [] is vr0, () is vr1 in the following classification comments. */
5747 if (mineq && maxeq)
5749 /* [( )] */
5750 if (*vr0type == vr1type)
5751 /* Nothing to do for equal ranges. */
5753 else if ((*vr0type == VR_RANGE
5754 && vr1type == VR_ANTI_RANGE)
5755 || (*vr0type == VR_ANTI_RANGE
5756 && vr1type == VR_RANGE))
5758 /* For anti-range with range intersection the result is empty. */
5759 *vr0type = VR_UNDEFINED;
5760 *vr0min = NULL_TREE;
5761 *vr0max = NULL_TREE;
5763 else
5764 gcc_unreachable ();
5766 else if (operand_less_p (*vr0max, vr1min) == 1
5767 || operand_less_p (vr1max, *vr0min) == 1)
5769 /* [ ] ( ) or ( ) [ ]
5770 If the ranges have an empty intersection, the result of the
5771 intersect operation is the range for intersecting an
5772 anti-range with a range or empty when intersecting two ranges. */
5773 if (*vr0type == VR_RANGE
5774 && vr1type == VR_ANTI_RANGE)
5776 else if (*vr0type == VR_ANTI_RANGE
5777 && vr1type == VR_RANGE)
5779 *vr0type = vr1type;
5780 *vr0min = vr1min;
5781 *vr0max = vr1max;
5783 else if (*vr0type == VR_RANGE
5784 && vr1type == VR_RANGE)
5786 *vr0type = VR_UNDEFINED;
5787 *vr0min = NULL_TREE;
5788 *vr0max = NULL_TREE;
5790 else if (*vr0type == VR_ANTI_RANGE
5791 && vr1type == VR_ANTI_RANGE)
5793 /* If the anti-ranges are adjacent to each other merge them. */
5794 if (TREE_CODE (*vr0max) == INTEGER_CST
5795 && TREE_CODE (vr1min) == INTEGER_CST
5796 && operand_less_p (*vr0max, vr1min) == 1
5797 && integer_onep (int_const_binop (MINUS_EXPR,
5798 vr1min, *vr0max)))
5799 *vr0max = vr1max;
5800 else if (TREE_CODE (vr1max) == INTEGER_CST
5801 && TREE_CODE (*vr0min) == INTEGER_CST
5802 && operand_less_p (vr1max, *vr0min) == 1
5803 && integer_onep (int_const_binop (MINUS_EXPR,
5804 *vr0min, vr1max)))
5805 *vr0min = vr1min;
5806 /* Else arbitrarily take VR0. */
5809 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5810 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5812 /* [ ( ) ] or [( ) ] or [ ( )] */
5813 if (*vr0type == VR_RANGE
5814 && vr1type == VR_RANGE)
5816 /* If both are ranges the result is the inner one. */
5817 *vr0type = vr1type;
5818 *vr0min = vr1min;
5819 *vr0max = vr1max;
5821 else if (*vr0type == VR_RANGE
5822 && vr1type == VR_ANTI_RANGE)
5824 /* Choose the right gap if the left one is empty. */
5825 if (mineq)
5827 if (TREE_CODE (vr1max) != INTEGER_CST)
5828 *vr0min = vr1max;
5829 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5830 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5831 *vr0min
5832 = int_const_binop (MINUS_EXPR, vr1max,
5833 build_int_cst (TREE_TYPE (vr1max), -1));
5834 else
5835 *vr0min
5836 = int_const_binop (PLUS_EXPR, vr1max,
5837 build_int_cst (TREE_TYPE (vr1max), 1));
5839 /* Choose the left gap if the right one is empty. */
5840 else if (maxeq)
5842 if (TREE_CODE (vr1min) != INTEGER_CST)
5843 *vr0max = vr1min;
5844 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5845 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5846 *vr0max
5847 = int_const_binop (PLUS_EXPR, vr1min,
5848 build_int_cst (TREE_TYPE (vr1min), -1));
5849 else
5850 *vr0max
5851 = int_const_binop (MINUS_EXPR, vr1min,
5852 build_int_cst (TREE_TYPE (vr1min), 1));
5854 /* Choose the anti-range if the range is effectively varying. */
5855 else if (vrp_val_is_min (*vr0min)
5856 && vrp_val_is_max (*vr0max))
5858 *vr0type = vr1type;
5859 *vr0min = vr1min;
5860 *vr0max = vr1max;
5862 /* Else choose the range. */
5864 else if (*vr0type == VR_ANTI_RANGE
5865 && vr1type == VR_ANTI_RANGE)
5866 /* If both are anti-ranges the result is the outer one. */
5868 else if (*vr0type == VR_ANTI_RANGE
5869 && vr1type == VR_RANGE)
5871 /* The intersection is empty. */
5872 *vr0type = VR_UNDEFINED;
5873 *vr0min = NULL_TREE;
5874 *vr0max = NULL_TREE;
5876 else
5877 gcc_unreachable ();
5879 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5880 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5882 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5883 if (*vr0type == VR_RANGE
5884 && vr1type == VR_RANGE)
5885 /* Choose the inner range. */
5887 else if (*vr0type == VR_ANTI_RANGE
5888 && vr1type == VR_RANGE)
5890 /* Choose the right gap if the left is empty. */
5891 if (mineq)
5893 *vr0type = VR_RANGE;
5894 if (TREE_CODE (*vr0max) != INTEGER_CST)
5895 *vr0min = *vr0max;
5896 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5897 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5898 *vr0min
5899 = int_const_binop (MINUS_EXPR, *vr0max,
5900 build_int_cst (TREE_TYPE (*vr0max), -1));
5901 else
5902 *vr0min
5903 = int_const_binop (PLUS_EXPR, *vr0max,
5904 build_int_cst (TREE_TYPE (*vr0max), 1));
5905 *vr0max = vr1max;
5907 /* Choose the left gap if the right is empty. */
5908 else if (maxeq)
5910 *vr0type = VR_RANGE;
5911 if (TREE_CODE (*vr0min) != INTEGER_CST)
5912 *vr0max = *vr0min;
5913 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5914 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5915 *vr0max
5916 = int_const_binop (PLUS_EXPR, *vr0min,
5917 build_int_cst (TREE_TYPE (*vr0min), -1));
5918 else
5919 *vr0max
5920 = int_const_binop (MINUS_EXPR, *vr0min,
5921 build_int_cst (TREE_TYPE (*vr0min), 1));
5922 *vr0min = vr1min;
5924 /* Choose the anti-range if the range is effectively varying. */
5925 else if (vrp_val_is_min (vr1min)
5926 && vrp_val_is_max (vr1max))
5928 /* Choose the anti-range if it is ~[0,0], that range is special
5929 enough to special case when vr1's range is relatively wide.
5930 At least for types bigger than int - this covers pointers
5931 and arguments to functions like ctz. */
5932 else if (*vr0min == *vr0max
5933 && integer_zerop (*vr0min)
5934 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5935 >= TYPE_PRECISION (integer_type_node))
5936 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5937 && TREE_CODE (vr1max) == INTEGER_CST
5938 && TREE_CODE (vr1min) == INTEGER_CST
5939 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5940 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5942 /* Else choose the range. */
5943 else
5945 *vr0type = vr1type;
5946 *vr0min = vr1min;
5947 *vr0max = vr1max;
5950 else if (*vr0type == VR_ANTI_RANGE
5951 && vr1type == VR_ANTI_RANGE)
5953 /* If both are anti-ranges the result is the outer one. */
5954 *vr0type = vr1type;
5955 *vr0min = vr1min;
5956 *vr0max = vr1max;
5958 else if (vr1type == VR_ANTI_RANGE
5959 && *vr0type == VR_RANGE)
5961 /* The intersection is empty. */
5962 *vr0type = VR_UNDEFINED;
5963 *vr0min = NULL_TREE;
5964 *vr0max = NULL_TREE;
5966 else
5967 gcc_unreachable ();
5969 else if ((operand_less_p (vr1min, *vr0max) == 1
5970 || operand_equal_p (vr1min, *vr0max, 0))
5971 && operand_less_p (*vr0min, vr1min) == 1)
5973 /* [ ( ] ) or [ ]( ) */
5974 if (*vr0type == VR_ANTI_RANGE
5975 && vr1type == VR_ANTI_RANGE)
5976 *vr0max = vr1max;
5977 else if (*vr0type == VR_RANGE
5978 && vr1type == VR_RANGE)
5979 *vr0min = vr1min;
5980 else if (*vr0type == VR_RANGE
5981 && vr1type == VR_ANTI_RANGE)
5983 if (TREE_CODE (vr1min) == INTEGER_CST)
5984 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5985 build_int_cst (TREE_TYPE (vr1min), 1));
5986 else
5987 *vr0max = vr1min;
5989 else if (*vr0type == VR_ANTI_RANGE
5990 && vr1type == VR_RANGE)
5992 *vr0type = VR_RANGE;
5993 if (TREE_CODE (*vr0max) == INTEGER_CST)
5994 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5995 build_int_cst (TREE_TYPE (*vr0max), 1));
5996 else
5997 *vr0min = *vr0max;
5998 *vr0max = vr1max;
6000 else
6001 gcc_unreachable ();
6003 else if ((operand_less_p (*vr0min, vr1max) == 1
6004 || operand_equal_p (*vr0min, vr1max, 0))
6005 && operand_less_p (vr1min, *vr0min) == 1)
6007 /* ( [ ) ] or ( )[ ] */
6008 if (*vr0type == VR_ANTI_RANGE
6009 && vr1type == VR_ANTI_RANGE)
6010 *vr0min = vr1min;
6011 else if (*vr0type == VR_RANGE
6012 && vr1type == VR_RANGE)
6013 *vr0max = vr1max;
6014 else if (*vr0type == VR_RANGE
6015 && vr1type == VR_ANTI_RANGE)
6017 if (TREE_CODE (vr1max) == INTEGER_CST)
6018 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6019 build_int_cst (TREE_TYPE (vr1max), 1));
6020 else
6021 *vr0min = vr1max;
6023 else if (*vr0type == VR_ANTI_RANGE
6024 && vr1type == VR_RANGE)
6026 *vr0type = VR_RANGE;
6027 if (TREE_CODE (*vr0min) == INTEGER_CST)
6028 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6029 build_int_cst (TREE_TYPE (*vr0min), 1));
6030 else
6031 *vr0max = *vr0min;
6032 *vr0min = vr1min;
6034 else
6035 gcc_unreachable ();
6038 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6039 result for the intersection. That's always a conservative
6040 correct estimate unless VR1 is a constant singleton range
6041 in which case we choose that. */
6042 if (vr1type == VR_RANGE
6043 && is_gimple_min_invariant (vr1min)
6044 && vrp_operand_equal_p (vr1min, vr1max))
6046 *vr0type = vr1type;
6047 *vr0min = vr1min;
6048 *vr0max = vr1max;
6051 return;
6055 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6056 in *VR0. This may not be the smallest possible such range. */
6058 static void
6059 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
6061 value_range saved;
6063 /* If either range is VR_VARYING the other one wins. */
6064 if (vr1->type == VR_VARYING)
6065 return;
6066 if (vr0->type == VR_VARYING)
6068 copy_value_range (vr0, vr1);
6069 return;
6072 /* When either range is VR_UNDEFINED the resulting range is
6073 VR_UNDEFINED, too. */
6074 if (vr0->type == VR_UNDEFINED)
6075 return;
6076 if (vr1->type == VR_UNDEFINED)
6078 set_value_range_to_undefined (vr0);
6079 return;
6082 /* Save the original vr0 so we can return it as conservative intersection
6083 result when our worker turns things to varying. */
6084 saved = *vr0;
6085 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6086 vr1->type, vr1->min, vr1->max);
6087 /* Make sure to canonicalize the result though as the inversion of a
6088 VR_RANGE can still be a VR_RANGE. */
6089 set_and_canonicalize_value_range (vr0, vr0->type,
6090 vr0->min, vr0->max, vr0->equiv);
6091 /* If that failed, use the saved original VR0. */
6092 if (vr0->type == VR_VARYING)
6094 *vr0 = saved;
6095 return;
6097 /* If the result is VR_UNDEFINED there is no need to mess with
6098 the equivalencies. */
6099 if (vr0->type == VR_UNDEFINED)
6100 return;
6102 /* The resulting set of equivalences for range intersection is the union of
6103 the two sets. */
6104 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6105 bitmap_ior_into (vr0->equiv, vr1->equiv);
6106 else if (vr1->equiv && !vr0->equiv)
6108 /* All equivalence bitmaps are allocated from the same obstack. So
6109 we can use the obstack associated with VR to allocate vr0->equiv. */
6110 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6111 bitmap_copy (vr0->equiv, vr1->equiv);
6115 void
6116 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6118 if (dump_file && (dump_flags & TDF_DETAILS))
6120 fprintf (dump_file, "Intersecting\n ");
6121 dump_value_range (dump_file, vr0);
6122 fprintf (dump_file, "\nand\n ");
6123 dump_value_range (dump_file, vr1);
6124 fprintf (dump_file, "\n");
6126 vrp_intersect_ranges_1 (vr0, vr1);
6127 if (dump_file && (dump_flags & TDF_DETAILS))
6129 fprintf (dump_file, "to\n ");
6130 dump_value_range (dump_file, vr0);
6131 fprintf (dump_file, "\n");
6135 /* Meet operation for value ranges. Given two value ranges VR0 and
6136 VR1, store in VR0 a range that contains both VR0 and VR1. This
6137 may not be the smallest possible such range. */
6139 static void
6140 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6142 value_range saved;
6144 if (vr0->type == VR_UNDEFINED)
6146 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6147 return;
6150 if (vr1->type == VR_UNDEFINED)
6152 /* VR0 already has the resulting range. */
6153 return;
6156 if (vr0->type == VR_VARYING)
6158 /* Nothing to do. VR0 already has the resulting range. */
6159 return;
6162 if (vr1->type == VR_VARYING)
6164 set_value_range_to_varying (vr0);
6165 return;
6168 saved = *vr0;
6169 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6170 vr1->type, vr1->min, vr1->max);
6171 if (vr0->type == VR_VARYING)
6173 /* Failed to find an efficient meet. Before giving up and setting
6174 the result to VARYING, see if we can at least derive a useful
6175 anti-range. FIXME, all this nonsense about distinguishing
6176 anti-ranges from ranges is necessary because of the odd
6177 semantics of range_includes_zero_p and friends. */
6178 if (((saved.type == VR_RANGE
6179 && range_includes_zero_p (saved.min, saved.max) == 0)
6180 || (saved.type == VR_ANTI_RANGE
6181 && range_includes_zero_p (saved.min, saved.max) == 1))
6182 && ((vr1->type == VR_RANGE
6183 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6184 || (vr1->type == VR_ANTI_RANGE
6185 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6187 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6189 /* Since this meet operation did not result from the meeting of
6190 two equivalent names, VR0 cannot have any equivalences. */
6191 if (vr0->equiv)
6192 bitmap_clear (vr0->equiv);
6193 return;
6196 set_value_range_to_varying (vr0);
6197 return;
6199 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6200 vr0->equiv);
6201 if (vr0->type == VR_VARYING)
6202 return;
6204 /* The resulting set of equivalences is always the intersection of
6205 the two sets. */
6206 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6207 bitmap_and_into (vr0->equiv, vr1->equiv);
6208 else if (vr0->equiv && !vr1->equiv)
6209 bitmap_clear (vr0->equiv);
6212 void
6213 vrp_meet (value_range *vr0, const value_range *vr1)
6215 if (dump_file && (dump_flags & TDF_DETAILS))
6217 fprintf (dump_file, "Meeting\n ");
6218 dump_value_range (dump_file, vr0);
6219 fprintf (dump_file, "\nand\n ");
6220 dump_value_range (dump_file, vr1);
6221 fprintf (dump_file, "\n");
6223 vrp_meet_1 (vr0, vr1);
6224 if (dump_file && (dump_flags & TDF_DETAILS))
6226 fprintf (dump_file, "to\n ");
6227 dump_value_range (dump_file, vr0);
6228 fprintf (dump_file, "\n");
6233 /* Visit all arguments for PHI node PHI that flow through executable
6234 edges. If a valid value range can be derived from all the incoming
6235 value ranges, set a new range for the LHS of PHI. */
6237 enum ssa_prop_result
6238 vrp_prop::visit_phi (gphi *phi)
6240 tree lhs = PHI_RESULT (phi);
6241 value_range vr_result = VR_INITIALIZER;
6242 extract_range_from_phi_node (phi, &vr_result);
6243 if (update_value_range (lhs, &vr_result))
6245 if (dump_file && (dump_flags & TDF_DETAILS))
6247 fprintf (dump_file, "Found new range for ");
6248 print_generic_expr (dump_file, lhs);
6249 fprintf (dump_file, ": ");
6250 dump_value_range (dump_file, &vr_result);
6251 fprintf (dump_file, "\n");
6254 if (vr_result.type == VR_VARYING)
6255 return SSA_PROP_VARYING;
6257 return SSA_PROP_INTERESTING;
6260 /* Nothing changed, don't add outgoing edges. */
6261 return SSA_PROP_NOT_INTERESTING;
6264 class vrp_folder : public substitute_and_fold_engine
6266 public:
6267 tree get_value (tree) FINAL OVERRIDE;
6268 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6269 bool fold_predicate_in (gimple_stmt_iterator *);
6271 class vr_values *vr_values;
6273 /* Delegators. */
6274 tree vrp_evaluate_conditional (tree_code code, tree op0,
6275 tree op1, gimple *stmt)
6276 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6277 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6278 { return vr_values->simplify_stmt_using_ranges (gsi); }
6279 tree op_with_constant_singleton_value_range (tree op)
6280 { return vr_values->op_with_constant_singleton_value_range (op); }
6283 /* If the statement pointed by SI has a predicate whose value can be
6284 computed using the value range information computed by VRP, compute
6285 its value and return true. Otherwise, return false. */
6287 bool
6288 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6290 bool assignment_p = false;
6291 tree val;
6292 gimple *stmt = gsi_stmt (*si);
6294 if (is_gimple_assign (stmt)
6295 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6297 assignment_p = true;
6298 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6299 gimple_assign_rhs1 (stmt),
6300 gimple_assign_rhs2 (stmt),
6301 stmt);
6303 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6304 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6305 gimple_cond_lhs (cond_stmt),
6306 gimple_cond_rhs (cond_stmt),
6307 stmt);
6308 else
6309 return false;
6311 if (val)
6313 if (assignment_p)
6314 val = fold_convert (gimple_expr_type (stmt), val);
6316 if (dump_file)
6318 fprintf (dump_file, "Folding predicate ");
6319 print_gimple_expr (dump_file, stmt, 0);
6320 fprintf (dump_file, " to ");
6321 print_generic_expr (dump_file, val);
6322 fprintf (dump_file, "\n");
6325 if (is_gimple_assign (stmt))
6326 gimple_assign_set_rhs_from_tree (si, val);
6327 else
6329 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6330 gcond *cond_stmt = as_a <gcond *> (stmt);
6331 if (integer_zerop (val))
6332 gimple_cond_make_false (cond_stmt);
6333 else if (integer_onep (val))
6334 gimple_cond_make_true (cond_stmt);
6335 else
6336 gcc_unreachable ();
6339 return true;
6342 return false;
6345 /* Callback for substitute_and_fold folding the stmt at *SI. */
6347 bool
6348 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6350 if (fold_predicate_in (si))
6351 return true;
6353 return simplify_stmt_using_ranges (si);
6356 /* If OP has a value range with a single constant value return that,
6357 otherwise return NULL_TREE. This returns OP itself if OP is a
6358 constant.
6360 Implemented as a pure wrapper right now, but this will change. */
6362 tree
6363 vrp_folder::get_value (tree op)
6365 return op_with_constant_singleton_value_range (op);
6368 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6369 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6370 BB. If no such ASSERT_EXPR is found, return OP. */
6372 static tree
6373 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6375 imm_use_iterator imm_iter;
6376 gimple *use_stmt;
6377 use_operand_p use_p;
6379 if (TREE_CODE (op) == SSA_NAME)
6381 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6383 use_stmt = USE_STMT (use_p);
6384 if (use_stmt != stmt
6385 && gimple_assign_single_p (use_stmt)
6386 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6387 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6388 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6389 return gimple_assign_lhs (use_stmt);
6392 return op;
6395 /* A hack. */
6396 static class vr_values *x_vr_values;
6398 /* A trivial wrapper so that we can present the generic jump threading
6399 code with a simple API for simplifying statements. STMT is the
6400 statement we want to simplify, WITHIN_STMT provides the location
6401 for any overflow warnings. */
6403 static tree
6404 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6405 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6406 basic_block bb)
6408 /* First see if the conditional is in the hash table. */
6409 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6410 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6411 return cached_lhs;
6413 vr_values *vr_values = x_vr_values;
6414 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6416 tree op0 = gimple_cond_lhs (cond_stmt);
6417 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6419 tree op1 = gimple_cond_rhs (cond_stmt);
6420 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6422 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6423 op0, op1, within_stmt);
6426 /* We simplify a switch statement by trying to determine which case label
6427 will be taken. If we are successful then we return the corresponding
6428 CASE_LABEL_EXPR. */
6429 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6431 tree op = gimple_switch_index (switch_stmt);
6432 if (TREE_CODE (op) != SSA_NAME)
6433 return NULL_TREE;
6435 op = lhs_of_dominating_assert (op, bb, stmt);
6437 value_range *vr = vr_values->get_value_range (op);
6438 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6439 || symbolic_range_p (vr))
6440 return NULL_TREE;
6442 if (vr->type == VR_RANGE)
6444 size_t i, j;
6445 /* Get the range of labels that contain a part of the operand's
6446 value range. */
6447 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6449 /* Is there only one such label? */
6450 if (i == j)
6452 tree label = gimple_switch_label (switch_stmt, i);
6454 /* The i'th label will be taken only if the value range of the
6455 operand is entirely within the bounds of this label. */
6456 if (CASE_HIGH (label) != NULL_TREE
6457 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6458 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6459 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6460 && tree_int_cst_equal (vr->min, vr->max)))
6461 return label;
6464 /* If there are no such labels then the default label will be
6465 taken. */
6466 if (i > j)
6467 return gimple_switch_label (switch_stmt, 0);
6470 if (vr->type == VR_ANTI_RANGE)
6472 unsigned n = gimple_switch_num_labels (switch_stmt);
6473 tree min_label = gimple_switch_label (switch_stmt, 1);
6474 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6476 /* The default label will be taken only if the anti-range of the
6477 operand is entirely outside the bounds of all the (non-default)
6478 case labels. */
6479 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6480 && (CASE_HIGH (max_label) != NULL_TREE
6481 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6482 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6483 return gimple_switch_label (switch_stmt, 0);
6486 return NULL_TREE;
6489 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6491 tree lhs = gimple_assign_lhs (assign_stmt);
6492 if (TREE_CODE (lhs) == SSA_NAME
6493 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6494 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6495 && stmt_interesting_for_vrp (stmt))
6497 edge dummy_e;
6498 tree dummy_tree;
6499 value_range new_vr = VR_INITIALIZER;
6500 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6501 &dummy_tree, &new_vr);
6502 if (range_int_cst_singleton_p (&new_vr))
6503 return new_vr.min;
6507 return NULL_TREE;
6510 class vrp_dom_walker : public dom_walker
6512 public:
6513 vrp_dom_walker (cdi_direction direction,
6514 class const_and_copies *const_and_copies,
6515 class avail_exprs_stack *avail_exprs_stack)
6516 : dom_walker (direction, REACHABLE_BLOCKS),
6517 m_const_and_copies (const_and_copies),
6518 m_avail_exprs_stack (avail_exprs_stack),
6519 m_dummy_cond (NULL) {}
6521 virtual edge before_dom_children (basic_block);
6522 virtual void after_dom_children (basic_block);
6524 class vr_values *vr_values;
6526 private:
6527 class const_and_copies *m_const_and_copies;
6528 class avail_exprs_stack *m_avail_exprs_stack;
6530 gcond *m_dummy_cond;
6534 /* Called before processing dominator children of BB. We want to look
6535 at ASSERT_EXPRs and record information from them in the appropriate
6536 tables.
6538 We could look at other statements here. It's not seen as likely
6539 to significantly increase the jump threads we discover. */
6541 edge
6542 vrp_dom_walker::before_dom_children (basic_block bb)
6544 gimple_stmt_iterator gsi;
6546 m_avail_exprs_stack->push_marker ();
6547 m_const_and_copies->push_marker ();
6548 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6550 gimple *stmt = gsi_stmt (gsi);
6551 if (gimple_assign_single_p (stmt)
6552 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6554 tree rhs1 = gimple_assign_rhs1 (stmt);
6555 tree cond = TREE_OPERAND (rhs1, 1);
6556 tree inverted = invert_truthvalue (cond);
6557 vec<cond_equivalence> p;
6558 p.create (3);
6559 record_conditions (&p, cond, inverted);
6560 for (unsigned int i = 0; i < p.length (); i++)
6561 m_avail_exprs_stack->record_cond (&p[i]);
6563 tree lhs = gimple_assign_lhs (stmt);
6564 m_const_and_copies->record_const_or_copy (lhs,
6565 TREE_OPERAND (rhs1, 0));
6566 p.release ();
6567 continue;
6569 break;
6571 return NULL;
6574 /* Called after processing dominator children of BB. This is where we
6575 actually call into the threader. */
6576 void
6577 vrp_dom_walker::after_dom_children (basic_block bb)
6579 if (!m_dummy_cond)
6580 m_dummy_cond = gimple_build_cond (NE_EXPR,
6581 integer_zero_node, integer_zero_node,
6582 NULL, NULL);
6584 x_vr_values = vr_values;
6585 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6586 m_avail_exprs_stack, NULL,
6587 simplify_stmt_for_jump_threading);
6588 x_vr_values = NULL;
6590 m_avail_exprs_stack->pop_to_marker ();
6591 m_const_and_copies->pop_to_marker ();
6594 /* Blocks which have more than one predecessor and more than
6595 one successor present jump threading opportunities, i.e.,
6596 when the block is reached from a specific predecessor, we
6597 may be able to determine which of the outgoing edges will
6598 be traversed. When this optimization applies, we are able
6599 to avoid conditionals at runtime and we may expose secondary
6600 optimization opportunities.
6602 This routine is effectively a driver for the generic jump
6603 threading code. It basically just presents the generic code
6604 with edges that may be suitable for jump threading.
6606 Unlike DOM, we do not iterate VRP if jump threading was successful.
6607 While iterating may expose new opportunities for VRP, it is expected
6608 those opportunities would be very limited and the compile time cost
6609 to expose those opportunities would be significant.
6611 As jump threading opportunities are discovered, they are registered
6612 for later realization. */
6614 static void
6615 identify_jump_threads (class vr_values *vr_values)
6617 int i;
6618 edge e;
6620 /* Ugh. When substituting values earlier in this pass we can
6621 wipe the dominance information. So rebuild the dominator
6622 information as we need it within the jump threading code. */
6623 calculate_dominance_info (CDI_DOMINATORS);
6625 /* We do not allow VRP information to be used for jump threading
6626 across a back edge in the CFG. Otherwise it becomes too
6627 difficult to avoid eliminating loop exit tests. Of course
6628 EDGE_DFS_BACK is not accurate at this time so we have to
6629 recompute it. */
6630 mark_dfs_back_edges ();
6632 /* Do not thread across edges we are about to remove. Just marking
6633 them as EDGE_IGNORE will do. */
6634 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6635 e->flags |= EDGE_IGNORE;
6637 /* Allocate our unwinder stack to unwind any temporary equivalences
6638 that might be recorded. */
6639 const_and_copies *equiv_stack = new const_and_copies ();
6641 hash_table<expr_elt_hasher> *avail_exprs
6642 = new hash_table<expr_elt_hasher> (1024);
6643 avail_exprs_stack *avail_exprs_stack
6644 = new class avail_exprs_stack (avail_exprs);
6646 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6647 walker.vr_values = vr_values;
6648 walker.walk (cfun->cfg->x_entry_block_ptr);
6650 /* Clear EDGE_IGNORE. */
6651 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6652 e->flags &= ~EDGE_IGNORE;
6654 /* We do not actually update the CFG or SSA graphs at this point as
6655 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6656 handle ASSERT_EXPRs gracefully. */
6657 delete equiv_stack;
6658 delete avail_exprs;
6659 delete avail_exprs_stack;
6662 /* Traverse all the blocks folding conditionals with known ranges. */
6664 void
6665 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6667 size_t i;
6669 /* We have completed propagating through the lattice. */
6670 vr_values.set_lattice_propagation_complete ();
6672 if (dump_file)
6674 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6675 vr_values.dump_all_value_ranges (dump_file);
6676 fprintf (dump_file, "\n");
6679 /* Set value range to non pointer SSA_NAMEs. */
6680 for (i = 0; i < num_ssa_names; i++)
6682 tree name = ssa_name (i);
6683 if (!name)
6684 continue;
6686 value_range *vr = get_value_range (name);
6687 if (!name
6688 || (vr->type == VR_VARYING)
6689 || (vr->type == VR_UNDEFINED)
6690 || (TREE_CODE (vr->min) != INTEGER_CST)
6691 || (TREE_CODE (vr->max) != INTEGER_CST))
6692 continue;
6694 if (POINTER_TYPE_P (TREE_TYPE (name))
6695 && ((vr->type == VR_RANGE
6696 && range_includes_zero_p (vr->min, vr->max) == 0)
6697 || (vr->type == VR_ANTI_RANGE
6698 && range_includes_zero_p (vr->min, vr->max) == 1)))
6699 set_ptr_nonnull (name);
6700 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6701 set_range_info (name, vr->type,
6702 wi::to_wide (vr->min),
6703 wi::to_wide (vr->max));
6706 /* If we're checking array refs, we want to merge information on
6707 the executability of each edge between vrp_folder and the
6708 check_array_bounds_dom_walker: each can clear the
6709 EDGE_EXECUTABLE flag on edges, in different ways.
6711 Hence, if we're going to call check_all_array_refs, set
6712 the flag on every edge now, rather than in
6713 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6714 it from some edges. */
6715 if (warn_array_bounds && warn_array_bounds_p)
6716 set_all_edges_as_executable (cfun);
6718 class vrp_folder vrp_folder;
6719 vrp_folder.vr_values = &vr_values;
6720 vrp_folder.substitute_and_fold ();
6722 if (warn_array_bounds && warn_array_bounds_p)
6723 check_all_array_refs ();
6726 /* Main entry point to VRP (Value Range Propagation). This pass is
6727 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6728 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6729 Programming Language Design and Implementation, pp. 67-78, 1995.
6730 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6732 This is essentially an SSA-CCP pass modified to deal with ranges
6733 instead of constants.
6735 While propagating ranges, we may find that two or more SSA name
6736 have equivalent, though distinct ranges. For instance,
6738 1 x_9 = p_3->a;
6739 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6740 3 if (p_4 == q_2)
6741 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6742 5 endif
6743 6 if (q_2)
6745 In the code above, pointer p_5 has range [q_2, q_2], but from the
6746 code we can also determine that p_5 cannot be NULL and, if q_2 had
6747 a non-varying range, p_5's range should also be compatible with it.
6749 These equivalences are created by two expressions: ASSERT_EXPR and
6750 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6751 result of another assertion, then we can use the fact that p_5 and
6752 p_4 are equivalent when evaluating p_5's range.
6754 Together with value ranges, we also propagate these equivalences
6755 between names so that we can take advantage of information from
6756 multiple ranges when doing final replacement. Note that this
6757 equivalency relation is transitive but not symmetric.
6759 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6760 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6761 in contexts where that assertion does not hold (e.g., in line 6).
6763 TODO, the main difference between this pass and Patterson's is that
6764 we do not propagate edge probabilities. We only compute whether
6765 edges can be taken or not. That is, instead of having a spectrum
6766 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6767 DON'T KNOW. In the future, it may be worthwhile to propagate
6768 probabilities to aid branch prediction. */
6770 static unsigned int
6771 execute_vrp (bool warn_array_bounds_p)
6773 int i;
6774 edge e;
6775 switch_update *su;
6777 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6778 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6779 scev_initialize ();
6781 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6782 Inserting assertions may split edges which will invalidate
6783 EDGE_DFS_BACK. */
6784 insert_range_assertions ();
6786 to_remove_edges.create (10);
6787 to_update_switch_stmts.create (5);
6788 threadedge_initialize_values ();
6790 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6791 mark_dfs_back_edges ();
6793 class vrp_prop vrp_prop;
6794 vrp_prop.vrp_initialize ();
6795 vrp_prop.ssa_propagate ();
6796 vrp_prop.vrp_finalize (warn_array_bounds_p);
6798 /* We must identify jump threading opportunities before we release
6799 the datastructures built by VRP. */
6800 identify_jump_threads (&vrp_prop.vr_values);
6802 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6803 was set by a type conversion can often be rewritten to use the
6804 RHS of the type conversion.
6806 However, doing so inhibits jump threading through the comparison.
6807 So that transformation is not performed until after jump threading
6808 is complete. */
6809 basic_block bb;
6810 FOR_EACH_BB_FN (bb, cfun)
6812 gimple *last = last_stmt (bb);
6813 if (last && gimple_code (last) == GIMPLE_COND)
6814 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6817 free_numbers_of_iterations_estimates (cfun);
6819 /* ASSERT_EXPRs must be removed before finalizing jump threads
6820 as finalizing jump threads calls the CFG cleanup code which
6821 does not properly handle ASSERT_EXPRs. */
6822 remove_range_assertions ();
6824 /* If we exposed any new variables, go ahead and put them into
6825 SSA form now, before we handle jump threading. This simplifies
6826 interactions between rewriting of _DECL nodes into SSA form
6827 and rewriting SSA_NAME nodes into SSA form after block
6828 duplication and CFG manipulation. */
6829 update_ssa (TODO_update_ssa);
6831 /* We identified all the jump threading opportunities earlier, but could
6832 not transform the CFG at that time. This routine transforms the
6833 CFG and arranges for the dominator tree to be rebuilt if necessary.
6835 Note the SSA graph update will occur during the normal TODO
6836 processing by the pass manager. */
6837 thread_through_all_blocks (false);
6839 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6840 CFG in a broken state and requires a cfg_cleanup run. */
6841 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6842 remove_edge (e);
6843 /* Update SWITCH_EXPR case label vector. */
6844 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6846 size_t j;
6847 size_t n = TREE_VEC_LENGTH (su->vec);
6848 tree label;
6849 gimple_switch_set_num_labels (su->stmt, n);
6850 for (j = 0; j < n; j++)
6851 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
6852 /* As we may have replaced the default label with a regular one
6853 make sure to make it a real default label again. This ensures
6854 optimal expansion. */
6855 label = gimple_switch_label (su->stmt, 0);
6856 CASE_LOW (label) = NULL_TREE;
6857 CASE_HIGH (label) = NULL_TREE;
6860 if (to_remove_edges.length () > 0)
6862 free_dominance_info (CDI_DOMINATORS);
6863 loops_state_set (LOOPS_NEED_FIXUP);
6866 to_remove_edges.release ();
6867 to_update_switch_stmts.release ();
6868 threadedge_finalize_values ();
6870 scev_finalize ();
6871 loop_optimizer_finalize ();
6872 return 0;
6875 namespace {
6877 const pass_data pass_data_vrp =
6879 GIMPLE_PASS, /* type */
6880 "vrp", /* name */
6881 OPTGROUP_NONE, /* optinfo_flags */
6882 TV_TREE_VRP, /* tv_id */
6883 PROP_ssa, /* properties_required */
6884 0, /* properties_provided */
6885 0, /* properties_destroyed */
6886 0, /* todo_flags_start */
6887 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6890 class pass_vrp : public gimple_opt_pass
6892 public:
6893 pass_vrp (gcc::context *ctxt)
6894 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6897 /* opt_pass methods: */
6898 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6899 void set_pass_param (unsigned int n, bool param)
6901 gcc_assert (n == 0);
6902 warn_array_bounds_p = param;
6904 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6905 virtual unsigned int execute (function *)
6906 { return execute_vrp (warn_array_bounds_p); }
6908 private:
6909 bool warn_array_bounds_p;
6910 }; // class pass_vrp
6912 } // anon namespace
6914 gimple_opt_pass *
6915 make_pass_vrp (gcc::context *ctxt)
6917 return new pass_vrp (ctxt);
6921 /* Worker for determine_value_range. */
6923 static void
6924 determine_value_range_1 (value_range *vr, tree expr)
6926 if (BINARY_CLASS_P (expr))
6928 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6929 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6930 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6931 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6932 &vr0, &vr1);
6934 else if (UNARY_CLASS_P (expr))
6936 value_range vr0 = VR_INITIALIZER;
6937 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6938 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6939 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6941 else if (TREE_CODE (expr) == INTEGER_CST)
6942 set_value_range_to_value (vr, expr, NULL);
6943 else
6945 value_range_type kind;
6946 wide_int min, max;
6947 /* For SSA names try to extract range info computed by VRP. Otherwise
6948 fall back to varying. */
6949 if (TREE_CODE (expr) == SSA_NAME
6950 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6951 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6952 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6953 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6954 else
6955 set_value_range_to_varying (vr);
6959 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6960 the determined range type. */
6962 value_range_type
6963 determine_value_range (tree expr, wide_int *min, wide_int *max)
6965 value_range vr = VR_INITIALIZER;
6966 determine_value_range_1 (&vr, expr);
6967 if ((vr.type == VR_RANGE
6968 || vr.type == VR_ANTI_RANGE)
6969 && !symbolic_range_p (&vr))
6971 *min = wi::to_wide (vr.min);
6972 *max = wi::to_wide (vr.max);
6973 return vr.type;
6976 return VR_VARYING;