2018-08-20 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / tree-vrp.c
blob2ddb0c2c197e9ade56ed67ac266d84d33171ee35
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 && code != POINTER_PLUS_EXPR
1441 && (vr0.type == VR_VARYING
1442 || vr1.type == VR_VARYING
1443 || vr0.type != vr1.type
1444 || symbolic_range_p (&vr0)
1445 || symbolic_range_p (&vr1)))
1447 set_value_range_to_varying (vr);
1448 return;
1451 /* Now evaluate the expression to determine the new range. */
1452 if (POINTER_TYPE_P (expr_type))
1454 if (code == MIN_EXPR || code == MAX_EXPR)
1456 /* For MIN/MAX expressions with pointers, we only care about
1457 nullness, if both are non null, then the result is nonnull.
1458 If both are null, then the result is null. Otherwise they
1459 are varying. */
1460 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1461 set_value_range_to_nonnull (vr, expr_type);
1462 else if (range_is_null (&vr0) && range_is_null (&vr1))
1463 set_value_range_to_null (vr, expr_type);
1464 else
1465 set_value_range_to_varying (vr);
1467 else if (code == POINTER_PLUS_EXPR)
1469 /* For pointer types, we are really only interested in asserting
1470 whether the expression evaluates to non-NULL. */
1471 if (range_is_nonnull (&vr0)
1472 || range_is_nonnull (&vr1)
1473 || (vr1.type == VR_RANGE
1474 && !symbolic_range_p (&vr1)
1475 && !range_includes_zero_p (vr1.min, vr1.max)))
1476 set_value_range_to_nonnull (vr, expr_type);
1477 else if (range_is_null (&vr0) && range_is_null (&vr1))
1478 set_value_range_to_null (vr, expr_type);
1479 else
1480 set_value_range_to_varying (vr);
1482 else if (code == BIT_AND_EXPR)
1484 /* For pointer types, we are really only interested in asserting
1485 whether the expression evaluates to non-NULL. */
1486 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1487 set_value_range_to_nonnull (vr, expr_type);
1488 else if (range_is_null (&vr0) || range_is_null (&vr1))
1489 set_value_range_to_null (vr, expr_type);
1490 else
1491 set_value_range_to_varying (vr);
1493 else
1494 set_value_range_to_varying (vr);
1496 return;
1499 /* For integer ranges, apply the operation to each end of the
1500 range and see what we end up with. */
1501 if (code == PLUS_EXPR || code == MINUS_EXPR)
1503 const bool minus_p = (code == MINUS_EXPR);
1504 tree min_op0 = vr0.min;
1505 tree min_op1 = minus_p ? vr1.max : vr1.min;
1506 tree max_op0 = vr0.max;
1507 tree max_op1 = minus_p ? vr1.min : vr1.max;
1508 tree sym_min_op0 = NULL_TREE;
1509 tree sym_min_op1 = NULL_TREE;
1510 tree sym_max_op0 = NULL_TREE;
1511 tree sym_max_op1 = NULL_TREE;
1512 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1514 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1516 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1517 single-symbolic ranges, try to compute the precise resulting range,
1518 but only if we know that this resulting range will also be constant
1519 or single-symbolic. */
1520 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1521 && (TREE_CODE (min_op0) == INTEGER_CST
1522 || (sym_min_op0
1523 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1524 && (TREE_CODE (min_op1) == INTEGER_CST
1525 || (sym_min_op1
1526 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1527 && (!(sym_min_op0 && sym_min_op1)
1528 || (sym_min_op0 == sym_min_op1
1529 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1530 && (TREE_CODE (max_op0) == INTEGER_CST
1531 || (sym_max_op0
1532 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1533 && (TREE_CODE (max_op1) == INTEGER_CST
1534 || (sym_max_op1
1535 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1536 && (!(sym_max_op0 && sym_max_op1)
1537 || (sym_max_op0 == sym_max_op1
1538 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1540 wide_int wmin, wmax;
1541 wi::overflow_type min_ovf = wi::OVF_NONE;
1542 wi::overflow_type max_ovf = wi::OVF_NONE;
1544 /* Build the bounds. */
1545 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1546 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1548 /* If we have overflow for the constant part and the resulting
1549 range will be symbolic, drop to VR_VARYING. */
1550 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1551 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1553 set_value_range_to_varying (vr);
1554 return;
1557 /* Adjust the range for possible overflow. */
1558 set_value_range_with_overflow (*vr, expr_type,
1559 wmin, wmax, min_ovf, max_ovf);
1560 if (vr->type == VR_VARYING)
1561 return;
1563 /* Build the symbolic bounds if needed. */
1564 adjust_symbolic_bound (vr->min, code, expr_type,
1565 sym_min_op0, sym_min_op1,
1566 neg_min_op0, neg_min_op1);
1567 adjust_symbolic_bound (vr->max, code, expr_type,
1568 sym_max_op0, sym_max_op1,
1569 neg_max_op0, neg_max_op1);
1570 /* ?? It would probably be cleaner to eliminate min/max/type
1571 entirely and hold these values in VR directly. */
1572 min = vr->min;
1573 max = vr->max;
1574 type = vr->type;
1576 else
1578 /* For other cases, for example if we have a PLUS_EXPR with two
1579 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1580 to compute a precise range for such a case.
1581 ??? General even mixed range kind operations can be expressed
1582 by for example transforming ~[3, 5] + [1, 2] to range-only
1583 operations and a union primitive:
1584 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1585 [-INF+1, 4] U [6, +INF(OVF)]
1586 though usually the union is not exactly representable with
1587 a single range or anti-range as the above is
1588 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1589 but one could use a scheme similar to equivalences for this. */
1590 set_value_range_to_varying (vr);
1591 return;
1594 else if (code == MIN_EXPR
1595 || code == MAX_EXPR)
1597 if (vr0.type == VR_RANGE
1598 && !symbolic_range_p (&vr0))
1600 type = VR_RANGE;
1601 if (vr1.type == VR_RANGE
1602 && !symbolic_range_p (&vr1))
1604 /* For operations that make the resulting range directly
1605 proportional to the original ranges, apply the operation to
1606 the same end of each range. */
1607 min = int_const_binop (code, vr0.min, vr1.min);
1608 max = int_const_binop (code, vr0.max, vr1.max);
1610 else if (code == MIN_EXPR)
1612 min = vrp_val_min (expr_type);
1613 max = vr0.max;
1615 else if (code == MAX_EXPR)
1617 min = vr0.min;
1618 max = vrp_val_max (expr_type);
1621 else if (vr1.type == VR_RANGE
1622 && !symbolic_range_p (&vr1))
1624 type = VR_RANGE;
1625 if (code == MIN_EXPR)
1627 min = vrp_val_min (expr_type);
1628 max = vr1.max;
1630 else if (code == MAX_EXPR)
1632 min = vr1.min;
1633 max = vrp_val_max (expr_type);
1636 else
1638 set_value_range_to_varying (vr);
1639 return;
1642 else if (code == MULT_EXPR)
1644 if (!range_int_cst_p (&vr0)
1645 || !range_int_cst_p (&vr1))
1647 set_value_range_to_varying (vr);
1648 return;
1650 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1651 return;
1653 else if (code == RSHIFT_EXPR
1654 || code == LSHIFT_EXPR)
1656 if (range_int_cst_p (&vr1)
1657 && !vrp_shift_undefined_p (vr1, prec))
1659 if (code == RSHIFT_EXPR)
1661 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1662 useful ranges just from the shift count. E.g.
1663 x >> 63 for signed 64-bit x is always [-1, 0]. */
1664 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1666 vr0.type = type = VR_RANGE;
1667 vr0.min = vrp_val_min (expr_type);
1668 vr0.max = vrp_val_max (expr_type);
1670 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1671 return;
1673 else if (code == LSHIFT_EXPR
1674 && range_int_cst_p (&vr0))
1676 wide_int res_lb, res_ub;
1677 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1678 wi::to_wide (vr0.min),
1679 wi::to_wide (vr0.max),
1680 wi::to_wide (vr1.min),
1681 wi::to_wide (vr1.max),
1682 TYPE_OVERFLOW_UNDEFINED (expr_type),
1683 TYPE_OVERFLOW_WRAPS (expr_type)))
1685 min = wide_int_to_tree (expr_type, res_lb);
1686 max = wide_int_to_tree (expr_type, res_ub);
1687 set_and_canonicalize_value_range (vr, VR_RANGE,
1688 min, max, NULL);
1689 return;
1693 set_value_range_to_varying (vr);
1694 return;
1696 else if (code == TRUNC_DIV_EXPR
1697 || code == FLOOR_DIV_EXPR
1698 || code == CEIL_DIV_EXPR
1699 || code == EXACT_DIV_EXPR
1700 || code == ROUND_DIV_EXPR)
1702 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1704 /* For division, if op1 has VR_RANGE but op0 does not, something
1705 can be deduced just from that range. Say [min, max] / [4, max]
1706 gives [min / 4, max / 4] range. */
1707 if (vr1.type == VR_RANGE
1708 && !symbolic_range_p (&vr1)
1709 && range_includes_zero_p (vr1.min, vr1.max) == 0)
1711 vr0.type = type = VR_RANGE;
1712 vr0.min = vrp_val_min (expr_type);
1713 vr0.max = vrp_val_max (expr_type);
1715 else
1717 set_value_range_to_varying (vr);
1718 return;
1722 /* For divisions, if flag_non_call_exceptions is true, we must
1723 not eliminate a division by zero. */
1724 if (cfun->can_throw_non_call_exceptions
1725 && (vr1.type != VR_RANGE
1726 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1728 set_value_range_to_varying (vr);
1729 return;
1732 /* For divisions, if op0 is VR_RANGE, we can deduce a range
1733 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
1734 include 0. */
1735 if (vr0.type == VR_RANGE
1736 && (vr1.type != VR_RANGE
1737 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1739 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
1740 int cmp;
1742 min = NULL_TREE;
1743 max = NULL_TREE;
1744 if (TYPE_UNSIGNED (expr_type)
1745 || value_range_nonnegative_p (&vr1))
1747 /* For unsigned division or when divisor is known
1748 to be non-negative, the range has to cover
1749 all numbers from 0 to max for positive max
1750 and all numbers from min to 0 for negative min. */
1751 cmp = compare_values (vr0.max, zero);
1752 if (cmp == -1)
1754 /* When vr0.max < 0, vr1.min != 0 and value
1755 ranges for dividend and divisor are available. */
1756 if (vr1.type == VR_RANGE
1757 && !symbolic_range_p (&vr0)
1758 && !symbolic_range_p (&vr1)
1759 && compare_values (vr1.min, zero) != 0)
1760 max = int_const_binop (code, vr0.max, vr1.min);
1761 else
1762 max = zero;
1764 else if (cmp == 0 || cmp == 1)
1765 max = vr0.max;
1766 else
1767 type = VR_VARYING;
1768 cmp = compare_values (vr0.min, zero);
1769 if (cmp == 1)
1771 /* For unsigned division when value ranges for dividend
1772 and divisor are available. */
1773 if (vr1.type == VR_RANGE
1774 && !symbolic_range_p (&vr0)
1775 && !symbolic_range_p (&vr1)
1776 && compare_values (vr1.max, zero) != 0)
1777 min = int_const_binop (code, vr0.min, vr1.max);
1778 else
1779 min = zero;
1781 else if (cmp == 0 || cmp == -1)
1782 min = vr0.min;
1783 else
1784 type = VR_VARYING;
1786 else
1788 /* Otherwise the range is -max .. max or min .. -min
1789 depending on which bound is bigger in absolute value,
1790 as the division can change the sign. */
1791 abs_extent_range (vr, vr0.min, vr0.max);
1792 return;
1794 if (type == VR_VARYING)
1796 set_value_range_to_varying (vr);
1797 return;
1800 else if (range_int_cst_p (&vr0) && range_int_cst_p (&vr1))
1802 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1803 return;
1806 else if (code == TRUNC_MOD_EXPR)
1808 if (range_is_null (&vr1))
1810 set_value_range_to_undefined (vr);
1811 return;
1813 wide_int wmin, wmax, tmp;
1814 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1815 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1816 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1817 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1818 vr0_min, vr0_max, vr1_min, vr1_max);
1819 min = wide_int_to_tree (expr_type, wmin);
1820 max = wide_int_to_tree (expr_type, wmax);
1821 set_value_range (vr, VR_RANGE, min, max, NULL);
1822 return;
1824 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1826 if (vrp_can_optimize_bit_op (vr, code, &vr0, &vr1))
1827 return;
1829 wide_int may_be_nonzero0, may_be_nonzero1;
1830 wide_int must_be_nonzero0, must_be_nonzero1;
1831 wide_int wmin, wmax;
1832 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1833 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1834 &may_be_nonzero0, &must_be_nonzero0);
1835 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1836 &may_be_nonzero1, &must_be_nonzero1);
1837 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1838 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1839 if (code == BIT_AND_EXPR)
1841 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1842 vr0_min, vr0_max,
1843 vr1_min, vr1_max,
1844 must_be_nonzero0,
1845 may_be_nonzero0,
1846 must_be_nonzero1,
1847 may_be_nonzero1))
1849 min = wide_int_to_tree (expr_type, wmin);
1850 max = wide_int_to_tree (expr_type, wmax);
1851 set_value_range (vr, VR_RANGE, min, max, NULL);
1853 else
1854 set_value_range_to_varying (vr);
1855 return;
1857 else if (code == BIT_IOR_EXPR)
1859 if (wide_int_range_bit_ior (wmin, wmax, sign,
1860 vr0_min, vr0_max,
1861 vr1_min, vr1_max,
1862 must_be_nonzero0,
1863 may_be_nonzero0,
1864 must_be_nonzero1,
1865 may_be_nonzero1))
1867 min = wide_int_to_tree (expr_type, wmin);
1868 max = wide_int_to_tree (expr_type, wmax);
1869 set_value_range (vr, VR_RANGE, min, max, NULL);
1871 else
1872 set_value_range_to_varying (vr);
1873 return;
1875 else if (code == BIT_XOR_EXPR)
1877 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1878 must_be_nonzero0,
1879 may_be_nonzero0,
1880 must_be_nonzero1,
1881 may_be_nonzero1))
1883 min = wide_int_to_tree (expr_type, wmin);
1884 max = wide_int_to_tree (expr_type, wmax);
1885 set_value_range (vr, VR_RANGE, min, max, NULL);
1887 else
1888 set_value_range_to_varying (vr);
1889 return;
1892 else
1893 gcc_unreachable ();
1895 /* If either MIN or MAX overflowed, then set the resulting range to
1896 VARYING. */
1897 if (min == NULL_TREE
1898 || TREE_OVERFLOW_P (min)
1899 || max == NULL_TREE
1900 || TREE_OVERFLOW_P (max))
1902 set_value_range_to_varying (vr);
1903 return;
1906 /* We punt for [-INF, +INF].
1907 We learn nothing when we have INF on both sides.
1908 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1909 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1911 set_value_range_to_varying (vr);
1912 return;
1915 cmp = compare_values (min, max);
1916 if (cmp == -2 || cmp == 1)
1918 /* If the new range has its limits swapped around (MIN > MAX),
1919 then the operation caused one of them to wrap around, mark
1920 the new range VARYING. */
1921 set_value_range_to_varying (vr);
1923 else
1924 set_value_range (vr, type, min, max, NULL);
1927 /* Calculates the absolute value of a range and puts the result in VR.
1928 VR0 is the input range. TYPE is the type of the resulting
1929 range. */
1931 static void
1932 extract_range_from_abs_expr (value_range &vr, tree type, value_range &vr0)
1934 /* Pass through vr0 in the easy cases. */
1935 if (TYPE_UNSIGNED (type)
1936 || value_range_nonnegative_p (&vr0))
1938 copy_value_range (&vr, &vr0);
1939 return;
1942 /* For the remaining varying or symbolic ranges we can't do anything
1943 useful. */
1944 if (vr0.type == VR_VARYING
1945 || symbolic_range_p (&vr0))
1947 set_value_range_to_varying (&vr);
1948 return;
1951 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
1952 useful range. */
1953 if (!TYPE_OVERFLOW_UNDEFINED (type)
1954 && ((vr0.type == VR_RANGE
1955 && vrp_val_is_min (vr0.min))
1956 || (vr0.type == VR_ANTI_RANGE
1957 && !vrp_val_is_min (vr0.min))))
1959 set_value_range_to_varying (&vr);
1960 return;
1963 /* ABS_EXPR may flip the range around, if the original range
1964 included negative values. */
1965 tree min, max;
1966 if (!vrp_val_is_min (vr0.min))
1967 min = fold_unary_to_constant (ABS_EXPR, type, vr0.min);
1968 else
1969 min = TYPE_MAX_VALUE (type);
1971 if (!vrp_val_is_min (vr0.max))
1972 max = fold_unary_to_constant (ABS_EXPR, type, vr0.max);
1973 else
1974 max = TYPE_MAX_VALUE (type);
1976 int cmp = compare_values (min, max);
1977 gcc_assert (vr0.type != VR_ANTI_RANGE);
1979 /* If the range contains zero then we know that the minimum value in the
1980 range will be zero. */
1981 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
1983 if (cmp == 1)
1984 max = min;
1985 min = build_int_cst (type, 0);
1987 else
1989 /* If the range was reversed, swap MIN and MAX. */
1990 if (cmp == 1)
1991 std::swap (min, max);
1994 cmp = compare_values (min, max);
1995 if (cmp == -2 || cmp == 1)
1997 /* If the new range has its limits swapped around (MIN > MAX),
1998 then the operation caused one of them to wrap around, mark
1999 the new range VARYING. */
2000 set_value_range_to_varying (&vr);
2002 else
2003 set_value_range (&vr, vr0.type, min, max, NULL);
2006 /* Extract range information from a unary operation CODE based on
2007 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2008 The resulting range is stored in *VR. */
2010 void
2011 extract_range_from_unary_expr (value_range *vr,
2012 enum tree_code code, tree type,
2013 value_range *vr0_, tree op0_type)
2015 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2017 /* VRP only operates on integral and pointer types. */
2018 if (!(INTEGRAL_TYPE_P (op0_type)
2019 || POINTER_TYPE_P (op0_type))
2020 || !(INTEGRAL_TYPE_P (type)
2021 || POINTER_TYPE_P (type)))
2023 set_value_range_to_varying (vr);
2024 return;
2027 /* If VR0 is UNDEFINED, so is the result. */
2028 if (vr0.type == VR_UNDEFINED)
2030 set_value_range_to_undefined (vr);
2031 return;
2034 /* Handle operations that we express in terms of others. */
2035 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2037 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2038 copy_value_range (vr, &vr0);
2039 return;
2041 else if (code == NEGATE_EXPR)
2043 /* -X is simply 0 - X, so re-use existing code that also handles
2044 anti-ranges fine. */
2045 value_range zero = VR_INITIALIZER;
2046 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2047 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2048 return;
2050 else if (code == BIT_NOT_EXPR)
2052 /* ~X is simply -1 - X, so re-use existing code that also handles
2053 anti-ranges fine. */
2054 value_range minusone = VR_INITIALIZER;
2055 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2056 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2057 type, &minusone, &vr0);
2058 return;
2061 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2062 and express op ~[] as (op []') U (op []''). */
2063 if (vr0.type == VR_ANTI_RANGE
2064 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2066 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2067 if (vrtem1.type != VR_UNDEFINED)
2069 value_range vrres = VR_INITIALIZER;
2070 extract_range_from_unary_expr (&vrres, code, type,
2071 &vrtem1, op0_type);
2072 vrp_meet (vr, &vrres);
2074 return;
2077 if (CONVERT_EXPR_CODE_P (code))
2079 tree inner_type = op0_type;
2080 tree outer_type = type;
2082 /* If the expression evaluates to a pointer, we are only interested in
2083 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
2084 if (POINTER_TYPE_P (type))
2086 if (range_is_nonnull (&vr0))
2087 set_value_range_to_nonnull (vr, type);
2088 else if (range_is_null (&vr0))
2089 set_value_range_to_null (vr, type);
2090 else
2091 set_value_range_to_varying (vr);
2092 return;
2095 /* If VR0 is varying and we increase the type precision, assume
2096 a full range for the following transformation. */
2097 if (vr0.type == VR_VARYING
2098 && INTEGRAL_TYPE_P (inner_type)
2099 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2101 vr0.type = VR_RANGE;
2102 vr0.min = TYPE_MIN_VALUE (inner_type);
2103 vr0.max = TYPE_MAX_VALUE (inner_type);
2106 /* If VR0 is a constant range or anti-range and the conversion is
2107 not truncating we can convert the min and max values and
2108 canonicalize the resulting range. Otherwise we can do the
2109 conversion if the size of the range is less than what the
2110 precision of the target type can represent and the range is
2111 not an anti-range. */
2112 if ((vr0.type == VR_RANGE
2113 || vr0.type == VR_ANTI_RANGE)
2114 && TREE_CODE (vr0.min) == INTEGER_CST
2115 && TREE_CODE (vr0.max) == INTEGER_CST
2116 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2117 || (vr0.type == VR_RANGE
2118 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2119 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2120 size_int (TYPE_PRECISION (outer_type)))))))
2122 tree new_min, new_max;
2123 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2124 0, false);
2125 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2126 0, false);
2127 set_and_canonicalize_value_range (vr, vr0.type,
2128 new_min, new_max, NULL);
2129 return;
2132 set_value_range_to_varying (vr);
2133 return;
2135 else if (code == ABS_EXPR)
2136 return extract_range_from_abs_expr (*vr, type, vr0);
2138 /* For unhandled operations fall back to varying. */
2139 set_value_range_to_varying (vr);
2140 return;
2143 /* Debugging dumps. */
2145 void dump_value_range (FILE *, const value_range *);
2146 void debug_value_range (value_range *);
2147 void dump_all_value_ranges (FILE *);
2148 void dump_vr_equiv (FILE *, bitmap);
2149 void debug_vr_equiv (bitmap);
2152 /* Dump value range VR to FILE. */
2154 void
2155 dump_value_range (FILE *file, const value_range *vr)
2157 if (vr == NULL)
2158 fprintf (file, "[]");
2159 else if (vr->type == VR_UNDEFINED)
2160 fprintf (file, "UNDEFINED");
2161 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2163 tree type = TREE_TYPE (vr->min);
2165 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2167 if (INTEGRAL_TYPE_P (type)
2168 && !TYPE_UNSIGNED (type)
2169 && vrp_val_is_min (vr->min))
2170 fprintf (file, "-INF");
2171 else
2172 print_generic_expr (file, vr->min);
2174 fprintf (file, ", ");
2176 if (INTEGRAL_TYPE_P (type)
2177 && vrp_val_is_max (vr->max))
2178 fprintf (file, "+INF");
2179 else
2180 print_generic_expr (file, vr->max);
2182 fprintf (file, "]");
2184 if (vr->equiv)
2186 bitmap_iterator bi;
2187 unsigned i, c = 0;
2189 fprintf (file, " EQUIVALENCES: { ");
2191 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2193 print_generic_expr (file, ssa_name (i));
2194 fprintf (file, " ");
2195 c++;
2198 fprintf (file, "} (%u elements)", c);
2201 else if (vr->type == VR_VARYING)
2202 fprintf (file, "VARYING");
2203 else
2204 fprintf (file, "INVALID RANGE");
2208 /* Dump value range VR to stderr. */
2210 DEBUG_FUNCTION void
2211 debug_value_range (value_range *vr)
2213 dump_value_range (stderr, vr);
2214 fprintf (stderr, "\n");
2217 void
2218 value_range::dump ()
2220 debug_value_range (this);
2224 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2225 create a new SSA name N and return the assertion assignment
2226 'N = ASSERT_EXPR <V, V OP W>'. */
2228 static gimple *
2229 build_assert_expr_for (tree cond, tree v)
2231 tree a;
2232 gassign *assertion;
2234 gcc_assert (TREE_CODE (v) == SSA_NAME
2235 && COMPARISON_CLASS_P (cond));
2237 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2238 assertion = gimple_build_assign (NULL_TREE, a);
2240 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2241 operand of the ASSERT_EXPR. Create it so the new name and the old one
2242 are registered in the replacement table so that we can fix the SSA web
2243 after adding all the ASSERT_EXPRs. */
2244 tree new_def = create_new_def_for (v, assertion, NULL);
2245 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2246 given we have to be able to fully propagate those out to re-create
2247 valid SSA when removing the asserts. */
2248 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2249 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2251 return assertion;
2255 /* Return false if EXPR is a predicate expression involving floating
2256 point values. */
2258 static inline bool
2259 fp_predicate (gimple *stmt)
2261 GIMPLE_CHECK (stmt, GIMPLE_COND);
2263 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2266 /* If the range of values taken by OP can be inferred after STMT executes,
2267 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2268 describes the inferred range. Return true if a range could be
2269 inferred. */
2271 bool
2272 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2274 *val_p = NULL_TREE;
2275 *comp_code_p = ERROR_MARK;
2277 /* Do not attempt to infer anything in names that flow through
2278 abnormal edges. */
2279 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2280 return false;
2282 /* If STMT is the last statement of a basic block with no normal
2283 successors, there is no point inferring anything about any of its
2284 operands. We would not be able to find a proper insertion point
2285 for the assertion, anyway. */
2286 if (stmt_ends_bb_p (stmt))
2288 edge_iterator ei;
2289 edge e;
2291 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2292 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2293 break;
2294 if (e == NULL)
2295 return false;
2298 if (infer_nonnull_range (stmt, op))
2300 *val_p = build_int_cst (TREE_TYPE (op), 0);
2301 *comp_code_p = NE_EXPR;
2302 return true;
2305 return false;
2309 void dump_asserts_for (FILE *, tree);
2310 void debug_asserts_for (tree);
2311 void dump_all_asserts (FILE *);
2312 void debug_all_asserts (void);
2314 /* Dump all the registered assertions for NAME to FILE. */
2316 void
2317 dump_asserts_for (FILE *file, tree name)
2319 assert_locus *loc;
2321 fprintf (file, "Assertions to be inserted for ");
2322 print_generic_expr (file, name);
2323 fprintf (file, "\n");
2325 loc = asserts_for[SSA_NAME_VERSION (name)];
2326 while (loc)
2328 fprintf (file, "\t");
2329 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2330 fprintf (file, "\n\tBB #%d", loc->bb->index);
2331 if (loc->e)
2333 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2334 loc->e->dest->index);
2335 dump_edge_info (file, loc->e, dump_flags, 0);
2337 fprintf (file, "\n\tPREDICATE: ");
2338 print_generic_expr (file, loc->expr);
2339 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2340 print_generic_expr (file, loc->val);
2341 fprintf (file, "\n\n");
2342 loc = loc->next;
2345 fprintf (file, "\n");
2349 /* Dump all the registered assertions for NAME to stderr. */
2351 DEBUG_FUNCTION void
2352 debug_asserts_for (tree name)
2354 dump_asserts_for (stderr, name);
2358 /* Dump all the registered assertions for all the names to FILE. */
2360 void
2361 dump_all_asserts (FILE *file)
2363 unsigned i;
2364 bitmap_iterator bi;
2366 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2367 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2368 dump_asserts_for (file, ssa_name (i));
2369 fprintf (file, "\n");
2373 /* Dump all the registered assertions for all the names to stderr. */
2375 DEBUG_FUNCTION void
2376 debug_all_asserts (void)
2378 dump_all_asserts (stderr);
2381 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2383 static void
2384 add_assert_info (vec<assert_info> &asserts,
2385 tree name, tree expr, enum tree_code comp_code, tree val)
2387 assert_info info;
2388 info.comp_code = comp_code;
2389 info.name = name;
2390 if (TREE_OVERFLOW_P (val))
2391 val = drop_tree_overflow (val);
2392 info.val = val;
2393 info.expr = expr;
2394 asserts.safe_push (info);
2397 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2398 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2399 E->DEST, then register this location as a possible insertion point
2400 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2402 BB, E and SI provide the exact insertion point for the new
2403 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2404 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2405 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2406 must not be NULL. */
2408 static void
2409 register_new_assert_for (tree name, tree expr,
2410 enum tree_code comp_code,
2411 tree val,
2412 basic_block bb,
2413 edge e,
2414 gimple_stmt_iterator si)
2416 assert_locus *n, *loc, *last_loc;
2417 basic_block dest_bb;
2419 gcc_checking_assert (bb == NULL || e == NULL);
2421 if (e == NULL)
2422 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2423 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2425 /* Never build an assert comparing against an integer constant with
2426 TREE_OVERFLOW set. This confuses our undefined overflow warning
2427 machinery. */
2428 if (TREE_OVERFLOW_P (val))
2429 val = drop_tree_overflow (val);
2431 /* The new assertion A will be inserted at BB or E. We need to
2432 determine if the new location is dominated by a previously
2433 registered location for A. If we are doing an edge insertion,
2434 assume that A will be inserted at E->DEST. Note that this is not
2435 necessarily true.
2437 If E is a critical edge, it will be split. But even if E is
2438 split, the new block will dominate the same set of blocks that
2439 E->DEST dominates.
2441 The reverse, however, is not true, blocks dominated by E->DEST
2442 will not be dominated by the new block created to split E. So,
2443 if the insertion location is on a critical edge, we will not use
2444 the new location to move another assertion previously registered
2445 at a block dominated by E->DEST. */
2446 dest_bb = (bb) ? bb : e->dest;
2448 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2449 VAL at a block dominating DEST_BB, then we don't need to insert a new
2450 one. Similarly, if the same assertion already exists at a block
2451 dominated by DEST_BB and the new location is not on a critical
2452 edge, then update the existing location for the assertion (i.e.,
2453 move the assertion up in the dominance tree).
2455 Note, this is implemented as a simple linked list because there
2456 should not be more than a handful of assertions registered per
2457 name. If this becomes a performance problem, a table hashed by
2458 COMP_CODE and VAL could be implemented. */
2459 loc = asserts_for[SSA_NAME_VERSION (name)];
2460 last_loc = loc;
2461 while (loc)
2463 if (loc->comp_code == comp_code
2464 && (loc->val == val
2465 || operand_equal_p (loc->val, val, 0))
2466 && (loc->expr == expr
2467 || operand_equal_p (loc->expr, expr, 0)))
2469 /* If E is not a critical edge and DEST_BB
2470 dominates the existing location for the assertion, move
2471 the assertion up in the dominance tree by updating its
2472 location information. */
2473 if ((e == NULL || !EDGE_CRITICAL_P (e))
2474 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2476 loc->bb = dest_bb;
2477 loc->e = e;
2478 loc->si = si;
2479 return;
2483 /* Update the last node of the list and move to the next one. */
2484 last_loc = loc;
2485 loc = loc->next;
2488 /* If we didn't find an assertion already registered for
2489 NAME COMP_CODE VAL, add a new one at the end of the list of
2490 assertions associated with NAME. */
2491 n = XNEW (struct assert_locus);
2492 n->bb = dest_bb;
2493 n->e = e;
2494 n->si = si;
2495 n->comp_code = comp_code;
2496 n->val = val;
2497 n->expr = expr;
2498 n->next = NULL;
2500 if (last_loc)
2501 last_loc->next = n;
2502 else
2503 asserts_for[SSA_NAME_VERSION (name)] = n;
2505 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2508 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2509 Extract a suitable test code and value and store them into *CODE_P and
2510 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2512 If no extraction was possible, return FALSE, otherwise return TRUE.
2514 If INVERT is true, then we invert the result stored into *CODE_P. */
2516 static bool
2517 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2518 tree cond_op0, tree cond_op1,
2519 bool invert, enum tree_code *code_p,
2520 tree *val_p)
2522 enum tree_code comp_code;
2523 tree val;
2525 /* Otherwise, we have a comparison of the form NAME COMP VAL
2526 or VAL COMP NAME. */
2527 if (name == cond_op1)
2529 /* If the predicate is of the form VAL COMP NAME, flip
2530 COMP around because we need to register NAME as the
2531 first operand in the predicate. */
2532 comp_code = swap_tree_comparison (cond_code);
2533 val = cond_op0;
2535 else if (name == cond_op0)
2537 /* The comparison is of the form NAME COMP VAL, so the
2538 comparison code remains unchanged. */
2539 comp_code = cond_code;
2540 val = cond_op1;
2542 else
2543 gcc_unreachable ();
2545 /* Invert the comparison code as necessary. */
2546 if (invert)
2547 comp_code = invert_tree_comparison (comp_code, 0);
2549 /* VRP only handles integral and pointer types. */
2550 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2551 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2552 return false;
2554 /* Do not register always-false predicates.
2555 FIXME: this works around a limitation in fold() when dealing with
2556 enumerations. Given 'enum { N1, N2 } x;', fold will not
2557 fold 'if (x > N2)' to 'if (0)'. */
2558 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2559 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2561 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2562 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2564 if (comp_code == GT_EXPR
2565 && (!max
2566 || compare_values (val, max) == 0))
2567 return false;
2569 if (comp_code == LT_EXPR
2570 && (!min
2571 || compare_values (val, min) == 0))
2572 return false;
2574 *code_p = comp_code;
2575 *val_p = val;
2576 return true;
2579 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2580 (otherwise return VAL). VAL and MASK must be zero-extended for
2581 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2582 (to transform signed values into unsigned) and at the end xor
2583 SGNBIT back. */
2585 static wide_int
2586 masked_increment (const wide_int &val_in, const wide_int &mask,
2587 const wide_int &sgnbit, unsigned int prec)
2589 wide_int bit = wi::one (prec), res;
2590 unsigned int i;
2592 wide_int val = val_in ^ sgnbit;
2593 for (i = 0; i < prec; i++, bit += bit)
2595 res = mask;
2596 if ((res & bit) == 0)
2597 continue;
2598 res = bit - 1;
2599 res = wi::bit_and_not (val + bit, res);
2600 res &= mask;
2601 if (wi::gtu_p (res, val))
2602 return res ^ sgnbit;
2604 return val ^ sgnbit;
2607 /* Helper for overflow_comparison_p
2609 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2610 OP1's defining statement to see if it ultimately has the form
2611 OP0 CODE (OP0 PLUS INTEGER_CST)
2613 If so, return TRUE indicating this is an overflow test and store into
2614 *NEW_CST an updated constant that can be used in a narrowed range test.
2616 REVERSED indicates if the comparison was originally:
2618 OP1 CODE' OP0.
2620 This affects how we build the updated constant. */
2622 static bool
2623 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2624 bool follow_assert_exprs, bool reversed, tree *new_cst)
2626 /* See if this is a relational operation between two SSA_NAMES with
2627 unsigned, overflow wrapping values. If so, check it more deeply. */
2628 if ((code == LT_EXPR || code == LE_EXPR
2629 || code == GE_EXPR || code == GT_EXPR)
2630 && TREE_CODE (op0) == SSA_NAME
2631 && TREE_CODE (op1) == SSA_NAME
2632 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2633 && TYPE_UNSIGNED (TREE_TYPE (op0))
2634 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2636 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2638 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2639 if (follow_assert_exprs)
2641 while (gimple_assign_single_p (op1_def)
2642 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2644 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2645 if (TREE_CODE (op1) != SSA_NAME)
2646 break;
2647 op1_def = SSA_NAME_DEF_STMT (op1);
2651 /* Now look at the defining statement of OP1 to see if it adds
2652 or subtracts a nonzero constant from another operand. */
2653 if (op1_def
2654 && is_gimple_assign (op1_def)
2655 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2656 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2657 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2659 tree target = gimple_assign_rhs1 (op1_def);
2661 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2662 for one where TARGET appears on the RHS. */
2663 if (follow_assert_exprs)
2665 /* Now see if that "other operand" is op0, following the chain
2666 of ASSERT_EXPRs if necessary. */
2667 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2668 while (op0 != target
2669 && gimple_assign_single_p (op0_def)
2670 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2672 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2673 if (TREE_CODE (op0) != SSA_NAME)
2674 break;
2675 op0_def = SSA_NAME_DEF_STMT (op0);
2679 /* If we did not find our target SSA_NAME, then this is not
2680 an overflow test. */
2681 if (op0 != target)
2682 return false;
2684 tree type = TREE_TYPE (op0);
2685 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2686 tree inc = gimple_assign_rhs2 (op1_def);
2687 if (reversed)
2688 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2689 else
2690 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2691 return true;
2694 return false;
2697 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2698 OP1's defining statement to see if it ultimately has the form
2699 OP0 CODE (OP0 PLUS INTEGER_CST)
2701 If so, return TRUE indicating this is an overflow test and store into
2702 *NEW_CST an updated constant that can be used in a narrowed range test.
2704 These statements are left as-is in the IL to facilitate discovery of
2705 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2706 the alternate range representation is often useful within VRP. */
2708 bool
2709 overflow_comparison_p (tree_code code, tree name, tree val,
2710 bool use_equiv_p, tree *new_cst)
2712 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2713 return true;
2714 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2715 use_equiv_p, true, new_cst);
2719 /* Try to register an edge assertion for SSA name NAME on edge E for
2720 the condition COND contributing to the conditional jump pointed to by BSI.
2721 Invert the condition COND if INVERT is true. */
2723 static void
2724 register_edge_assert_for_2 (tree name, edge e,
2725 enum tree_code cond_code,
2726 tree cond_op0, tree cond_op1, bool invert,
2727 vec<assert_info> &asserts)
2729 tree val;
2730 enum tree_code comp_code;
2732 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2733 cond_op0,
2734 cond_op1,
2735 invert, &comp_code, &val))
2736 return;
2738 /* Queue the assert. */
2739 tree x;
2740 if (overflow_comparison_p (comp_code, name, val, false, &x))
2742 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2743 ? GT_EXPR : LE_EXPR);
2744 add_assert_info (asserts, name, name, new_code, x);
2746 add_assert_info (asserts, name, name, comp_code, val);
2748 /* In the case of NAME <= CST and NAME being defined as
2749 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2750 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2751 This catches range and anti-range tests. */
2752 if ((comp_code == LE_EXPR
2753 || comp_code == GT_EXPR)
2754 && TREE_CODE (val) == INTEGER_CST
2755 && TYPE_UNSIGNED (TREE_TYPE (val)))
2757 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2758 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2760 /* Extract CST2 from the (optional) addition. */
2761 if (is_gimple_assign (def_stmt)
2762 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2764 name2 = gimple_assign_rhs1 (def_stmt);
2765 cst2 = gimple_assign_rhs2 (def_stmt);
2766 if (TREE_CODE (name2) == SSA_NAME
2767 && TREE_CODE (cst2) == INTEGER_CST)
2768 def_stmt = SSA_NAME_DEF_STMT (name2);
2771 /* Extract NAME2 from the (optional) sign-changing cast. */
2772 if (gimple_assign_cast_p (def_stmt))
2774 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2775 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2776 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2777 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2778 name3 = gimple_assign_rhs1 (def_stmt);
2781 /* If name3 is used later, create an ASSERT_EXPR for it. */
2782 if (name3 != NULL_TREE
2783 && TREE_CODE (name3) == SSA_NAME
2784 && (cst2 == NULL_TREE
2785 || TREE_CODE (cst2) == INTEGER_CST)
2786 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2788 tree tmp;
2790 /* Build an expression for the range test. */
2791 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2792 if (cst2 != NULL_TREE)
2793 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2795 if (dump_file)
2797 fprintf (dump_file, "Adding assert for ");
2798 print_generic_expr (dump_file, name3);
2799 fprintf (dump_file, " from ");
2800 print_generic_expr (dump_file, tmp);
2801 fprintf (dump_file, "\n");
2804 add_assert_info (asserts, name3, tmp, comp_code, val);
2807 /* If name2 is used later, create an ASSERT_EXPR for it. */
2808 if (name2 != NULL_TREE
2809 && TREE_CODE (name2) == SSA_NAME
2810 && TREE_CODE (cst2) == INTEGER_CST
2811 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2813 tree tmp;
2815 /* Build an expression for the range test. */
2816 tmp = name2;
2817 if (TREE_TYPE (name) != TREE_TYPE (name2))
2818 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2819 if (cst2 != NULL_TREE)
2820 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2822 if (dump_file)
2824 fprintf (dump_file, "Adding assert for ");
2825 print_generic_expr (dump_file, name2);
2826 fprintf (dump_file, " from ");
2827 print_generic_expr (dump_file, tmp);
2828 fprintf (dump_file, "\n");
2831 add_assert_info (asserts, name2, tmp, comp_code, val);
2835 /* In the case of post-in/decrement tests like if (i++) ... and uses
2836 of the in/decremented value on the edge the extra name we want to
2837 assert for is not on the def chain of the name compared. Instead
2838 it is in the set of use stmts.
2839 Similar cases happen for conversions that were simplified through
2840 fold_{sign_changed,widened}_comparison. */
2841 if ((comp_code == NE_EXPR
2842 || comp_code == EQ_EXPR)
2843 && TREE_CODE (val) == INTEGER_CST)
2845 imm_use_iterator ui;
2846 gimple *use_stmt;
2847 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2849 if (!is_gimple_assign (use_stmt))
2850 continue;
2852 /* Cut off to use-stmts that are dominating the predecessor. */
2853 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2854 continue;
2856 tree name2 = gimple_assign_lhs (use_stmt);
2857 if (TREE_CODE (name2) != SSA_NAME)
2858 continue;
2860 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2861 tree cst;
2862 if (code == PLUS_EXPR
2863 || code == MINUS_EXPR)
2865 cst = gimple_assign_rhs2 (use_stmt);
2866 if (TREE_CODE (cst) != INTEGER_CST)
2867 continue;
2868 cst = int_const_binop (code, val, cst);
2870 else if (CONVERT_EXPR_CODE_P (code))
2872 /* For truncating conversions we cannot record
2873 an inequality. */
2874 if (comp_code == NE_EXPR
2875 && (TYPE_PRECISION (TREE_TYPE (name2))
2876 < TYPE_PRECISION (TREE_TYPE (name))))
2877 continue;
2878 cst = fold_convert (TREE_TYPE (name2), val);
2880 else
2881 continue;
2883 if (TREE_OVERFLOW_P (cst))
2884 cst = drop_tree_overflow (cst);
2885 add_assert_info (asserts, name2, name2, comp_code, cst);
2889 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2890 && TREE_CODE (val) == INTEGER_CST)
2892 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2893 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2894 tree val2 = NULL_TREE;
2895 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2896 wide_int mask = wi::zero (prec);
2897 unsigned int nprec = prec;
2898 enum tree_code rhs_code = ERROR_MARK;
2900 if (is_gimple_assign (def_stmt))
2901 rhs_code = gimple_assign_rhs_code (def_stmt);
2903 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2904 assert that A != CST1 -+ CST2. */
2905 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2906 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2908 tree op0 = gimple_assign_rhs1 (def_stmt);
2909 tree op1 = gimple_assign_rhs2 (def_stmt);
2910 if (TREE_CODE (op0) == SSA_NAME
2911 && TREE_CODE (op1) == INTEGER_CST)
2913 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2914 ? MINUS_EXPR : PLUS_EXPR);
2915 op1 = int_const_binop (reverse_op, val, op1);
2916 if (TREE_OVERFLOW (op1))
2917 op1 = drop_tree_overflow (op1);
2918 add_assert_info (asserts, op0, op0, comp_code, op1);
2922 /* Add asserts for NAME cmp CST and NAME being defined
2923 as NAME = (int) NAME2. */
2924 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2925 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2926 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2927 && gimple_assign_cast_p (def_stmt))
2929 name2 = gimple_assign_rhs1 (def_stmt);
2930 if (CONVERT_EXPR_CODE_P (rhs_code)
2931 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2932 && TYPE_UNSIGNED (TREE_TYPE (name2))
2933 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2934 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2935 || !tree_int_cst_equal (val,
2936 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2938 tree tmp, cst;
2939 enum tree_code new_comp_code = comp_code;
2941 cst = fold_convert (TREE_TYPE (name2),
2942 TYPE_MIN_VALUE (TREE_TYPE (val)));
2943 /* Build an expression for the range test. */
2944 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2945 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2946 fold_convert (TREE_TYPE (name2), val));
2947 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2949 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2950 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2951 build_int_cst (TREE_TYPE (name2), 1));
2954 if (dump_file)
2956 fprintf (dump_file, "Adding assert for ");
2957 print_generic_expr (dump_file, name2);
2958 fprintf (dump_file, " from ");
2959 print_generic_expr (dump_file, tmp);
2960 fprintf (dump_file, "\n");
2963 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2967 /* Add asserts for NAME cmp CST and NAME being defined as
2968 NAME = NAME2 >> CST2.
2970 Extract CST2 from the right shift. */
2971 if (rhs_code == RSHIFT_EXPR)
2973 name2 = gimple_assign_rhs1 (def_stmt);
2974 cst2 = gimple_assign_rhs2 (def_stmt);
2975 if (TREE_CODE (name2) == SSA_NAME
2976 && tree_fits_uhwi_p (cst2)
2977 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2978 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2979 && type_has_mode_precision_p (TREE_TYPE (val)))
2981 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2982 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2985 if (val2 != NULL_TREE
2986 && TREE_CODE (val2) == INTEGER_CST
2987 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2988 TREE_TYPE (val),
2989 val2, cst2), val))
2991 enum tree_code new_comp_code = comp_code;
2992 tree tmp, new_val;
2994 tmp = name2;
2995 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2997 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2999 tree type = build_nonstandard_integer_type (prec, 1);
3000 tmp = build1 (NOP_EXPR, type, name2);
3001 val2 = fold_convert (type, val2);
3003 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
3004 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
3005 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
3007 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3009 wide_int minval
3010 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3011 new_val = val2;
3012 if (minval == wi::to_wide (new_val))
3013 new_val = NULL_TREE;
3015 else
3017 wide_int maxval
3018 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3019 mask |= wi::to_wide (val2);
3020 if (wi::eq_p (mask, maxval))
3021 new_val = NULL_TREE;
3022 else
3023 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3026 if (new_val)
3028 if (dump_file)
3030 fprintf (dump_file, "Adding assert for ");
3031 print_generic_expr (dump_file, name2);
3032 fprintf (dump_file, " from ");
3033 print_generic_expr (dump_file, tmp);
3034 fprintf (dump_file, "\n");
3037 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3041 /* Add asserts for NAME cmp CST and NAME being defined as
3042 NAME = NAME2 & CST2.
3044 Extract CST2 from the and.
3046 Also handle
3047 NAME = (unsigned) NAME2;
3048 casts where NAME's type is unsigned and has smaller precision
3049 than NAME2's type as if it was NAME = NAME2 & MASK. */
3050 names[0] = NULL_TREE;
3051 names[1] = NULL_TREE;
3052 cst2 = NULL_TREE;
3053 if (rhs_code == BIT_AND_EXPR
3054 || (CONVERT_EXPR_CODE_P (rhs_code)
3055 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3056 && TYPE_UNSIGNED (TREE_TYPE (val))
3057 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3058 > prec))
3060 name2 = gimple_assign_rhs1 (def_stmt);
3061 if (rhs_code == BIT_AND_EXPR)
3062 cst2 = gimple_assign_rhs2 (def_stmt);
3063 else
3065 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3066 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3068 if (TREE_CODE (name2) == SSA_NAME
3069 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3070 && TREE_CODE (cst2) == INTEGER_CST
3071 && !integer_zerop (cst2)
3072 && (nprec > 1
3073 || TYPE_UNSIGNED (TREE_TYPE (val))))
3075 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3076 if (gimple_assign_cast_p (def_stmt2))
3078 names[1] = gimple_assign_rhs1 (def_stmt2);
3079 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3080 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3081 || (TYPE_PRECISION (TREE_TYPE (name2))
3082 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3083 names[1] = NULL_TREE;
3085 names[0] = name2;
3088 if (names[0] || names[1])
3090 wide_int minv, maxv, valv, cst2v;
3091 wide_int tem, sgnbit;
3092 bool valid_p = false, valn, cst2n;
3093 enum tree_code ccode = comp_code;
3095 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3096 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3097 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3098 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3099 /* If CST2 doesn't have most significant bit set,
3100 but VAL is negative, we have comparison like
3101 if ((x & 0x123) > -4) (always true). Just give up. */
3102 if (!cst2n && valn)
3103 ccode = ERROR_MARK;
3104 if (cst2n)
3105 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3106 else
3107 sgnbit = wi::zero (nprec);
3108 minv = valv & cst2v;
3109 switch (ccode)
3111 case EQ_EXPR:
3112 /* Minimum unsigned value for equality is VAL & CST2
3113 (should be equal to VAL, otherwise we probably should
3114 have folded the comparison into false) and
3115 maximum unsigned value is VAL | ~CST2. */
3116 maxv = valv | ~cst2v;
3117 valid_p = true;
3118 break;
3120 case NE_EXPR:
3121 tem = valv | ~cst2v;
3122 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3123 if (valv == 0)
3125 cst2n = false;
3126 sgnbit = wi::zero (nprec);
3127 goto gt_expr;
3129 /* If (VAL | ~CST2) is all ones, handle it as
3130 (X & CST2) < VAL. */
3131 if (tem == -1)
3133 cst2n = false;
3134 valn = false;
3135 sgnbit = wi::zero (nprec);
3136 goto lt_expr;
3138 if (!cst2n && wi::neg_p (cst2v))
3139 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3140 if (sgnbit != 0)
3142 if (valv == sgnbit)
3144 cst2n = true;
3145 valn = true;
3146 goto gt_expr;
3148 if (tem == wi::mask (nprec - 1, false, nprec))
3150 cst2n = true;
3151 goto lt_expr;
3153 if (!cst2n)
3154 sgnbit = wi::zero (nprec);
3156 break;
3158 case GE_EXPR:
3159 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3160 is VAL and maximum unsigned value is ~0. For signed
3161 comparison, if CST2 doesn't have most significant bit
3162 set, handle it similarly. If CST2 has MSB set,
3163 the minimum is the same, and maximum is ~0U/2. */
3164 if (minv != valv)
3166 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3167 VAL. */
3168 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3169 if (minv == valv)
3170 break;
3172 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3173 valid_p = true;
3174 break;
3176 case GT_EXPR:
3177 gt_expr:
3178 /* Find out smallest MINV where MINV > VAL
3179 && (MINV & CST2) == MINV, if any. If VAL is signed and
3180 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3181 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3182 if (minv == valv)
3183 break;
3184 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3185 valid_p = true;
3186 break;
3188 case LE_EXPR:
3189 /* Minimum unsigned value for <= is 0 and maximum
3190 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3191 Otherwise, find smallest VAL2 where VAL2 > VAL
3192 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3193 as maximum.
3194 For signed comparison, if CST2 doesn't have most
3195 significant bit set, handle it similarly. If CST2 has
3196 MSB set, the maximum is the same and minimum is INT_MIN. */
3197 if (minv == valv)
3198 maxv = valv;
3199 else
3201 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3202 if (maxv == valv)
3203 break;
3204 maxv -= 1;
3206 maxv |= ~cst2v;
3207 minv = sgnbit;
3208 valid_p = true;
3209 break;
3211 case LT_EXPR:
3212 lt_expr:
3213 /* Minimum unsigned value for < is 0 and maximum
3214 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3215 Otherwise, find smallest VAL2 where VAL2 > VAL
3216 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3217 as maximum.
3218 For signed comparison, if CST2 doesn't have most
3219 significant bit set, handle it similarly. If CST2 has
3220 MSB set, the maximum is the same and minimum is INT_MIN. */
3221 if (minv == valv)
3223 if (valv == sgnbit)
3224 break;
3225 maxv = valv;
3227 else
3229 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3230 if (maxv == valv)
3231 break;
3233 maxv -= 1;
3234 maxv |= ~cst2v;
3235 minv = sgnbit;
3236 valid_p = true;
3237 break;
3239 default:
3240 break;
3242 if (valid_p
3243 && (maxv - minv) != -1)
3245 tree tmp, new_val, type;
3246 int i;
3248 for (i = 0; i < 2; i++)
3249 if (names[i])
3251 wide_int maxv2 = maxv;
3252 tmp = names[i];
3253 type = TREE_TYPE (names[i]);
3254 if (!TYPE_UNSIGNED (type))
3256 type = build_nonstandard_integer_type (nprec, 1);
3257 tmp = build1 (NOP_EXPR, type, names[i]);
3259 if (minv != 0)
3261 tmp = build2 (PLUS_EXPR, type, tmp,
3262 wide_int_to_tree (type, -minv));
3263 maxv2 = maxv - minv;
3265 new_val = wide_int_to_tree (type, maxv2);
3267 if (dump_file)
3269 fprintf (dump_file, "Adding assert for ");
3270 print_generic_expr (dump_file, names[i]);
3271 fprintf (dump_file, " from ");
3272 print_generic_expr (dump_file, tmp);
3273 fprintf (dump_file, "\n");
3276 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3283 /* OP is an operand of a truth value expression which is known to have
3284 a particular value. Register any asserts for OP and for any
3285 operands in OP's defining statement.
3287 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3288 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3290 static void
3291 register_edge_assert_for_1 (tree op, enum tree_code code,
3292 edge e, vec<assert_info> &asserts)
3294 gimple *op_def;
3295 tree val;
3296 enum tree_code rhs_code;
3298 /* We only care about SSA_NAMEs. */
3299 if (TREE_CODE (op) != SSA_NAME)
3300 return;
3302 /* We know that OP will have a zero or nonzero value. */
3303 val = build_int_cst (TREE_TYPE (op), 0);
3304 add_assert_info (asserts, op, op, code, val);
3306 /* Now look at how OP is set. If it's set from a comparison,
3307 a truth operation or some bit operations, then we may be able
3308 to register information about the operands of that assignment. */
3309 op_def = SSA_NAME_DEF_STMT (op);
3310 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3311 return;
3313 rhs_code = gimple_assign_rhs_code (op_def);
3315 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3317 bool invert = (code == EQ_EXPR ? true : false);
3318 tree op0 = gimple_assign_rhs1 (op_def);
3319 tree op1 = gimple_assign_rhs2 (op_def);
3321 if (TREE_CODE (op0) == SSA_NAME)
3322 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3323 if (TREE_CODE (op1) == SSA_NAME)
3324 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3326 else if ((code == NE_EXPR
3327 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3328 || (code == EQ_EXPR
3329 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3331 /* Recurse on each operand. */
3332 tree op0 = gimple_assign_rhs1 (op_def);
3333 tree op1 = gimple_assign_rhs2 (op_def);
3334 if (TREE_CODE (op0) == SSA_NAME
3335 && has_single_use (op0))
3336 register_edge_assert_for_1 (op0, code, e, asserts);
3337 if (TREE_CODE (op1) == SSA_NAME
3338 && has_single_use (op1))
3339 register_edge_assert_for_1 (op1, code, e, asserts);
3341 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3342 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3344 /* Recurse, flipping CODE. */
3345 code = invert_tree_comparison (code, false);
3346 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3348 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3350 /* Recurse through the copy. */
3351 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3353 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3355 /* Recurse through the type conversion, unless it is a narrowing
3356 conversion or conversion from non-integral type. */
3357 tree rhs = gimple_assign_rhs1 (op_def);
3358 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3359 && (TYPE_PRECISION (TREE_TYPE (rhs))
3360 <= TYPE_PRECISION (TREE_TYPE (op))))
3361 register_edge_assert_for_1 (rhs, code, e, asserts);
3365 /* Check if comparison
3366 NAME COND_OP INTEGER_CST
3367 has a form of
3368 (X & 11...100..0) COND_OP XX...X00...0
3369 Such comparison can yield assertions like
3370 X >= XX...X00...0
3371 X <= XX...X11...1
3372 in case of COND_OP being EQ_EXPR or
3373 X < XX...X00...0
3374 X > XX...X11...1
3375 in case of NE_EXPR. */
3377 static bool
3378 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3379 tree *new_name, tree *low, enum tree_code *low_code,
3380 tree *high, enum tree_code *high_code)
3382 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3384 if (!is_gimple_assign (def_stmt)
3385 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3386 return false;
3388 tree t = gimple_assign_rhs1 (def_stmt);
3389 tree maskt = gimple_assign_rhs2 (def_stmt);
3390 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3391 return false;
3393 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3394 wide_int inv_mask = ~mask;
3395 /* Must have been removed by now so don't bother optimizing. */
3396 if (mask == 0 || inv_mask == 0)
3397 return false;
3399 /* Assume VALT is INTEGER_CST. */
3400 wi::tree_to_wide_ref val = wi::to_wide (valt);
3402 if ((inv_mask & (inv_mask + 1)) != 0
3403 || (val & mask) != val)
3404 return false;
3406 bool is_range = cond_code == EQ_EXPR;
3408 tree type = TREE_TYPE (t);
3409 wide_int min = wi::min_value (type),
3410 max = wi::max_value (type);
3412 if (is_range)
3414 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3415 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3417 else
3419 /* We can still generate assertion if one of alternatives
3420 is known to always be false. */
3421 if (val == min)
3423 *low_code = (enum tree_code) 0;
3424 *high_code = GT_EXPR;
3426 else if ((val | inv_mask) == max)
3428 *low_code = LT_EXPR;
3429 *high_code = (enum tree_code) 0;
3431 else
3432 return false;
3435 *new_name = t;
3436 *low = wide_int_to_tree (type, val);
3437 *high = wide_int_to_tree (type, val | inv_mask);
3439 return true;
3442 /* Try to register an edge assertion for SSA name NAME on edge E for
3443 the condition COND contributing to the conditional jump pointed to by
3444 SI. */
3446 void
3447 register_edge_assert_for (tree name, edge e,
3448 enum tree_code cond_code, tree cond_op0,
3449 tree cond_op1, vec<assert_info> &asserts)
3451 tree val;
3452 enum tree_code comp_code;
3453 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3455 /* Do not attempt to infer anything in names that flow through
3456 abnormal edges. */
3457 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3458 return;
3460 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3461 cond_op0, cond_op1,
3462 is_else_edge,
3463 &comp_code, &val))
3464 return;
3466 /* Register ASSERT_EXPRs for name. */
3467 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3468 cond_op1, is_else_edge, asserts);
3471 /* If COND is effectively an equality test of an SSA_NAME against
3472 the value zero or one, then we may be able to assert values
3473 for SSA_NAMEs which flow into COND. */
3475 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3476 statement of NAME we can assert both operands of the BIT_AND_EXPR
3477 have nonzero value. */
3478 if (((comp_code == EQ_EXPR && integer_onep (val))
3479 || (comp_code == NE_EXPR && integer_zerop (val))))
3481 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3483 if (is_gimple_assign (def_stmt)
3484 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3486 tree op0 = gimple_assign_rhs1 (def_stmt);
3487 tree op1 = gimple_assign_rhs2 (def_stmt);
3488 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3489 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3493 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3494 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3495 have zero value. */
3496 if (((comp_code == EQ_EXPR && integer_zerop (val))
3497 || (comp_code == NE_EXPR && integer_onep (val))))
3499 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3501 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3502 necessarily zero value, or if type-precision is one. */
3503 if (is_gimple_assign (def_stmt)
3504 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3505 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3506 || comp_code == EQ_EXPR)))
3508 tree op0 = gimple_assign_rhs1 (def_stmt);
3509 tree op1 = gimple_assign_rhs2 (def_stmt);
3510 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3511 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3515 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3516 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3517 && TREE_CODE (val) == INTEGER_CST)
3519 enum tree_code low_code, high_code;
3520 tree low, high;
3521 if (is_masked_range_test (name, val, comp_code, &name, &low,
3522 &low_code, &high, &high_code))
3524 if (low_code != ERROR_MARK)
3525 register_edge_assert_for_2 (name, e, low_code, name,
3526 low, /*invert*/false, asserts);
3527 if (high_code != ERROR_MARK)
3528 register_edge_assert_for_2 (name, e, high_code, name,
3529 high, /*invert*/false, asserts);
3534 /* Finish found ASSERTS for E and register them at GSI. */
3536 static void
3537 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3538 vec<assert_info> &asserts)
3540 for (unsigned i = 0; i < asserts.length (); ++i)
3541 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3542 reachable from E. */
3543 if (live_on_edge (e, asserts[i].name))
3544 register_new_assert_for (asserts[i].name, asserts[i].expr,
3545 asserts[i].comp_code, asserts[i].val,
3546 NULL, e, gsi);
3551 /* Determine whether the outgoing edges of BB should receive an
3552 ASSERT_EXPR for each of the operands of BB's LAST statement.
3553 The last statement of BB must be a COND_EXPR.
3555 If any of the sub-graphs rooted at BB have an interesting use of
3556 the predicate operands, an assert location node is added to the
3557 list of assertions for the corresponding operands. */
3559 static void
3560 find_conditional_asserts (basic_block bb, gcond *last)
3562 gimple_stmt_iterator bsi;
3563 tree op;
3564 edge_iterator ei;
3565 edge e;
3566 ssa_op_iter iter;
3568 bsi = gsi_for_stmt (last);
3570 /* Look for uses of the operands in each of the sub-graphs
3571 rooted at BB. We need to check each of the outgoing edges
3572 separately, so that we know what kind of ASSERT_EXPR to
3573 insert. */
3574 FOR_EACH_EDGE (e, ei, bb->succs)
3576 if (e->dest == bb)
3577 continue;
3579 /* Register the necessary assertions for each operand in the
3580 conditional predicate. */
3581 auto_vec<assert_info, 8> asserts;
3582 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3583 register_edge_assert_for (op, e,
3584 gimple_cond_code (last),
3585 gimple_cond_lhs (last),
3586 gimple_cond_rhs (last), asserts);
3587 finish_register_edge_assert_for (e, bsi, asserts);
3591 struct case_info
3593 tree expr;
3594 basic_block bb;
3597 /* Compare two case labels sorting first by the destination bb index
3598 and then by the case value. */
3600 static int
3601 compare_case_labels (const void *p1, const void *p2)
3603 const struct case_info *ci1 = (const struct case_info *) p1;
3604 const struct case_info *ci2 = (const struct case_info *) p2;
3605 int idx1 = ci1->bb->index;
3606 int idx2 = ci2->bb->index;
3608 if (idx1 < idx2)
3609 return -1;
3610 else if (idx1 == idx2)
3612 /* Make sure the default label is first in a group. */
3613 if (!CASE_LOW (ci1->expr))
3614 return -1;
3615 else if (!CASE_LOW (ci2->expr))
3616 return 1;
3617 else
3618 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3619 CASE_LOW (ci2->expr));
3621 else
3622 return 1;
3625 /* Determine whether the outgoing edges of BB should receive an
3626 ASSERT_EXPR for each of the operands of BB's LAST statement.
3627 The last statement of BB must be a SWITCH_EXPR.
3629 If any of the sub-graphs rooted at BB have an interesting use of
3630 the predicate operands, an assert location node is added to the
3631 list of assertions for the corresponding operands. */
3633 static void
3634 find_switch_asserts (basic_block bb, gswitch *last)
3636 gimple_stmt_iterator bsi;
3637 tree op;
3638 edge e;
3639 struct case_info *ci;
3640 size_t n = gimple_switch_num_labels (last);
3641 #if GCC_VERSION >= 4000
3642 unsigned int idx;
3643 #else
3644 /* Work around GCC 3.4 bug (PR 37086). */
3645 volatile unsigned int idx;
3646 #endif
3648 bsi = gsi_for_stmt (last);
3649 op = gimple_switch_index (last);
3650 if (TREE_CODE (op) != SSA_NAME)
3651 return;
3653 /* Build a vector of case labels sorted by destination label. */
3654 ci = XNEWVEC (struct case_info, n);
3655 for (idx = 0; idx < n; ++idx)
3657 ci[idx].expr = gimple_switch_label (last, idx);
3658 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
3660 edge default_edge = find_edge (bb, ci[0].bb);
3661 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3663 for (idx = 0; idx < n; ++idx)
3665 tree min, max;
3666 tree cl = ci[idx].expr;
3667 basic_block cbb = ci[idx].bb;
3669 min = CASE_LOW (cl);
3670 max = CASE_HIGH (cl);
3672 /* If there are multiple case labels with the same destination
3673 we need to combine them to a single value range for the edge. */
3674 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3676 /* Skip labels until the last of the group. */
3677 do {
3678 ++idx;
3679 } while (idx < n && cbb == ci[idx].bb);
3680 --idx;
3682 /* Pick up the maximum of the case label range. */
3683 if (CASE_HIGH (ci[idx].expr))
3684 max = CASE_HIGH (ci[idx].expr);
3685 else
3686 max = CASE_LOW (ci[idx].expr);
3689 /* Can't extract a useful assertion out of a range that includes the
3690 default label. */
3691 if (min == NULL_TREE)
3692 continue;
3694 /* Find the edge to register the assert expr on. */
3695 e = find_edge (bb, cbb);
3697 /* Register the necessary assertions for the operand in the
3698 SWITCH_EXPR. */
3699 auto_vec<assert_info, 8> asserts;
3700 register_edge_assert_for (op, e,
3701 max ? GE_EXPR : EQ_EXPR,
3702 op, fold_convert (TREE_TYPE (op), min),
3703 asserts);
3704 if (max)
3705 register_edge_assert_for (op, e, LE_EXPR, op,
3706 fold_convert (TREE_TYPE (op), max),
3707 asserts);
3708 finish_register_edge_assert_for (e, bsi, asserts);
3711 XDELETEVEC (ci);
3713 if (!live_on_edge (default_edge, op))
3714 return;
3716 /* Now register along the default label assertions that correspond to the
3717 anti-range of each label. */
3718 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3719 if (insertion_limit == 0)
3720 return;
3722 /* We can't do this if the default case shares a label with another case. */
3723 tree default_cl = gimple_switch_default_label (last);
3724 for (idx = 1; idx < n; idx++)
3726 tree min, max;
3727 tree cl = gimple_switch_label (last, idx);
3728 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3729 continue;
3731 min = CASE_LOW (cl);
3732 max = CASE_HIGH (cl);
3734 /* Combine contiguous case ranges to reduce the number of assertions
3735 to insert. */
3736 for (idx = idx + 1; idx < n; idx++)
3738 tree next_min, next_max;
3739 tree next_cl = gimple_switch_label (last, idx);
3740 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3741 break;
3743 next_min = CASE_LOW (next_cl);
3744 next_max = CASE_HIGH (next_cl);
3746 wide_int difference = (wi::to_wide (next_min)
3747 - wi::to_wide (max ? max : min));
3748 if (wi::eq_p (difference, 1))
3749 max = next_max ? next_max : next_min;
3750 else
3751 break;
3753 idx--;
3755 if (max == NULL_TREE)
3757 /* Register the assertion OP != MIN. */
3758 auto_vec<assert_info, 8> asserts;
3759 min = fold_convert (TREE_TYPE (op), min);
3760 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3761 asserts);
3762 finish_register_edge_assert_for (default_edge, bsi, asserts);
3764 else
3766 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3767 which will give OP the anti-range ~[MIN,MAX]. */
3768 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3769 min = fold_convert (TREE_TYPE (uop), min);
3770 max = fold_convert (TREE_TYPE (uop), max);
3772 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3773 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3774 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3775 NULL, default_edge, bsi);
3778 if (--insertion_limit == 0)
3779 break;
3784 /* Traverse all the statements in block BB looking for statements that
3785 may generate useful assertions for the SSA names in their operand.
3786 If a statement produces a useful assertion A for name N_i, then the
3787 list of assertions already generated for N_i is scanned to
3788 determine if A is actually needed.
3790 If N_i already had the assertion A at a location dominating the
3791 current location, then nothing needs to be done. Otherwise, the
3792 new location for A is recorded instead.
3794 1- For every statement S in BB, all the variables used by S are
3795 added to bitmap FOUND_IN_SUBGRAPH.
3797 2- If statement S uses an operand N in a way that exposes a known
3798 value range for N, then if N was not already generated by an
3799 ASSERT_EXPR, create a new assert location for N. For instance,
3800 if N is a pointer and the statement dereferences it, we can
3801 assume that N is not NULL.
3803 3- COND_EXPRs are a special case of #2. We can derive range
3804 information from the predicate but need to insert different
3805 ASSERT_EXPRs for each of the sub-graphs rooted at the
3806 conditional block. If the last statement of BB is a conditional
3807 expression of the form 'X op Y', then
3809 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3811 b) If the conditional is the only entry point to the sub-graph
3812 corresponding to the THEN_CLAUSE, recurse into it. On
3813 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3814 an ASSERT_EXPR is added for the corresponding variable.
3816 c) Repeat step (b) on the ELSE_CLAUSE.
3818 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3820 For instance,
3822 if (a == 9)
3823 b = a;
3824 else
3825 b = c + 1;
3827 In this case, an assertion on the THEN clause is useful to
3828 determine that 'a' is always 9 on that edge. However, an assertion
3829 on the ELSE clause would be unnecessary.
3831 4- If BB does not end in a conditional expression, then we recurse
3832 into BB's dominator children.
3834 At the end of the recursive traversal, every SSA name will have a
3835 list of locations where ASSERT_EXPRs should be added. When a new
3836 location for name N is found, it is registered by calling
3837 register_new_assert_for. That function keeps track of all the
3838 registered assertions to prevent adding unnecessary assertions.
3839 For instance, if a pointer P_4 is dereferenced more than once in a
3840 dominator tree, only the location dominating all the dereference of
3841 P_4 will receive an ASSERT_EXPR. */
3843 static void
3844 find_assert_locations_1 (basic_block bb, sbitmap live)
3846 gimple *last;
3848 last = last_stmt (bb);
3850 /* If BB's last statement is a conditional statement involving integer
3851 operands, determine if we need to add ASSERT_EXPRs. */
3852 if (last
3853 && gimple_code (last) == GIMPLE_COND
3854 && !fp_predicate (last)
3855 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3856 find_conditional_asserts (bb, as_a <gcond *> (last));
3858 /* If BB's last statement is a switch statement involving integer
3859 operands, determine if we need to add ASSERT_EXPRs. */
3860 if (last
3861 && gimple_code (last) == GIMPLE_SWITCH
3862 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3863 find_switch_asserts (bb, as_a <gswitch *> (last));
3865 /* Traverse all the statements in BB marking used names and looking
3866 for statements that may infer assertions for their used operands. */
3867 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3868 gsi_prev (&si))
3870 gimple *stmt;
3871 tree op;
3872 ssa_op_iter i;
3874 stmt = gsi_stmt (si);
3876 if (is_gimple_debug (stmt))
3877 continue;
3879 /* See if we can derive an assertion for any of STMT's operands. */
3880 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3882 tree value;
3883 enum tree_code comp_code;
3885 /* If op is not live beyond this stmt, do not bother to insert
3886 asserts for it. */
3887 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3888 continue;
3890 /* If OP is used in such a way that we can infer a value
3891 range for it, and we don't find a previous assertion for
3892 it, create a new assertion location node for OP. */
3893 if (infer_value_range (stmt, op, &comp_code, &value))
3895 /* If we are able to infer a nonzero value range for OP,
3896 then walk backwards through the use-def chain to see if OP
3897 was set via a typecast.
3899 If so, then we can also infer a nonzero value range
3900 for the operand of the NOP_EXPR. */
3901 if (comp_code == NE_EXPR && integer_zerop (value))
3903 tree t = op;
3904 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3906 while (is_gimple_assign (def_stmt)
3907 && CONVERT_EXPR_CODE_P
3908 (gimple_assign_rhs_code (def_stmt))
3909 && TREE_CODE
3910 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3911 && POINTER_TYPE_P
3912 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3914 t = gimple_assign_rhs1 (def_stmt);
3915 def_stmt = SSA_NAME_DEF_STMT (t);
3917 /* Note we want to register the assert for the
3918 operand of the NOP_EXPR after SI, not after the
3919 conversion. */
3920 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3921 register_new_assert_for (t, t, comp_code, value,
3922 bb, NULL, si);
3926 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3930 /* Update live. */
3931 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3932 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3933 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3934 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3937 /* Traverse all PHI nodes in BB, updating live. */
3938 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3939 gsi_next (&si))
3941 use_operand_p arg_p;
3942 ssa_op_iter i;
3943 gphi *phi = si.phi ();
3944 tree res = gimple_phi_result (phi);
3946 if (virtual_operand_p (res))
3947 continue;
3949 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3951 tree arg = USE_FROM_PTR (arg_p);
3952 if (TREE_CODE (arg) == SSA_NAME)
3953 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3956 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3960 /* Do an RPO walk over the function computing SSA name liveness
3961 on-the-fly and deciding on assert expressions to insert. */
3963 static void
3964 find_assert_locations (void)
3966 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3967 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3968 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3969 int rpo_cnt, i;
3971 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3972 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3973 for (i = 0; i < rpo_cnt; ++i)
3974 bb_rpo[rpo[i]] = i;
3976 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3977 the order we compute liveness and insert asserts we otherwise
3978 fail to insert asserts into the loop latch. */
3979 loop_p loop;
3980 FOR_EACH_LOOP (loop, 0)
3982 i = loop->latch->index;
3983 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3984 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3985 !gsi_end_p (gsi); gsi_next (&gsi))
3987 gphi *phi = gsi.phi ();
3988 if (virtual_operand_p (gimple_phi_result (phi)))
3989 continue;
3990 tree arg = gimple_phi_arg_def (phi, j);
3991 if (TREE_CODE (arg) == SSA_NAME)
3993 if (live[i] == NULL)
3995 live[i] = sbitmap_alloc (num_ssa_names);
3996 bitmap_clear (live[i]);
3998 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
4003 for (i = rpo_cnt - 1; i >= 0; --i)
4005 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
4006 edge e;
4007 edge_iterator ei;
4009 if (!live[rpo[i]])
4011 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4012 bitmap_clear (live[rpo[i]]);
4015 /* Process BB and update the live information with uses in
4016 this block. */
4017 find_assert_locations_1 (bb, live[rpo[i]]);
4019 /* Merge liveness into the predecessor blocks and free it. */
4020 if (!bitmap_empty_p (live[rpo[i]]))
4022 int pred_rpo = i;
4023 FOR_EACH_EDGE (e, ei, bb->preds)
4025 int pred = e->src->index;
4026 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4027 continue;
4029 if (!live[pred])
4031 live[pred] = sbitmap_alloc (num_ssa_names);
4032 bitmap_clear (live[pred]);
4034 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4036 if (bb_rpo[pred] < pred_rpo)
4037 pred_rpo = bb_rpo[pred];
4040 /* Record the RPO number of the last visited block that needs
4041 live information from this block. */
4042 last_rpo[rpo[i]] = pred_rpo;
4044 else
4046 sbitmap_free (live[rpo[i]]);
4047 live[rpo[i]] = NULL;
4050 /* We can free all successors live bitmaps if all their
4051 predecessors have been visited already. */
4052 FOR_EACH_EDGE (e, ei, bb->succs)
4053 if (last_rpo[e->dest->index] == i
4054 && live[e->dest->index])
4056 sbitmap_free (live[e->dest->index]);
4057 live[e->dest->index] = NULL;
4061 XDELETEVEC (rpo);
4062 XDELETEVEC (bb_rpo);
4063 XDELETEVEC (last_rpo);
4064 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4065 if (live[i])
4066 sbitmap_free (live[i]);
4067 XDELETEVEC (live);
4070 /* Create an ASSERT_EXPR for NAME and insert it in the location
4071 indicated by LOC. Return true if we made any edge insertions. */
4073 static bool
4074 process_assert_insertions_for (tree name, assert_locus *loc)
4076 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4077 gimple *stmt;
4078 tree cond;
4079 gimple *assert_stmt;
4080 edge_iterator ei;
4081 edge e;
4083 /* If we have X <=> X do not insert an assert expr for that. */
4084 if (loc->expr == loc->val)
4085 return false;
4087 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4088 assert_stmt = build_assert_expr_for (cond, name);
4089 if (loc->e)
4091 /* We have been asked to insert the assertion on an edge. This
4092 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4093 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4094 || (gimple_code (gsi_stmt (loc->si))
4095 == GIMPLE_SWITCH));
4097 gsi_insert_on_edge (loc->e, assert_stmt);
4098 return true;
4101 /* If the stmt iterator points at the end then this is an insertion
4102 at the beginning of a block. */
4103 if (gsi_end_p (loc->si))
4105 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4106 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4107 return false;
4110 /* Otherwise, we can insert right after LOC->SI iff the
4111 statement must not be the last statement in the block. */
4112 stmt = gsi_stmt (loc->si);
4113 if (!stmt_ends_bb_p (stmt))
4115 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4116 return false;
4119 /* If STMT must be the last statement in BB, we can only insert new
4120 assertions on the non-abnormal edge out of BB. Note that since
4121 STMT is not control flow, there may only be one non-abnormal/eh edge
4122 out of BB. */
4123 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4124 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4126 gsi_insert_on_edge (e, assert_stmt);
4127 return true;
4130 gcc_unreachable ();
4133 /* Qsort helper for sorting assert locations. If stable is true, don't
4134 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4135 on the other side some pointers might be NULL. */
4137 template <bool stable>
4138 static int
4139 compare_assert_loc (const void *pa, const void *pb)
4141 assert_locus * const a = *(assert_locus * const *)pa;
4142 assert_locus * const b = *(assert_locus * const *)pb;
4144 /* If stable, some asserts might be optimized away already, sort
4145 them last. */
4146 if (stable)
4148 if (a == NULL)
4149 return b != NULL;
4150 else if (b == NULL)
4151 return -1;
4154 if (a->e == NULL && b->e != NULL)
4155 return 1;
4156 else if (a->e != NULL && b->e == NULL)
4157 return -1;
4159 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4160 no need to test both a->e and b->e. */
4162 /* Sort after destination index. */
4163 if (a->e == NULL)
4165 else if (a->e->dest->index > b->e->dest->index)
4166 return 1;
4167 else if (a->e->dest->index < b->e->dest->index)
4168 return -1;
4170 /* Sort after comp_code. */
4171 if (a->comp_code > b->comp_code)
4172 return 1;
4173 else if (a->comp_code < b->comp_code)
4174 return -1;
4176 hashval_t ha, hb;
4178 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4179 uses DECL_UID of the VAR_DECL, so sorting might differ between
4180 -g and -g0. When doing the removal of redundant assert exprs
4181 and commonization to successors, this does not matter, but for
4182 the final sort needs to be stable. */
4183 if (stable)
4185 ha = 0;
4186 hb = 0;
4188 else
4190 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4191 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4194 /* Break the tie using hashing and source/bb index. */
4195 if (ha == hb)
4196 return (a->e != NULL
4197 ? a->e->src->index - b->e->src->index
4198 : a->bb->index - b->bb->index);
4199 return ha > hb ? 1 : -1;
4202 /* Process all the insertions registered for every name N_i registered
4203 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4204 found in ASSERTS_FOR[i]. */
4206 static void
4207 process_assert_insertions (void)
4209 unsigned i;
4210 bitmap_iterator bi;
4211 bool update_edges_p = false;
4212 int num_asserts = 0;
4214 if (dump_file && (dump_flags & TDF_DETAILS))
4215 dump_all_asserts (dump_file);
4217 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4219 assert_locus *loc = asserts_for[i];
4220 gcc_assert (loc);
4222 auto_vec<assert_locus *, 16> asserts;
4223 for (; loc; loc = loc->next)
4224 asserts.safe_push (loc);
4225 asserts.qsort (compare_assert_loc<false>);
4227 /* Push down common asserts to successors and remove redundant ones. */
4228 unsigned ecnt = 0;
4229 assert_locus *common = NULL;
4230 unsigned commonj = 0;
4231 for (unsigned j = 0; j < asserts.length (); ++j)
4233 loc = asserts[j];
4234 if (! loc->e)
4235 common = NULL;
4236 else if (! common
4237 || loc->e->dest != common->e->dest
4238 || loc->comp_code != common->comp_code
4239 || ! operand_equal_p (loc->val, common->val, 0)
4240 || ! operand_equal_p (loc->expr, common->expr, 0))
4242 commonj = j;
4243 common = loc;
4244 ecnt = 1;
4246 else if (loc->e == asserts[j-1]->e)
4248 /* Remove duplicate asserts. */
4249 if (commonj == j - 1)
4251 commonj = j;
4252 common = loc;
4254 free (asserts[j-1]);
4255 asserts[j-1] = NULL;
4257 else
4259 ecnt++;
4260 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4262 /* We have the same assertion on all incoming edges of a BB.
4263 Insert it at the beginning of that block. */
4264 loc->bb = loc->e->dest;
4265 loc->e = NULL;
4266 loc->si = gsi_none ();
4267 common = NULL;
4268 /* Clear asserts commoned. */
4269 for (; commonj != j; ++commonj)
4270 if (asserts[commonj])
4272 free (asserts[commonj]);
4273 asserts[commonj] = NULL;
4279 /* The asserts vector sorting above might be unstable for
4280 -fcompare-debug, sort again to ensure a stable sort. */
4281 asserts.qsort (compare_assert_loc<true>);
4282 for (unsigned j = 0; j < asserts.length (); ++j)
4284 loc = asserts[j];
4285 if (! loc)
4286 break;
4287 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4288 num_asserts++;
4289 free (loc);
4293 if (update_edges_p)
4294 gsi_commit_edge_inserts ();
4296 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4297 num_asserts);
4301 /* Traverse the flowgraph looking for conditional jumps to insert range
4302 expressions. These range expressions are meant to provide information
4303 to optimizations that need to reason in terms of value ranges. They
4304 will not be expanded into RTL. For instance, given:
4306 x = ...
4307 y = ...
4308 if (x < y)
4309 y = x - 2;
4310 else
4311 x = y + 3;
4313 this pass will transform the code into:
4315 x = ...
4316 y = ...
4317 if (x < y)
4319 x = ASSERT_EXPR <x, x < y>
4320 y = x - 2
4322 else
4324 y = ASSERT_EXPR <y, x >= y>
4325 x = y + 3
4328 The idea is that once copy and constant propagation have run, other
4329 optimizations will be able to determine what ranges of values can 'x'
4330 take in different paths of the code, simply by checking the reaching
4331 definition of 'x'. */
4333 static void
4334 insert_range_assertions (void)
4336 need_assert_for = BITMAP_ALLOC (NULL);
4337 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4339 calculate_dominance_info (CDI_DOMINATORS);
4341 find_assert_locations ();
4342 if (!bitmap_empty_p (need_assert_for))
4344 process_assert_insertions ();
4345 update_ssa (TODO_update_ssa_no_phi);
4348 if (dump_file && (dump_flags & TDF_DETAILS))
4350 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4351 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4354 free (asserts_for);
4355 BITMAP_FREE (need_assert_for);
4358 class vrp_prop : public ssa_propagation_engine
4360 public:
4361 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4362 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4364 void vrp_initialize (void);
4365 void vrp_finalize (bool);
4366 void check_all_array_refs (void);
4367 void check_array_ref (location_t, tree, bool);
4368 void check_mem_ref (location_t, tree, bool);
4369 void search_for_addr_array (tree, location_t);
4371 class vr_values vr_values;
4372 /* Temporary delegator to minimize code churn. */
4373 value_range *get_value_range (const_tree op)
4374 { return vr_values.get_value_range (op); }
4375 void set_defs_to_varying (gimple *stmt)
4376 { return vr_values.set_defs_to_varying (stmt); }
4377 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4378 tree *output_p, value_range *vr)
4379 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4380 bool update_value_range (const_tree op, value_range *vr)
4381 { return vr_values.update_value_range (op, vr); }
4382 void extract_range_basic (value_range *vr, gimple *stmt)
4383 { vr_values.extract_range_basic (vr, stmt); }
4384 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4385 { vr_values.extract_range_from_phi_node (phi, vr); }
4387 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4388 and "struct" hacks. If VRP can determine that the
4389 array subscript is a constant, check if it is outside valid
4390 range. If the array subscript is a RANGE, warn if it is
4391 non-overlapping with valid range.
4392 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4394 void
4395 vrp_prop::check_array_ref (location_t location, tree ref,
4396 bool ignore_off_by_one)
4398 value_range *vr = NULL;
4399 tree low_sub, up_sub;
4400 tree low_bound, up_bound, up_bound_p1;
4402 if (TREE_NO_WARNING (ref))
4403 return;
4405 low_sub = up_sub = TREE_OPERAND (ref, 1);
4406 up_bound = array_ref_up_bound (ref);
4408 if (!up_bound
4409 || TREE_CODE (up_bound) != INTEGER_CST
4410 || (warn_array_bounds < 2
4411 && array_at_struct_end_p (ref)))
4413 /* Accesses to trailing arrays via pointers may access storage
4414 beyond the types array bounds. For such arrays, or for flexible
4415 array members, as well as for other arrays of an unknown size,
4416 replace the upper bound with a more permissive one that assumes
4417 the size of the largest object is PTRDIFF_MAX. */
4418 tree eltsize = array_ref_element_size (ref);
4420 if (TREE_CODE (eltsize) != INTEGER_CST
4421 || integer_zerop (eltsize))
4423 up_bound = NULL_TREE;
4424 up_bound_p1 = NULL_TREE;
4426 else
4428 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4429 tree arg = TREE_OPERAND (ref, 0);
4430 poly_int64 off;
4432 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4433 maxbound = wide_int_to_tree (sizetype,
4434 wi::sub (wi::to_wide (maxbound),
4435 off));
4436 else
4437 maxbound = fold_convert (sizetype, maxbound);
4439 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4441 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4442 build_int_cst (ptrdiff_type_node, 1));
4445 else
4446 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4447 build_int_cst (TREE_TYPE (up_bound), 1));
4449 low_bound = array_ref_low_bound (ref);
4451 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4453 bool warned = false;
4455 /* Empty array. */
4456 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4457 warned = warning_at (location, OPT_Warray_bounds,
4458 "array subscript %E is above array bounds of %qT",
4459 low_bound, artype);
4461 if (TREE_CODE (low_sub) == SSA_NAME)
4463 vr = get_value_range (low_sub);
4464 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4466 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4467 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4471 if (vr && vr->type == VR_ANTI_RANGE)
4473 if (up_bound
4474 && TREE_CODE (up_sub) == INTEGER_CST
4475 && (ignore_off_by_one
4476 ? tree_int_cst_lt (up_bound, up_sub)
4477 : tree_int_cst_le (up_bound, up_sub))
4478 && TREE_CODE (low_sub) == INTEGER_CST
4479 && tree_int_cst_le (low_sub, low_bound))
4480 warned = warning_at (location, OPT_Warray_bounds,
4481 "array subscript [%E, %E] is outside "
4482 "array bounds of %qT",
4483 low_sub, up_sub, artype);
4485 else if (up_bound
4486 && TREE_CODE (up_sub) == INTEGER_CST
4487 && (ignore_off_by_one
4488 ? !tree_int_cst_le (up_sub, up_bound_p1)
4489 : !tree_int_cst_le (up_sub, up_bound)))
4491 if (dump_file && (dump_flags & TDF_DETAILS))
4493 fprintf (dump_file, "Array bound warning for ");
4494 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4495 fprintf (dump_file, "\n");
4497 warned = warning_at (location, OPT_Warray_bounds,
4498 "array subscript %E is above array bounds of %qT",
4499 up_sub, artype);
4501 else if (TREE_CODE (low_sub) == INTEGER_CST
4502 && tree_int_cst_lt (low_sub, low_bound))
4504 if (dump_file && (dump_flags & TDF_DETAILS))
4506 fprintf (dump_file, "Array bound warning for ");
4507 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4508 fprintf (dump_file, "\n");
4510 warned = warning_at (location, OPT_Warray_bounds,
4511 "array subscript %E is below array bounds of %qT",
4512 low_sub, artype);
4515 if (warned)
4517 ref = TREE_OPERAND (ref, 0);
4519 if (DECL_P (ref))
4520 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4522 TREE_NO_WARNING (ref) = 1;
4526 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4527 references to string constants. If VRP can determine that the array
4528 subscript is a constant, check if it is outside valid range.
4529 If the array subscript is a RANGE, warn if it is non-overlapping
4530 with valid range.
4531 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4532 (used to allow one-past-the-end indices for code that takes
4533 the address of the just-past-the-end element of an array). */
4535 void
4536 vrp_prop::check_mem_ref (location_t location, tree ref,
4537 bool ignore_off_by_one)
4539 if (TREE_NO_WARNING (ref))
4540 return;
4542 tree arg = TREE_OPERAND (ref, 0);
4543 /* The constant and variable offset of the reference. */
4544 tree cstoff = TREE_OPERAND (ref, 1);
4545 tree varoff = NULL_TREE;
4547 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4549 /* The array or string constant bounds in bytes. Initially set
4550 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4551 determined. */
4552 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4554 /* The minimum and maximum intermediate offset. For a reference
4555 to be valid, not only does the final offset/subscript must be
4556 in bounds but all intermediate offsets should be as well.
4557 GCC may be able to deal gracefully with such out-of-bounds
4558 offsets so the checking is only enbaled at -Warray-bounds=2
4559 where it may help detect bugs in uses of the intermediate
4560 offsets that could otherwise not be detectable. */
4561 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4562 offset_int extrema[2] = { 0, wi::abs (ioff) };
4564 /* The range of the byte offset into the reference. */
4565 offset_int offrange[2] = { 0, 0 };
4567 value_range *vr = NULL;
4569 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4570 The loop computes the the range of the final offset for expressions
4571 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4572 in some range. */
4573 while (TREE_CODE (arg) == SSA_NAME)
4575 gimple *def = SSA_NAME_DEF_STMT (arg);
4576 if (!is_gimple_assign (def))
4577 break;
4579 tree_code code = gimple_assign_rhs_code (def);
4580 if (code == POINTER_PLUS_EXPR)
4582 arg = gimple_assign_rhs1 (def);
4583 varoff = gimple_assign_rhs2 (def);
4585 else if (code == ASSERT_EXPR)
4587 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4588 continue;
4590 else
4591 return;
4593 /* VAROFF should always be a SSA_NAME here (and not even
4594 INTEGER_CST) but there's no point in taking chances. */
4595 if (TREE_CODE (varoff) != SSA_NAME)
4596 break;
4598 vr = get_value_range (varoff);
4599 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4600 break;
4602 if (TREE_CODE (vr->min) != INTEGER_CST
4603 || TREE_CODE (vr->max) != INTEGER_CST)
4604 break;
4606 if (vr->type == VR_RANGE)
4608 if (tree_int_cst_lt (vr->min, vr->max))
4610 offset_int min
4611 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4612 offset_int max
4613 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4614 if (min < max)
4616 offrange[0] += min;
4617 offrange[1] += max;
4619 else
4621 offrange[0] += max;
4622 offrange[1] += min;
4625 else
4627 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4628 to OFFRANGE. */
4629 offrange[0] += arrbounds[0];
4630 offrange[1] += arrbounds[1];
4633 else
4635 /* For an anti-range, analogously to the above, conservatively
4636 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4637 offrange[0] += arrbounds[0];
4638 offrange[1] += arrbounds[1];
4641 /* Keep track of the minimum and maximum offset. */
4642 if (offrange[1] < 0 && offrange[1] < extrema[0])
4643 extrema[0] = offrange[1];
4644 if (offrange[0] > 0 && offrange[0] > extrema[1])
4645 extrema[1] = offrange[0];
4647 if (offrange[0] < arrbounds[0])
4648 offrange[0] = arrbounds[0];
4650 if (offrange[1] > arrbounds[1])
4651 offrange[1] = arrbounds[1];
4654 if (TREE_CODE (arg) == ADDR_EXPR)
4656 arg = TREE_OPERAND (arg, 0);
4657 if (TREE_CODE (arg) != STRING_CST
4658 && TREE_CODE (arg) != VAR_DECL)
4659 return;
4661 else
4662 return;
4664 /* The type of the object being referred to. It can be an array,
4665 string literal, or a non-array type when the MEM_REF represents
4666 a reference/subscript via a pointer to an object that is not
4667 an element of an array. References to members of structs and
4668 unions are excluded because MEM_REF doesn't make it possible
4669 to identify the member where the reference originated.
4670 Incomplete types are excluded as well because their size is
4671 not known. */
4672 tree reftype = TREE_TYPE (arg);
4673 if (POINTER_TYPE_P (reftype)
4674 || !COMPLETE_TYPE_P (reftype)
4675 || RECORD_OR_UNION_TYPE_P (reftype))
4676 return;
4678 offset_int eltsize;
4679 if (TREE_CODE (reftype) == ARRAY_TYPE)
4681 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4683 if (tree dom = TYPE_DOMAIN (reftype))
4685 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4686 if (array_at_struct_end_p (arg)
4687 || !bnds[0] || !bnds[1])
4689 arrbounds[0] = 0;
4690 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4692 else
4694 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4695 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4698 else
4700 arrbounds[0] = 0;
4701 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4704 if (TREE_CODE (ref) == MEM_REF)
4706 /* For MEM_REF determine a tighter bound of the non-array
4707 element type. */
4708 tree eltype = TREE_TYPE (reftype);
4709 while (TREE_CODE (eltype) == ARRAY_TYPE)
4710 eltype = TREE_TYPE (eltype);
4711 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4714 else
4716 eltsize = 1;
4717 arrbounds[0] = 0;
4718 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4721 offrange[0] += ioff;
4722 offrange[1] += ioff;
4724 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4725 is set (when taking the address of the one-past-last element
4726 of an array) but always use the stricter bound in diagnostics. */
4727 offset_int ubound = arrbounds[1];
4728 if (ignore_off_by_one)
4729 ubound += 1;
4731 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4733 /* Treat a reference to a non-array object as one to an array
4734 of a single element. */
4735 if (TREE_CODE (reftype) != ARRAY_TYPE)
4736 reftype = build_array_type_nelts (reftype, 1);
4738 if (TREE_CODE (ref) == MEM_REF)
4740 /* Extract the element type out of MEM_REF and use its size
4741 to compute the index to print in the diagnostic; arrays
4742 in MEM_REF don't mean anything. */
4743 tree type = TREE_TYPE (ref);
4744 while (TREE_CODE (type) == ARRAY_TYPE)
4745 type = TREE_TYPE (type);
4746 tree size = TYPE_SIZE_UNIT (type);
4747 offrange[0] = offrange[0] / wi::to_offset (size);
4748 offrange[1] = offrange[1] / wi::to_offset (size);
4750 else
4752 /* For anything other than MEM_REF, compute the index to
4753 print in the diagnostic as the offset over element size. */
4754 offrange[0] = offrange[0] / eltsize;
4755 offrange[1] = offrange[1] / eltsize;
4758 bool warned;
4759 if (offrange[0] == offrange[1])
4760 warned = warning_at (location, OPT_Warray_bounds,
4761 "array subscript %wi is outside array bounds "
4762 "of %qT",
4763 offrange[0].to_shwi (), reftype);
4764 else
4765 warned = warning_at (location, OPT_Warray_bounds,
4766 "array subscript [%wi, %wi] is outside "
4767 "array bounds of %qT",
4768 offrange[0].to_shwi (),
4769 offrange[1].to_shwi (), reftype);
4770 if (warned && DECL_P (arg))
4771 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4773 TREE_NO_WARNING (ref) = 1;
4774 return;
4777 if (warn_array_bounds < 2)
4778 return;
4780 /* At level 2 check also intermediate offsets. */
4781 int i = 0;
4782 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4784 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4786 warning_at (location, OPT_Warray_bounds,
4787 "intermediate array offset %wi is outside array bounds "
4788 "of %qT",
4789 tmpidx, reftype);
4790 TREE_NO_WARNING (ref) = 1;
4794 /* Searches if the expr T, located at LOCATION computes
4795 address of an ARRAY_REF, and call check_array_ref on it. */
4797 void
4798 vrp_prop::search_for_addr_array (tree t, location_t location)
4800 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4803 if (TREE_CODE (t) == ARRAY_REF)
4804 check_array_ref (location, t, true /*ignore_off_by_one*/);
4805 else if (TREE_CODE (t) == MEM_REF)
4806 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4808 t = TREE_OPERAND (t, 0);
4810 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4812 if (TREE_CODE (t) != MEM_REF
4813 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4814 || TREE_NO_WARNING (t))
4815 return;
4817 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4818 tree low_bound, up_bound, el_sz;
4819 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4820 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4821 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4822 return;
4824 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4825 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4826 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4827 if (!low_bound
4828 || TREE_CODE (low_bound) != INTEGER_CST
4829 || !up_bound
4830 || TREE_CODE (up_bound) != INTEGER_CST
4831 || !el_sz
4832 || TREE_CODE (el_sz) != INTEGER_CST)
4833 return;
4835 offset_int idx;
4836 if (!mem_ref_offset (t).is_constant (&idx))
4837 return;
4839 bool warned = false;
4840 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4841 if (idx < 0)
4843 if (dump_file && (dump_flags & TDF_DETAILS))
4845 fprintf (dump_file, "Array bound warning for ");
4846 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4847 fprintf (dump_file, "\n");
4849 warned = warning_at (location, OPT_Warray_bounds,
4850 "array subscript %wi is below "
4851 "array bounds of %qT",
4852 idx.to_shwi (), TREE_TYPE (tem));
4854 else if (idx > (wi::to_offset (up_bound)
4855 - wi::to_offset (low_bound) + 1))
4857 if (dump_file && (dump_flags & TDF_DETAILS))
4859 fprintf (dump_file, "Array bound warning for ");
4860 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4861 fprintf (dump_file, "\n");
4863 warned = warning_at (location, OPT_Warray_bounds,
4864 "array subscript %wu is above "
4865 "array bounds of %qT",
4866 idx.to_uhwi (), TREE_TYPE (tem));
4869 if (warned)
4871 if (DECL_P (t))
4872 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4874 TREE_NO_WARNING (t) = 1;
4878 /* walk_tree() callback that checks if *TP is
4879 an ARRAY_REF inside an ADDR_EXPR (in which an array
4880 subscript one outside the valid range is allowed). Call
4881 check_array_ref for each ARRAY_REF found. The location is
4882 passed in DATA. */
4884 static tree
4885 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4887 tree t = *tp;
4888 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4889 location_t location;
4891 if (EXPR_HAS_LOCATION (t))
4892 location = EXPR_LOCATION (t);
4893 else
4894 location = gimple_location (wi->stmt);
4896 *walk_subtree = TRUE;
4898 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4899 if (TREE_CODE (t) == ARRAY_REF)
4900 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4901 else if (TREE_CODE (t) == MEM_REF)
4902 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4903 else if (TREE_CODE (t) == ADDR_EXPR)
4905 vrp_prop->search_for_addr_array (t, location);
4906 *walk_subtree = FALSE;
4909 return NULL_TREE;
4912 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4913 to walk over all statements of all reachable BBs and call
4914 check_array_bounds on them. */
4916 class check_array_bounds_dom_walker : public dom_walker
4918 public:
4919 check_array_bounds_dom_walker (vrp_prop *prop)
4920 : dom_walker (CDI_DOMINATORS,
4921 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4922 flags, so that we can merge in information on
4923 non-executable edges from vrp_folder . */
4924 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4925 m_prop (prop) {}
4926 ~check_array_bounds_dom_walker () {}
4928 edge before_dom_children (basic_block) FINAL OVERRIDE;
4930 private:
4931 vrp_prop *m_prop;
4934 /* Implementation of dom_walker::before_dom_children.
4936 Walk over all statements of BB and call check_array_bounds on them,
4937 and determine if there's a unique successor edge. */
4939 edge
4940 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4942 gimple_stmt_iterator si;
4943 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4945 gimple *stmt = gsi_stmt (si);
4946 struct walk_stmt_info wi;
4947 if (!gimple_has_location (stmt)
4948 || is_gimple_debug (stmt))
4949 continue;
4951 memset (&wi, 0, sizeof (wi));
4953 wi.info = m_prop;
4955 walk_gimple_op (stmt, check_array_bounds, &wi);
4958 /* Determine if there's a unique successor edge, and if so, return
4959 that back to dom_walker, ensuring that we don't visit blocks that
4960 became unreachable during the VRP propagation
4961 (PR tree-optimization/83312). */
4962 return find_taken_edge (bb, NULL_TREE);
4965 /* Walk over all statements of all reachable BBs and call check_array_bounds
4966 on them. */
4968 void
4969 vrp_prop::check_all_array_refs ()
4971 check_array_bounds_dom_walker w (this);
4972 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4975 /* Return true if all imm uses of VAR are either in STMT, or
4976 feed (optionally through a chain of single imm uses) GIMPLE_COND
4977 in basic block COND_BB. */
4979 static bool
4980 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4982 use_operand_p use_p, use2_p;
4983 imm_use_iterator iter;
4985 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4986 if (USE_STMT (use_p) != stmt)
4988 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4989 if (is_gimple_debug (use_stmt))
4990 continue;
4991 while (is_gimple_assign (use_stmt)
4992 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4993 && single_imm_use (gimple_assign_lhs (use_stmt),
4994 &use2_p, &use_stmt2))
4995 use_stmt = use_stmt2;
4996 if (gimple_code (use_stmt) != GIMPLE_COND
4997 || gimple_bb (use_stmt) != cond_bb)
4998 return false;
5000 return true;
5003 /* Handle
5004 _4 = x_3 & 31;
5005 if (_4 != 0)
5006 goto <bb 6>;
5007 else
5008 goto <bb 7>;
5009 <bb 6>:
5010 __builtin_unreachable ();
5011 <bb 7>:
5012 x_5 = ASSERT_EXPR <x_3, ...>;
5013 If x_3 has no other immediate uses (checked by caller),
5014 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
5015 from the non-zero bitmask. */
5017 void
5018 maybe_set_nonzero_bits (edge e, tree var)
5020 basic_block cond_bb = e->src;
5021 gimple *stmt = last_stmt (cond_bb);
5022 tree cst;
5024 if (stmt == NULL
5025 || gimple_code (stmt) != GIMPLE_COND
5026 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5027 ? EQ_EXPR : NE_EXPR)
5028 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5029 || !integer_zerop (gimple_cond_rhs (stmt)))
5030 return;
5032 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5033 if (!is_gimple_assign (stmt)
5034 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5035 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5036 return;
5037 if (gimple_assign_rhs1 (stmt) != var)
5039 gimple *stmt2;
5041 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5042 return;
5043 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5044 if (!gimple_assign_cast_p (stmt2)
5045 || gimple_assign_rhs1 (stmt2) != var
5046 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5047 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5048 != TYPE_PRECISION (TREE_TYPE (var))))
5049 return;
5051 cst = gimple_assign_rhs2 (stmt);
5052 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5053 wi::to_wide (cst)));
5056 /* Convert range assertion expressions into the implied copies and
5057 copy propagate away the copies. Doing the trivial copy propagation
5058 here avoids the need to run the full copy propagation pass after
5059 VRP.
5061 FIXME, this will eventually lead to copy propagation removing the
5062 names that had useful range information attached to them. For
5063 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5064 then N_i will have the range [3, +INF].
5066 However, by converting the assertion into the implied copy
5067 operation N_i = N_j, we will then copy-propagate N_j into the uses
5068 of N_i and lose the range information. We may want to hold on to
5069 ASSERT_EXPRs a little while longer as the ranges could be used in
5070 things like jump threading.
5072 The problem with keeping ASSERT_EXPRs around is that passes after
5073 VRP need to handle them appropriately.
5075 Another approach would be to make the range information a first
5076 class property of the SSA_NAME so that it can be queried from
5077 any pass. This is made somewhat more complex by the need for
5078 multiple ranges to be associated with one SSA_NAME. */
5080 static void
5081 remove_range_assertions (void)
5083 basic_block bb;
5084 gimple_stmt_iterator si;
5085 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5086 a basic block preceeded by GIMPLE_COND branching to it and
5087 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5088 int is_unreachable;
5090 /* Note that the BSI iterator bump happens at the bottom of the
5091 loop and no bump is necessary if we're removing the statement
5092 referenced by the current BSI. */
5093 FOR_EACH_BB_FN (bb, cfun)
5094 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5096 gimple *stmt = gsi_stmt (si);
5098 if (is_gimple_assign (stmt)
5099 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5101 tree lhs = gimple_assign_lhs (stmt);
5102 tree rhs = gimple_assign_rhs1 (stmt);
5103 tree var;
5105 var = ASSERT_EXPR_VAR (rhs);
5107 if (TREE_CODE (var) == SSA_NAME
5108 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5109 && SSA_NAME_RANGE_INFO (lhs))
5111 if (is_unreachable == -1)
5113 is_unreachable = 0;
5114 if (single_pred_p (bb)
5115 && assert_unreachable_fallthru_edge_p
5116 (single_pred_edge (bb)))
5117 is_unreachable = 1;
5119 /* Handle
5120 if (x_7 >= 10 && x_7 < 20)
5121 __builtin_unreachable ();
5122 x_8 = ASSERT_EXPR <x_7, ...>;
5123 if the only uses of x_7 are in the ASSERT_EXPR and
5124 in the condition. In that case, we can copy the
5125 range info from x_8 computed in this pass also
5126 for x_7. */
5127 if (is_unreachable
5128 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5129 single_pred (bb)))
5131 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5132 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5133 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5134 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5138 /* Propagate the RHS into every use of the LHS. For SSA names
5139 also propagate abnormals as it merely restores the original
5140 IL in this case (an replace_uses_by would assert). */
5141 if (TREE_CODE (var) == SSA_NAME)
5143 imm_use_iterator iter;
5144 use_operand_p use_p;
5145 gimple *use_stmt;
5146 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5147 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5148 SET_USE (use_p, var);
5150 else
5151 replace_uses_by (lhs, var);
5153 /* And finally, remove the copy, it is not needed. */
5154 gsi_remove (&si, true);
5155 release_defs (stmt);
5157 else
5159 if (!is_gimple_debug (gsi_stmt (si)))
5160 is_unreachable = 0;
5161 gsi_next (&si);
5166 /* Return true if STMT is interesting for VRP. */
5168 bool
5169 stmt_interesting_for_vrp (gimple *stmt)
5171 if (gimple_code (stmt) == GIMPLE_PHI)
5173 tree res = gimple_phi_result (stmt);
5174 return (!virtual_operand_p (res)
5175 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5176 || POINTER_TYPE_P (TREE_TYPE (res))));
5178 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5180 tree lhs = gimple_get_lhs (stmt);
5182 /* In general, assignments with virtual operands are not useful
5183 for deriving ranges, with the obvious exception of calls to
5184 builtin functions. */
5185 if (lhs && TREE_CODE (lhs) == SSA_NAME
5186 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5187 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5188 && (is_gimple_call (stmt)
5189 || !gimple_vuse (stmt)))
5190 return true;
5191 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5192 switch (gimple_call_internal_fn (stmt))
5194 case IFN_ADD_OVERFLOW:
5195 case IFN_SUB_OVERFLOW:
5196 case IFN_MUL_OVERFLOW:
5197 case IFN_ATOMIC_COMPARE_EXCHANGE:
5198 /* These internal calls return _Complex integer type,
5199 but are interesting to VRP nevertheless. */
5200 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5201 return true;
5202 break;
5203 default:
5204 break;
5207 else if (gimple_code (stmt) == GIMPLE_COND
5208 || gimple_code (stmt) == GIMPLE_SWITCH)
5209 return true;
5211 return false;
5214 /* Initialization required by ssa_propagate engine. */
5216 void
5217 vrp_prop::vrp_initialize ()
5219 basic_block bb;
5221 FOR_EACH_BB_FN (bb, cfun)
5223 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5224 gsi_next (&si))
5226 gphi *phi = si.phi ();
5227 if (!stmt_interesting_for_vrp (phi))
5229 tree lhs = PHI_RESULT (phi);
5230 set_value_range_to_varying (get_value_range (lhs));
5231 prop_set_simulate_again (phi, false);
5233 else
5234 prop_set_simulate_again (phi, true);
5237 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5238 gsi_next (&si))
5240 gimple *stmt = gsi_stmt (si);
5242 /* If the statement is a control insn, then we do not
5243 want to avoid simulating the statement once. Failure
5244 to do so means that those edges will never get added. */
5245 if (stmt_ends_bb_p (stmt))
5246 prop_set_simulate_again (stmt, true);
5247 else if (!stmt_interesting_for_vrp (stmt))
5249 set_defs_to_varying (stmt);
5250 prop_set_simulate_again (stmt, false);
5252 else
5253 prop_set_simulate_again (stmt, true);
5258 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5259 that includes the value VAL. The search is restricted to the range
5260 [START_IDX, n - 1] where n is the size of VEC.
5262 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5263 returned.
5265 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5266 it is placed in IDX and false is returned.
5268 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5269 returned. */
5271 bool
5272 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5274 size_t n = gimple_switch_num_labels (stmt);
5275 size_t low, high;
5277 /* Find case label for minimum of the value range or the next one.
5278 At each iteration we are searching in [low, high - 1]. */
5280 for (low = start_idx, high = n; high != low; )
5282 tree t;
5283 int cmp;
5284 /* Note that i != high, so we never ask for n. */
5285 size_t i = (high + low) / 2;
5286 t = gimple_switch_label (stmt, i);
5288 /* Cache the result of comparing CASE_LOW and val. */
5289 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5291 if (cmp == 0)
5293 /* Ranges cannot be empty. */
5294 *idx = i;
5295 return true;
5297 else if (cmp > 0)
5298 high = i;
5299 else
5301 low = i + 1;
5302 if (CASE_HIGH (t) != NULL
5303 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5305 *idx = i;
5306 return true;
5311 *idx = high;
5312 return false;
5315 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5316 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5317 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5318 then MAX_IDX < MIN_IDX.
5319 Returns true if the default label is not needed. */
5321 bool
5322 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5323 size_t *max_idx)
5325 size_t i, j;
5326 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5327 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5329 if (i == j
5330 && min_take_default
5331 && max_take_default)
5333 /* Only the default case label reached.
5334 Return an empty range. */
5335 *min_idx = 1;
5336 *max_idx = 0;
5337 return false;
5339 else
5341 bool take_default = min_take_default || max_take_default;
5342 tree low, high;
5343 size_t k;
5345 if (max_take_default)
5346 j--;
5348 /* If the case label range is continuous, we do not need
5349 the default case label. Verify that. */
5350 high = CASE_LOW (gimple_switch_label (stmt, i));
5351 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5352 high = CASE_HIGH (gimple_switch_label (stmt, i));
5353 for (k = i + 1; k <= j; ++k)
5355 low = CASE_LOW (gimple_switch_label (stmt, k));
5356 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5358 take_default = true;
5359 break;
5361 high = low;
5362 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5363 high = CASE_HIGH (gimple_switch_label (stmt, k));
5366 *min_idx = i;
5367 *max_idx = j;
5368 return !take_default;
5372 /* Evaluate statement STMT. If the statement produces a useful range,
5373 return SSA_PROP_INTERESTING and record the SSA name with the
5374 interesting range into *OUTPUT_P.
5376 If STMT is a conditional branch and we can determine its truth
5377 value, the taken edge is recorded in *TAKEN_EDGE_P.
5379 If STMT produces a varying value, return SSA_PROP_VARYING. */
5381 enum ssa_prop_result
5382 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5384 value_range vr = VR_INITIALIZER;
5385 tree lhs = gimple_get_lhs (stmt);
5386 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5388 if (*output_p)
5390 if (update_value_range (*output_p, &vr))
5392 if (dump_file && (dump_flags & TDF_DETAILS))
5394 fprintf (dump_file, "Found new range for ");
5395 print_generic_expr (dump_file, *output_p);
5396 fprintf (dump_file, ": ");
5397 dump_value_range (dump_file, &vr);
5398 fprintf (dump_file, "\n");
5401 if (vr.type == VR_VARYING)
5402 return SSA_PROP_VARYING;
5404 return SSA_PROP_INTERESTING;
5406 return SSA_PROP_NOT_INTERESTING;
5409 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5410 switch (gimple_call_internal_fn (stmt))
5412 case IFN_ADD_OVERFLOW:
5413 case IFN_SUB_OVERFLOW:
5414 case IFN_MUL_OVERFLOW:
5415 case IFN_ATOMIC_COMPARE_EXCHANGE:
5416 /* These internal calls return _Complex integer type,
5417 which VRP does not track, but the immediate uses
5418 thereof might be interesting. */
5419 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5421 imm_use_iterator iter;
5422 use_operand_p use_p;
5423 enum ssa_prop_result res = SSA_PROP_VARYING;
5425 set_value_range_to_varying (get_value_range (lhs));
5427 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5429 gimple *use_stmt = USE_STMT (use_p);
5430 if (!is_gimple_assign (use_stmt))
5431 continue;
5432 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5433 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5434 continue;
5435 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5436 tree use_lhs = gimple_assign_lhs (use_stmt);
5437 if (TREE_CODE (rhs1) != rhs_code
5438 || TREE_OPERAND (rhs1, 0) != lhs
5439 || TREE_CODE (use_lhs) != SSA_NAME
5440 || !stmt_interesting_for_vrp (use_stmt)
5441 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5442 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5443 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5444 continue;
5446 /* If there is a change in the value range for any of the
5447 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5448 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5449 or IMAGPART_EXPR immediate uses, but none of them have
5450 a change in their value ranges, return
5451 SSA_PROP_NOT_INTERESTING. If there are no
5452 {REAL,IMAG}PART_EXPR uses at all,
5453 return SSA_PROP_VARYING. */
5454 value_range new_vr = VR_INITIALIZER;
5455 extract_range_basic (&new_vr, use_stmt);
5456 value_range *old_vr = get_value_range (use_lhs);
5457 if (old_vr->type != new_vr.type
5458 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5459 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5460 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5461 res = SSA_PROP_INTERESTING;
5462 else
5463 res = SSA_PROP_NOT_INTERESTING;
5464 BITMAP_FREE (new_vr.equiv);
5465 if (res == SSA_PROP_INTERESTING)
5467 *output_p = lhs;
5468 return res;
5472 return res;
5474 break;
5475 default:
5476 break;
5479 /* All other statements produce nothing of interest for VRP, so mark
5480 their outputs varying and prevent further simulation. */
5481 set_defs_to_varying (stmt);
5483 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5486 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5487 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5488 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5489 possible such range. The resulting range is not canonicalized. */
5491 static void
5492 union_ranges (enum value_range_type *vr0type,
5493 tree *vr0min, tree *vr0max,
5494 enum value_range_type vr1type,
5495 tree vr1min, tree vr1max)
5497 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5498 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5500 /* [] is vr0, () is vr1 in the following classification comments. */
5501 if (mineq && maxeq)
5503 /* [( )] */
5504 if (*vr0type == vr1type)
5505 /* Nothing to do for equal ranges. */
5507 else if ((*vr0type == VR_RANGE
5508 && vr1type == VR_ANTI_RANGE)
5509 || (*vr0type == VR_ANTI_RANGE
5510 && vr1type == VR_RANGE))
5512 /* For anti-range with range union the result is varying. */
5513 goto give_up;
5515 else
5516 gcc_unreachable ();
5518 else if (operand_less_p (*vr0max, vr1min) == 1
5519 || operand_less_p (vr1max, *vr0min) == 1)
5521 /* [ ] ( ) or ( ) [ ]
5522 If the ranges have an empty intersection, result of the union
5523 operation is the anti-range or if both are anti-ranges
5524 it covers all. */
5525 if (*vr0type == VR_ANTI_RANGE
5526 && vr1type == VR_ANTI_RANGE)
5527 goto give_up;
5528 else if (*vr0type == VR_ANTI_RANGE
5529 && vr1type == VR_RANGE)
5531 else if (*vr0type == VR_RANGE
5532 && vr1type == VR_ANTI_RANGE)
5534 *vr0type = vr1type;
5535 *vr0min = vr1min;
5536 *vr0max = vr1max;
5538 else if (*vr0type == VR_RANGE
5539 && vr1type == VR_RANGE)
5541 /* The result is the convex hull of both ranges. */
5542 if (operand_less_p (*vr0max, vr1min) == 1)
5544 /* If the result can be an anti-range, create one. */
5545 if (TREE_CODE (*vr0max) == INTEGER_CST
5546 && TREE_CODE (vr1min) == INTEGER_CST
5547 && vrp_val_is_min (*vr0min)
5548 && vrp_val_is_max (vr1max))
5550 tree min = int_const_binop (PLUS_EXPR,
5551 *vr0max,
5552 build_int_cst (TREE_TYPE (*vr0max), 1));
5553 tree max = int_const_binop (MINUS_EXPR,
5554 vr1min,
5555 build_int_cst (TREE_TYPE (vr1min), 1));
5556 if (!operand_less_p (max, min))
5558 *vr0type = VR_ANTI_RANGE;
5559 *vr0min = min;
5560 *vr0max = max;
5562 else
5563 *vr0max = vr1max;
5565 else
5566 *vr0max = vr1max;
5568 else
5570 /* If the result can be an anti-range, create one. */
5571 if (TREE_CODE (vr1max) == INTEGER_CST
5572 && TREE_CODE (*vr0min) == INTEGER_CST
5573 && vrp_val_is_min (vr1min)
5574 && vrp_val_is_max (*vr0max))
5576 tree min = int_const_binop (PLUS_EXPR,
5577 vr1max,
5578 build_int_cst (TREE_TYPE (vr1max), 1));
5579 tree max = int_const_binop (MINUS_EXPR,
5580 *vr0min,
5581 build_int_cst (TREE_TYPE (*vr0min), 1));
5582 if (!operand_less_p (max, min))
5584 *vr0type = VR_ANTI_RANGE;
5585 *vr0min = min;
5586 *vr0max = max;
5588 else
5589 *vr0min = vr1min;
5591 else
5592 *vr0min = vr1min;
5595 else
5596 gcc_unreachable ();
5598 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5599 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5601 /* [ ( ) ] or [( ) ] or [ ( )] */
5602 if (*vr0type == VR_RANGE
5603 && vr1type == VR_RANGE)
5605 else if (*vr0type == VR_ANTI_RANGE
5606 && vr1type == VR_ANTI_RANGE)
5608 *vr0type = vr1type;
5609 *vr0min = vr1min;
5610 *vr0max = vr1max;
5612 else if (*vr0type == VR_ANTI_RANGE
5613 && vr1type == VR_RANGE)
5615 /* Arbitrarily choose the right or left gap. */
5616 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5617 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5618 build_int_cst (TREE_TYPE (vr1min), 1));
5619 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5620 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5621 build_int_cst (TREE_TYPE (vr1max), 1));
5622 else
5623 goto give_up;
5625 else if (*vr0type == VR_RANGE
5626 && vr1type == VR_ANTI_RANGE)
5627 /* The result covers everything. */
5628 goto give_up;
5629 else
5630 gcc_unreachable ();
5632 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5633 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5635 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5636 if (*vr0type == VR_RANGE
5637 && vr1type == VR_RANGE)
5639 *vr0type = vr1type;
5640 *vr0min = vr1min;
5641 *vr0max = vr1max;
5643 else if (*vr0type == VR_ANTI_RANGE
5644 && vr1type == VR_ANTI_RANGE)
5646 else if (*vr0type == VR_RANGE
5647 && vr1type == VR_ANTI_RANGE)
5649 *vr0type = VR_ANTI_RANGE;
5650 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5652 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5653 build_int_cst (TREE_TYPE (*vr0min), 1));
5654 *vr0min = vr1min;
5656 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5658 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5659 build_int_cst (TREE_TYPE (*vr0max), 1));
5660 *vr0max = vr1max;
5662 else
5663 goto give_up;
5665 else if (*vr0type == VR_ANTI_RANGE
5666 && vr1type == VR_RANGE)
5667 /* The result covers everything. */
5668 goto give_up;
5669 else
5670 gcc_unreachable ();
5672 else if ((operand_less_p (vr1min, *vr0max) == 1
5673 || operand_equal_p (vr1min, *vr0max, 0))
5674 && operand_less_p (*vr0min, vr1min) == 1
5675 && operand_less_p (*vr0max, vr1max) == 1)
5677 /* [ ( ] ) or [ ]( ) */
5678 if (*vr0type == VR_RANGE
5679 && vr1type == VR_RANGE)
5680 *vr0max = vr1max;
5681 else if (*vr0type == VR_ANTI_RANGE
5682 && vr1type == VR_ANTI_RANGE)
5683 *vr0min = vr1min;
5684 else if (*vr0type == VR_ANTI_RANGE
5685 && vr1type == VR_RANGE)
5687 if (TREE_CODE (vr1min) == INTEGER_CST)
5688 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5689 build_int_cst (TREE_TYPE (vr1min), 1));
5690 else
5691 goto give_up;
5693 else if (*vr0type == VR_RANGE
5694 && vr1type == VR_ANTI_RANGE)
5696 if (TREE_CODE (*vr0max) == INTEGER_CST)
5698 *vr0type = vr1type;
5699 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5700 build_int_cst (TREE_TYPE (*vr0max), 1));
5701 *vr0max = vr1max;
5703 else
5704 goto give_up;
5706 else
5707 gcc_unreachable ();
5709 else if ((operand_less_p (*vr0min, vr1max) == 1
5710 || operand_equal_p (*vr0min, vr1max, 0))
5711 && operand_less_p (vr1min, *vr0min) == 1
5712 && operand_less_p (vr1max, *vr0max) == 1)
5714 /* ( [ ) ] or ( )[ ] */
5715 if (*vr0type == VR_RANGE
5716 && vr1type == VR_RANGE)
5717 *vr0min = vr1min;
5718 else if (*vr0type == VR_ANTI_RANGE
5719 && vr1type == VR_ANTI_RANGE)
5720 *vr0max = vr1max;
5721 else if (*vr0type == VR_ANTI_RANGE
5722 && vr1type == VR_RANGE)
5724 if (TREE_CODE (vr1max) == INTEGER_CST)
5725 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5726 build_int_cst (TREE_TYPE (vr1max), 1));
5727 else
5728 goto give_up;
5730 else if (*vr0type == VR_RANGE
5731 && vr1type == VR_ANTI_RANGE)
5733 if (TREE_CODE (*vr0min) == INTEGER_CST)
5735 *vr0type = vr1type;
5736 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5737 build_int_cst (TREE_TYPE (*vr0min), 1));
5738 *vr0min = vr1min;
5740 else
5741 goto give_up;
5743 else
5744 gcc_unreachable ();
5746 else
5747 goto give_up;
5749 return;
5751 give_up:
5752 *vr0type = VR_VARYING;
5753 *vr0min = NULL_TREE;
5754 *vr0max = NULL_TREE;
5757 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5758 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5759 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5760 possible such range. The resulting range is not canonicalized. */
5762 static void
5763 intersect_ranges (enum value_range_type *vr0type,
5764 tree *vr0min, tree *vr0max,
5765 enum value_range_type vr1type,
5766 tree vr1min, tree vr1max)
5768 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5769 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5771 /* [] is vr0, () is vr1 in the following classification comments. */
5772 if (mineq && maxeq)
5774 /* [( )] */
5775 if (*vr0type == vr1type)
5776 /* Nothing to do for equal ranges. */
5778 else if ((*vr0type == VR_RANGE
5779 && vr1type == VR_ANTI_RANGE)
5780 || (*vr0type == VR_ANTI_RANGE
5781 && vr1type == VR_RANGE))
5783 /* For anti-range with range intersection the result is empty. */
5784 *vr0type = VR_UNDEFINED;
5785 *vr0min = NULL_TREE;
5786 *vr0max = NULL_TREE;
5788 else
5789 gcc_unreachable ();
5791 else if (operand_less_p (*vr0max, vr1min) == 1
5792 || operand_less_p (vr1max, *vr0min) == 1)
5794 /* [ ] ( ) or ( ) [ ]
5795 If the ranges have an empty intersection, the result of the
5796 intersect operation is the range for intersecting an
5797 anti-range with a range or empty when intersecting two ranges. */
5798 if (*vr0type == VR_RANGE
5799 && vr1type == VR_ANTI_RANGE)
5801 else if (*vr0type == VR_ANTI_RANGE
5802 && vr1type == VR_RANGE)
5804 *vr0type = vr1type;
5805 *vr0min = vr1min;
5806 *vr0max = vr1max;
5808 else if (*vr0type == VR_RANGE
5809 && vr1type == VR_RANGE)
5811 *vr0type = VR_UNDEFINED;
5812 *vr0min = NULL_TREE;
5813 *vr0max = NULL_TREE;
5815 else if (*vr0type == VR_ANTI_RANGE
5816 && vr1type == VR_ANTI_RANGE)
5818 /* If the anti-ranges are adjacent to each other merge them. */
5819 if (TREE_CODE (*vr0max) == INTEGER_CST
5820 && TREE_CODE (vr1min) == INTEGER_CST
5821 && operand_less_p (*vr0max, vr1min) == 1
5822 && integer_onep (int_const_binop (MINUS_EXPR,
5823 vr1min, *vr0max)))
5824 *vr0max = vr1max;
5825 else if (TREE_CODE (vr1max) == INTEGER_CST
5826 && TREE_CODE (*vr0min) == INTEGER_CST
5827 && operand_less_p (vr1max, *vr0min) == 1
5828 && integer_onep (int_const_binop (MINUS_EXPR,
5829 *vr0min, vr1max)))
5830 *vr0min = vr1min;
5831 /* Else arbitrarily take VR0. */
5834 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5835 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5837 /* [ ( ) ] or [( ) ] or [ ( )] */
5838 if (*vr0type == VR_RANGE
5839 && vr1type == VR_RANGE)
5841 /* If both are ranges the result is the inner one. */
5842 *vr0type = vr1type;
5843 *vr0min = vr1min;
5844 *vr0max = vr1max;
5846 else if (*vr0type == VR_RANGE
5847 && vr1type == VR_ANTI_RANGE)
5849 /* Choose the right gap if the left one is empty. */
5850 if (mineq)
5852 if (TREE_CODE (vr1max) != INTEGER_CST)
5853 *vr0min = vr1max;
5854 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5855 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5856 *vr0min
5857 = int_const_binop (MINUS_EXPR, vr1max,
5858 build_int_cst (TREE_TYPE (vr1max), -1));
5859 else
5860 *vr0min
5861 = int_const_binop (PLUS_EXPR, vr1max,
5862 build_int_cst (TREE_TYPE (vr1max), 1));
5864 /* Choose the left gap if the right one is empty. */
5865 else if (maxeq)
5867 if (TREE_CODE (vr1min) != INTEGER_CST)
5868 *vr0max = vr1min;
5869 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5870 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5871 *vr0max
5872 = int_const_binop (PLUS_EXPR, vr1min,
5873 build_int_cst (TREE_TYPE (vr1min), -1));
5874 else
5875 *vr0max
5876 = int_const_binop (MINUS_EXPR, vr1min,
5877 build_int_cst (TREE_TYPE (vr1min), 1));
5879 /* Choose the anti-range if the range is effectively varying. */
5880 else if (vrp_val_is_min (*vr0min)
5881 && vrp_val_is_max (*vr0max))
5883 *vr0type = vr1type;
5884 *vr0min = vr1min;
5885 *vr0max = vr1max;
5887 /* Else choose the range. */
5889 else if (*vr0type == VR_ANTI_RANGE
5890 && vr1type == VR_ANTI_RANGE)
5891 /* If both are anti-ranges the result is the outer one. */
5893 else if (*vr0type == VR_ANTI_RANGE
5894 && vr1type == VR_RANGE)
5896 /* The intersection is empty. */
5897 *vr0type = VR_UNDEFINED;
5898 *vr0min = NULL_TREE;
5899 *vr0max = NULL_TREE;
5901 else
5902 gcc_unreachable ();
5904 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5905 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5907 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5908 if (*vr0type == VR_RANGE
5909 && vr1type == VR_RANGE)
5910 /* Choose the inner range. */
5912 else if (*vr0type == VR_ANTI_RANGE
5913 && vr1type == VR_RANGE)
5915 /* Choose the right gap if the left is empty. */
5916 if (mineq)
5918 *vr0type = VR_RANGE;
5919 if (TREE_CODE (*vr0max) != INTEGER_CST)
5920 *vr0min = *vr0max;
5921 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5922 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5923 *vr0min
5924 = int_const_binop (MINUS_EXPR, *vr0max,
5925 build_int_cst (TREE_TYPE (*vr0max), -1));
5926 else
5927 *vr0min
5928 = int_const_binop (PLUS_EXPR, *vr0max,
5929 build_int_cst (TREE_TYPE (*vr0max), 1));
5930 *vr0max = vr1max;
5932 /* Choose the left gap if the right is empty. */
5933 else if (maxeq)
5935 *vr0type = VR_RANGE;
5936 if (TREE_CODE (*vr0min) != INTEGER_CST)
5937 *vr0max = *vr0min;
5938 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5939 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5940 *vr0max
5941 = int_const_binop (PLUS_EXPR, *vr0min,
5942 build_int_cst (TREE_TYPE (*vr0min), -1));
5943 else
5944 *vr0max
5945 = int_const_binop (MINUS_EXPR, *vr0min,
5946 build_int_cst (TREE_TYPE (*vr0min), 1));
5947 *vr0min = vr1min;
5949 /* Choose the anti-range if the range is effectively varying. */
5950 else if (vrp_val_is_min (vr1min)
5951 && vrp_val_is_max (vr1max))
5953 /* Choose the anti-range if it is ~[0,0], that range is special
5954 enough to special case when vr1's range is relatively wide.
5955 At least for types bigger than int - this covers pointers
5956 and arguments to functions like ctz. */
5957 else if (*vr0min == *vr0max
5958 && integer_zerop (*vr0min)
5959 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5960 >= TYPE_PRECISION (integer_type_node))
5961 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5962 && TREE_CODE (vr1max) == INTEGER_CST
5963 && TREE_CODE (vr1min) == INTEGER_CST
5964 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5965 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5967 /* Else choose the range. */
5968 else
5970 *vr0type = vr1type;
5971 *vr0min = vr1min;
5972 *vr0max = vr1max;
5975 else if (*vr0type == VR_ANTI_RANGE
5976 && vr1type == VR_ANTI_RANGE)
5978 /* If both are anti-ranges the result is the outer one. */
5979 *vr0type = vr1type;
5980 *vr0min = vr1min;
5981 *vr0max = vr1max;
5983 else if (vr1type == VR_ANTI_RANGE
5984 && *vr0type == VR_RANGE)
5986 /* The intersection is empty. */
5987 *vr0type = VR_UNDEFINED;
5988 *vr0min = NULL_TREE;
5989 *vr0max = NULL_TREE;
5991 else
5992 gcc_unreachable ();
5994 else if ((operand_less_p (vr1min, *vr0max) == 1
5995 || operand_equal_p (vr1min, *vr0max, 0))
5996 && operand_less_p (*vr0min, vr1min) == 1)
5998 /* [ ( ] ) or [ ]( ) */
5999 if (*vr0type == VR_ANTI_RANGE
6000 && vr1type == VR_ANTI_RANGE)
6001 *vr0max = vr1max;
6002 else if (*vr0type == VR_RANGE
6003 && vr1type == VR_RANGE)
6004 *vr0min = vr1min;
6005 else if (*vr0type == VR_RANGE
6006 && vr1type == VR_ANTI_RANGE)
6008 if (TREE_CODE (vr1min) == INTEGER_CST)
6009 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6010 build_int_cst (TREE_TYPE (vr1min), 1));
6011 else
6012 *vr0max = vr1min;
6014 else if (*vr0type == VR_ANTI_RANGE
6015 && vr1type == VR_RANGE)
6017 *vr0type = VR_RANGE;
6018 if (TREE_CODE (*vr0max) == INTEGER_CST)
6019 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6020 build_int_cst (TREE_TYPE (*vr0max), 1));
6021 else
6022 *vr0min = *vr0max;
6023 *vr0max = vr1max;
6025 else
6026 gcc_unreachable ();
6028 else if ((operand_less_p (*vr0min, vr1max) == 1
6029 || operand_equal_p (*vr0min, vr1max, 0))
6030 && operand_less_p (vr1min, *vr0min) == 1)
6032 /* ( [ ) ] or ( )[ ] */
6033 if (*vr0type == VR_ANTI_RANGE
6034 && vr1type == VR_ANTI_RANGE)
6035 *vr0min = vr1min;
6036 else if (*vr0type == VR_RANGE
6037 && vr1type == VR_RANGE)
6038 *vr0max = vr1max;
6039 else if (*vr0type == VR_RANGE
6040 && vr1type == VR_ANTI_RANGE)
6042 if (TREE_CODE (vr1max) == INTEGER_CST)
6043 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6044 build_int_cst (TREE_TYPE (vr1max), 1));
6045 else
6046 *vr0min = vr1max;
6048 else if (*vr0type == VR_ANTI_RANGE
6049 && vr1type == VR_RANGE)
6051 *vr0type = VR_RANGE;
6052 if (TREE_CODE (*vr0min) == INTEGER_CST)
6053 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6054 build_int_cst (TREE_TYPE (*vr0min), 1));
6055 else
6056 *vr0max = *vr0min;
6057 *vr0min = vr1min;
6059 else
6060 gcc_unreachable ();
6063 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6064 result for the intersection. That's always a conservative
6065 correct estimate unless VR1 is a constant singleton range
6066 in which case we choose that. */
6067 if (vr1type == VR_RANGE
6068 && is_gimple_min_invariant (vr1min)
6069 && vrp_operand_equal_p (vr1min, vr1max))
6071 *vr0type = vr1type;
6072 *vr0min = vr1min;
6073 *vr0max = vr1max;
6076 return;
6080 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6081 in *VR0. This may not be the smallest possible such range. */
6083 static void
6084 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
6086 value_range saved;
6088 /* If either range is VR_VARYING the other one wins. */
6089 if (vr1->type == VR_VARYING)
6090 return;
6091 if (vr0->type == VR_VARYING)
6093 copy_value_range (vr0, vr1);
6094 return;
6097 /* When either range is VR_UNDEFINED the resulting range is
6098 VR_UNDEFINED, too. */
6099 if (vr0->type == VR_UNDEFINED)
6100 return;
6101 if (vr1->type == VR_UNDEFINED)
6103 set_value_range_to_undefined (vr0);
6104 return;
6107 /* Save the original vr0 so we can return it as conservative intersection
6108 result when our worker turns things to varying. */
6109 saved = *vr0;
6110 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6111 vr1->type, vr1->min, vr1->max);
6112 /* Make sure to canonicalize the result though as the inversion of a
6113 VR_RANGE can still be a VR_RANGE. */
6114 set_and_canonicalize_value_range (vr0, vr0->type,
6115 vr0->min, vr0->max, vr0->equiv);
6116 /* If that failed, use the saved original VR0. */
6117 if (vr0->type == VR_VARYING)
6119 *vr0 = saved;
6120 return;
6122 /* If the result is VR_UNDEFINED there is no need to mess with
6123 the equivalencies. */
6124 if (vr0->type == VR_UNDEFINED)
6125 return;
6127 /* The resulting set of equivalences for range intersection is the union of
6128 the two sets. */
6129 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6130 bitmap_ior_into (vr0->equiv, vr1->equiv);
6131 else if (vr1->equiv && !vr0->equiv)
6133 /* All equivalence bitmaps are allocated from the same obstack. So
6134 we can use the obstack associated with VR to allocate vr0->equiv. */
6135 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6136 bitmap_copy (vr0->equiv, vr1->equiv);
6140 void
6141 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6143 if (dump_file && (dump_flags & TDF_DETAILS))
6145 fprintf (dump_file, "Intersecting\n ");
6146 dump_value_range (dump_file, vr0);
6147 fprintf (dump_file, "\nand\n ");
6148 dump_value_range (dump_file, vr1);
6149 fprintf (dump_file, "\n");
6151 vrp_intersect_ranges_1 (vr0, vr1);
6152 if (dump_file && (dump_flags & TDF_DETAILS))
6154 fprintf (dump_file, "to\n ");
6155 dump_value_range (dump_file, vr0);
6156 fprintf (dump_file, "\n");
6160 /* Meet operation for value ranges. Given two value ranges VR0 and
6161 VR1, store in VR0 a range that contains both VR0 and VR1. This
6162 may not be the smallest possible such range. */
6164 static void
6165 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6167 value_range saved;
6169 if (vr0->type == VR_UNDEFINED)
6171 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6172 return;
6175 if (vr1->type == VR_UNDEFINED)
6177 /* VR0 already has the resulting range. */
6178 return;
6181 if (vr0->type == VR_VARYING)
6183 /* Nothing to do. VR0 already has the resulting range. */
6184 return;
6187 if (vr1->type == VR_VARYING)
6189 set_value_range_to_varying (vr0);
6190 return;
6193 saved = *vr0;
6194 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6195 vr1->type, vr1->min, vr1->max);
6196 if (vr0->type == VR_VARYING)
6198 /* Failed to find an efficient meet. Before giving up and setting
6199 the result to VARYING, see if we can at least derive a useful
6200 anti-range. FIXME, all this nonsense about distinguishing
6201 anti-ranges from ranges is necessary because of the odd
6202 semantics of range_includes_zero_p and friends. */
6203 if (((saved.type == VR_RANGE
6204 && range_includes_zero_p (saved.min, saved.max) == 0)
6205 || (saved.type == VR_ANTI_RANGE
6206 && range_includes_zero_p (saved.min, saved.max) == 1))
6207 && ((vr1->type == VR_RANGE
6208 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6209 || (vr1->type == VR_ANTI_RANGE
6210 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6212 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6214 /* Since this meet operation did not result from the meeting of
6215 two equivalent names, VR0 cannot have any equivalences. */
6216 if (vr0->equiv)
6217 bitmap_clear (vr0->equiv);
6218 return;
6221 set_value_range_to_varying (vr0);
6222 return;
6224 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6225 vr0->equiv);
6226 if (vr0->type == VR_VARYING)
6227 return;
6229 /* The resulting set of equivalences is always the intersection of
6230 the two sets. */
6231 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6232 bitmap_and_into (vr0->equiv, vr1->equiv);
6233 else if (vr0->equiv && !vr1->equiv)
6234 bitmap_clear (vr0->equiv);
6237 void
6238 vrp_meet (value_range *vr0, const value_range *vr1)
6240 if (dump_file && (dump_flags & TDF_DETAILS))
6242 fprintf (dump_file, "Meeting\n ");
6243 dump_value_range (dump_file, vr0);
6244 fprintf (dump_file, "\nand\n ");
6245 dump_value_range (dump_file, vr1);
6246 fprintf (dump_file, "\n");
6248 vrp_meet_1 (vr0, vr1);
6249 if (dump_file && (dump_flags & TDF_DETAILS))
6251 fprintf (dump_file, "to\n ");
6252 dump_value_range (dump_file, vr0);
6253 fprintf (dump_file, "\n");
6258 /* Visit all arguments for PHI node PHI that flow through executable
6259 edges. If a valid value range can be derived from all the incoming
6260 value ranges, set a new range for the LHS of PHI. */
6262 enum ssa_prop_result
6263 vrp_prop::visit_phi (gphi *phi)
6265 tree lhs = PHI_RESULT (phi);
6266 value_range vr_result = VR_INITIALIZER;
6267 extract_range_from_phi_node (phi, &vr_result);
6268 if (update_value_range (lhs, &vr_result))
6270 if (dump_file && (dump_flags & TDF_DETAILS))
6272 fprintf (dump_file, "Found new range for ");
6273 print_generic_expr (dump_file, lhs);
6274 fprintf (dump_file, ": ");
6275 dump_value_range (dump_file, &vr_result);
6276 fprintf (dump_file, "\n");
6279 if (vr_result.type == VR_VARYING)
6280 return SSA_PROP_VARYING;
6282 return SSA_PROP_INTERESTING;
6285 /* Nothing changed, don't add outgoing edges. */
6286 return SSA_PROP_NOT_INTERESTING;
6289 class vrp_folder : public substitute_and_fold_engine
6291 public:
6292 tree get_value (tree) FINAL OVERRIDE;
6293 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6294 bool fold_predicate_in (gimple_stmt_iterator *);
6296 class vr_values *vr_values;
6298 /* Delegators. */
6299 tree vrp_evaluate_conditional (tree_code code, tree op0,
6300 tree op1, gimple *stmt)
6301 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6302 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6303 { return vr_values->simplify_stmt_using_ranges (gsi); }
6304 tree op_with_constant_singleton_value_range (tree op)
6305 { return vr_values->op_with_constant_singleton_value_range (op); }
6308 /* If the statement pointed by SI has a predicate whose value can be
6309 computed using the value range information computed by VRP, compute
6310 its value and return true. Otherwise, return false. */
6312 bool
6313 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6315 bool assignment_p = false;
6316 tree val;
6317 gimple *stmt = gsi_stmt (*si);
6319 if (is_gimple_assign (stmt)
6320 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6322 assignment_p = true;
6323 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6324 gimple_assign_rhs1 (stmt),
6325 gimple_assign_rhs2 (stmt),
6326 stmt);
6328 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6329 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6330 gimple_cond_lhs (cond_stmt),
6331 gimple_cond_rhs (cond_stmt),
6332 stmt);
6333 else
6334 return false;
6336 if (val)
6338 if (assignment_p)
6339 val = fold_convert (gimple_expr_type (stmt), val);
6341 if (dump_file)
6343 fprintf (dump_file, "Folding predicate ");
6344 print_gimple_expr (dump_file, stmt, 0);
6345 fprintf (dump_file, " to ");
6346 print_generic_expr (dump_file, val);
6347 fprintf (dump_file, "\n");
6350 if (is_gimple_assign (stmt))
6351 gimple_assign_set_rhs_from_tree (si, val);
6352 else
6354 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6355 gcond *cond_stmt = as_a <gcond *> (stmt);
6356 if (integer_zerop (val))
6357 gimple_cond_make_false (cond_stmt);
6358 else if (integer_onep (val))
6359 gimple_cond_make_true (cond_stmt);
6360 else
6361 gcc_unreachable ();
6364 return true;
6367 return false;
6370 /* Callback for substitute_and_fold folding the stmt at *SI. */
6372 bool
6373 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6375 if (fold_predicate_in (si))
6376 return true;
6378 return simplify_stmt_using_ranges (si);
6381 /* If OP has a value range with a single constant value return that,
6382 otherwise return NULL_TREE. This returns OP itself if OP is a
6383 constant.
6385 Implemented as a pure wrapper right now, but this will change. */
6387 tree
6388 vrp_folder::get_value (tree op)
6390 return op_with_constant_singleton_value_range (op);
6393 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6394 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6395 BB. If no such ASSERT_EXPR is found, return OP. */
6397 static tree
6398 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6400 imm_use_iterator imm_iter;
6401 gimple *use_stmt;
6402 use_operand_p use_p;
6404 if (TREE_CODE (op) == SSA_NAME)
6406 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6408 use_stmt = USE_STMT (use_p);
6409 if (use_stmt != stmt
6410 && gimple_assign_single_p (use_stmt)
6411 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6412 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6413 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6414 return gimple_assign_lhs (use_stmt);
6417 return op;
6420 /* A hack. */
6421 static class vr_values *x_vr_values;
6423 /* A trivial wrapper so that we can present the generic jump threading
6424 code with a simple API for simplifying statements. STMT is the
6425 statement we want to simplify, WITHIN_STMT provides the location
6426 for any overflow warnings. */
6428 static tree
6429 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6430 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6431 basic_block bb)
6433 /* First see if the conditional is in the hash table. */
6434 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6435 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6436 return cached_lhs;
6438 vr_values *vr_values = x_vr_values;
6439 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6441 tree op0 = gimple_cond_lhs (cond_stmt);
6442 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6444 tree op1 = gimple_cond_rhs (cond_stmt);
6445 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6447 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6448 op0, op1, within_stmt);
6451 /* We simplify a switch statement by trying to determine which case label
6452 will be taken. If we are successful then we return the corresponding
6453 CASE_LABEL_EXPR. */
6454 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6456 tree op = gimple_switch_index (switch_stmt);
6457 if (TREE_CODE (op) != SSA_NAME)
6458 return NULL_TREE;
6460 op = lhs_of_dominating_assert (op, bb, stmt);
6462 value_range *vr = vr_values->get_value_range (op);
6463 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6464 || symbolic_range_p (vr))
6465 return NULL_TREE;
6467 if (vr->type == VR_RANGE)
6469 size_t i, j;
6470 /* Get the range of labels that contain a part of the operand's
6471 value range. */
6472 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6474 /* Is there only one such label? */
6475 if (i == j)
6477 tree label = gimple_switch_label (switch_stmt, i);
6479 /* The i'th label will be taken only if the value range of the
6480 operand is entirely within the bounds of this label. */
6481 if (CASE_HIGH (label) != NULL_TREE
6482 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6483 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6484 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6485 && tree_int_cst_equal (vr->min, vr->max)))
6486 return label;
6489 /* If there are no such labels then the default label will be
6490 taken. */
6491 if (i > j)
6492 return gimple_switch_label (switch_stmt, 0);
6495 if (vr->type == VR_ANTI_RANGE)
6497 unsigned n = gimple_switch_num_labels (switch_stmt);
6498 tree min_label = gimple_switch_label (switch_stmt, 1);
6499 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6501 /* The default label will be taken only if the anti-range of the
6502 operand is entirely outside the bounds of all the (non-default)
6503 case labels. */
6504 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6505 && (CASE_HIGH (max_label) != NULL_TREE
6506 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6507 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6508 return gimple_switch_label (switch_stmt, 0);
6511 return NULL_TREE;
6514 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6516 tree lhs = gimple_assign_lhs (assign_stmt);
6517 if (TREE_CODE (lhs) == SSA_NAME
6518 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6519 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6520 && stmt_interesting_for_vrp (stmt))
6522 edge dummy_e;
6523 tree dummy_tree;
6524 value_range new_vr = VR_INITIALIZER;
6525 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6526 &dummy_tree, &new_vr);
6527 if (range_int_cst_singleton_p (&new_vr))
6528 return new_vr.min;
6532 return NULL_TREE;
6535 class vrp_dom_walker : public dom_walker
6537 public:
6538 vrp_dom_walker (cdi_direction direction,
6539 class const_and_copies *const_and_copies,
6540 class avail_exprs_stack *avail_exprs_stack)
6541 : dom_walker (direction, REACHABLE_BLOCKS),
6542 m_const_and_copies (const_and_copies),
6543 m_avail_exprs_stack (avail_exprs_stack),
6544 m_dummy_cond (NULL) {}
6546 virtual edge before_dom_children (basic_block);
6547 virtual void after_dom_children (basic_block);
6549 class vr_values *vr_values;
6551 private:
6552 class const_and_copies *m_const_and_copies;
6553 class avail_exprs_stack *m_avail_exprs_stack;
6555 gcond *m_dummy_cond;
6559 /* Called before processing dominator children of BB. We want to look
6560 at ASSERT_EXPRs and record information from them in the appropriate
6561 tables.
6563 We could look at other statements here. It's not seen as likely
6564 to significantly increase the jump threads we discover. */
6566 edge
6567 vrp_dom_walker::before_dom_children (basic_block bb)
6569 gimple_stmt_iterator gsi;
6571 m_avail_exprs_stack->push_marker ();
6572 m_const_and_copies->push_marker ();
6573 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6575 gimple *stmt = gsi_stmt (gsi);
6576 if (gimple_assign_single_p (stmt)
6577 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6579 tree rhs1 = gimple_assign_rhs1 (stmt);
6580 tree cond = TREE_OPERAND (rhs1, 1);
6581 tree inverted = invert_truthvalue (cond);
6582 vec<cond_equivalence> p;
6583 p.create (3);
6584 record_conditions (&p, cond, inverted);
6585 for (unsigned int i = 0; i < p.length (); i++)
6586 m_avail_exprs_stack->record_cond (&p[i]);
6588 tree lhs = gimple_assign_lhs (stmt);
6589 m_const_and_copies->record_const_or_copy (lhs,
6590 TREE_OPERAND (rhs1, 0));
6591 p.release ();
6592 continue;
6594 break;
6596 return NULL;
6599 /* Called after processing dominator children of BB. This is where we
6600 actually call into the threader. */
6601 void
6602 vrp_dom_walker::after_dom_children (basic_block bb)
6604 if (!m_dummy_cond)
6605 m_dummy_cond = gimple_build_cond (NE_EXPR,
6606 integer_zero_node, integer_zero_node,
6607 NULL, NULL);
6609 x_vr_values = vr_values;
6610 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6611 m_avail_exprs_stack, NULL,
6612 simplify_stmt_for_jump_threading);
6613 x_vr_values = NULL;
6615 m_avail_exprs_stack->pop_to_marker ();
6616 m_const_and_copies->pop_to_marker ();
6619 /* Blocks which have more than one predecessor and more than
6620 one successor present jump threading opportunities, i.e.,
6621 when the block is reached from a specific predecessor, we
6622 may be able to determine which of the outgoing edges will
6623 be traversed. When this optimization applies, we are able
6624 to avoid conditionals at runtime and we may expose secondary
6625 optimization opportunities.
6627 This routine is effectively a driver for the generic jump
6628 threading code. It basically just presents the generic code
6629 with edges that may be suitable for jump threading.
6631 Unlike DOM, we do not iterate VRP if jump threading was successful.
6632 While iterating may expose new opportunities for VRP, it is expected
6633 those opportunities would be very limited and the compile time cost
6634 to expose those opportunities would be significant.
6636 As jump threading opportunities are discovered, they are registered
6637 for later realization. */
6639 static void
6640 identify_jump_threads (class vr_values *vr_values)
6642 int i;
6643 edge e;
6645 /* Ugh. When substituting values earlier in this pass we can
6646 wipe the dominance information. So rebuild the dominator
6647 information as we need it within the jump threading code. */
6648 calculate_dominance_info (CDI_DOMINATORS);
6650 /* We do not allow VRP information to be used for jump threading
6651 across a back edge in the CFG. Otherwise it becomes too
6652 difficult to avoid eliminating loop exit tests. Of course
6653 EDGE_DFS_BACK is not accurate at this time so we have to
6654 recompute it. */
6655 mark_dfs_back_edges ();
6657 /* Do not thread across edges we are about to remove. Just marking
6658 them as EDGE_IGNORE will do. */
6659 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6660 e->flags |= EDGE_IGNORE;
6662 /* Allocate our unwinder stack to unwind any temporary equivalences
6663 that might be recorded. */
6664 const_and_copies *equiv_stack = new const_and_copies ();
6666 hash_table<expr_elt_hasher> *avail_exprs
6667 = new hash_table<expr_elt_hasher> (1024);
6668 avail_exprs_stack *avail_exprs_stack
6669 = new class avail_exprs_stack (avail_exprs);
6671 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6672 walker.vr_values = vr_values;
6673 walker.walk (cfun->cfg->x_entry_block_ptr);
6675 /* Clear EDGE_IGNORE. */
6676 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6677 e->flags &= ~EDGE_IGNORE;
6679 /* We do not actually update the CFG or SSA graphs at this point as
6680 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6681 handle ASSERT_EXPRs gracefully. */
6682 delete equiv_stack;
6683 delete avail_exprs;
6684 delete avail_exprs_stack;
6687 /* Traverse all the blocks folding conditionals with known ranges. */
6689 void
6690 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6692 size_t i;
6694 /* We have completed propagating through the lattice. */
6695 vr_values.set_lattice_propagation_complete ();
6697 if (dump_file)
6699 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6700 vr_values.dump_all_value_ranges (dump_file);
6701 fprintf (dump_file, "\n");
6704 /* Set value range to non pointer SSA_NAMEs. */
6705 for (i = 0; i < num_ssa_names; i++)
6707 tree name = ssa_name (i);
6708 if (!name)
6709 continue;
6711 value_range *vr = get_value_range (name);
6712 if (!name
6713 || (vr->type == VR_VARYING)
6714 || (vr->type == VR_UNDEFINED)
6715 || (TREE_CODE (vr->min) != INTEGER_CST)
6716 || (TREE_CODE (vr->max) != INTEGER_CST))
6717 continue;
6719 if (POINTER_TYPE_P (TREE_TYPE (name))
6720 && ((vr->type == VR_RANGE
6721 && range_includes_zero_p (vr->min, vr->max) == 0)
6722 || (vr->type == VR_ANTI_RANGE
6723 && range_includes_zero_p (vr->min, vr->max) == 1)))
6724 set_ptr_nonnull (name);
6725 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6726 set_range_info (name, vr->type,
6727 wi::to_wide (vr->min),
6728 wi::to_wide (vr->max));
6731 /* If we're checking array refs, we want to merge information on
6732 the executability of each edge between vrp_folder and the
6733 check_array_bounds_dom_walker: each can clear the
6734 EDGE_EXECUTABLE flag on edges, in different ways.
6736 Hence, if we're going to call check_all_array_refs, set
6737 the flag on every edge now, rather than in
6738 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6739 it from some edges. */
6740 if (warn_array_bounds && warn_array_bounds_p)
6741 set_all_edges_as_executable (cfun);
6743 class vrp_folder vrp_folder;
6744 vrp_folder.vr_values = &vr_values;
6745 vrp_folder.substitute_and_fold ();
6747 if (warn_array_bounds && warn_array_bounds_p)
6748 check_all_array_refs ();
6751 /* Main entry point to VRP (Value Range Propagation). This pass is
6752 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6753 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6754 Programming Language Design and Implementation, pp. 67-78, 1995.
6755 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6757 This is essentially an SSA-CCP pass modified to deal with ranges
6758 instead of constants.
6760 While propagating ranges, we may find that two or more SSA name
6761 have equivalent, though distinct ranges. For instance,
6763 1 x_9 = p_3->a;
6764 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6765 3 if (p_4 == q_2)
6766 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6767 5 endif
6768 6 if (q_2)
6770 In the code above, pointer p_5 has range [q_2, q_2], but from the
6771 code we can also determine that p_5 cannot be NULL and, if q_2 had
6772 a non-varying range, p_5's range should also be compatible with it.
6774 These equivalences are created by two expressions: ASSERT_EXPR and
6775 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6776 result of another assertion, then we can use the fact that p_5 and
6777 p_4 are equivalent when evaluating p_5's range.
6779 Together with value ranges, we also propagate these equivalences
6780 between names so that we can take advantage of information from
6781 multiple ranges when doing final replacement. Note that this
6782 equivalency relation is transitive but not symmetric.
6784 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6785 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6786 in contexts where that assertion does not hold (e.g., in line 6).
6788 TODO, the main difference between this pass and Patterson's is that
6789 we do not propagate edge probabilities. We only compute whether
6790 edges can be taken or not. That is, instead of having a spectrum
6791 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6792 DON'T KNOW. In the future, it may be worthwhile to propagate
6793 probabilities to aid branch prediction. */
6795 static unsigned int
6796 execute_vrp (bool warn_array_bounds_p)
6798 int i;
6799 edge e;
6800 switch_update *su;
6802 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6803 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6804 scev_initialize ();
6806 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6807 Inserting assertions may split edges which will invalidate
6808 EDGE_DFS_BACK. */
6809 insert_range_assertions ();
6811 to_remove_edges.create (10);
6812 to_update_switch_stmts.create (5);
6813 threadedge_initialize_values ();
6815 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6816 mark_dfs_back_edges ();
6818 class vrp_prop vrp_prop;
6819 vrp_prop.vrp_initialize ();
6820 vrp_prop.ssa_propagate ();
6821 vrp_prop.vrp_finalize (warn_array_bounds_p);
6823 /* We must identify jump threading opportunities before we release
6824 the datastructures built by VRP. */
6825 identify_jump_threads (&vrp_prop.vr_values);
6827 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6828 was set by a type conversion can often be rewritten to use the
6829 RHS of the type conversion.
6831 However, doing so inhibits jump threading through the comparison.
6832 So that transformation is not performed until after jump threading
6833 is complete. */
6834 basic_block bb;
6835 FOR_EACH_BB_FN (bb, cfun)
6837 gimple *last = last_stmt (bb);
6838 if (last && gimple_code (last) == GIMPLE_COND)
6839 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6842 free_numbers_of_iterations_estimates (cfun);
6844 /* ASSERT_EXPRs must be removed before finalizing jump threads
6845 as finalizing jump threads calls the CFG cleanup code which
6846 does not properly handle ASSERT_EXPRs. */
6847 remove_range_assertions ();
6849 /* If we exposed any new variables, go ahead and put them into
6850 SSA form now, before we handle jump threading. This simplifies
6851 interactions between rewriting of _DECL nodes into SSA form
6852 and rewriting SSA_NAME nodes into SSA form after block
6853 duplication and CFG manipulation. */
6854 update_ssa (TODO_update_ssa);
6856 /* We identified all the jump threading opportunities earlier, but could
6857 not transform the CFG at that time. This routine transforms the
6858 CFG and arranges for the dominator tree to be rebuilt if necessary.
6860 Note the SSA graph update will occur during the normal TODO
6861 processing by the pass manager. */
6862 thread_through_all_blocks (false);
6864 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6865 CFG in a broken state and requires a cfg_cleanup run. */
6866 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6867 remove_edge (e);
6868 /* Update SWITCH_EXPR case label vector. */
6869 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6871 size_t j;
6872 size_t n = TREE_VEC_LENGTH (su->vec);
6873 tree label;
6874 gimple_switch_set_num_labels (su->stmt, n);
6875 for (j = 0; j < n; j++)
6876 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
6877 /* As we may have replaced the default label with a regular one
6878 make sure to make it a real default label again. This ensures
6879 optimal expansion. */
6880 label = gimple_switch_label (su->stmt, 0);
6881 CASE_LOW (label) = NULL_TREE;
6882 CASE_HIGH (label) = NULL_TREE;
6885 if (to_remove_edges.length () > 0)
6887 free_dominance_info (CDI_DOMINATORS);
6888 loops_state_set (LOOPS_NEED_FIXUP);
6891 to_remove_edges.release ();
6892 to_update_switch_stmts.release ();
6893 threadedge_finalize_values ();
6895 scev_finalize ();
6896 loop_optimizer_finalize ();
6897 return 0;
6900 namespace {
6902 const pass_data pass_data_vrp =
6904 GIMPLE_PASS, /* type */
6905 "vrp", /* name */
6906 OPTGROUP_NONE, /* optinfo_flags */
6907 TV_TREE_VRP, /* tv_id */
6908 PROP_ssa, /* properties_required */
6909 0, /* properties_provided */
6910 0, /* properties_destroyed */
6911 0, /* todo_flags_start */
6912 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6915 class pass_vrp : public gimple_opt_pass
6917 public:
6918 pass_vrp (gcc::context *ctxt)
6919 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6922 /* opt_pass methods: */
6923 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6924 void set_pass_param (unsigned int n, bool param)
6926 gcc_assert (n == 0);
6927 warn_array_bounds_p = param;
6929 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6930 virtual unsigned int execute (function *)
6931 { return execute_vrp (warn_array_bounds_p); }
6933 private:
6934 bool warn_array_bounds_p;
6935 }; // class pass_vrp
6937 } // anon namespace
6939 gimple_opt_pass *
6940 make_pass_vrp (gcc::context *ctxt)
6942 return new pass_vrp (ctxt);
6946 /* Worker for determine_value_range. */
6948 static void
6949 determine_value_range_1 (value_range *vr, tree expr)
6951 if (BINARY_CLASS_P (expr))
6953 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6954 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6955 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6956 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6957 &vr0, &vr1);
6959 else if (UNARY_CLASS_P (expr))
6961 value_range vr0 = VR_INITIALIZER;
6962 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6963 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6964 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6966 else if (TREE_CODE (expr) == INTEGER_CST)
6967 set_value_range_to_value (vr, expr, NULL);
6968 else
6970 value_range_type kind;
6971 wide_int min, max;
6972 /* For SSA names try to extract range info computed by VRP. Otherwise
6973 fall back to varying. */
6974 if (TREE_CODE (expr) == SSA_NAME
6975 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6976 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6977 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6978 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6979 else
6980 set_value_range_to_varying (vr);
6984 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6985 the determined range type. */
6987 value_range_type
6988 determine_value_range (tree expr, wide_int *min, wide_int *max)
6990 value_range vr = VR_INITIALIZER;
6991 determine_value_range_1 (&vr, expr);
6992 if ((vr.type == VR_RANGE
6993 || vr.type == VR_ANTI_RANGE)
6994 && !symbolic_range_p (&vr))
6996 *min = wi::to_wide (vr.min);
6997 *max = wi::to_wide (vr.max);
6998 return vr.type;
7001 return VR_VARYING;