2018-11-12 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / tree-vrp.c
blobf5e0d03099edfeccde59f3268c4c557b66aec000
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 void
77 value_range_base::set (enum value_range_kind kind, tree min, tree max)
79 m_kind = kind;
80 m_min = min;
81 m_max = max;
82 if (flag_checking)
83 check ();
86 void
87 value_range::set_equiv (bitmap equiv)
89 /* Since updating the equivalence set involves deep copying the
90 bitmaps, only do it if absolutely necessary.
92 All equivalence bitmaps are allocated from the same obstack. So
93 we can use the obstack associated with EQUIV to allocate vr->equiv. */
94 if (m_equiv == NULL
95 && equiv != NULL)
96 m_equiv = BITMAP_ALLOC (equiv->obstack);
98 if (equiv != m_equiv)
100 if (equiv && !bitmap_empty_p (equiv))
101 bitmap_copy (m_equiv, equiv);
102 else
103 bitmap_clear (m_equiv);
107 /* Initialize value_range. */
109 void
110 value_range::set (enum value_range_kind kind, tree min, tree max,
111 bitmap equiv)
113 value_range_base::set (kind, min, max);
114 set_equiv (equiv);
115 if (flag_checking)
116 check ();
119 value_range_base::value_range_base (value_range_kind kind, tree min, tree max)
121 set (kind, min, max);
124 value_range::value_range (value_range_kind kind, tree min, tree max,
125 bitmap equiv)
127 m_equiv = NULL;
128 set (kind, min, max, equiv);
131 value_range::value_range (const value_range_base &other)
133 m_equiv = NULL;
134 set (other.kind (), other.min(), other.max (), NULL);
137 /* Like above, but keep the equivalences intact. */
139 void
140 value_range::update (value_range_kind kind, tree min, tree max)
142 set (kind, min, max, m_equiv);
145 /* Copy value_range in FROM into THIS while avoiding bitmap sharing.
147 Note: The code that avoids the bitmap sharing looks at the existing
148 this->m_equiv, so this function cannot be used to initalize an
149 object. Use the constructors for initialization. */
151 void
152 value_range::deep_copy (const value_range *from)
154 set (from->m_kind, from->min (), from->max (), from->m_equiv);
157 /* Check the validity of the range. */
159 void
160 value_range_base::check ()
162 switch (m_kind)
164 case VR_RANGE:
165 case VR_ANTI_RANGE:
167 int cmp;
169 gcc_assert (m_min && m_max);
171 gcc_assert (!TREE_OVERFLOW_P (m_min) && !TREE_OVERFLOW_P (m_max));
173 /* Creating ~[-MIN, +MAX] is stupid because that would be
174 the empty set. */
175 if (INTEGRAL_TYPE_P (TREE_TYPE (m_min)) && m_kind == VR_ANTI_RANGE)
176 gcc_assert (!vrp_val_is_min (m_min) || !vrp_val_is_max (m_max));
178 cmp = compare_values (m_min, m_max);
179 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
180 break;
182 case VR_UNDEFINED:
183 case VR_VARYING:
184 gcc_assert (!min () && !max ());
185 break;
186 default:
187 gcc_unreachable ();
191 void
192 value_range::check ()
194 value_range_base::check ();
195 switch (m_kind)
197 case VR_UNDEFINED:
198 case VR_VARYING:
199 gcc_assert (!m_equiv || bitmap_empty_p (m_equiv));
200 default:;
204 /* Returns TRUE if THIS == OTHER. Ignores the equivalence bitmap if
205 IGNORE_EQUIVS is TRUE. */
207 bool
208 value_range::equal_p (const value_range &other, bool ignore_equivs) const
210 return (ignore_equivs_equal_p (other)
211 && (ignore_equivs
212 || vrp_bitmap_equal_p (m_equiv, other.m_equiv)));
215 /* Return equality while ignoring equivalence bitmap. */
217 bool
218 value_range_base::ignore_equivs_equal_p (const value_range_base &other) const
220 return (m_kind == other.m_kind
221 && vrp_operand_equal_p (m_min, other.m_min)
222 && vrp_operand_equal_p (m_max, other.m_max));
225 bool
226 value_range::operator== (const value_range &other) const
228 return equal_p (other, /*ignore_equivs=*/false);
231 bool
232 value_range::operator!= (const value_range &other) const
234 return !(*this == other);
237 /* Return TRUE if this is a symbolic range. */
239 bool
240 value_range_base::symbolic_p () const
242 return (!varying_p ()
243 && !undefined_p ()
244 && (!is_gimple_min_invariant (m_min)
245 || !is_gimple_min_invariant (m_max)));
248 /* NOTE: This is not the inverse of symbolic_p because the range
249 could also be varying or undefined. Ideally they should be inverse
250 of each other, with varying only applying to symbolics. Varying of
251 constants would be represented as [-MIN, +MAX]. */
253 bool
254 value_range_base::constant_p () const
256 return (!varying_p ()
257 && !undefined_p ()
258 && TREE_CODE (m_min) == INTEGER_CST
259 && TREE_CODE (m_max) == INTEGER_CST);
262 void
263 value_range_base::set_undefined ()
265 *this = value_range_base (VR_UNDEFINED, NULL, NULL);
268 void
269 value_range::set_undefined ()
271 equiv_clear ();
272 *this = value_range (VR_UNDEFINED, NULL, NULL, NULL);
275 void
276 value_range_base::set_varying ()
278 *this = value_range_base (VR_VARYING, NULL, NULL);
281 void
282 value_range::set_varying ()
284 equiv_clear ();
285 *this = value_range (VR_VARYING, NULL, NULL, NULL);
288 /* Return TRUE if it is possible that range contains VAL. */
290 bool
291 value_range_base::may_contain_p (tree val) const
293 if (varying_p ())
294 return true;
296 if (undefined_p ())
297 return true;
299 if (m_kind == VR_ANTI_RANGE)
301 int res = value_inside_range (val, min (), max ());
302 return res == 0 || res == -2;
304 return value_inside_range (val, min (), max ()) != 0;
307 void
308 value_range::equiv_clear ()
310 if (m_equiv)
311 bitmap_clear (m_equiv);
314 /* Add VAR and VAR's equivalence set (VAR_VR) to the equivalence
315 bitmap. If no equivalence table has been created, OBSTACK is the
316 obstack to use (NULL for the default obstack).
318 This is the central point where equivalence processing can be
319 turned on/off. */
321 void
322 value_range::equiv_add (const_tree var,
323 const value_range *var_vr,
324 bitmap_obstack *obstack)
326 if (!m_equiv)
327 m_equiv = BITMAP_ALLOC (obstack);
328 unsigned ver = SSA_NAME_VERSION (var);
329 bitmap_set_bit (m_equiv, ver);
330 if (var_vr && var_vr->m_equiv)
331 bitmap_ior_into (m_equiv, var_vr->m_equiv);
334 /* If range is a singleton, place it in RESULT and return TRUE.
335 Note: A singleton can be any gimple invariant, not just constants.
336 So, [&x, &x] counts as a singleton. */
338 bool
339 value_range_base::singleton_p (tree *result) const
341 if (m_kind == VR_RANGE
342 && vrp_operand_equal_p (min (), max ())
343 && is_gimple_min_invariant (min ()))
345 if (result)
346 *result = min ();
347 return true;
349 return false;
352 tree
353 value_range_base::type () const
355 /* Types are only valid for VR_RANGE and VR_ANTI_RANGE, which are
356 known to have non-zero min/max. */
357 gcc_assert (min ());
358 return TREE_TYPE (min ());
361 /* Dump value range to FILE. */
363 void
364 value_range_base::dump (FILE *file) const
366 if (undefined_p ())
367 fprintf (file, "UNDEFINED");
368 else if (m_kind == VR_RANGE || m_kind == VR_ANTI_RANGE)
370 tree type = TREE_TYPE (min ());
372 fprintf (file, "%s[", (m_kind == VR_ANTI_RANGE) ? "~" : "");
374 if (INTEGRAL_TYPE_P (type)
375 && !TYPE_UNSIGNED (type)
376 && vrp_val_is_min (min ()))
377 fprintf (file, "-INF");
378 else
379 print_generic_expr (file, min ());
381 fprintf (file, ", ");
383 if (INTEGRAL_TYPE_P (type)
384 && vrp_val_is_max (max ()))
385 fprintf (file, "+INF");
386 else
387 print_generic_expr (file, max ());
389 fprintf (file, "]");
391 else if (varying_p ())
392 fprintf (file, "VARYING");
393 else
394 fprintf (file, "INVALID RANGE");
397 void
398 value_range::dump (FILE *file) const
400 value_range_base::dump (file);
401 if ((m_kind == VR_RANGE || m_kind == VR_ANTI_RANGE)
402 && m_equiv)
404 bitmap_iterator bi;
405 unsigned i, c = 0;
407 fprintf (file, " EQUIVALENCES: { ");
409 EXECUTE_IF_SET_IN_BITMAP (m_equiv, 0, i, bi)
411 print_generic_expr (file, ssa_name (i));
412 fprintf (file, " ");
413 c++;
416 fprintf (file, "} (%u elements)", c);
420 void
421 value_range_base::dump () const
423 dump_value_range (stderr, this);
424 fprintf (stderr, "\n");
427 void
428 value_range::dump () const
430 dump_value_range (stderr, this);
431 fprintf (stderr, "\n");
434 /* Return true if the SSA name NAME is live on the edge E. */
436 static bool
437 live_on_edge (edge e, tree name)
439 return (live[e->dest->index]
440 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
443 /* Location information for ASSERT_EXPRs. Each instance of this
444 structure describes an ASSERT_EXPR for an SSA name. Since a single
445 SSA name may have more than one assertion associated with it, these
446 locations are kept in a linked list attached to the corresponding
447 SSA name. */
448 struct assert_locus
450 /* Basic block where the assertion would be inserted. */
451 basic_block bb;
453 /* Some assertions need to be inserted on an edge (e.g., assertions
454 generated by COND_EXPRs). In those cases, BB will be NULL. */
455 edge e;
457 /* Pointer to the statement that generated this assertion. */
458 gimple_stmt_iterator si;
460 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
461 enum tree_code comp_code;
463 /* Value being compared against. */
464 tree val;
466 /* Expression to compare. */
467 tree expr;
469 /* Next node in the linked list. */
470 assert_locus *next;
473 /* If bit I is present, it means that SSA name N_i has a list of
474 assertions that should be inserted in the IL. */
475 static bitmap need_assert_for;
477 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
478 holds a list of ASSERT_LOCUS_T nodes that describe where
479 ASSERT_EXPRs for SSA name N_I should be inserted. */
480 static assert_locus **asserts_for;
482 /* Return the maximum value for TYPE. */
484 tree
485 vrp_val_max (const_tree type)
487 if (!INTEGRAL_TYPE_P (type))
488 return NULL_TREE;
490 return TYPE_MAX_VALUE (type);
493 /* Return the minimum value for TYPE. */
495 tree
496 vrp_val_min (const_tree type)
498 if (!INTEGRAL_TYPE_P (type))
499 return NULL_TREE;
501 return TYPE_MIN_VALUE (type);
504 /* Return whether VAL is equal to the maximum value of its type.
505 We can't do a simple equality comparison with TYPE_MAX_VALUE because
506 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
507 is not == to the integer constant with the same value in the type. */
509 bool
510 vrp_val_is_max (const_tree val)
512 tree type_max = vrp_val_max (TREE_TYPE (val));
513 return (val == type_max
514 || (type_max != NULL_TREE
515 && operand_equal_p (val, type_max, 0)));
518 /* Return whether VAL is equal to the minimum value of its type. */
520 bool
521 vrp_val_is_min (const_tree val)
523 tree type_min = vrp_val_min (TREE_TYPE (val));
524 return (val == type_min
525 || (type_min != NULL_TREE
526 && operand_equal_p (val, type_min, 0)));
529 /* VR_TYPE describes a range with mininum value *MIN and maximum
530 value *MAX. Restrict the range to the set of values that have
531 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
532 return the new range type.
534 SGN gives the sign of the values described by the range. */
536 enum value_range_kind
537 intersect_range_with_nonzero_bits (enum value_range_kind vr_type,
538 wide_int *min, wide_int *max,
539 const wide_int &nonzero_bits,
540 signop sgn)
542 if (vr_type == VR_ANTI_RANGE)
544 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
545 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
546 to create an inclusive upper bound for A and an inclusive lower
547 bound for B. */
548 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
549 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
551 /* If the calculation of A_MAX wrapped, A is effectively empty
552 and A_MAX is the highest value that satisfies NONZERO_BITS.
553 Likewise if the calculation of B_MIN wrapped, B is effectively
554 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
555 bool a_empty = wi::ge_p (a_max, *min, sgn);
556 bool b_empty = wi::le_p (b_min, *max, sgn);
558 /* If both A and B are empty, there are no valid values. */
559 if (a_empty && b_empty)
560 return VR_UNDEFINED;
562 /* If exactly one of A or B is empty, return a VR_RANGE for the
563 other one. */
564 if (a_empty || b_empty)
566 *min = b_min;
567 *max = a_max;
568 gcc_checking_assert (wi::le_p (*min, *max, sgn));
569 return VR_RANGE;
572 /* Update the VR_ANTI_RANGE bounds. */
573 *min = a_max + 1;
574 *max = b_min - 1;
575 gcc_checking_assert (wi::le_p (*min, *max, sgn));
577 /* Now check whether the excluded range includes any values that
578 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
579 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
581 unsigned int precision = min->get_precision ();
582 *min = wi::min_value (precision, sgn);
583 *max = wi::max_value (precision, sgn);
584 vr_type = VR_RANGE;
587 if (vr_type == VR_RANGE)
589 *max = wi::round_down_for_mask (*max, nonzero_bits);
591 /* Check that the range contains at least one valid value. */
592 if (wi::gt_p (*min, *max, sgn))
593 return VR_UNDEFINED;
595 *min = wi::round_up_for_mask (*min, nonzero_bits);
596 gcc_checking_assert (wi::le_p (*min, *max, sgn));
598 return vr_type;
601 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
603 void
604 set_value_range (value_range *vr, enum value_range_kind kind,
605 tree min, tree max, bitmap equiv)
607 *vr = value_range (kind, min, max, equiv);
611 /* Set value range to the canonical form of {VRTYPE, MIN, MAX, EQUIV}.
612 This means adjusting VRTYPE, MIN and MAX representing the case of a
613 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
614 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
615 In corner cases where MAX+1 or MIN-1 wraps this will fall back
616 to varying.
617 This routine exists to ease canonicalization in the case where we
618 extract ranges from var + CST op limit. */
620 void
621 value_range_base::set_and_canonicalize (enum value_range_kind kind,
622 tree min, tree max)
624 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
625 if (kind == VR_UNDEFINED)
627 set_undefined ();
628 return;
630 else if (kind == VR_VARYING)
632 set_varying ();
633 return;
636 /* Nothing to canonicalize for symbolic ranges. */
637 if (TREE_CODE (min) != INTEGER_CST
638 || TREE_CODE (max) != INTEGER_CST)
640 set (kind, min, max);
641 return;
644 /* Wrong order for min and max, to swap them and the VR type we need
645 to adjust them. */
646 if (tree_int_cst_lt (max, min))
648 tree one, tmp;
650 /* For one bit precision if max < min, then the swapped
651 range covers all values, so for VR_RANGE it is varying and
652 for VR_ANTI_RANGE empty range, so drop to varying as well. */
653 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
655 set_varying ();
656 return;
659 one = build_int_cst (TREE_TYPE (min), 1);
660 tmp = int_const_binop (PLUS_EXPR, max, one);
661 max = int_const_binop (MINUS_EXPR, min, one);
662 min = tmp;
664 /* There's one corner case, if we had [C+1, C] before we now have
665 that again. But this represents an empty value range, so drop
666 to varying in this case. */
667 if (tree_int_cst_lt (max, min))
669 set_varying ();
670 return;
673 kind = kind == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
676 /* Anti-ranges that can be represented as ranges should be so. */
677 if (kind == VR_ANTI_RANGE)
679 /* For -fstrict-enums we may receive out-of-range ranges so consider
680 values < -INF and values > INF as -INF/INF as well. */
681 tree type = TREE_TYPE (min);
682 bool is_min = (INTEGRAL_TYPE_P (type)
683 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
684 bool is_max = (INTEGRAL_TYPE_P (type)
685 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
687 if (is_min && is_max)
689 /* We cannot deal with empty ranges, drop to varying.
690 ??? This could be VR_UNDEFINED instead. */
691 set_varying ();
692 return;
694 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
695 && (is_min || is_max))
697 /* Non-empty boolean ranges can always be represented
698 as a singleton range. */
699 if (is_min)
700 min = max = vrp_val_max (TREE_TYPE (min));
701 else
702 min = max = vrp_val_min (TREE_TYPE (min));
703 kind = VR_RANGE;
705 else if (is_min
706 /* As a special exception preserve non-null ranges. */
707 && !(TYPE_UNSIGNED (TREE_TYPE (min))
708 && integer_zerop (max)))
710 tree one = build_int_cst (TREE_TYPE (max), 1);
711 min = int_const_binop (PLUS_EXPR, max, one);
712 max = vrp_val_max (TREE_TYPE (max));
713 kind = VR_RANGE;
715 else if (is_max)
717 tree one = build_int_cst (TREE_TYPE (min), 1);
718 max = int_const_binop (MINUS_EXPR, min, one);
719 min = vrp_val_min (TREE_TYPE (min));
720 kind = VR_RANGE;
724 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
725 to make sure VRP iteration terminates, otherwise we can get into
726 oscillations. */
728 set (kind, min, max);
731 void
732 value_range::set_and_canonicalize (enum value_range_kind kind,
733 tree min, tree max, bitmap equiv)
735 value_range_base::set_and_canonicalize (kind, min, max);
736 if (this->kind () == VR_RANGE || this->kind () == VR_ANTI_RANGE)
737 set_equiv (equiv);
738 else
739 equiv_clear ();
742 /* Set value range VR to a single value. This function is only called
743 with values we get from statements, and exists to clear the
744 TREE_OVERFLOW flag. */
746 void
747 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
749 gcc_assert (is_gimple_min_invariant (val));
750 if (TREE_OVERFLOW_P (val))
751 val = drop_tree_overflow (val);
752 set_value_range (vr, VR_RANGE, val, val, equiv);
755 /* Set value range VR to a non-NULL range of type TYPE. */
757 void
758 set_value_range_to_nonnull (value_range *vr, tree type)
760 tree zero = build_int_cst (type, 0);
761 set_value_range (vr, VR_ANTI_RANGE, zero, zero, NULL);
765 /* Set value range VR to a NULL range of type TYPE. */
767 void
768 set_value_range_to_null (value_range *vr, tree type)
770 set_value_range_to_value (vr, build_int_cst (type, 0), NULL);
773 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
775 bool
776 vrp_operand_equal_p (const_tree val1, const_tree val2)
778 if (val1 == val2)
779 return true;
780 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
781 return false;
782 return true;
785 /* Return true, if the bitmaps B1 and B2 are equal. */
787 bool
788 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
790 return (b1 == b2
791 || ((!b1 || bitmap_empty_p (b1))
792 && (!b2 || bitmap_empty_p (b2)))
793 || (b1 && b2
794 && bitmap_equal_p (b1, b2)));
797 /* Return true if VR is [0, 0]. */
799 static inline bool
800 range_is_null (const value_range *vr)
802 return vr->zero_p ();
805 static inline bool
806 range_is_nonnull (const value_range *vr)
808 return (vr->kind () == VR_ANTI_RANGE
809 && vr->min () == vr->max ()
810 && integer_zerop (vr->min ()));
813 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
814 a singleton. */
816 bool
817 range_int_cst_p (const value_range_base *vr)
819 return (vr->kind () == VR_RANGE
820 && TREE_CODE (vr->min ()) == INTEGER_CST
821 && TREE_CODE (vr->max ()) == INTEGER_CST);
824 /* Return true if VR is a INTEGER_CST singleton. */
826 bool
827 range_int_cst_singleton_p (const value_range_base *vr)
829 return (range_int_cst_p (vr)
830 && tree_int_cst_equal (vr->min (), vr->max ()));
833 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
834 otherwise. We only handle additive operations and set NEG to true if the
835 symbol is negated and INV to the invariant part, if any. */
837 tree
838 get_single_symbol (tree t, bool *neg, tree *inv)
840 bool neg_;
841 tree inv_;
843 *inv = NULL_TREE;
844 *neg = false;
846 if (TREE_CODE (t) == PLUS_EXPR
847 || TREE_CODE (t) == POINTER_PLUS_EXPR
848 || TREE_CODE (t) == MINUS_EXPR)
850 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
852 neg_ = (TREE_CODE (t) == MINUS_EXPR);
853 inv_ = TREE_OPERAND (t, 0);
854 t = TREE_OPERAND (t, 1);
856 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
858 neg_ = false;
859 inv_ = TREE_OPERAND (t, 1);
860 t = TREE_OPERAND (t, 0);
862 else
863 return NULL_TREE;
865 else
867 neg_ = false;
868 inv_ = NULL_TREE;
871 if (TREE_CODE (t) == NEGATE_EXPR)
873 t = TREE_OPERAND (t, 0);
874 neg_ = !neg_;
877 if (TREE_CODE (t) != SSA_NAME)
878 return NULL_TREE;
880 if (inv_ && TREE_OVERFLOW_P (inv_))
881 inv_ = drop_tree_overflow (inv_);
883 *neg = neg_;
884 *inv = inv_;
885 return t;
888 /* The reverse operation: build a symbolic expression with TYPE
889 from symbol SYM, negated according to NEG, and invariant INV. */
891 static tree
892 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
894 const bool pointer_p = POINTER_TYPE_P (type);
895 tree t = sym;
897 if (neg)
898 t = build1 (NEGATE_EXPR, type, t);
900 if (integer_zerop (inv))
901 return t;
903 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
906 /* Return
907 1 if VAL < VAL2
908 0 if !(VAL < VAL2)
909 -2 if those are incomparable. */
911 operand_less_p (tree val, tree val2)
913 /* LT is folded faster than GE and others. Inline the common case. */
914 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
915 return tree_int_cst_lt (val, val2);
916 else
918 tree tcmp;
920 fold_defer_overflow_warnings ();
922 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
924 fold_undefer_and_ignore_overflow_warnings ();
926 if (!tcmp
927 || TREE_CODE (tcmp) != INTEGER_CST)
928 return -2;
930 if (!integer_zerop (tcmp))
931 return 1;
934 return 0;
937 /* Compare two values VAL1 and VAL2. Return
939 -2 if VAL1 and VAL2 cannot be compared at compile-time,
940 -1 if VAL1 < VAL2,
941 0 if VAL1 == VAL2,
942 +1 if VAL1 > VAL2, and
943 +2 if VAL1 != VAL2
945 This is similar to tree_int_cst_compare but supports pointer values
946 and values that cannot be compared at compile time.
948 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
949 true if the return value is only valid if we assume that signed
950 overflow is undefined. */
953 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
955 if (val1 == val2)
956 return 0;
958 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
959 both integers. */
960 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
961 == POINTER_TYPE_P (TREE_TYPE (val2)));
963 /* Convert the two values into the same type. This is needed because
964 sizetype causes sign extension even for unsigned types. */
965 val2 = fold_convert (TREE_TYPE (val1), val2);
966 STRIP_USELESS_TYPE_CONVERSION (val2);
968 const bool overflow_undefined
969 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
970 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
971 tree inv1, inv2;
972 bool neg1, neg2;
973 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
974 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
976 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
977 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
978 if (sym1 && sym2)
980 /* Both values must use the same name with the same sign. */
981 if (sym1 != sym2 || neg1 != neg2)
982 return -2;
984 /* [-]NAME + CST == [-]NAME + CST. */
985 if (inv1 == inv2)
986 return 0;
988 /* If overflow is defined we cannot simplify more. */
989 if (!overflow_undefined)
990 return -2;
992 if (strict_overflow_p != NULL
993 /* Symbolic range building sets TREE_NO_WARNING to declare
994 that overflow doesn't happen. */
995 && (!inv1 || !TREE_NO_WARNING (val1))
996 && (!inv2 || !TREE_NO_WARNING (val2)))
997 *strict_overflow_p = true;
999 if (!inv1)
1000 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1001 if (!inv2)
1002 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1004 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
1005 TYPE_SIGN (TREE_TYPE (val1)));
1008 const bool cst1 = is_gimple_min_invariant (val1);
1009 const bool cst2 = is_gimple_min_invariant (val2);
1011 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1012 it might be possible to say something depending on the constants. */
1013 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1015 if (!overflow_undefined)
1016 return -2;
1018 if (strict_overflow_p != NULL
1019 /* Symbolic range building sets TREE_NO_WARNING to declare
1020 that overflow doesn't happen. */
1021 && (!sym1 || !TREE_NO_WARNING (val1))
1022 && (!sym2 || !TREE_NO_WARNING (val2)))
1023 *strict_overflow_p = true;
1025 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1026 tree cst = cst1 ? val1 : val2;
1027 tree inv = cst1 ? inv2 : inv1;
1029 /* Compute the difference between the constants. If it overflows or
1030 underflows, this means that we can trivially compare the NAME with
1031 it and, consequently, the two values with each other. */
1032 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
1033 if (wi::cmp (0, wi::to_wide (inv), sgn)
1034 != wi::cmp (diff, wi::to_wide (cst), sgn))
1036 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
1037 return cst1 ? res : -res;
1040 return -2;
1043 /* We cannot say anything more for non-constants. */
1044 if (!cst1 || !cst2)
1045 return -2;
1047 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1049 /* We cannot compare overflowed values. */
1050 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1051 return -2;
1053 if (TREE_CODE (val1) == INTEGER_CST
1054 && TREE_CODE (val2) == INTEGER_CST)
1055 return tree_int_cst_compare (val1, val2);
1057 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
1059 if (known_eq (wi::to_poly_widest (val1),
1060 wi::to_poly_widest (val2)))
1061 return 0;
1062 if (known_lt (wi::to_poly_widest (val1),
1063 wi::to_poly_widest (val2)))
1064 return -1;
1065 if (known_gt (wi::to_poly_widest (val1),
1066 wi::to_poly_widest (val2)))
1067 return 1;
1070 return -2;
1072 else
1074 tree t;
1076 /* First see if VAL1 and VAL2 are not the same. */
1077 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1078 return 0;
1080 /* If VAL1 is a lower address than VAL2, return -1. */
1081 if (operand_less_p (val1, val2) == 1)
1082 return -1;
1084 /* If VAL1 is a higher address than VAL2, return +1. */
1085 if (operand_less_p (val2, val1) == 1)
1086 return 1;
1088 /* If VAL1 is different than VAL2, return +2.
1089 For integer constants we either have already returned -1 or 1
1090 or they are equivalent. We still might succeed in proving
1091 something about non-trivial operands. */
1092 if (TREE_CODE (val1) != INTEGER_CST
1093 || TREE_CODE (val2) != INTEGER_CST)
1095 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1096 if (t && integer_onep (t))
1097 return 2;
1100 return -2;
1104 /* Compare values like compare_values_warnv. */
1107 compare_values (tree val1, tree val2)
1109 bool sop;
1110 return compare_values_warnv (val1, val2, &sop);
1114 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1115 0 if VAL is not inside [MIN, MAX],
1116 -2 if we cannot tell either way.
1118 Benchmark compile/20001226-1.c compilation time after changing this
1119 function. */
1122 value_inside_range (tree val, tree min, tree max)
1124 int cmp1, cmp2;
1126 cmp1 = operand_less_p (val, min);
1127 if (cmp1 == -2)
1128 return -2;
1129 if (cmp1 == 1)
1130 return 0;
1132 cmp2 = operand_less_p (max, val);
1133 if (cmp2 == -2)
1134 return -2;
1136 return !cmp2;
1140 /* Return TRUE if *VR includes the value zero. */
1142 bool
1143 range_includes_zero_p (const value_range_base *vr)
1145 if (vr->varying_p () || vr->undefined_p ())
1146 return true;
1147 tree zero = build_int_cst (vr->type (), 0);
1148 return vr->may_contain_p (zero);
1151 /* If *VR has a value range that is a single constant value return that,
1152 otherwise return NULL_TREE.
1154 ?? This actually returns TRUE for [&x, &x], so perhaps "constant"
1155 is not the best name. */
1157 tree
1158 value_range_constant_singleton (const value_range_base *vr)
1160 tree result = NULL;
1161 if (vr->singleton_p (&result))
1162 return result;
1163 return NULL;
1166 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
1168 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
1170 Return TRUE if VR was a constant range and we were able to compute
1171 the bit masks. */
1173 bool
1174 vrp_set_zero_nonzero_bits (const tree expr_type,
1175 const value_range_base *vr,
1176 wide_int *may_be_nonzero,
1177 wide_int *must_be_nonzero)
1179 if (!range_int_cst_p (vr))
1181 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1182 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1183 return false;
1185 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
1186 wi::to_wide (vr->min ()),
1187 wi::to_wide (vr->max ()),
1188 *may_be_nonzero, *must_be_nonzero);
1189 return true;
1192 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1193 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1194 false otherwise. If *AR can be represented with a single range
1195 *VR1 will be VR_UNDEFINED. */
1197 static bool
1198 ranges_from_anti_range (const value_range *ar,
1199 value_range *vr0, value_range *vr1)
1201 tree type = ar->type ();
1203 vr0->set_undefined ();
1204 vr1->set_undefined ();
1206 /* As a future improvement, we could handle ~[0, A] as: [-INF, -1] U
1207 [A+1, +INF]. Not sure if this helps in practice, though. */
1209 if (ar->kind () != VR_ANTI_RANGE
1210 || TREE_CODE (ar->min ()) != INTEGER_CST
1211 || TREE_CODE (ar->max ()) != INTEGER_CST
1212 || !vrp_val_min (type)
1213 || !vrp_val_max (type))
1214 return false;
1216 if (!vrp_val_is_min (ar->min ()))
1217 *vr0 = value_range (VR_RANGE,
1218 vrp_val_min (type),
1219 wide_int_to_tree (type, wi::to_wide (ar->min ()) - 1));
1220 if (!vrp_val_is_max (ar->max ()))
1221 *vr1 = value_range (VR_RANGE,
1222 wide_int_to_tree (type, wi::to_wide (ar->max ()) + 1),
1223 vrp_val_max (type));
1224 if (vr0->undefined_p ())
1226 *vr0 = *vr1;
1227 vr1->set_undefined ();
1230 return !vr0->undefined_p ();
1233 /* Extract the components of a value range into a pair of wide ints in
1234 [WMIN, WMAX].
1236 If the value range is anything but a VR_*RANGE of constants, the
1237 resulting wide ints are set to [-MIN, +MAX] for the type. */
1239 static void inline
1240 extract_range_into_wide_ints (const value_range *vr,
1241 signop sign, unsigned prec,
1242 wide_int &wmin, wide_int &wmax)
1244 gcc_assert (vr->kind () != VR_ANTI_RANGE || vr->symbolic_p ());
1245 if (range_int_cst_p (vr))
1247 wmin = wi::to_wide (vr->min ());
1248 wmax = wi::to_wide (vr->max ());
1250 else
1252 wmin = wi::min_value (prec, sign);
1253 wmax = wi::max_value (prec, sign);
1257 /* Value range wrapper for wide_int_range_multiplicative_op:
1259 *VR = *VR0 .CODE. *VR1. */
1261 static void
1262 extract_range_from_multiplicative_op (value_range *vr,
1263 enum tree_code code,
1264 const value_range *vr0,
1265 const value_range *vr1)
1267 gcc_assert (code == MULT_EXPR
1268 || code == TRUNC_DIV_EXPR
1269 || code == FLOOR_DIV_EXPR
1270 || code == CEIL_DIV_EXPR
1271 || code == EXACT_DIV_EXPR
1272 || code == ROUND_DIV_EXPR
1273 || code == RSHIFT_EXPR
1274 || code == LSHIFT_EXPR);
1275 gcc_assert (vr0->kind () == VR_RANGE
1276 && vr0->kind () == vr1->kind ());
1278 tree type = vr0->type ();
1279 wide_int res_lb, res_ub;
1280 wide_int vr0_lb = wi::to_wide (vr0->min ());
1281 wide_int vr0_ub = wi::to_wide (vr0->max ());
1282 wide_int vr1_lb = wi::to_wide (vr1->min ());
1283 wide_int vr1_ub = wi::to_wide (vr1->max ());
1284 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1285 unsigned prec = TYPE_PRECISION (type);
1287 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1288 code, TYPE_SIGN (type), prec,
1289 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1290 overflow_undefined))
1291 vr->set_and_canonicalize (VR_RANGE,
1292 wide_int_to_tree (type, res_lb),
1293 wide_int_to_tree (type, res_ub), NULL);
1294 else
1295 vr->set_varying ();
1298 /* If BOUND will include a symbolic bound, adjust it accordingly,
1299 otherwise leave it as is.
1301 CODE is the original operation that combined the bounds (PLUS_EXPR
1302 or MINUS_EXPR).
1304 TYPE is the type of the original operation.
1306 SYM_OPn is the symbolic for OPn if it has a symbolic.
1308 NEG_OPn is TRUE if the OPn was negated. */
1310 static void
1311 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1312 tree sym_op0, tree sym_op1,
1313 bool neg_op0, bool neg_op1)
1315 bool minus_p = (code == MINUS_EXPR);
1316 /* If the result bound is constant, we're done; otherwise, build the
1317 symbolic lower bound. */
1318 if (sym_op0 == sym_op1)
1320 else if (sym_op0)
1321 bound = build_symbolic_expr (type, sym_op0,
1322 neg_op0, bound);
1323 else if (sym_op1)
1325 /* We may not negate if that might introduce
1326 undefined overflow. */
1327 if (!minus_p
1328 || neg_op1
1329 || TYPE_OVERFLOW_WRAPS (type))
1330 bound = build_symbolic_expr (type, sym_op1,
1331 neg_op1 ^ minus_p, bound);
1332 else
1333 bound = NULL_TREE;
1337 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1338 int bound according to CODE. CODE is the operation combining the
1339 bound (either a PLUS_EXPR or a MINUS_EXPR).
1341 TYPE is the type of the combine operation.
1343 WI is the wide int to store the result.
1345 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1346 if over/underflow occurred. */
1348 static void
1349 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1350 tree type, tree op0, tree op1)
1352 bool minus_p = (code == MINUS_EXPR);
1353 const signop sgn = TYPE_SIGN (type);
1354 const unsigned int prec = TYPE_PRECISION (type);
1356 /* Combine the bounds, if any. */
1357 if (op0 && op1)
1359 if (minus_p)
1360 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1361 else
1362 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1364 else if (op0)
1365 wi = wi::to_wide (op0);
1366 else if (op1)
1368 if (minus_p)
1369 wi = wi::neg (wi::to_wide (op1), &ovf);
1370 else
1371 wi = wi::to_wide (op1);
1373 else
1374 wi = wi::shwi (0, prec);
1377 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1378 put the result in VR.
1380 TYPE is the type of the range.
1382 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1383 occurred while originally calculating WMIN or WMAX. -1 indicates
1384 underflow. +1 indicates overflow. 0 indicates neither. */
1386 static void
1387 set_value_range_with_overflow (value_range_kind &kind, tree &min, tree &max,
1388 tree type,
1389 const wide_int &wmin, const wide_int &wmax,
1390 wi::overflow_type min_ovf,
1391 wi::overflow_type max_ovf)
1393 const signop sgn = TYPE_SIGN (type);
1394 const unsigned int prec = TYPE_PRECISION (type);
1396 /* For one bit precision if max < min, then the swapped
1397 range covers all values. */
1398 if (prec == 1 && wi::lt_p (wmax, wmin, sgn))
1400 kind = VR_VARYING;
1401 return;
1404 if (TYPE_OVERFLOW_WRAPS (type))
1406 /* If overflow wraps, truncate the values and adjust the
1407 range kind and bounds appropriately. */
1408 wide_int tmin = wide_int::from (wmin, prec, sgn);
1409 wide_int tmax = wide_int::from (wmax, prec, sgn);
1410 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1412 /* If the limits are swapped, we wrapped around and cover
1413 the entire range. We have a similar check at the end of
1414 extract_range_from_binary_expr_1. */
1415 if (wi::gt_p (tmin, tmax, sgn))
1416 kind = VR_VARYING;
1417 else
1419 kind = VR_RANGE;
1420 /* No overflow or both overflow or underflow. The
1421 range kind stays VR_RANGE. */
1422 min = wide_int_to_tree (type, tmin);
1423 max = wide_int_to_tree (type, tmax);
1425 return;
1427 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1428 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1430 /* Min underflow or max overflow. The range kind
1431 changes to VR_ANTI_RANGE. */
1432 bool covers = false;
1433 wide_int tem = tmin;
1434 tmin = tmax + 1;
1435 if (wi::cmp (tmin, tmax, sgn) < 0)
1436 covers = true;
1437 tmax = tem - 1;
1438 if (wi::cmp (tmax, tem, sgn) > 0)
1439 covers = true;
1440 /* If the anti-range would cover nothing, drop to varying.
1441 Likewise if the anti-range bounds are outside of the
1442 types values. */
1443 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1445 kind = VR_VARYING;
1446 return;
1448 kind = VR_ANTI_RANGE;
1449 min = wide_int_to_tree (type, tmin);
1450 max = wide_int_to_tree (type, tmax);
1451 return;
1453 else
1455 /* Other underflow and/or overflow, drop to VR_VARYING. */
1456 kind = VR_VARYING;
1457 return;
1460 else
1462 /* If overflow does not wrap, saturate to the types min/max
1463 value. */
1464 wide_int type_min = wi::min_value (prec, sgn);
1465 wide_int type_max = wi::max_value (prec, sgn);
1466 kind = VR_RANGE;
1467 if (min_ovf == wi::OVF_UNDERFLOW)
1468 min = wide_int_to_tree (type, type_min);
1469 else if (min_ovf == wi::OVF_OVERFLOW)
1470 min = wide_int_to_tree (type, type_max);
1471 else
1472 min = wide_int_to_tree (type, wmin);
1474 if (max_ovf == wi::OVF_UNDERFLOW)
1475 max = wide_int_to_tree (type, type_min);
1476 else if (max_ovf == wi::OVF_OVERFLOW)
1477 max = wide_int_to_tree (type, type_max);
1478 else
1479 max = wide_int_to_tree (type, wmax);
1483 /* Extract range information from a binary operation CODE based on
1484 the ranges of each of its operands *VR0 and *VR1 with resulting
1485 type EXPR_TYPE. The resulting range is stored in *VR. */
1487 void
1488 extract_range_from_binary_expr_1 (value_range *vr,
1489 enum tree_code code, tree expr_type,
1490 const value_range *vr0_,
1491 const value_range *vr1_)
1493 signop sign = TYPE_SIGN (expr_type);
1494 unsigned int prec = TYPE_PRECISION (expr_type);
1495 value_range vr0 = *vr0_, vr1 = *vr1_;
1496 value_range vrtem0, vrtem1;
1497 enum value_range_kind type;
1498 tree min = NULL_TREE, max = NULL_TREE;
1499 int cmp;
1501 if (!INTEGRAL_TYPE_P (expr_type)
1502 && !POINTER_TYPE_P (expr_type))
1504 vr->set_varying ();
1505 return;
1508 /* Not all binary expressions can be applied to ranges in a
1509 meaningful way. Handle only arithmetic operations. */
1510 if (code != PLUS_EXPR
1511 && code != MINUS_EXPR
1512 && code != POINTER_PLUS_EXPR
1513 && code != MULT_EXPR
1514 && code != TRUNC_DIV_EXPR
1515 && code != FLOOR_DIV_EXPR
1516 && code != CEIL_DIV_EXPR
1517 && code != EXACT_DIV_EXPR
1518 && code != ROUND_DIV_EXPR
1519 && code != TRUNC_MOD_EXPR
1520 && code != RSHIFT_EXPR
1521 && code != LSHIFT_EXPR
1522 && code != MIN_EXPR
1523 && code != MAX_EXPR
1524 && code != BIT_AND_EXPR
1525 && code != BIT_IOR_EXPR
1526 && code != BIT_XOR_EXPR)
1528 vr->set_varying ();
1529 return;
1532 /* If both ranges are UNDEFINED, so is the result. */
1533 if (vr0.undefined_p () && vr1.undefined_p ())
1535 vr->set_undefined ();
1536 return;
1538 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1539 code. At some point we may want to special-case operations that
1540 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1541 operand. */
1542 else if (vr0.undefined_p ())
1543 vr0.set_varying ();
1544 else if (vr1.undefined_p ())
1545 vr1.set_varying ();
1547 /* We get imprecise results from ranges_from_anti_range when
1548 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1549 range, but then we also need to hack up vrp_union. It's just
1550 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1551 if (code == EXACT_DIV_EXPR && range_is_nonnull (&vr0))
1553 set_value_range_to_nonnull (vr, expr_type);
1554 return;
1557 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1558 and express ~[] op X as ([]' op X) U ([]'' op X). */
1559 if (vr0.kind () == VR_ANTI_RANGE
1560 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1562 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1563 if (!vrtem1.undefined_p ())
1565 value_range vrres;
1566 extract_range_from_binary_expr_1 (&vrres, code, expr_type, &vrtem1, vr1_);
1567 vr->union_ (&vrres);
1569 return;
1571 /* Likewise for X op ~[]. */
1572 if (vr1.kind () == VR_ANTI_RANGE
1573 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1575 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1576 if (!vrtem1.undefined_p ())
1578 value_range vrres;
1579 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1580 vr0_, &vrtem1);
1581 vr->union_ (&vrres);
1583 return;
1586 /* The type of the resulting value range defaults to VR0.TYPE. */
1587 type = vr0.kind ();
1589 /* Refuse to operate on VARYING ranges, ranges of different kinds
1590 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1591 because we may be able to derive a useful range even if one of
1592 the operands is VR_VARYING or symbolic range. Similarly for
1593 divisions, MIN/MAX and PLUS/MINUS.
1595 TODO, we may be able to derive anti-ranges in some cases. */
1596 if (code != BIT_AND_EXPR
1597 && code != BIT_IOR_EXPR
1598 && code != TRUNC_DIV_EXPR
1599 && code != FLOOR_DIV_EXPR
1600 && code != CEIL_DIV_EXPR
1601 && code != EXACT_DIV_EXPR
1602 && code != ROUND_DIV_EXPR
1603 && code != TRUNC_MOD_EXPR
1604 && code != MIN_EXPR
1605 && code != MAX_EXPR
1606 && code != PLUS_EXPR
1607 && code != MINUS_EXPR
1608 && code != RSHIFT_EXPR
1609 && code != POINTER_PLUS_EXPR
1610 && (vr0.varying_p ()
1611 || vr1.varying_p ()
1612 || vr0.kind () != vr1.kind ()
1613 || vr0.symbolic_p ()
1614 || vr1.symbolic_p ()))
1616 vr->set_varying ();
1617 return;
1620 /* Now evaluate the expression to determine the new range. */
1621 if (POINTER_TYPE_P (expr_type))
1623 if (code == MIN_EXPR || code == MAX_EXPR)
1625 /* For MIN/MAX expressions with pointers, we only care about
1626 nullness, if both are non null, then the result is nonnull.
1627 If both are null, then the result is null. Otherwise they
1628 are varying. */
1629 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1630 set_value_range_to_nonnull (vr, expr_type);
1631 else if (range_is_null (&vr0) && range_is_null (&vr1))
1632 set_value_range_to_null (vr, expr_type);
1633 else
1634 vr->set_varying ();
1636 else if (code == POINTER_PLUS_EXPR)
1638 /* For pointer types, we are really only interested in asserting
1639 whether the expression evaluates to non-NULL. */
1640 if (!range_includes_zero_p (&vr0)
1641 || !range_includes_zero_p (&vr1))
1642 set_value_range_to_nonnull (vr, expr_type);
1643 else if (range_is_null (&vr0) && range_is_null (&vr1))
1644 set_value_range_to_null (vr, expr_type);
1645 else
1646 vr->set_varying ();
1648 else if (code == BIT_AND_EXPR)
1650 /* For pointer types, we are really only interested in asserting
1651 whether the expression evaluates to non-NULL. */
1652 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1653 set_value_range_to_nonnull (vr, expr_type);
1654 else if (range_is_null (&vr0) || range_is_null (&vr1))
1655 set_value_range_to_null (vr, expr_type);
1656 else
1657 vr->set_varying ();
1659 else
1660 vr->set_varying ();
1662 return;
1665 /* For integer ranges, apply the operation to each end of the
1666 range and see what we end up with. */
1667 if (code == PLUS_EXPR || code == MINUS_EXPR)
1669 /* This will normalize things such that calculating
1670 [0,0] - VR_VARYING is not dropped to varying, but is
1671 calculated as [MIN+1, MAX]. */
1672 if (vr0.varying_p ())
1673 vr0.update (VR_RANGE,
1674 vrp_val_min (expr_type),
1675 vrp_val_max (expr_type));
1676 if (vr1.varying_p ())
1677 vr1.update (VR_RANGE,
1678 vrp_val_min (expr_type),
1679 vrp_val_max (expr_type));
1681 const bool minus_p = (code == MINUS_EXPR);
1682 tree min_op0 = vr0.min ();
1683 tree min_op1 = minus_p ? vr1.max () : vr1.min ();
1684 tree max_op0 = vr0.max ();
1685 tree max_op1 = minus_p ? vr1.min () : vr1.max ();
1686 tree sym_min_op0 = NULL_TREE;
1687 tree sym_min_op1 = NULL_TREE;
1688 tree sym_max_op0 = NULL_TREE;
1689 tree sym_max_op1 = NULL_TREE;
1690 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1692 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1694 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1695 single-symbolic ranges, try to compute the precise resulting range,
1696 but only if we know that this resulting range will also be constant
1697 or single-symbolic. */
1698 if (vr0.kind () == VR_RANGE && vr1.kind () == VR_RANGE
1699 && (TREE_CODE (min_op0) == INTEGER_CST
1700 || (sym_min_op0
1701 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1702 && (TREE_CODE (min_op1) == INTEGER_CST
1703 || (sym_min_op1
1704 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1705 && (!(sym_min_op0 && sym_min_op1)
1706 || (sym_min_op0 == sym_min_op1
1707 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1708 && (TREE_CODE (max_op0) == INTEGER_CST
1709 || (sym_max_op0
1710 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1711 && (TREE_CODE (max_op1) == INTEGER_CST
1712 || (sym_max_op1
1713 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1714 && (!(sym_max_op0 && sym_max_op1)
1715 || (sym_max_op0 == sym_max_op1
1716 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1718 wide_int wmin, wmax;
1719 wi::overflow_type min_ovf = wi::OVF_NONE;
1720 wi::overflow_type max_ovf = wi::OVF_NONE;
1722 /* Build the bounds. */
1723 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1724 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1726 /* If we have overflow for the constant part and the resulting
1727 range will be symbolic, drop to VR_VARYING. */
1728 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1729 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1731 vr->set_varying ();
1732 return;
1735 /* Adjust the range for possible overflow. */
1736 min = NULL_TREE;
1737 max = NULL_TREE;
1738 set_value_range_with_overflow (type, min, max, expr_type,
1739 wmin, wmax, min_ovf, max_ovf);
1740 if (type == VR_VARYING)
1742 vr->set_varying ();
1743 return;
1746 /* Build the symbolic bounds if needed. */
1747 adjust_symbolic_bound (min, code, expr_type,
1748 sym_min_op0, sym_min_op1,
1749 neg_min_op0, neg_min_op1);
1750 adjust_symbolic_bound (max, code, expr_type,
1751 sym_max_op0, sym_max_op1,
1752 neg_max_op0, neg_max_op1);
1754 else
1756 /* For other cases, for example if we have a PLUS_EXPR with two
1757 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1758 to compute a precise range for such a case.
1759 ??? General even mixed range kind operations can be expressed
1760 by for example transforming ~[3, 5] + [1, 2] to range-only
1761 operations and a union primitive:
1762 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1763 [-INF+1, 4] U [6, +INF(OVF)]
1764 though usually the union is not exactly representable with
1765 a single range or anti-range as the above is
1766 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1767 but one could use a scheme similar to equivalences for this. */
1768 vr->set_varying ();
1769 return;
1772 else if (code == MIN_EXPR
1773 || code == MAX_EXPR)
1775 wide_int wmin, wmax;
1776 wide_int vr0_min, vr0_max;
1777 wide_int vr1_min, vr1_max;
1778 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1779 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1780 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1781 vr0_min, vr0_max, vr1_min, vr1_max))
1782 vr->update (VR_RANGE, wide_int_to_tree (expr_type, wmin),
1783 wide_int_to_tree (expr_type, wmax));
1784 else
1785 vr->set_varying ();
1786 return;
1788 else if (code == MULT_EXPR)
1790 if (!range_int_cst_p (&vr0)
1791 || !range_int_cst_p (&vr1))
1793 vr->set_varying ();
1794 return;
1796 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1797 return;
1799 else if (code == RSHIFT_EXPR
1800 || code == LSHIFT_EXPR)
1802 if (range_int_cst_p (&vr1)
1803 && !wide_int_range_shift_undefined_p
1804 (TYPE_SIGN (TREE_TYPE (vr1.min ())),
1805 prec,
1806 wi::to_wide (vr1.min ()),
1807 wi::to_wide (vr1.max ())))
1809 if (code == RSHIFT_EXPR)
1811 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1812 useful ranges just from the shift count. E.g.
1813 x >> 63 for signed 64-bit x is always [-1, 0]. */
1814 if (vr0.kind () != VR_RANGE || vr0.symbolic_p ())
1815 vr0.update (VR_RANGE,
1816 vrp_val_min (expr_type),
1817 vrp_val_max (expr_type));
1818 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1819 return;
1821 else if (code == LSHIFT_EXPR
1822 && range_int_cst_p (&vr0))
1824 wide_int res_lb, res_ub;
1825 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1826 wi::to_wide (vr0.min ()),
1827 wi::to_wide (vr0.max ()),
1828 wi::to_wide (vr1.min ()),
1829 wi::to_wide (vr1.max ()),
1830 TYPE_OVERFLOW_UNDEFINED (expr_type)))
1832 min = wide_int_to_tree (expr_type, res_lb);
1833 max = wide_int_to_tree (expr_type, res_ub);
1834 vr->set_and_canonicalize (VR_RANGE, min, max, NULL);
1835 return;
1839 vr->set_varying ();
1840 return;
1842 else if (code == TRUNC_DIV_EXPR
1843 || code == FLOOR_DIV_EXPR
1844 || code == CEIL_DIV_EXPR
1845 || code == EXACT_DIV_EXPR
1846 || code == ROUND_DIV_EXPR)
1848 wide_int dividend_min, dividend_max, divisor_min, divisor_max;
1849 wide_int wmin, wmax, extra_min, extra_max;
1850 bool extra_range_p;
1852 /* Special case explicit division by zero as undefined. */
1853 if (range_is_null (&vr1))
1855 vr->set_undefined ();
1856 return;
1859 /* First, normalize ranges into constants we can handle. Note
1860 that VR_ANTI_RANGE's of constants were already normalized
1861 before arriving here.
1863 NOTE: As a future improvement, we may be able to do better
1864 with mixed symbolic (anti-)ranges like [0, A]. See note in
1865 ranges_from_anti_range. */
1866 extract_range_into_wide_ints (&vr0, sign, prec,
1867 dividend_min, dividend_max);
1868 extract_range_into_wide_ints (&vr1, sign, prec,
1869 divisor_min, divisor_max);
1870 if (!wide_int_range_div (wmin, wmax, code, sign, prec,
1871 dividend_min, dividend_max,
1872 divisor_min, divisor_max,
1873 TYPE_OVERFLOW_UNDEFINED (expr_type),
1874 extra_range_p, extra_min, extra_max))
1876 vr->set_undefined ();
1877 return;
1879 set_value_range (vr, VR_RANGE,
1880 wide_int_to_tree (expr_type, wmin),
1881 wide_int_to_tree (expr_type, wmax), NULL);
1882 if (extra_range_p)
1884 value_range extra_range;
1885 set_value_range (&extra_range, VR_RANGE,
1886 wide_int_to_tree (expr_type, extra_min),
1887 wide_int_to_tree (expr_type, extra_max), NULL);
1888 vr->union_ (&extra_range);
1890 return;
1892 else if (code == TRUNC_MOD_EXPR)
1894 if (range_is_null (&vr1))
1896 vr->set_undefined ();
1897 return;
1899 wide_int wmin, wmax, tmp;
1900 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1901 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1902 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1903 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1904 vr0_min, vr0_max, vr1_min, vr1_max);
1905 min = wide_int_to_tree (expr_type, wmin);
1906 max = wide_int_to_tree (expr_type, wmax);
1907 set_value_range (vr, VR_RANGE, min, max, NULL);
1908 return;
1910 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1912 wide_int may_be_nonzero0, may_be_nonzero1;
1913 wide_int must_be_nonzero0, must_be_nonzero1;
1914 wide_int wmin, wmax;
1915 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1916 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1917 &may_be_nonzero0, &must_be_nonzero0);
1918 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1919 &may_be_nonzero1, &must_be_nonzero1);
1920 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1921 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1922 if (code == BIT_AND_EXPR)
1924 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1925 vr0_min, vr0_max,
1926 vr1_min, vr1_max,
1927 must_be_nonzero0,
1928 may_be_nonzero0,
1929 must_be_nonzero1,
1930 may_be_nonzero1))
1932 min = wide_int_to_tree (expr_type, wmin);
1933 max = wide_int_to_tree (expr_type, wmax);
1934 set_value_range (vr, VR_RANGE, min, max, NULL);
1936 else
1937 vr->set_varying ();
1938 return;
1940 else if (code == BIT_IOR_EXPR)
1942 if (wide_int_range_bit_ior (wmin, wmax, sign,
1943 vr0_min, vr0_max,
1944 vr1_min, vr1_max,
1945 must_be_nonzero0,
1946 may_be_nonzero0,
1947 must_be_nonzero1,
1948 may_be_nonzero1))
1950 min = wide_int_to_tree (expr_type, wmin);
1951 max = wide_int_to_tree (expr_type, wmax);
1952 set_value_range (vr, VR_RANGE, min, max, NULL);
1954 else
1955 vr->set_varying ();
1956 return;
1958 else if (code == BIT_XOR_EXPR)
1960 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1961 must_be_nonzero0,
1962 may_be_nonzero0,
1963 must_be_nonzero1,
1964 may_be_nonzero1))
1966 min = wide_int_to_tree (expr_type, wmin);
1967 max = wide_int_to_tree (expr_type, wmax);
1968 set_value_range (vr, VR_RANGE, min, max, NULL);
1970 else
1971 vr->set_varying ();
1972 return;
1975 else
1976 gcc_unreachable ();
1978 /* If either MIN or MAX overflowed, then set the resulting range to
1979 VARYING. */
1980 if (min == NULL_TREE
1981 || TREE_OVERFLOW_P (min)
1982 || max == NULL_TREE
1983 || TREE_OVERFLOW_P (max))
1985 vr->set_varying ();
1986 return;
1989 /* We punt for [-INF, +INF].
1990 We learn nothing when we have INF on both sides.
1991 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1992 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1994 vr->set_varying ();
1995 return;
1998 cmp = compare_values (min, max);
1999 if (cmp == -2 || cmp == 1)
2001 /* If the new range has its limits swapped around (MIN > MAX),
2002 then the operation caused one of them to wrap around, mark
2003 the new range VARYING. */
2004 vr->set_varying ();
2006 else
2007 set_value_range (vr, type, min, max, NULL);
2010 /* Extract range information from a unary operation CODE based on
2011 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2012 The resulting range is stored in *VR. */
2014 void
2015 extract_range_from_unary_expr (value_range *vr,
2016 enum tree_code code, tree type,
2017 const value_range *vr0_, tree op0_type)
2019 signop sign = TYPE_SIGN (type);
2020 unsigned int prec = TYPE_PRECISION (type);
2021 value_range vr0 = *vr0_;
2022 value_range vrtem0, vrtem1;
2024 /* VRP only operates on integral and pointer types. */
2025 if (!(INTEGRAL_TYPE_P (op0_type)
2026 || POINTER_TYPE_P (op0_type))
2027 || !(INTEGRAL_TYPE_P (type)
2028 || POINTER_TYPE_P (type)))
2030 vr->set_varying ();
2031 return;
2034 /* If VR0 is UNDEFINED, so is the result. */
2035 if (vr0.undefined_p ())
2037 vr->set_undefined ();
2038 return;
2041 /* Handle operations that we express in terms of others. */
2042 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2044 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2045 vr->deep_copy (&vr0);
2046 return;
2048 else if (code == NEGATE_EXPR)
2050 /* -X is simply 0 - X, so re-use existing code that also handles
2051 anti-ranges fine. */
2052 value_range zero;
2053 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2054 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2055 return;
2057 else if (code == BIT_NOT_EXPR)
2059 /* ~X is simply -1 - X, so re-use existing code that also handles
2060 anti-ranges fine. */
2061 value_range minusone;
2062 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2063 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2064 type, &minusone, &vr0);
2065 return;
2068 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2069 and express op ~[] as (op []') U (op []''). */
2070 if (vr0.kind () == VR_ANTI_RANGE
2071 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2073 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2074 if (!vrtem1.undefined_p ())
2076 value_range vrres;
2077 extract_range_from_unary_expr (&vrres, code, type,
2078 &vrtem1, op0_type);
2079 vr->union_ (&vrres);
2081 return;
2084 if (CONVERT_EXPR_CODE_P (code))
2086 tree inner_type = op0_type;
2087 tree outer_type = type;
2089 /* If the expression involves a pointer, we are only interested in
2090 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).
2092 This may lose precision when converting (char *)~[0,2] to
2093 int, because we'll forget that the pointer can also not be 1
2094 or 2. In practice we don't care, as this is some idiot
2095 storing a magic constant to a pointer. */
2096 if (POINTER_TYPE_P (type) || POINTER_TYPE_P (op0_type))
2098 if (!range_includes_zero_p (&vr0))
2099 set_value_range_to_nonnull (vr, type);
2100 else if (range_is_null (&vr0))
2101 set_value_range_to_null (vr, type);
2102 else
2103 vr->set_varying ();
2104 return;
2107 /* The POINTER_TYPE_P code above will have dealt with all
2108 pointer anti-ranges. Any remaining anti-ranges at this point
2109 will be integer conversions from SSA names that will be
2110 normalized into VARYING. For instance: ~[x_55, x_55]. */
2111 gcc_assert (vr0.kind () != VR_ANTI_RANGE
2112 || TREE_CODE (vr0.min ()) != INTEGER_CST);
2114 /* NOTES: Previously we were returning VARYING for all symbolics, but
2115 we can do better by treating them as [-MIN, +MAX]. For
2116 example, converting [SYM, SYM] from INT to LONG UNSIGNED,
2117 we can return: ~[0x8000000, 0xffffffff7fffffff].
2119 We were also failing to convert ~[0,0] from char* to unsigned,
2120 instead choosing to return VR_VARYING. Now we return ~[0,0]. */
2121 wide_int vr0_min, vr0_max, wmin, wmax;
2122 signop inner_sign = TYPE_SIGN (inner_type);
2123 signop outer_sign = TYPE_SIGN (outer_type);
2124 unsigned inner_prec = TYPE_PRECISION (inner_type);
2125 unsigned outer_prec = TYPE_PRECISION (outer_type);
2126 extract_range_into_wide_ints (&vr0, inner_sign, inner_prec,
2127 vr0_min, vr0_max);
2128 if (wide_int_range_convert (wmin, wmax,
2129 inner_sign, inner_prec,
2130 outer_sign, outer_prec,
2131 vr0_min, vr0_max))
2133 tree min = wide_int_to_tree (outer_type, wmin);
2134 tree max = wide_int_to_tree (outer_type, wmax);
2135 vr->set_and_canonicalize (VR_RANGE, min, max, NULL);
2137 else
2138 vr->set_varying ();
2139 return;
2141 else if (code == ABS_EXPR)
2143 wide_int wmin, wmax;
2144 wide_int vr0_min, vr0_max;
2145 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
2146 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
2147 TYPE_OVERFLOW_UNDEFINED (type)))
2148 set_value_range (vr, VR_RANGE,
2149 wide_int_to_tree (type, wmin),
2150 wide_int_to_tree (type, wmax), NULL);
2151 else
2152 vr->set_varying ();
2153 return;
2156 /* For unhandled operations fall back to varying. */
2157 vr->set_varying ();
2158 return;
2161 /* Debugging dumps. */
2163 void
2164 dump_value_range (FILE *file, const value_range *vr)
2166 if (!vr)
2167 fprintf (file, "[]");
2168 else
2169 vr->dump (file);
2172 void
2173 dump_value_range (FILE *file, const value_range_base *vr)
2175 if (!vr)
2176 fprintf (file, "[]");
2177 else
2178 vr->dump (file);
2181 /* Dump value range VR to stderr. */
2183 DEBUG_FUNCTION void
2184 debug_value_range (const value_range_base *vr)
2186 dump_value_range (stderr, vr);
2189 /* Dump value range VR to stderr. */
2191 DEBUG_FUNCTION void
2192 debug_value_range (const value_range *vr)
2194 dump_value_range (stderr, vr);
2198 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2199 create a new SSA name N and return the assertion assignment
2200 'N = ASSERT_EXPR <V, V OP W>'. */
2202 static gimple *
2203 build_assert_expr_for (tree cond, tree v)
2205 tree a;
2206 gassign *assertion;
2208 gcc_assert (TREE_CODE (v) == SSA_NAME
2209 && COMPARISON_CLASS_P (cond));
2211 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2212 assertion = gimple_build_assign (NULL_TREE, a);
2214 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2215 operand of the ASSERT_EXPR. Create it so the new name and the old one
2216 are registered in the replacement table so that we can fix the SSA web
2217 after adding all the ASSERT_EXPRs. */
2218 tree new_def = create_new_def_for (v, assertion, NULL);
2219 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2220 given we have to be able to fully propagate those out to re-create
2221 valid SSA when removing the asserts. */
2222 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2223 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2225 return assertion;
2229 /* Return false if EXPR is a predicate expression involving floating
2230 point values. */
2232 static inline bool
2233 fp_predicate (gimple *stmt)
2235 GIMPLE_CHECK (stmt, GIMPLE_COND);
2237 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2240 /* If the range of values taken by OP can be inferred after STMT executes,
2241 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2242 describes the inferred range. Return true if a range could be
2243 inferred. */
2245 bool
2246 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2248 *val_p = NULL_TREE;
2249 *comp_code_p = ERROR_MARK;
2251 /* Do not attempt to infer anything in names that flow through
2252 abnormal edges. */
2253 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2254 return false;
2256 /* If STMT is the last statement of a basic block with no normal
2257 successors, there is no point inferring anything about any of its
2258 operands. We would not be able to find a proper insertion point
2259 for the assertion, anyway. */
2260 if (stmt_ends_bb_p (stmt))
2262 edge_iterator ei;
2263 edge e;
2265 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2266 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2267 break;
2268 if (e == NULL)
2269 return false;
2272 if (infer_nonnull_range (stmt, op))
2274 *val_p = build_int_cst (TREE_TYPE (op), 0);
2275 *comp_code_p = NE_EXPR;
2276 return true;
2279 return false;
2283 void dump_asserts_for (FILE *, tree);
2284 void debug_asserts_for (tree);
2285 void dump_all_asserts (FILE *);
2286 void debug_all_asserts (void);
2288 /* Dump all the registered assertions for NAME to FILE. */
2290 void
2291 dump_asserts_for (FILE *file, tree name)
2293 assert_locus *loc;
2295 fprintf (file, "Assertions to be inserted for ");
2296 print_generic_expr (file, name);
2297 fprintf (file, "\n");
2299 loc = asserts_for[SSA_NAME_VERSION (name)];
2300 while (loc)
2302 fprintf (file, "\t");
2303 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2304 fprintf (file, "\n\tBB #%d", loc->bb->index);
2305 if (loc->e)
2307 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2308 loc->e->dest->index);
2309 dump_edge_info (file, loc->e, dump_flags, 0);
2311 fprintf (file, "\n\tPREDICATE: ");
2312 print_generic_expr (file, loc->expr);
2313 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2314 print_generic_expr (file, loc->val);
2315 fprintf (file, "\n\n");
2316 loc = loc->next;
2319 fprintf (file, "\n");
2323 /* Dump all the registered assertions for NAME to stderr. */
2325 DEBUG_FUNCTION void
2326 debug_asserts_for (tree name)
2328 dump_asserts_for (stderr, name);
2332 /* Dump all the registered assertions for all the names to FILE. */
2334 void
2335 dump_all_asserts (FILE *file)
2337 unsigned i;
2338 bitmap_iterator bi;
2340 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2341 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2342 dump_asserts_for (file, ssa_name (i));
2343 fprintf (file, "\n");
2347 /* Dump all the registered assertions for all the names to stderr. */
2349 DEBUG_FUNCTION void
2350 debug_all_asserts (void)
2352 dump_all_asserts (stderr);
2355 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2357 static void
2358 add_assert_info (vec<assert_info> &asserts,
2359 tree name, tree expr, enum tree_code comp_code, tree val)
2361 assert_info info;
2362 info.comp_code = comp_code;
2363 info.name = name;
2364 if (TREE_OVERFLOW_P (val))
2365 val = drop_tree_overflow (val);
2366 info.val = val;
2367 info.expr = expr;
2368 asserts.safe_push (info);
2369 if (dump_enabled_p ())
2370 dump_printf (MSG_NOTE | MSG_PRIORITY_INTERNALS,
2371 "Adding assert for %T from %T %s %T\n",
2372 name, expr, op_symbol_code (comp_code), val);
2375 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2376 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2377 E->DEST, then register this location as a possible insertion point
2378 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2380 BB, E and SI provide the exact insertion point for the new
2381 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2382 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2383 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2384 must not be NULL. */
2386 static void
2387 register_new_assert_for (tree name, tree expr,
2388 enum tree_code comp_code,
2389 tree val,
2390 basic_block bb,
2391 edge e,
2392 gimple_stmt_iterator si)
2394 assert_locus *n, *loc, *last_loc;
2395 basic_block dest_bb;
2397 gcc_checking_assert (bb == NULL || e == NULL);
2399 if (e == NULL)
2400 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2401 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2403 /* Never build an assert comparing against an integer constant with
2404 TREE_OVERFLOW set. This confuses our undefined overflow warning
2405 machinery. */
2406 if (TREE_OVERFLOW_P (val))
2407 val = drop_tree_overflow (val);
2409 /* The new assertion A will be inserted at BB or E. We need to
2410 determine if the new location is dominated by a previously
2411 registered location for A. If we are doing an edge insertion,
2412 assume that A will be inserted at E->DEST. Note that this is not
2413 necessarily true.
2415 If E is a critical edge, it will be split. But even if E is
2416 split, the new block will dominate the same set of blocks that
2417 E->DEST dominates.
2419 The reverse, however, is not true, blocks dominated by E->DEST
2420 will not be dominated by the new block created to split E. So,
2421 if the insertion location is on a critical edge, we will not use
2422 the new location to move another assertion previously registered
2423 at a block dominated by E->DEST. */
2424 dest_bb = (bb) ? bb : e->dest;
2426 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2427 VAL at a block dominating DEST_BB, then we don't need to insert a new
2428 one. Similarly, if the same assertion already exists at a block
2429 dominated by DEST_BB and the new location is not on a critical
2430 edge, then update the existing location for the assertion (i.e.,
2431 move the assertion up in the dominance tree).
2433 Note, this is implemented as a simple linked list because there
2434 should not be more than a handful of assertions registered per
2435 name. If this becomes a performance problem, a table hashed by
2436 COMP_CODE and VAL could be implemented. */
2437 loc = asserts_for[SSA_NAME_VERSION (name)];
2438 last_loc = loc;
2439 while (loc)
2441 if (loc->comp_code == comp_code
2442 && (loc->val == val
2443 || operand_equal_p (loc->val, val, 0))
2444 && (loc->expr == expr
2445 || operand_equal_p (loc->expr, expr, 0)))
2447 /* If E is not a critical edge and DEST_BB
2448 dominates the existing location for the assertion, move
2449 the assertion up in the dominance tree by updating its
2450 location information. */
2451 if ((e == NULL || !EDGE_CRITICAL_P (e))
2452 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2454 loc->bb = dest_bb;
2455 loc->e = e;
2456 loc->si = si;
2457 return;
2461 /* Update the last node of the list and move to the next one. */
2462 last_loc = loc;
2463 loc = loc->next;
2466 /* If we didn't find an assertion already registered for
2467 NAME COMP_CODE VAL, add a new one at the end of the list of
2468 assertions associated with NAME. */
2469 n = XNEW (struct assert_locus);
2470 n->bb = dest_bb;
2471 n->e = e;
2472 n->si = si;
2473 n->comp_code = comp_code;
2474 n->val = val;
2475 n->expr = expr;
2476 n->next = NULL;
2478 if (last_loc)
2479 last_loc->next = n;
2480 else
2481 asserts_for[SSA_NAME_VERSION (name)] = n;
2483 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2486 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2487 Extract a suitable test code and value and store them into *CODE_P and
2488 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2490 If no extraction was possible, return FALSE, otherwise return TRUE.
2492 If INVERT is true, then we invert the result stored into *CODE_P. */
2494 static bool
2495 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2496 tree cond_op0, tree cond_op1,
2497 bool invert, enum tree_code *code_p,
2498 tree *val_p)
2500 enum tree_code comp_code;
2501 tree val;
2503 /* Otherwise, we have a comparison of the form NAME COMP VAL
2504 or VAL COMP NAME. */
2505 if (name == cond_op1)
2507 /* If the predicate is of the form VAL COMP NAME, flip
2508 COMP around because we need to register NAME as the
2509 first operand in the predicate. */
2510 comp_code = swap_tree_comparison (cond_code);
2511 val = cond_op0;
2513 else if (name == cond_op0)
2515 /* The comparison is of the form NAME COMP VAL, so the
2516 comparison code remains unchanged. */
2517 comp_code = cond_code;
2518 val = cond_op1;
2520 else
2521 gcc_unreachable ();
2523 /* Invert the comparison code as necessary. */
2524 if (invert)
2525 comp_code = invert_tree_comparison (comp_code, 0);
2527 /* VRP only handles integral and pointer types. */
2528 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2529 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2530 return false;
2532 /* Do not register always-false predicates.
2533 FIXME: this works around a limitation in fold() when dealing with
2534 enumerations. Given 'enum { N1, N2 } x;', fold will not
2535 fold 'if (x > N2)' to 'if (0)'. */
2536 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2537 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2539 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2540 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2542 if (comp_code == GT_EXPR
2543 && (!max
2544 || compare_values (val, max) == 0))
2545 return false;
2547 if (comp_code == LT_EXPR
2548 && (!min
2549 || compare_values (val, min) == 0))
2550 return false;
2552 *code_p = comp_code;
2553 *val_p = val;
2554 return true;
2557 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2558 (otherwise return VAL). VAL and MASK must be zero-extended for
2559 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2560 (to transform signed values into unsigned) and at the end xor
2561 SGNBIT back. */
2563 static wide_int
2564 masked_increment (const wide_int &val_in, const wide_int &mask,
2565 const wide_int &sgnbit, unsigned int prec)
2567 wide_int bit = wi::one (prec), res;
2568 unsigned int i;
2570 wide_int val = val_in ^ sgnbit;
2571 for (i = 0; i < prec; i++, bit += bit)
2573 res = mask;
2574 if ((res & bit) == 0)
2575 continue;
2576 res = bit - 1;
2577 res = wi::bit_and_not (val + bit, res);
2578 res &= mask;
2579 if (wi::gtu_p (res, val))
2580 return res ^ sgnbit;
2582 return val ^ sgnbit;
2585 /* Helper for overflow_comparison_p
2587 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2588 OP1's defining statement to see if it ultimately has the form
2589 OP0 CODE (OP0 PLUS INTEGER_CST)
2591 If so, return TRUE indicating this is an overflow test and store into
2592 *NEW_CST an updated constant that can be used in a narrowed range test.
2594 REVERSED indicates if the comparison was originally:
2596 OP1 CODE' OP0.
2598 This affects how we build the updated constant. */
2600 static bool
2601 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2602 bool follow_assert_exprs, bool reversed, tree *new_cst)
2604 /* See if this is a relational operation between two SSA_NAMES with
2605 unsigned, overflow wrapping values. If so, check it more deeply. */
2606 if ((code == LT_EXPR || code == LE_EXPR
2607 || code == GE_EXPR || code == GT_EXPR)
2608 && TREE_CODE (op0) == SSA_NAME
2609 && TREE_CODE (op1) == SSA_NAME
2610 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2611 && TYPE_UNSIGNED (TREE_TYPE (op0))
2612 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2614 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2616 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2617 if (follow_assert_exprs)
2619 while (gimple_assign_single_p (op1_def)
2620 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2622 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2623 if (TREE_CODE (op1) != SSA_NAME)
2624 break;
2625 op1_def = SSA_NAME_DEF_STMT (op1);
2629 /* Now look at the defining statement of OP1 to see if it adds
2630 or subtracts a nonzero constant from another operand. */
2631 if (op1_def
2632 && is_gimple_assign (op1_def)
2633 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2634 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2635 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2637 tree target = gimple_assign_rhs1 (op1_def);
2639 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2640 for one where TARGET appears on the RHS. */
2641 if (follow_assert_exprs)
2643 /* Now see if that "other operand" is op0, following the chain
2644 of ASSERT_EXPRs if necessary. */
2645 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2646 while (op0 != target
2647 && gimple_assign_single_p (op0_def)
2648 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2650 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2651 if (TREE_CODE (op0) != SSA_NAME)
2652 break;
2653 op0_def = SSA_NAME_DEF_STMT (op0);
2657 /* If we did not find our target SSA_NAME, then this is not
2658 an overflow test. */
2659 if (op0 != target)
2660 return false;
2662 tree type = TREE_TYPE (op0);
2663 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2664 tree inc = gimple_assign_rhs2 (op1_def);
2665 if (reversed)
2666 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2667 else
2668 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2669 return true;
2672 return false;
2675 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2676 OP1's defining statement to see if it ultimately has the form
2677 OP0 CODE (OP0 PLUS INTEGER_CST)
2679 If so, return TRUE indicating this is an overflow test and store into
2680 *NEW_CST an updated constant that can be used in a narrowed range test.
2682 These statements are left as-is in the IL to facilitate discovery of
2683 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2684 the alternate range representation is often useful within VRP. */
2686 bool
2687 overflow_comparison_p (tree_code code, tree name, tree val,
2688 bool use_equiv_p, tree *new_cst)
2690 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2691 return true;
2692 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2693 use_equiv_p, true, new_cst);
2697 /* Try to register an edge assertion for SSA name NAME on edge E for
2698 the condition COND contributing to the conditional jump pointed to by BSI.
2699 Invert the condition COND if INVERT is true. */
2701 static void
2702 register_edge_assert_for_2 (tree name, edge e,
2703 enum tree_code cond_code,
2704 tree cond_op0, tree cond_op1, bool invert,
2705 vec<assert_info> &asserts)
2707 tree val;
2708 enum tree_code comp_code;
2710 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2711 cond_op0,
2712 cond_op1,
2713 invert, &comp_code, &val))
2714 return;
2716 /* Queue the assert. */
2717 tree x;
2718 if (overflow_comparison_p (comp_code, name, val, false, &x))
2720 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2721 ? GT_EXPR : LE_EXPR);
2722 add_assert_info (asserts, name, name, new_code, x);
2724 add_assert_info (asserts, name, name, comp_code, val);
2726 /* In the case of NAME <= CST and NAME being defined as
2727 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2728 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2729 This catches range and anti-range tests. */
2730 if ((comp_code == LE_EXPR
2731 || comp_code == GT_EXPR)
2732 && TREE_CODE (val) == INTEGER_CST
2733 && TYPE_UNSIGNED (TREE_TYPE (val)))
2735 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2736 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2738 /* Extract CST2 from the (optional) addition. */
2739 if (is_gimple_assign (def_stmt)
2740 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2742 name2 = gimple_assign_rhs1 (def_stmt);
2743 cst2 = gimple_assign_rhs2 (def_stmt);
2744 if (TREE_CODE (name2) == SSA_NAME
2745 && TREE_CODE (cst2) == INTEGER_CST)
2746 def_stmt = SSA_NAME_DEF_STMT (name2);
2749 /* Extract NAME2 from the (optional) sign-changing cast. */
2750 if (gimple_assign_cast_p (def_stmt))
2752 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2753 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2754 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2755 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2756 name3 = gimple_assign_rhs1 (def_stmt);
2759 /* If name3 is used later, create an ASSERT_EXPR for it. */
2760 if (name3 != NULL_TREE
2761 && TREE_CODE (name3) == SSA_NAME
2762 && (cst2 == NULL_TREE
2763 || TREE_CODE (cst2) == INTEGER_CST)
2764 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2766 tree tmp;
2768 /* Build an expression for the range test. */
2769 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2770 if (cst2 != NULL_TREE)
2771 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2772 add_assert_info (asserts, name3, tmp, comp_code, val);
2775 /* If name2 is used later, create an ASSERT_EXPR for it. */
2776 if (name2 != NULL_TREE
2777 && TREE_CODE (name2) == SSA_NAME
2778 && TREE_CODE (cst2) == INTEGER_CST
2779 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2781 tree tmp;
2783 /* Build an expression for the range test. */
2784 tmp = name2;
2785 if (TREE_TYPE (name) != TREE_TYPE (name2))
2786 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2787 if (cst2 != NULL_TREE)
2788 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2789 add_assert_info (asserts, name2, tmp, comp_code, val);
2793 /* In the case of post-in/decrement tests like if (i++) ... and uses
2794 of the in/decremented value on the edge the extra name we want to
2795 assert for is not on the def chain of the name compared. Instead
2796 it is in the set of use stmts.
2797 Similar cases happen for conversions that were simplified through
2798 fold_{sign_changed,widened}_comparison. */
2799 if ((comp_code == NE_EXPR
2800 || comp_code == EQ_EXPR)
2801 && TREE_CODE (val) == INTEGER_CST)
2803 imm_use_iterator ui;
2804 gimple *use_stmt;
2805 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2807 if (!is_gimple_assign (use_stmt))
2808 continue;
2810 /* Cut off to use-stmts that are dominating the predecessor. */
2811 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2812 continue;
2814 tree name2 = gimple_assign_lhs (use_stmt);
2815 if (TREE_CODE (name2) != SSA_NAME)
2816 continue;
2818 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2819 tree cst;
2820 if (code == PLUS_EXPR
2821 || code == MINUS_EXPR)
2823 cst = gimple_assign_rhs2 (use_stmt);
2824 if (TREE_CODE (cst) != INTEGER_CST)
2825 continue;
2826 cst = int_const_binop (code, val, cst);
2828 else if (CONVERT_EXPR_CODE_P (code))
2830 /* For truncating conversions we cannot record
2831 an inequality. */
2832 if (comp_code == NE_EXPR
2833 && (TYPE_PRECISION (TREE_TYPE (name2))
2834 < TYPE_PRECISION (TREE_TYPE (name))))
2835 continue;
2836 cst = fold_convert (TREE_TYPE (name2), val);
2838 else
2839 continue;
2841 if (TREE_OVERFLOW_P (cst))
2842 cst = drop_tree_overflow (cst);
2843 add_assert_info (asserts, name2, name2, comp_code, cst);
2847 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2848 && TREE_CODE (val) == INTEGER_CST)
2850 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2851 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2852 tree val2 = NULL_TREE;
2853 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2854 wide_int mask = wi::zero (prec);
2855 unsigned int nprec = prec;
2856 enum tree_code rhs_code = ERROR_MARK;
2858 if (is_gimple_assign (def_stmt))
2859 rhs_code = gimple_assign_rhs_code (def_stmt);
2861 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2862 assert that A != CST1 -+ CST2. */
2863 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2864 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2866 tree op0 = gimple_assign_rhs1 (def_stmt);
2867 tree op1 = gimple_assign_rhs2 (def_stmt);
2868 if (TREE_CODE (op0) == SSA_NAME
2869 && TREE_CODE (op1) == INTEGER_CST)
2871 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2872 ? MINUS_EXPR : PLUS_EXPR);
2873 op1 = int_const_binop (reverse_op, val, op1);
2874 if (TREE_OVERFLOW (op1))
2875 op1 = drop_tree_overflow (op1);
2876 add_assert_info (asserts, op0, op0, comp_code, op1);
2880 /* Add asserts for NAME cmp CST and NAME being defined
2881 as NAME = (int) NAME2. */
2882 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2883 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2884 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2885 && gimple_assign_cast_p (def_stmt))
2887 name2 = gimple_assign_rhs1 (def_stmt);
2888 if (CONVERT_EXPR_CODE_P (rhs_code)
2889 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2890 && TYPE_UNSIGNED (TREE_TYPE (name2))
2891 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2892 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2893 || !tree_int_cst_equal (val,
2894 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2896 tree tmp, cst;
2897 enum tree_code new_comp_code = comp_code;
2899 cst = fold_convert (TREE_TYPE (name2),
2900 TYPE_MIN_VALUE (TREE_TYPE (val)));
2901 /* Build an expression for the range test. */
2902 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2903 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2904 fold_convert (TREE_TYPE (name2), val));
2905 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2907 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2908 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2909 build_int_cst (TREE_TYPE (name2), 1));
2911 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2915 /* Add asserts for NAME cmp CST and NAME being defined as
2916 NAME = NAME2 >> CST2.
2918 Extract CST2 from the right shift. */
2919 if (rhs_code == RSHIFT_EXPR)
2921 name2 = gimple_assign_rhs1 (def_stmt);
2922 cst2 = gimple_assign_rhs2 (def_stmt);
2923 if (TREE_CODE (name2) == SSA_NAME
2924 && tree_fits_uhwi_p (cst2)
2925 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2926 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2927 && type_has_mode_precision_p (TREE_TYPE (val)))
2929 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2930 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2933 if (val2 != NULL_TREE
2934 && TREE_CODE (val2) == INTEGER_CST
2935 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2936 TREE_TYPE (val),
2937 val2, cst2), val))
2939 enum tree_code new_comp_code = comp_code;
2940 tree tmp, new_val;
2942 tmp = name2;
2943 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2945 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2947 tree type = build_nonstandard_integer_type (prec, 1);
2948 tmp = build1 (NOP_EXPR, type, name2);
2949 val2 = fold_convert (type, val2);
2951 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2952 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2953 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2955 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2957 wide_int minval
2958 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2959 new_val = val2;
2960 if (minval == wi::to_wide (new_val))
2961 new_val = NULL_TREE;
2963 else
2965 wide_int maxval
2966 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2967 mask |= wi::to_wide (val2);
2968 if (wi::eq_p (mask, maxval))
2969 new_val = NULL_TREE;
2970 else
2971 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2974 if (new_val)
2975 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2978 /* Add asserts for NAME cmp CST and NAME being defined as
2979 NAME = NAME2 & CST2.
2981 Extract CST2 from the and.
2983 Also handle
2984 NAME = (unsigned) NAME2;
2985 casts where NAME's type is unsigned and has smaller precision
2986 than NAME2's type as if it was NAME = NAME2 & MASK. */
2987 names[0] = NULL_TREE;
2988 names[1] = NULL_TREE;
2989 cst2 = NULL_TREE;
2990 if (rhs_code == BIT_AND_EXPR
2991 || (CONVERT_EXPR_CODE_P (rhs_code)
2992 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2993 && TYPE_UNSIGNED (TREE_TYPE (val))
2994 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2995 > prec))
2997 name2 = gimple_assign_rhs1 (def_stmt);
2998 if (rhs_code == BIT_AND_EXPR)
2999 cst2 = gimple_assign_rhs2 (def_stmt);
3000 else
3002 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3003 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3005 if (TREE_CODE (name2) == SSA_NAME
3006 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3007 && TREE_CODE (cst2) == INTEGER_CST
3008 && !integer_zerop (cst2)
3009 && (nprec > 1
3010 || TYPE_UNSIGNED (TREE_TYPE (val))))
3012 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3013 if (gimple_assign_cast_p (def_stmt2))
3015 names[1] = gimple_assign_rhs1 (def_stmt2);
3016 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3017 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3018 || (TYPE_PRECISION (TREE_TYPE (name2))
3019 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3020 names[1] = NULL_TREE;
3022 names[0] = name2;
3025 if (names[0] || names[1])
3027 wide_int minv, maxv, valv, cst2v;
3028 wide_int tem, sgnbit;
3029 bool valid_p = false, valn, cst2n;
3030 enum tree_code ccode = comp_code;
3032 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3033 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3034 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3035 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3036 /* If CST2 doesn't have most significant bit set,
3037 but VAL is negative, we have comparison like
3038 if ((x & 0x123) > -4) (always true). Just give up. */
3039 if (!cst2n && valn)
3040 ccode = ERROR_MARK;
3041 if (cst2n)
3042 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3043 else
3044 sgnbit = wi::zero (nprec);
3045 minv = valv & cst2v;
3046 switch (ccode)
3048 case EQ_EXPR:
3049 /* Minimum unsigned value for equality is VAL & CST2
3050 (should be equal to VAL, otherwise we probably should
3051 have folded the comparison into false) and
3052 maximum unsigned value is VAL | ~CST2. */
3053 maxv = valv | ~cst2v;
3054 valid_p = true;
3055 break;
3057 case NE_EXPR:
3058 tem = valv | ~cst2v;
3059 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3060 if (valv == 0)
3062 cst2n = false;
3063 sgnbit = wi::zero (nprec);
3064 goto gt_expr;
3066 /* If (VAL | ~CST2) is all ones, handle it as
3067 (X & CST2) < VAL. */
3068 if (tem == -1)
3070 cst2n = false;
3071 valn = false;
3072 sgnbit = wi::zero (nprec);
3073 goto lt_expr;
3075 if (!cst2n && wi::neg_p (cst2v))
3076 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3077 if (sgnbit != 0)
3079 if (valv == sgnbit)
3081 cst2n = true;
3082 valn = true;
3083 goto gt_expr;
3085 if (tem == wi::mask (nprec - 1, false, nprec))
3087 cst2n = true;
3088 goto lt_expr;
3090 if (!cst2n)
3091 sgnbit = wi::zero (nprec);
3093 break;
3095 case GE_EXPR:
3096 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3097 is VAL and maximum unsigned value is ~0. For signed
3098 comparison, if CST2 doesn't have most significant bit
3099 set, handle it similarly. If CST2 has MSB set,
3100 the minimum is the same, and maximum is ~0U/2. */
3101 if (minv != valv)
3103 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3104 VAL. */
3105 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3106 if (minv == valv)
3107 break;
3109 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3110 valid_p = true;
3111 break;
3113 case GT_EXPR:
3114 gt_expr:
3115 /* Find out smallest MINV where MINV > VAL
3116 && (MINV & CST2) == MINV, if any. If VAL is signed and
3117 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3118 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3119 if (minv == valv)
3120 break;
3121 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3122 valid_p = true;
3123 break;
3125 case LE_EXPR:
3126 /* Minimum unsigned value for <= is 0 and maximum
3127 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3128 Otherwise, find smallest VAL2 where VAL2 > VAL
3129 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3130 as maximum.
3131 For signed comparison, if CST2 doesn't have most
3132 significant bit set, handle it similarly. If CST2 has
3133 MSB set, the maximum is the same and minimum is INT_MIN. */
3134 if (minv == valv)
3135 maxv = valv;
3136 else
3138 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3139 if (maxv == valv)
3140 break;
3141 maxv -= 1;
3143 maxv |= ~cst2v;
3144 minv = sgnbit;
3145 valid_p = true;
3146 break;
3148 case LT_EXPR:
3149 lt_expr:
3150 /* Minimum unsigned value for < is 0 and maximum
3151 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3152 Otherwise, find smallest VAL2 where VAL2 > VAL
3153 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3154 as maximum.
3155 For signed comparison, if CST2 doesn't have most
3156 significant bit set, handle it similarly. If CST2 has
3157 MSB set, the maximum is the same and minimum is INT_MIN. */
3158 if (minv == valv)
3160 if (valv == sgnbit)
3161 break;
3162 maxv = valv;
3164 else
3166 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3167 if (maxv == valv)
3168 break;
3170 maxv -= 1;
3171 maxv |= ~cst2v;
3172 minv = sgnbit;
3173 valid_p = true;
3174 break;
3176 default:
3177 break;
3179 if (valid_p
3180 && (maxv - minv) != -1)
3182 tree tmp, new_val, type;
3183 int i;
3185 for (i = 0; i < 2; i++)
3186 if (names[i])
3188 wide_int maxv2 = maxv;
3189 tmp = names[i];
3190 type = TREE_TYPE (names[i]);
3191 if (!TYPE_UNSIGNED (type))
3193 type = build_nonstandard_integer_type (nprec, 1);
3194 tmp = build1 (NOP_EXPR, type, names[i]);
3196 if (minv != 0)
3198 tmp = build2 (PLUS_EXPR, type, tmp,
3199 wide_int_to_tree (type, -minv));
3200 maxv2 = maxv - minv;
3202 new_val = wide_int_to_tree (type, maxv2);
3203 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3210 /* OP is an operand of a truth value expression which is known to have
3211 a particular value. Register any asserts for OP and for any
3212 operands in OP's defining statement.
3214 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3215 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3217 static void
3218 register_edge_assert_for_1 (tree op, enum tree_code code,
3219 edge e, vec<assert_info> &asserts)
3221 gimple *op_def;
3222 tree val;
3223 enum tree_code rhs_code;
3225 /* We only care about SSA_NAMEs. */
3226 if (TREE_CODE (op) != SSA_NAME)
3227 return;
3229 /* We know that OP will have a zero or nonzero value. */
3230 val = build_int_cst (TREE_TYPE (op), 0);
3231 add_assert_info (asserts, op, op, code, val);
3233 /* Now look at how OP is set. If it's set from a comparison,
3234 a truth operation or some bit operations, then we may be able
3235 to register information about the operands of that assignment. */
3236 op_def = SSA_NAME_DEF_STMT (op);
3237 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3238 return;
3240 rhs_code = gimple_assign_rhs_code (op_def);
3242 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3244 bool invert = (code == EQ_EXPR ? true : false);
3245 tree op0 = gimple_assign_rhs1 (op_def);
3246 tree op1 = gimple_assign_rhs2 (op_def);
3248 if (TREE_CODE (op0) == SSA_NAME)
3249 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3250 if (TREE_CODE (op1) == SSA_NAME)
3251 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3253 else if ((code == NE_EXPR
3254 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3255 || (code == EQ_EXPR
3256 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3258 /* Recurse on each operand. */
3259 tree op0 = gimple_assign_rhs1 (op_def);
3260 tree op1 = gimple_assign_rhs2 (op_def);
3261 if (TREE_CODE (op0) == SSA_NAME
3262 && has_single_use (op0))
3263 register_edge_assert_for_1 (op0, code, e, asserts);
3264 if (TREE_CODE (op1) == SSA_NAME
3265 && has_single_use (op1))
3266 register_edge_assert_for_1 (op1, code, e, asserts);
3268 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3269 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3271 /* Recurse, flipping CODE. */
3272 code = invert_tree_comparison (code, false);
3273 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3275 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3277 /* Recurse through the copy. */
3278 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3280 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3282 /* Recurse through the type conversion, unless it is a narrowing
3283 conversion or conversion from non-integral type. */
3284 tree rhs = gimple_assign_rhs1 (op_def);
3285 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3286 && (TYPE_PRECISION (TREE_TYPE (rhs))
3287 <= TYPE_PRECISION (TREE_TYPE (op))))
3288 register_edge_assert_for_1 (rhs, code, e, asserts);
3292 /* Check if comparison
3293 NAME COND_OP INTEGER_CST
3294 has a form of
3295 (X & 11...100..0) COND_OP XX...X00...0
3296 Such comparison can yield assertions like
3297 X >= XX...X00...0
3298 X <= XX...X11...1
3299 in case of COND_OP being EQ_EXPR or
3300 X < XX...X00...0
3301 X > XX...X11...1
3302 in case of NE_EXPR. */
3304 static bool
3305 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3306 tree *new_name, tree *low, enum tree_code *low_code,
3307 tree *high, enum tree_code *high_code)
3309 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3311 if (!is_gimple_assign (def_stmt)
3312 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3313 return false;
3315 tree t = gimple_assign_rhs1 (def_stmt);
3316 tree maskt = gimple_assign_rhs2 (def_stmt);
3317 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3318 return false;
3320 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3321 wide_int inv_mask = ~mask;
3322 /* Must have been removed by now so don't bother optimizing. */
3323 if (mask == 0 || inv_mask == 0)
3324 return false;
3326 /* Assume VALT is INTEGER_CST. */
3327 wi::tree_to_wide_ref val = wi::to_wide (valt);
3329 if ((inv_mask & (inv_mask + 1)) != 0
3330 || (val & mask) != val)
3331 return false;
3333 bool is_range = cond_code == EQ_EXPR;
3335 tree type = TREE_TYPE (t);
3336 wide_int min = wi::min_value (type),
3337 max = wi::max_value (type);
3339 if (is_range)
3341 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3342 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3344 else
3346 /* We can still generate assertion if one of alternatives
3347 is known to always be false. */
3348 if (val == min)
3350 *low_code = (enum tree_code) 0;
3351 *high_code = GT_EXPR;
3353 else if ((val | inv_mask) == max)
3355 *low_code = LT_EXPR;
3356 *high_code = (enum tree_code) 0;
3358 else
3359 return false;
3362 *new_name = t;
3363 *low = wide_int_to_tree (type, val);
3364 *high = wide_int_to_tree (type, val | inv_mask);
3366 return true;
3369 /* Try to register an edge assertion for SSA name NAME on edge E for
3370 the condition COND contributing to the conditional jump pointed to by
3371 SI. */
3373 void
3374 register_edge_assert_for (tree name, edge e,
3375 enum tree_code cond_code, tree cond_op0,
3376 tree cond_op1, vec<assert_info> &asserts)
3378 tree val;
3379 enum tree_code comp_code;
3380 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3382 /* Do not attempt to infer anything in names that flow through
3383 abnormal edges. */
3384 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3385 return;
3387 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3388 cond_op0, cond_op1,
3389 is_else_edge,
3390 &comp_code, &val))
3391 return;
3393 /* Register ASSERT_EXPRs for name. */
3394 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3395 cond_op1, is_else_edge, asserts);
3398 /* If COND is effectively an equality test of an SSA_NAME against
3399 the value zero or one, then we may be able to assert values
3400 for SSA_NAMEs which flow into COND. */
3402 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3403 statement of NAME we can assert both operands of the BIT_AND_EXPR
3404 have nonzero value. */
3405 if (((comp_code == EQ_EXPR && integer_onep (val))
3406 || (comp_code == NE_EXPR && integer_zerop (val))))
3408 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3410 if (is_gimple_assign (def_stmt)
3411 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3413 tree op0 = gimple_assign_rhs1 (def_stmt);
3414 tree op1 = gimple_assign_rhs2 (def_stmt);
3415 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3416 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3420 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3421 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3422 have zero value. */
3423 if (((comp_code == EQ_EXPR && integer_zerop (val))
3424 || (comp_code == NE_EXPR && integer_onep (val))))
3426 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3428 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3429 necessarily zero value, or if type-precision is one. */
3430 if (is_gimple_assign (def_stmt)
3431 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3432 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3433 || comp_code == EQ_EXPR)))
3435 tree op0 = gimple_assign_rhs1 (def_stmt);
3436 tree op1 = gimple_assign_rhs2 (def_stmt);
3437 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3438 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3442 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3443 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3444 && TREE_CODE (val) == INTEGER_CST)
3446 enum tree_code low_code, high_code;
3447 tree low, high;
3448 if (is_masked_range_test (name, val, comp_code, &name, &low,
3449 &low_code, &high, &high_code))
3451 if (low_code != ERROR_MARK)
3452 register_edge_assert_for_2 (name, e, low_code, name,
3453 low, /*invert*/false, asserts);
3454 if (high_code != ERROR_MARK)
3455 register_edge_assert_for_2 (name, e, high_code, name,
3456 high, /*invert*/false, asserts);
3461 /* Finish found ASSERTS for E and register them at GSI. */
3463 static void
3464 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3465 vec<assert_info> &asserts)
3467 for (unsigned i = 0; i < asserts.length (); ++i)
3468 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3469 reachable from E. */
3470 if (live_on_edge (e, asserts[i].name))
3471 register_new_assert_for (asserts[i].name, asserts[i].expr,
3472 asserts[i].comp_code, asserts[i].val,
3473 NULL, e, gsi);
3478 /* Determine whether the outgoing edges of BB should receive an
3479 ASSERT_EXPR for each of the operands of BB's LAST statement.
3480 The last statement of BB must be a COND_EXPR.
3482 If any of the sub-graphs rooted at BB have an interesting use of
3483 the predicate operands, an assert location node is added to the
3484 list of assertions for the corresponding operands. */
3486 static void
3487 find_conditional_asserts (basic_block bb, gcond *last)
3489 gimple_stmt_iterator bsi;
3490 tree op;
3491 edge_iterator ei;
3492 edge e;
3493 ssa_op_iter iter;
3495 bsi = gsi_for_stmt (last);
3497 /* Look for uses of the operands in each of the sub-graphs
3498 rooted at BB. We need to check each of the outgoing edges
3499 separately, so that we know what kind of ASSERT_EXPR to
3500 insert. */
3501 FOR_EACH_EDGE (e, ei, bb->succs)
3503 if (e->dest == bb)
3504 continue;
3506 /* Register the necessary assertions for each operand in the
3507 conditional predicate. */
3508 auto_vec<assert_info, 8> asserts;
3509 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3510 register_edge_assert_for (op, e,
3511 gimple_cond_code (last),
3512 gimple_cond_lhs (last),
3513 gimple_cond_rhs (last), asserts);
3514 finish_register_edge_assert_for (e, bsi, asserts);
3518 struct case_info
3520 tree expr;
3521 basic_block bb;
3524 /* Compare two case labels sorting first by the destination bb index
3525 and then by the case value. */
3527 static int
3528 compare_case_labels (const void *p1, const void *p2)
3530 const struct case_info *ci1 = (const struct case_info *) p1;
3531 const struct case_info *ci2 = (const struct case_info *) p2;
3532 int idx1 = ci1->bb->index;
3533 int idx2 = ci2->bb->index;
3535 if (idx1 < idx2)
3536 return -1;
3537 else if (idx1 == idx2)
3539 /* Make sure the default label is first in a group. */
3540 if (!CASE_LOW (ci1->expr))
3541 return -1;
3542 else if (!CASE_LOW (ci2->expr))
3543 return 1;
3544 else
3545 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3546 CASE_LOW (ci2->expr));
3548 else
3549 return 1;
3552 /* Determine whether the outgoing edges of BB should receive an
3553 ASSERT_EXPR for each of the operands of BB's LAST statement.
3554 The last statement of BB must be a SWITCH_EXPR.
3556 If any of the sub-graphs rooted at BB have an interesting use of
3557 the predicate operands, an assert location node is added to the
3558 list of assertions for the corresponding operands. */
3560 static void
3561 find_switch_asserts (basic_block bb, gswitch *last)
3563 gimple_stmt_iterator bsi;
3564 tree op;
3565 edge e;
3566 struct case_info *ci;
3567 size_t n = gimple_switch_num_labels (last);
3568 #if GCC_VERSION >= 4000
3569 unsigned int idx;
3570 #else
3571 /* Work around GCC 3.4 bug (PR 37086). */
3572 volatile unsigned int idx;
3573 #endif
3575 bsi = gsi_for_stmt (last);
3576 op = gimple_switch_index (last);
3577 if (TREE_CODE (op) != SSA_NAME)
3578 return;
3580 /* Build a vector of case labels sorted by destination label. */
3581 ci = XNEWVEC (struct case_info, n);
3582 for (idx = 0; idx < n; ++idx)
3584 ci[idx].expr = gimple_switch_label (last, idx);
3585 ci[idx].bb = label_to_block (cfun, CASE_LABEL (ci[idx].expr));
3587 edge default_edge = find_edge (bb, ci[0].bb);
3588 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3590 for (idx = 0; idx < n; ++idx)
3592 tree min, max;
3593 tree cl = ci[idx].expr;
3594 basic_block cbb = ci[idx].bb;
3596 min = CASE_LOW (cl);
3597 max = CASE_HIGH (cl);
3599 /* If there are multiple case labels with the same destination
3600 we need to combine them to a single value range for the edge. */
3601 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3603 /* Skip labels until the last of the group. */
3604 do {
3605 ++idx;
3606 } while (idx < n && cbb == ci[idx].bb);
3607 --idx;
3609 /* Pick up the maximum of the case label range. */
3610 if (CASE_HIGH (ci[idx].expr))
3611 max = CASE_HIGH (ci[idx].expr);
3612 else
3613 max = CASE_LOW (ci[idx].expr);
3616 /* Can't extract a useful assertion out of a range that includes the
3617 default label. */
3618 if (min == NULL_TREE)
3619 continue;
3621 /* Find the edge to register the assert expr on. */
3622 e = find_edge (bb, cbb);
3624 /* Register the necessary assertions for the operand in the
3625 SWITCH_EXPR. */
3626 auto_vec<assert_info, 8> asserts;
3627 register_edge_assert_for (op, e,
3628 max ? GE_EXPR : EQ_EXPR,
3629 op, fold_convert (TREE_TYPE (op), min),
3630 asserts);
3631 if (max)
3632 register_edge_assert_for (op, e, LE_EXPR, op,
3633 fold_convert (TREE_TYPE (op), max),
3634 asserts);
3635 finish_register_edge_assert_for (e, bsi, asserts);
3638 XDELETEVEC (ci);
3640 if (!live_on_edge (default_edge, op))
3641 return;
3643 /* Now register along the default label assertions that correspond to the
3644 anti-range of each label. */
3645 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3646 if (insertion_limit == 0)
3647 return;
3649 /* We can't do this if the default case shares a label with another case. */
3650 tree default_cl = gimple_switch_default_label (last);
3651 for (idx = 1; idx < n; idx++)
3653 tree min, max;
3654 tree cl = gimple_switch_label (last, idx);
3655 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3656 continue;
3658 min = CASE_LOW (cl);
3659 max = CASE_HIGH (cl);
3661 /* Combine contiguous case ranges to reduce the number of assertions
3662 to insert. */
3663 for (idx = idx + 1; idx < n; idx++)
3665 tree next_min, next_max;
3666 tree next_cl = gimple_switch_label (last, idx);
3667 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3668 break;
3670 next_min = CASE_LOW (next_cl);
3671 next_max = CASE_HIGH (next_cl);
3673 wide_int difference = (wi::to_wide (next_min)
3674 - wi::to_wide (max ? max : min));
3675 if (wi::eq_p (difference, 1))
3676 max = next_max ? next_max : next_min;
3677 else
3678 break;
3680 idx--;
3682 if (max == NULL_TREE)
3684 /* Register the assertion OP != MIN. */
3685 auto_vec<assert_info, 8> asserts;
3686 min = fold_convert (TREE_TYPE (op), min);
3687 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3688 asserts);
3689 finish_register_edge_assert_for (default_edge, bsi, asserts);
3691 else
3693 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3694 which will give OP the anti-range ~[MIN,MAX]. */
3695 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3696 min = fold_convert (TREE_TYPE (uop), min);
3697 max = fold_convert (TREE_TYPE (uop), max);
3699 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3700 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3701 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3702 NULL, default_edge, bsi);
3705 if (--insertion_limit == 0)
3706 break;
3711 /* Traverse all the statements in block BB looking for statements that
3712 may generate useful assertions for the SSA names in their operand.
3713 If a statement produces a useful assertion A for name N_i, then the
3714 list of assertions already generated for N_i is scanned to
3715 determine if A is actually needed.
3717 If N_i already had the assertion A at a location dominating the
3718 current location, then nothing needs to be done. Otherwise, the
3719 new location for A is recorded instead.
3721 1- For every statement S in BB, all the variables used by S are
3722 added to bitmap FOUND_IN_SUBGRAPH.
3724 2- If statement S uses an operand N in a way that exposes a known
3725 value range for N, then if N was not already generated by an
3726 ASSERT_EXPR, create a new assert location for N. For instance,
3727 if N is a pointer and the statement dereferences it, we can
3728 assume that N is not NULL.
3730 3- COND_EXPRs are a special case of #2. We can derive range
3731 information from the predicate but need to insert different
3732 ASSERT_EXPRs for each of the sub-graphs rooted at the
3733 conditional block. If the last statement of BB is a conditional
3734 expression of the form 'X op Y', then
3736 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3738 b) If the conditional is the only entry point to the sub-graph
3739 corresponding to the THEN_CLAUSE, recurse into it. On
3740 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3741 an ASSERT_EXPR is added for the corresponding variable.
3743 c) Repeat step (b) on the ELSE_CLAUSE.
3745 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3747 For instance,
3749 if (a == 9)
3750 b = a;
3751 else
3752 b = c + 1;
3754 In this case, an assertion on the THEN clause is useful to
3755 determine that 'a' is always 9 on that edge. However, an assertion
3756 on the ELSE clause would be unnecessary.
3758 4- If BB does not end in a conditional expression, then we recurse
3759 into BB's dominator children.
3761 At the end of the recursive traversal, every SSA name will have a
3762 list of locations where ASSERT_EXPRs should be added. When a new
3763 location for name N is found, it is registered by calling
3764 register_new_assert_for. That function keeps track of all the
3765 registered assertions to prevent adding unnecessary assertions.
3766 For instance, if a pointer P_4 is dereferenced more than once in a
3767 dominator tree, only the location dominating all the dereference of
3768 P_4 will receive an ASSERT_EXPR. */
3770 static void
3771 find_assert_locations_1 (basic_block bb, sbitmap live)
3773 gimple *last;
3775 last = last_stmt (bb);
3777 /* If BB's last statement is a conditional statement involving integer
3778 operands, determine if we need to add ASSERT_EXPRs. */
3779 if (last
3780 && gimple_code (last) == GIMPLE_COND
3781 && !fp_predicate (last)
3782 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3783 find_conditional_asserts (bb, as_a <gcond *> (last));
3785 /* If BB's last statement is a switch statement involving integer
3786 operands, determine if we need to add ASSERT_EXPRs. */
3787 if (last
3788 && gimple_code (last) == GIMPLE_SWITCH
3789 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3790 find_switch_asserts (bb, as_a <gswitch *> (last));
3792 /* Traverse all the statements in BB marking used names and looking
3793 for statements that may infer assertions for their used operands. */
3794 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3795 gsi_prev (&si))
3797 gimple *stmt;
3798 tree op;
3799 ssa_op_iter i;
3801 stmt = gsi_stmt (si);
3803 if (is_gimple_debug (stmt))
3804 continue;
3806 /* See if we can derive an assertion for any of STMT's operands. */
3807 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3809 tree value;
3810 enum tree_code comp_code;
3812 /* If op is not live beyond this stmt, do not bother to insert
3813 asserts for it. */
3814 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3815 continue;
3817 /* If OP is used in such a way that we can infer a value
3818 range for it, and we don't find a previous assertion for
3819 it, create a new assertion location node for OP. */
3820 if (infer_value_range (stmt, op, &comp_code, &value))
3822 /* If we are able to infer a nonzero value range for OP,
3823 then walk backwards through the use-def chain to see if OP
3824 was set via a typecast.
3826 If so, then we can also infer a nonzero value range
3827 for the operand of the NOP_EXPR. */
3828 if (comp_code == NE_EXPR && integer_zerop (value))
3830 tree t = op;
3831 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3833 while (is_gimple_assign (def_stmt)
3834 && CONVERT_EXPR_CODE_P
3835 (gimple_assign_rhs_code (def_stmt))
3836 && TREE_CODE
3837 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3838 && POINTER_TYPE_P
3839 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3841 t = gimple_assign_rhs1 (def_stmt);
3842 def_stmt = SSA_NAME_DEF_STMT (t);
3844 /* Note we want to register the assert for the
3845 operand of the NOP_EXPR after SI, not after the
3846 conversion. */
3847 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3848 register_new_assert_for (t, t, comp_code, value,
3849 bb, NULL, si);
3853 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3857 /* Update live. */
3858 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3859 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3860 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3861 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3864 /* Traverse all PHI nodes in BB, updating live. */
3865 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3866 gsi_next (&si))
3868 use_operand_p arg_p;
3869 ssa_op_iter i;
3870 gphi *phi = si.phi ();
3871 tree res = gimple_phi_result (phi);
3873 if (virtual_operand_p (res))
3874 continue;
3876 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3878 tree arg = USE_FROM_PTR (arg_p);
3879 if (TREE_CODE (arg) == SSA_NAME)
3880 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3883 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3887 /* Do an RPO walk over the function computing SSA name liveness
3888 on-the-fly and deciding on assert expressions to insert. */
3890 static void
3891 find_assert_locations (void)
3893 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3894 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3895 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3896 int rpo_cnt, i;
3898 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3899 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3900 for (i = 0; i < rpo_cnt; ++i)
3901 bb_rpo[rpo[i]] = i;
3903 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3904 the order we compute liveness and insert asserts we otherwise
3905 fail to insert asserts into the loop latch. */
3906 loop_p loop;
3907 FOR_EACH_LOOP (loop, 0)
3909 i = loop->latch->index;
3910 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3911 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3912 !gsi_end_p (gsi); gsi_next (&gsi))
3914 gphi *phi = gsi.phi ();
3915 if (virtual_operand_p (gimple_phi_result (phi)))
3916 continue;
3917 tree arg = gimple_phi_arg_def (phi, j);
3918 if (TREE_CODE (arg) == SSA_NAME)
3920 if (live[i] == NULL)
3922 live[i] = sbitmap_alloc (num_ssa_names);
3923 bitmap_clear (live[i]);
3925 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3930 for (i = rpo_cnt - 1; i >= 0; --i)
3932 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3933 edge e;
3934 edge_iterator ei;
3936 if (!live[rpo[i]])
3938 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
3939 bitmap_clear (live[rpo[i]]);
3942 /* Process BB and update the live information with uses in
3943 this block. */
3944 find_assert_locations_1 (bb, live[rpo[i]]);
3946 /* Merge liveness into the predecessor blocks and free it. */
3947 if (!bitmap_empty_p (live[rpo[i]]))
3949 int pred_rpo = i;
3950 FOR_EACH_EDGE (e, ei, bb->preds)
3952 int pred = e->src->index;
3953 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3954 continue;
3956 if (!live[pred])
3958 live[pred] = sbitmap_alloc (num_ssa_names);
3959 bitmap_clear (live[pred]);
3961 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
3963 if (bb_rpo[pred] < pred_rpo)
3964 pred_rpo = bb_rpo[pred];
3967 /* Record the RPO number of the last visited block that needs
3968 live information from this block. */
3969 last_rpo[rpo[i]] = pred_rpo;
3971 else
3973 sbitmap_free (live[rpo[i]]);
3974 live[rpo[i]] = NULL;
3977 /* We can free all successors live bitmaps if all their
3978 predecessors have been visited already. */
3979 FOR_EACH_EDGE (e, ei, bb->succs)
3980 if (last_rpo[e->dest->index] == i
3981 && live[e->dest->index])
3983 sbitmap_free (live[e->dest->index]);
3984 live[e->dest->index] = NULL;
3988 XDELETEVEC (rpo);
3989 XDELETEVEC (bb_rpo);
3990 XDELETEVEC (last_rpo);
3991 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
3992 if (live[i])
3993 sbitmap_free (live[i]);
3994 XDELETEVEC (live);
3997 /* Create an ASSERT_EXPR for NAME and insert it in the location
3998 indicated by LOC. Return true if we made any edge insertions. */
4000 static bool
4001 process_assert_insertions_for (tree name, assert_locus *loc)
4003 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4004 gimple *stmt;
4005 tree cond;
4006 gimple *assert_stmt;
4007 edge_iterator ei;
4008 edge e;
4010 /* If we have X <=> X do not insert an assert expr for that. */
4011 if (loc->expr == loc->val)
4012 return false;
4014 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4015 assert_stmt = build_assert_expr_for (cond, name);
4016 if (loc->e)
4018 /* We have been asked to insert the assertion on an edge. This
4019 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4020 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4021 || (gimple_code (gsi_stmt (loc->si))
4022 == GIMPLE_SWITCH));
4024 gsi_insert_on_edge (loc->e, assert_stmt);
4025 return true;
4028 /* If the stmt iterator points at the end then this is an insertion
4029 at the beginning of a block. */
4030 if (gsi_end_p (loc->si))
4032 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4033 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4034 return false;
4037 /* Otherwise, we can insert right after LOC->SI iff the
4038 statement must not be the last statement in the block. */
4039 stmt = gsi_stmt (loc->si);
4040 if (!stmt_ends_bb_p (stmt))
4042 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4043 return false;
4046 /* If STMT must be the last statement in BB, we can only insert new
4047 assertions on the non-abnormal edge out of BB. Note that since
4048 STMT is not control flow, there may only be one non-abnormal/eh edge
4049 out of BB. */
4050 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4051 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4053 gsi_insert_on_edge (e, assert_stmt);
4054 return true;
4057 gcc_unreachable ();
4060 /* Qsort helper for sorting assert locations. If stable is true, don't
4061 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4062 on the other side some pointers might be NULL. */
4064 template <bool stable>
4065 static int
4066 compare_assert_loc (const void *pa, const void *pb)
4068 assert_locus * const a = *(assert_locus * const *)pa;
4069 assert_locus * const b = *(assert_locus * const *)pb;
4071 /* If stable, some asserts might be optimized away already, sort
4072 them last. */
4073 if (stable)
4075 if (a == NULL)
4076 return b != NULL;
4077 else if (b == NULL)
4078 return -1;
4081 if (a->e == NULL && b->e != NULL)
4082 return 1;
4083 else if (a->e != NULL && b->e == NULL)
4084 return -1;
4086 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4087 no need to test both a->e and b->e. */
4089 /* Sort after destination index. */
4090 if (a->e == NULL)
4092 else if (a->e->dest->index > b->e->dest->index)
4093 return 1;
4094 else if (a->e->dest->index < b->e->dest->index)
4095 return -1;
4097 /* Sort after comp_code. */
4098 if (a->comp_code > b->comp_code)
4099 return 1;
4100 else if (a->comp_code < b->comp_code)
4101 return -1;
4103 hashval_t ha, hb;
4105 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4106 uses DECL_UID of the VAR_DECL, so sorting might differ between
4107 -g and -g0. When doing the removal of redundant assert exprs
4108 and commonization to successors, this does not matter, but for
4109 the final sort needs to be stable. */
4110 if (stable)
4112 ha = 0;
4113 hb = 0;
4115 else
4117 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4118 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4121 /* Break the tie using hashing and source/bb index. */
4122 if (ha == hb)
4123 return (a->e != NULL
4124 ? a->e->src->index - b->e->src->index
4125 : a->bb->index - b->bb->index);
4126 return ha > hb ? 1 : -1;
4129 /* Process all the insertions registered for every name N_i registered
4130 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4131 found in ASSERTS_FOR[i]. */
4133 static void
4134 process_assert_insertions (void)
4136 unsigned i;
4137 bitmap_iterator bi;
4138 bool update_edges_p = false;
4139 int num_asserts = 0;
4141 if (dump_file && (dump_flags & TDF_DETAILS))
4142 dump_all_asserts (dump_file);
4144 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4146 assert_locus *loc = asserts_for[i];
4147 gcc_assert (loc);
4149 auto_vec<assert_locus *, 16> asserts;
4150 for (; loc; loc = loc->next)
4151 asserts.safe_push (loc);
4152 asserts.qsort (compare_assert_loc<false>);
4154 /* Push down common asserts to successors and remove redundant ones. */
4155 unsigned ecnt = 0;
4156 assert_locus *common = NULL;
4157 unsigned commonj = 0;
4158 for (unsigned j = 0; j < asserts.length (); ++j)
4160 loc = asserts[j];
4161 if (! loc->e)
4162 common = NULL;
4163 else if (! common
4164 || loc->e->dest != common->e->dest
4165 || loc->comp_code != common->comp_code
4166 || ! operand_equal_p (loc->val, common->val, 0)
4167 || ! operand_equal_p (loc->expr, common->expr, 0))
4169 commonj = j;
4170 common = loc;
4171 ecnt = 1;
4173 else if (loc->e == asserts[j-1]->e)
4175 /* Remove duplicate asserts. */
4176 if (commonj == j - 1)
4178 commonj = j;
4179 common = loc;
4181 free (asserts[j-1]);
4182 asserts[j-1] = NULL;
4184 else
4186 ecnt++;
4187 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4189 /* We have the same assertion on all incoming edges of a BB.
4190 Insert it at the beginning of that block. */
4191 loc->bb = loc->e->dest;
4192 loc->e = NULL;
4193 loc->si = gsi_none ();
4194 common = NULL;
4195 /* Clear asserts commoned. */
4196 for (; commonj != j; ++commonj)
4197 if (asserts[commonj])
4199 free (asserts[commonj]);
4200 asserts[commonj] = NULL;
4206 /* The asserts vector sorting above might be unstable for
4207 -fcompare-debug, sort again to ensure a stable sort. */
4208 asserts.qsort (compare_assert_loc<true>);
4209 for (unsigned j = 0; j < asserts.length (); ++j)
4211 loc = asserts[j];
4212 if (! loc)
4213 break;
4214 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4215 num_asserts++;
4216 free (loc);
4220 if (update_edges_p)
4221 gsi_commit_edge_inserts ();
4223 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4224 num_asserts);
4228 /* Traverse the flowgraph looking for conditional jumps to insert range
4229 expressions. These range expressions are meant to provide information
4230 to optimizations that need to reason in terms of value ranges. They
4231 will not be expanded into RTL. For instance, given:
4233 x = ...
4234 y = ...
4235 if (x < y)
4236 y = x - 2;
4237 else
4238 x = y + 3;
4240 this pass will transform the code into:
4242 x = ...
4243 y = ...
4244 if (x < y)
4246 x = ASSERT_EXPR <x, x < y>
4247 y = x - 2
4249 else
4251 y = ASSERT_EXPR <y, x >= y>
4252 x = y + 3
4255 The idea is that once copy and constant propagation have run, other
4256 optimizations will be able to determine what ranges of values can 'x'
4257 take in different paths of the code, simply by checking the reaching
4258 definition of 'x'. */
4260 static void
4261 insert_range_assertions (void)
4263 need_assert_for = BITMAP_ALLOC (NULL);
4264 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4266 calculate_dominance_info (CDI_DOMINATORS);
4268 find_assert_locations ();
4269 if (!bitmap_empty_p (need_assert_for))
4271 process_assert_insertions ();
4272 update_ssa (TODO_update_ssa_no_phi);
4275 if (dump_file && (dump_flags & TDF_DETAILS))
4277 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4278 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4281 free (asserts_for);
4282 BITMAP_FREE (need_assert_for);
4285 class vrp_prop : public ssa_propagation_engine
4287 public:
4288 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4289 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4291 void vrp_initialize (void);
4292 void vrp_finalize (bool);
4293 void check_all_array_refs (void);
4294 void check_array_ref (location_t, tree, bool);
4295 void check_mem_ref (location_t, tree, bool);
4296 void search_for_addr_array (tree, location_t);
4298 class vr_values vr_values;
4299 /* Temporary delegator to minimize code churn. */
4300 value_range *get_value_range (const_tree op)
4301 { return vr_values.get_value_range (op); }
4302 void set_defs_to_varying (gimple *stmt)
4303 { return vr_values.set_defs_to_varying (stmt); }
4304 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4305 tree *output_p, value_range *vr)
4306 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4307 bool update_value_range (const_tree op, value_range *vr)
4308 { return vr_values.update_value_range (op, vr); }
4309 void extract_range_basic (value_range *vr, gimple *stmt)
4310 { vr_values.extract_range_basic (vr, stmt); }
4311 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4312 { vr_values.extract_range_from_phi_node (phi, vr); }
4314 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4315 and "struct" hacks. If VRP can determine that the
4316 array subscript is a constant, check if it is outside valid
4317 range. If the array subscript is a RANGE, warn if it is
4318 non-overlapping with valid range.
4319 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4321 void
4322 vrp_prop::check_array_ref (location_t location, tree ref,
4323 bool ignore_off_by_one)
4325 const value_range *vr = NULL;
4326 tree low_sub, up_sub;
4327 tree low_bound, up_bound, up_bound_p1;
4329 if (TREE_NO_WARNING (ref))
4330 return;
4332 low_sub = up_sub = TREE_OPERAND (ref, 1);
4333 up_bound = array_ref_up_bound (ref);
4335 if (!up_bound
4336 || TREE_CODE (up_bound) != INTEGER_CST
4337 || (warn_array_bounds < 2
4338 && array_at_struct_end_p (ref)))
4340 /* Accesses to trailing arrays via pointers may access storage
4341 beyond the types array bounds. For such arrays, or for flexible
4342 array members, as well as for other arrays of an unknown size,
4343 replace the upper bound with a more permissive one that assumes
4344 the size of the largest object is PTRDIFF_MAX. */
4345 tree eltsize = array_ref_element_size (ref);
4347 if (TREE_CODE (eltsize) != INTEGER_CST
4348 || integer_zerop (eltsize))
4350 up_bound = NULL_TREE;
4351 up_bound_p1 = NULL_TREE;
4353 else
4355 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4356 tree arg = TREE_OPERAND (ref, 0);
4357 poly_int64 off;
4359 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4360 maxbound = wide_int_to_tree (sizetype,
4361 wi::sub (wi::to_wide (maxbound),
4362 off));
4363 else
4364 maxbound = fold_convert (sizetype, maxbound);
4366 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4368 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4369 build_int_cst (ptrdiff_type_node, 1));
4372 else
4373 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4374 build_int_cst (TREE_TYPE (up_bound), 1));
4376 low_bound = array_ref_low_bound (ref);
4378 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4380 bool warned = false;
4382 /* Empty array. */
4383 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4384 warned = warning_at (location, OPT_Warray_bounds,
4385 "array subscript %E is above array bounds of %qT",
4386 low_bound, artype);
4388 if (TREE_CODE (low_sub) == SSA_NAME)
4390 vr = get_value_range (low_sub);
4391 if (!vr->undefined_p () && !vr->varying_p ())
4393 low_sub = vr->kind () == VR_RANGE ? vr->max () : vr->min ();
4394 up_sub = vr->kind () == VR_RANGE ? vr->min () : vr->max ();
4398 if (vr && vr->kind () == VR_ANTI_RANGE)
4400 if (up_bound
4401 && TREE_CODE (up_sub) == INTEGER_CST
4402 && (ignore_off_by_one
4403 ? tree_int_cst_lt (up_bound, up_sub)
4404 : tree_int_cst_le (up_bound, up_sub))
4405 && TREE_CODE (low_sub) == INTEGER_CST
4406 && tree_int_cst_le (low_sub, low_bound))
4407 warned = warning_at (location, OPT_Warray_bounds,
4408 "array subscript [%E, %E] is outside "
4409 "array bounds of %qT",
4410 low_sub, up_sub, artype);
4412 else if (up_bound
4413 && TREE_CODE (up_sub) == INTEGER_CST
4414 && (ignore_off_by_one
4415 ? !tree_int_cst_le (up_sub, up_bound_p1)
4416 : !tree_int_cst_le (up_sub, up_bound)))
4418 if (dump_file && (dump_flags & TDF_DETAILS))
4420 fprintf (dump_file, "Array bound warning for ");
4421 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4422 fprintf (dump_file, "\n");
4424 warned = warning_at (location, OPT_Warray_bounds,
4425 "array subscript %E is above array bounds of %qT",
4426 up_sub, artype);
4428 else if (TREE_CODE (low_sub) == INTEGER_CST
4429 && tree_int_cst_lt (low_sub, low_bound))
4431 if (dump_file && (dump_flags & TDF_DETAILS))
4433 fprintf (dump_file, "Array bound warning for ");
4434 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4435 fprintf (dump_file, "\n");
4437 warned = warning_at (location, OPT_Warray_bounds,
4438 "array subscript %E is below array bounds of %qT",
4439 low_sub, artype);
4442 if (warned)
4444 ref = TREE_OPERAND (ref, 0);
4446 if (DECL_P (ref))
4447 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4449 TREE_NO_WARNING (ref) = 1;
4453 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4454 references to string constants. If VRP can determine that the array
4455 subscript is a constant, check if it is outside valid range.
4456 If the array subscript is a RANGE, warn if it is non-overlapping
4457 with valid range.
4458 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4459 (used to allow one-past-the-end indices for code that takes
4460 the address of the just-past-the-end element of an array). */
4462 void
4463 vrp_prop::check_mem_ref (location_t location, tree ref,
4464 bool ignore_off_by_one)
4466 if (TREE_NO_WARNING (ref))
4467 return;
4469 tree arg = TREE_OPERAND (ref, 0);
4470 /* The constant and variable offset of the reference. */
4471 tree cstoff = TREE_OPERAND (ref, 1);
4472 tree varoff = NULL_TREE;
4474 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4476 /* The array or string constant bounds in bytes. Initially set
4477 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4478 determined. */
4479 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4481 /* The minimum and maximum intermediate offset. For a reference
4482 to be valid, not only does the final offset/subscript must be
4483 in bounds but all intermediate offsets should be as well.
4484 GCC may be able to deal gracefully with such out-of-bounds
4485 offsets so the checking is only enbaled at -Warray-bounds=2
4486 where it may help detect bugs in uses of the intermediate
4487 offsets that could otherwise not be detectable. */
4488 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4489 offset_int extrema[2] = { 0, wi::abs (ioff) };
4491 /* The range of the byte offset into the reference. */
4492 offset_int offrange[2] = { 0, 0 };
4494 const value_range *vr = NULL;
4496 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4497 The loop computes the the range of the final offset for expressions
4498 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4499 in some range. */
4500 while (TREE_CODE (arg) == SSA_NAME)
4502 gimple *def = SSA_NAME_DEF_STMT (arg);
4503 if (!is_gimple_assign (def))
4504 break;
4506 tree_code code = gimple_assign_rhs_code (def);
4507 if (code == POINTER_PLUS_EXPR)
4509 arg = gimple_assign_rhs1 (def);
4510 varoff = gimple_assign_rhs2 (def);
4512 else if (code == ASSERT_EXPR)
4514 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4515 continue;
4517 else
4518 return;
4520 /* VAROFF should always be a SSA_NAME here (and not even
4521 INTEGER_CST) but there's no point in taking chances. */
4522 if (TREE_CODE (varoff) != SSA_NAME)
4523 break;
4525 vr = get_value_range (varoff);
4526 if (!vr || vr->undefined_p () || vr->varying_p ())
4527 break;
4529 if (!vr->constant_p ())
4530 break;
4532 if (vr->kind () == VR_RANGE)
4534 if (tree_int_cst_lt (vr->min (), vr->max ()))
4536 offset_int min
4537 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min ()));
4538 offset_int max
4539 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max ()));
4540 if (min < max)
4542 offrange[0] += min;
4543 offrange[1] += max;
4545 else
4547 offrange[0] += max;
4548 offrange[1] += min;
4551 else
4553 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4554 to OFFRANGE. */
4555 offrange[0] += arrbounds[0];
4556 offrange[1] += arrbounds[1];
4559 else
4561 /* For an anti-range, analogously to the above, conservatively
4562 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4563 offrange[0] += arrbounds[0];
4564 offrange[1] += arrbounds[1];
4567 /* Keep track of the minimum and maximum offset. */
4568 if (offrange[1] < 0 && offrange[1] < extrema[0])
4569 extrema[0] = offrange[1];
4570 if (offrange[0] > 0 && offrange[0] > extrema[1])
4571 extrema[1] = offrange[0];
4573 if (offrange[0] < arrbounds[0])
4574 offrange[0] = arrbounds[0];
4576 if (offrange[1] > arrbounds[1])
4577 offrange[1] = arrbounds[1];
4580 if (TREE_CODE (arg) == ADDR_EXPR)
4582 arg = TREE_OPERAND (arg, 0);
4583 if (TREE_CODE (arg) != STRING_CST
4584 && TREE_CODE (arg) != VAR_DECL)
4585 return;
4587 else
4588 return;
4590 /* The type of the object being referred to. It can be an array,
4591 string literal, or a non-array type when the MEM_REF represents
4592 a reference/subscript via a pointer to an object that is not
4593 an element of an array. References to members of structs and
4594 unions are excluded because MEM_REF doesn't make it possible
4595 to identify the member where the reference originated.
4596 Incomplete types are excluded as well because their size is
4597 not known. */
4598 tree reftype = TREE_TYPE (arg);
4599 if (POINTER_TYPE_P (reftype)
4600 || !COMPLETE_TYPE_P (reftype)
4601 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4602 || RECORD_OR_UNION_TYPE_P (reftype))
4603 return;
4605 offset_int eltsize;
4606 if (TREE_CODE (reftype) == ARRAY_TYPE)
4608 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4610 if (tree dom = TYPE_DOMAIN (reftype))
4612 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4613 if (array_at_struct_end_p (arg)
4614 || !bnds[0] || !bnds[1])
4616 arrbounds[0] = 0;
4617 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4619 else
4621 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4622 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4625 else
4627 arrbounds[0] = 0;
4628 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4631 if (TREE_CODE (ref) == MEM_REF)
4633 /* For MEM_REF determine a tighter bound of the non-array
4634 element type. */
4635 tree eltype = TREE_TYPE (reftype);
4636 while (TREE_CODE (eltype) == ARRAY_TYPE)
4637 eltype = TREE_TYPE (eltype);
4638 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4641 else
4643 eltsize = 1;
4644 arrbounds[0] = 0;
4645 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4648 offrange[0] += ioff;
4649 offrange[1] += ioff;
4651 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4652 is set (when taking the address of the one-past-last element
4653 of an array) but always use the stricter bound in diagnostics. */
4654 offset_int ubound = arrbounds[1];
4655 if (ignore_off_by_one)
4656 ubound += 1;
4658 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4660 /* Treat a reference to a non-array object as one to an array
4661 of a single element. */
4662 if (TREE_CODE (reftype) != ARRAY_TYPE)
4663 reftype = build_array_type_nelts (reftype, 1);
4665 if (TREE_CODE (ref) == MEM_REF)
4667 /* Extract the element type out of MEM_REF and use its size
4668 to compute the index to print in the diagnostic; arrays
4669 in MEM_REF don't mean anything. */
4670 tree type = TREE_TYPE (ref);
4671 while (TREE_CODE (type) == ARRAY_TYPE)
4672 type = TREE_TYPE (type);
4673 tree size = TYPE_SIZE_UNIT (type);
4674 offrange[0] = offrange[0] / wi::to_offset (size);
4675 offrange[1] = offrange[1] / wi::to_offset (size);
4677 else
4679 /* For anything other than MEM_REF, compute the index to
4680 print in the diagnostic as the offset over element size. */
4681 offrange[0] = offrange[0] / eltsize;
4682 offrange[1] = offrange[1] / eltsize;
4685 bool warned;
4686 if (offrange[0] == offrange[1])
4687 warned = warning_at (location, OPT_Warray_bounds,
4688 "array subscript %wi is outside array bounds "
4689 "of %qT",
4690 offrange[0].to_shwi (), reftype);
4691 else
4692 warned = warning_at (location, OPT_Warray_bounds,
4693 "array subscript [%wi, %wi] is outside "
4694 "array bounds of %qT",
4695 offrange[0].to_shwi (),
4696 offrange[1].to_shwi (), reftype);
4697 if (warned && DECL_P (arg))
4698 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4700 TREE_NO_WARNING (ref) = 1;
4701 return;
4704 if (warn_array_bounds < 2)
4705 return;
4707 /* At level 2 check also intermediate offsets. */
4708 int i = 0;
4709 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4711 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4713 warning_at (location, OPT_Warray_bounds,
4714 "intermediate array offset %wi is outside array bounds "
4715 "of %qT",
4716 tmpidx, reftype);
4717 TREE_NO_WARNING (ref) = 1;
4721 /* Searches if the expr T, located at LOCATION computes
4722 address of an ARRAY_REF, and call check_array_ref on it. */
4724 void
4725 vrp_prop::search_for_addr_array (tree t, location_t location)
4727 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4730 if (TREE_CODE (t) == ARRAY_REF)
4731 check_array_ref (location, t, true /*ignore_off_by_one*/);
4732 else if (TREE_CODE (t) == MEM_REF)
4733 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4735 t = TREE_OPERAND (t, 0);
4737 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4739 if (TREE_CODE (t) != MEM_REF
4740 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4741 || TREE_NO_WARNING (t))
4742 return;
4744 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4745 tree low_bound, up_bound, el_sz;
4746 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4747 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4748 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4749 return;
4751 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4752 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4753 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4754 if (!low_bound
4755 || TREE_CODE (low_bound) != INTEGER_CST
4756 || !up_bound
4757 || TREE_CODE (up_bound) != INTEGER_CST
4758 || !el_sz
4759 || TREE_CODE (el_sz) != INTEGER_CST)
4760 return;
4762 offset_int idx;
4763 if (!mem_ref_offset (t).is_constant (&idx))
4764 return;
4766 bool warned = false;
4767 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4768 if (idx < 0)
4770 if (dump_file && (dump_flags & TDF_DETAILS))
4772 fprintf (dump_file, "Array bound warning for ");
4773 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4774 fprintf (dump_file, "\n");
4776 warned = warning_at (location, OPT_Warray_bounds,
4777 "array subscript %wi is below "
4778 "array bounds of %qT",
4779 idx.to_shwi (), TREE_TYPE (tem));
4781 else if (idx > (wi::to_offset (up_bound)
4782 - wi::to_offset (low_bound) + 1))
4784 if (dump_file && (dump_flags & TDF_DETAILS))
4786 fprintf (dump_file, "Array bound warning for ");
4787 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4788 fprintf (dump_file, "\n");
4790 warned = warning_at (location, OPT_Warray_bounds,
4791 "array subscript %wu is above "
4792 "array bounds of %qT",
4793 idx.to_uhwi (), TREE_TYPE (tem));
4796 if (warned)
4798 if (DECL_P (t))
4799 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4801 TREE_NO_WARNING (t) = 1;
4805 /* walk_tree() callback that checks if *TP is
4806 an ARRAY_REF inside an ADDR_EXPR (in which an array
4807 subscript one outside the valid range is allowed). Call
4808 check_array_ref for each ARRAY_REF found. The location is
4809 passed in DATA. */
4811 static tree
4812 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4814 tree t = *tp;
4815 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4816 location_t location;
4818 if (EXPR_HAS_LOCATION (t))
4819 location = EXPR_LOCATION (t);
4820 else
4821 location = gimple_location (wi->stmt);
4823 *walk_subtree = TRUE;
4825 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4826 if (TREE_CODE (t) == ARRAY_REF)
4827 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4828 else if (TREE_CODE (t) == MEM_REF)
4829 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4830 else if (TREE_CODE (t) == ADDR_EXPR)
4832 vrp_prop->search_for_addr_array (t, location);
4833 *walk_subtree = FALSE;
4836 return NULL_TREE;
4839 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4840 to walk over all statements of all reachable BBs and call
4841 check_array_bounds on them. */
4843 class check_array_bounds_dom_walker : public dom_walker
4845 public:
4846 check_array_bounds_dom_walker (vrp_prop *prop)
4847 : dom_walker (CDI_DOMINATORS,
4848 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4849 flags, so that we can merge in information on
4850 non-executable edges from vrp_folder . */
4851 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4852 m_prop (prop) {}
4853 ~check_array_bounds_dom_walker () {}
4855 edge before_dom_children (basic_block) FINAL OVERRIDE;
4857 private:
4858 vrp_prop *m_prop;
4861 /* Implementation of dom_walker::before_dom_children.
4863 Walk over all statements of BB and call check_array_bounds on them,
4864 and determine if there's a unique successor edge. */
4866 edge
4867 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4869 gimple_stmt_iterator si;
4870 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4872 gimple *stmt = gsi_stmt (si);
4873 struct walk_stmt_info wi;
4874 if (!gimple_has_location (stmt)
4875 || is_gimple_debug (stmt))
4876 continue;
4878 memset (&wi, 0, sizeof (wi));
4880 wi.info = m_prop;
4882 walk_gimple_op (stmt, check_array_bounds, &wi);
4885 /* Determine if there's a unique successor edge, and if so, return
4886 that back to dom_walker, ensuring that we don't visit blocks that
4887 became unreachable during the VRP propagation
4888 (PR tree-optimization/83312). */
4889 return find_taken_edge (bb, NULL_TREE);
4892 /* Walk over all statements of all reachable BBs and call check_array_bounds
4893 on them. */
4895 void
4896 vrp_prop::check_all_array_refs ()
4898 check_array_bounds_dom_walker w (this);
4899 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4902 /* Return true if all imm uses of VAR are either in STMT, or
4903 feed (optionally through a chain of single imm uses) GIMPLE_COND
4904 in basic block COND_BB. */
4906 static bool
4907 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4909 use_operand_p use_p, use2_p;
4910 imm_use_iterator iter;
4912 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4913 if (USE_STMT (use_p) != stmt)
4915 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4916 if (is_gimple_debug (use_stmt))
4917 continue;
4918 while (is_gimple_assign (use_stmt)
4919 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4920 && single_imm_use (gimple_assign_lhs (use_stmt),
4921 &use2_p, &use_stmt2))
4922 use_stmt = use_stmt2;
4923 if (gimple_code (use_stmt) != GIMPLE_COND
4924 || gimple_bb (use_stmt) != cond_bb)
4925 return false;
4927 return true;
4930 /* Handle
4931 _4 = x_3 & 31;
4932 if (_4 != 0)
4933 goto <bb 6>;
4934 else
4935 goto <bb 7>;
4936 <bb 6>:
4937 __builtin_unreachable ();
4938 <bb 7>:
4939 x_5 = ASSERT_EXPR <x_3, ...>;
4940 If x_3 has no other immediate uses (checked by caller),
4941 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4942 from the non-zero bitmask. */
4944 void
4945 maybe_set_nonzero_bits (edge e, tree var)
4947 basic_block cond_bb = e->src;
4948 gimple *stmt = last_stmt (cond_bb);
4949 tree cst;
4951 if (stmt == NULL
4952 || gimple_code (stmt) != GIMPLE_COND
4953 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
4954 ? EQ_EXPR : NE_EXPR)
4955 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
4956 || !integer_zerop (gimple_cond_rhs (stmt)))
4957 return;
4959 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
4960 if (!is_gimple_assign (stmt)
4961 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4962 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
4963 return;
4964 if (gimple_assign_rhs1 (stmt) != var)
4966 gimple *stmt2;
4968 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
4969 return;
4970 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
4971 if (!gimple_assign_cast_p (stmt2)
4972 || gimple_assign_rhs1 (stmt2) != var
4973 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
4974 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
4975 != TYPE_PRECISION (TREE_TYPE (var))))
4976 return;
4978 cst = gimple_assign_rhs2 (stmt);
4979 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
4980 wi::to_wide (cst)));
4983 /* Convert range assertion expressions into the implied copies and
4984 copy propagate away the copies. Doing the trivial copy propagation
4985 here avoids the need to run the full copy propagation pass after
4986 VRP.
4988 FIXME, this will eventually lead to copy propagation removing the
4989 names that had useful range information attached to them. For
4990 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4991 then N_i will have the range [3, +INF].
4993 However, by converting the assertion into the implied copy
4994 operation N_i = N_j, we will then copy-propagate N_j into the uses
4995 of N_i and lose the range information. We may want to hold on to
4996 ASSERT_EXPRs a little while longer as the ranges could be used in
4997 things like jump threading.
4999 The problem with keeping ASSERT_EXPRs around is that passes after
5000 VRP need to handle them appropriately.
5002 Another approach would be to make the range information a first
5003 class property of the SSA_NAME so that it can be queried from
5004 any pass. This is made somewhat more complex by the need for
5005 multiple ranges to be associated with one SSA_NAME. */
5007 static void
5008 remove_range_assertions (void)
5010 basic_block bb;
5011 gimple_stmt_iterator si;
5012 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5013 a basic block preceeded by GIMPLE_COND branching to it and
5014 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5015 int is_unreachable;
5017 /* Note that the BSI iterator bump happens at the bottom of the
5018 loop and no bump is necessary if we're removing the statement
5019 referenced by the current BSI. */
5020 FOR_EACH_BB_FN (bb, cfun)
5021 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5023 gimple *stmt = gsi_stmt (si);
5025 if (is_gimple_assign (stmt)
5026 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5028 tree lhs = gimple_assign_lhs (stmt);
5029 tree rhs = gimple_assign_rhs1 (stmt);
5030 tree var;
5032 var = ASSERT_EXPR_VAR (rhs);
5034 if (TREE_CODE (var) == SSA_NAME
5035 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5036 && SSA_NAME_RANGE_INFO (lhs))
5038 if (is_unreachable == -1)
5040 is_unreachable = 0;
5041 if (single_pred_p (bb)
5042 && assert_unreachable_fallthru_edge_p
5043 (single_pred_edge (bb)))
5044 is_unreachable = 1;
5046 /* Handle
5047 if (x_7 >= 10 && x_7 < 20)
5048 __builtin_unreachable ();
5049 x_8 = ASSERT_EXPR <x_7, ...>;
5050 if the only uses of x_7 are in the ASSERT_EXPR and
5051 in the condition. In that case, we can copy the
5052 range info from x_8 computed in this pass also
5053 for x_7. */
5054 if (is_unreachable
5055 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5056 single_pred (bb)))
5058 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5059 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5060 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5061 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5065 /* Propagate the RHS into every use of the LHS. For SSA names
5066 also propagate abnormals as it merely restores the original
5067 IL in this case (an replace_uses_by would assert). */
5068 if (TREE_CODE (var) == SSA_NAME)
5070 imm_use_iterator iter;
5071 use_operand_p use_p;
5072 gimple *use_stmt;
5073 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5074 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5075 SET_USE (use_p, var);
5077 else
5078 replace_uses_by (lhs, var);
5080 /* And finally, remove the copy, it is not needed. */
5081 gsi_remove (&si, true);
5082 release_defs (stmt);
5084 else
5086 if (!is_gimple_debug (gsi_stmt (si)))
5087 is_unreachable = 0;
5088 gsi_next (&si);
5093 /* Return true if STMT is interesting for VRP. */
5095 bool
5096 stmt_interesting_for_vrp (gimple *stmt)
5098 if (gimple_code (stmt) == GIMPLE_PHI)
5100 tree res = gimple_phi_result (stmt);
5101 return (!virtual_operand_p (res)
5102 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5103 || POINTER_TYPE_P (TREE_TYPE (res))));
5105 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5107 tree lhs = gimple_get_lhs (stmt);
5109 /* In general, assignments with virtual operands are not useful
5110 for deriving ranges, with the obvious exception of calls to
5111 builtin functions. */
5112 if (lhs && TREE_CODE (lhs) == SSA_NAME
5113 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5114 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5115 && (is_gimple_call (stmt)
5116 || !gimple_vuse (stmt)))
5117 return true;
5118 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5119 switch (gimple_call_internal_fn (stmt))
5121 case IFN_ADD_OVERFLOW:
5122 case IFN_SUB_OVERFLOW:
5123 case IFN_MUL_OVERFLOW:
5124 case IFN_ATOMIC_COMPARE_EXCHANGE:
5125 /* These internal calls return _Complex integer type,
5126 but are interesting to VRP nevertheless. */
5127 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5128 return true;
5129 break;
5130 default:
5131 break;
5134 else if (gimple_code (stmt) == GIMPLE_COND
5135 || gimple_code (stmt) == GIMPLE_SWITCH)
5136 return true;
5138 return false;
5141 /* Initialization required by ssa_propagate engine. */
5143 void
5144 vrp_prop::vrp_initialize ()
5146 basic_block bb;
5148 FOR_EACH_BB_FN (bb, cfun)
5150 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5151 gsi_next (&si))
5153 gphi *phi = si.phi ();
5154 if (!stmt_interesting_for_vrp (phi))
5156 tree lhs = PHI_RESULT (phi);
5157 get_value_range (lhs)->set_varying ();
5158 prop_set_simulate_again (phi, false);
5160 else
5161 prop_set_simulate_again (phi, true);
5164 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5165 gsi_next (&si))
5167 gimple *stmt = gsi_stmt (si);
5169 /* If the statement is a control insn, then we do not
5170 want to avoid simulating the statement once. Failure
5171 to do so means that those edges will never get added. */
5172 if (stmt_ends_bb_p (stmt))
5173 prop_set_simulate_again (stmt, true);
5174 else if (!stmt_interesting_for_vrp (stmt))
5176 set_defs_to_varying (stmt);
5177 prop_set_simulate_again (stmt, false);
5179 else
5180 prop_set_simulate_again (stmt, true);
5185 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5186 that includes the value VAL. The search is restricted to the range
5187 [START_IDX, n - 1] where n is the size of VEC.
5189 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5190 returned.
5192 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5193 it is placed in IDX and false is returned.
5195 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5196 returned. */
5198 bool
5199 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5201 size_t n = gimple_switch_num_labels (stmt);
5202 size_t low, high;
5204 /* Find case label for minimum of the value range or the next one.
5205 At each iteration we are searching in [low, high - 1]. */
5207 for (low = start_idx, high = n; high != low; )
5209 tree t;
5210 int cmp;
5211 /* Note that i != high, so we never ask for n. */
5212 size_t i = (high + low) / 2;
5213 t = gimple_switch_label (stmt, i);
5215 /* Cache the result of comparing CASE_LOW and val. */
5216 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5218 if (cmp == 0)
5220 /* Ranges cannot be empty. */
5221 *idx = i;
5222 return true;
5224 else if (cmp > 0)
5225 high = i;
5226 else
5228 low = i + 1;
5229 if (CASE_HIGH (t) != NULL
5230 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5232 *idx = i;
5233 return true;
5238 *idx = high;
5239 return false;
5242 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5243 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5244 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5245 then MAX_IDX < MIN_IDX.
5246 Returns true if the default label is not needed. */
5248 bool
5249 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5250 size_t *max_idx)
5252 size_t i, j;
5253 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5254 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5256 if (i == j
5257 && min_take_default
5258 && max_take_default)
5260 /* Only the default case label reached.
5261 Return an empty range. */
5262 *min_idx = 1;
5263 *max_idx = 0;
5264 return false;
5266 else
5268 bool take_default = min_take_default || max_take_default;
5269 tree low, high;
5270 size_t k;
5272 if (max_take_default)
5273 j--;
5275 /* If the case label range is continuous, we do not need
5276 the default case label. Verify that. */
5277 high = CASE_LOW (gimple_switch_label (stmt, i));
5278 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5279 high = CASE_HIGH (gimple_switch_label (stmt, i));
5280 for (k = i + 1; k <= j; ++k)
5282 low = CASE_LOW (gimple_switch_label (stmt, k));
5283 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5285 take_default = true;
5286 break;
5288 high = low;
5289 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5290 high = CASE_HIGH (gimple_switch_label (stmt, k));
5293 *min_idx = i;
5294 *max_idx = j;
5295 return !take_default;
5299 /* Evaluate statement STMT. If the statement produces a useful range,
5300 return SSA_PROP_INTERESTING and record the SSA name with the
5301 interesting range into *OUTPUT_P.
5303 If STMT is a conditional branch and we can determine its truth
5304 value, the taken edge is recorded in *TAKEN_EDGE_P.
5306 If STMT produces a varying value, return SSA_PROP_VARYING. */
5308 enum ssa_prop_result
5309 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5311 tree lhs = gimple_get_lhs (stmt);
5312 value_range vr;
5313 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5315 if (*output_p)
5317 if (update_value_range (*output_p, &vr))
5319 if (dump_file && (dump_flags & TDF_DETAILS))
5321 fprintf (dump_file, "Found new range for ");
5322 print_generic_expr (dump_file, *output_p);
5323 fprintf (dump_file, ": ");
5324 dump_value_range (dump_file, &vr);
5325 fprintf (dump_file, "\n");
5328 if (vr.varying_p ())
5329 return SSA_PROP_VARYING;
5331 return SSA_PROP_INTERESTING;
5333 return SSA_PROP_NOT_INTERESTING;
5336 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5337 switch (gimple_call_internal_fn (stmt))
5339 case IFN_ADD_OVERFLOW:
5340 case IFN_SUB_OVERFLOW:
5341 case IFN_MUL_OVERFLOW:
5342 case IFN_ATOMIC_COMPARE_EXCHANGE:
5343 /* These internal calls return _Complex integer type,
5344 which VRP does not track, but the immediate uses
5345 thereof might be interesting. */
5346 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5348 imm_use_iterator iter;
5349 use_operand_p use_p;
5350 enum ssa_prop_result res = SSA_PROP_VARYING;
5352 get_value_range (lhs)->set_varying ();
5354 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5356 gimple *use_stmt = USE_STMT (use_p);
5357 if (!is_gimple_assign (use_stmt))
5358 continue;
5359 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5360 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5361 continue;
5362 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5363 tree use_lhs = gimple_assign_lhs (use_stmt);
5364 if (TREE_CODE (rhs1) != rhs_code
5365 || TREE_OPERAND (rhs1, 0) != lhs
5366 || TREE_CODE (use_lhs) != SSA_NAME
5367 || !stmt_interesting_for_vrp (use_stmt)
5368 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5369 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5370 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5371 continue;
5373 /* If there is a change in the value range for any of the
5374 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5375 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5376 or IMAGPART_EXPR immediate uses, but none of them have
5377 a change in their value ranges, return
5378 SSA_PROP_NOT_INTERESTING. If there are no
5379 {REAL,IMAG}PART_EXPR uses at all,
5380 return SSA_PROP_VARYING. */
5381 value_range new_vr;
5382 extract_range_basic (&new_vr, use_stmt);
5383 const value_range *old_vr = get_value_range (use_lhs);
5384 if (*old_vr != new_vr)
5385 res = SSA_PROP_INTERESTING;
5386 else
5387 res = SSA_PROP_NOT_INTERESTING;
5388 new_vr.equiv_clear ();
5389 if (res == SSA_PROP_INTERESTING)
5391 *output_p = lhs;
5392 return res;
5396 return res;
5398 break;
5399 default:
5400 break;
5403 /* All other statements produce nothing of interest for VRP, so mark
5404 their outputs varying and prevent further simulation. */
5405 set_defs_to_varying (stmt);
5407 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5410 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5411 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5412 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5413 possible such range. The resulting range is not canonicalized. */
5415 static void
5416 union_ranges (enum value_range_kind *vr0type,
5417 tree *vr0min, tree *vr0max,
5418 enum value_range_kind vr1type,
5419 tree vr1min, tree vr1max)
5421 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5422 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5424 /* [] is vr0, () is vr1 in the following classification comments. */
5425 if (mineq && maxeq)
5427 /* [( )] */
5428 if (*vr0type == vr1type)
5429 /* Nothing to do for equal ranges. */
5431 else if ((*vr0type == VR_RANGE
5432 && vr1type == VR_ANTI_RANGE)
5433 || (*vr0type == VR_ANTI_RANGE
5434 && vr1type == VR_RANGE))
5436 /* For anti-range with range union the result is varying. */
5437 goto give_up;
5439 else
5440 gcc_unreachable ();
5442 else if (operand_less_p (*vr0max, vr1min) == 1
5443 || operand_less_p (vr1max, *vr0min) == 1)
5445 /* [ ] ( ) or ( ) [ ]
5446 If the ranges have an empty intersection, result of the union
5447 operation is the anti-range or if both are anti-ranges
5448 it covers all. */
5449 if (*vr0type == VR_ANTI_RANGE
5450 && vr1type == VR_ANTI_RANGE)
5451 goto give_up;
5452 else if (*vr0type == VR_ANTI_RANGE
5453 && vr1type == VR_RANGE)
5455 else if (*vr0type == VR_RANGE
5456 && vr1type == VR_ANTI_RANGE)
5458 *vr0type = vr1type;
5459 *vr0min = vr1min;
5460 *vr0max = vr1max;
5462 else if (*vr0type == VR_RANGE
5463 && vr1type == VR_RANGE)
5465 /* The result is the convex hull of both ranges. */
5466 if (operand_less_p (*vr0max, vr1min) == 1)
5468 /* If the result can be an anti-range, create one. */
5469 if (TREE_CODE (*vr0max) == INTEGER_CST
5470 && TREE_CODE (vr1min) == INTEGER_CST
5471 && vrp_val_is_min (*vr0min)
5472 && vrp_val_is_max (vr1max))
5474 tree min = int_const_binop (PLUS_EXPR,
5475 *vr0max,
5476 build_int_cst (TREE_TYPE (*vr0max), 1));
5477 tree max = int_const_binop (MINUS_EXPR,
5478 vr1min,
5479 build_int_cst (TREE_TYPE (vr1min), 1));
5480 if (!operand_less_p (max, min))
5482 *vr0type = VR_ANTI_RANGE;
5483 *vr0min = min;
5484 *vr0max = max;
5486 else
5487 *vr0max = vr1max;
5489 else
5490 *vr0max = vr1max;
5492 else
5494 /* If the result can be an anti-range, create one. */
5495 if (TREE_CODE (vr1max) == INTEGER_CST
5496 && TREE_CODE (*vr0min) == INTEGER_CST
5497 && vrp_val_is_min (vr1min)
5498 && vrp_val_is_max (*vr0max))
5500 tree min = int_const_binop (PLUS_EXPR,
5501 vr1max,
5502 build_int_cst (TREE_TYPE (vr1max), 1));
5503 tree max = int_const_binop (MINUS_EXPR,
5504 *vr0min,
5505 build_int_cst (TREE_TYPE (*vr0min), 1));
5506 if (!operand_less_p (max, min))
5508 *vr0type = VR_ANTI_RANGE;
5509 *vr0min = min;
5510 *vr0max = max;
5512 else
5513 *vr0min = vr1min;
5515 else
5516 *vr0min = vr1min;
5519 else
5520 gcc_unreachable ();
5522 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5523 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5525 /* [ ( ) ] or [( ) ] or [ ( )] */
5526 if (*vr0type == VR_RANGE
5527 && vr1type == VR_RANGE)
5529 else if (*vr0type == VR_ANTI_RANGE
5530 && vr1type == VR_ANTI_RANGE)
5532 *vr0type = vr1type;
5533 *vr0min = vr1min;
5534 *vr0max = vr1max;
5536 else if (*vr0type == VR_ANTI_RANGE
5537 && vr1type == VR_RANGE)
5539 /* Arbitrarily choose the right or left gap. */
5540 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5541 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5542 build_int_cst (TREE_TYPE (vr1min), 1));
5543 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5544 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5545 build_int_cst (TREE_TYPE (vr1max), 1));
5546 else
5547 goto give_up;
5549 else if (*vr0type == VR_RANGE
5550 && vr1type == VR_ANTI_RANGE)
5551 /* The result covers everything. */
5552 goto give_up;
5553 else
5554 gcc_unreachable ();
5556 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5557 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5559 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5560 if (*vr0type == VR_RANGE
5561 && vr1type == VR_RANGE)
5563 *vr0type = vr1type;
5564 *vr0min = vr1min;
5565 *vr0max = vr1max;
5567 else if (*vr0type == VR_ANTI_RANGE
5568 && vr1type == VR_ANTI_RANGE)
5570 else if (*vr0type == VR_RANGE
5571 && vr1type == VR_ANTI_RANGE)
5573 *vr0type = VR_ANTI_RANGE;
5574 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5576 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5577 build_int_cst (TREE_TYPE (*vr0min), 1));
5578 *vr0min = vr1min;
5580 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5582 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5583 build_int_cst (TREE_TYPE (*vr0max), 1));
5584 *vr0max = vr1max;
5586 else
5587 goto give_up;
5589 else if (*vr0type == VR_ANTI_RANGE
5590 && vr1type == VR_RANGE)
5591 /* The result covers everything. */
5592 goto give_up;
5593 else
5594 gcc_unreachable ();
5596 else if ((operand_less_p (vr1min, *vr0max) == 1
5597 || operand_equal_p (vr1min, *vr0max, 0))
5598 && operand_less_p (*vr0min, vr1min) == 1
5599 && operand_less_p (*vr0max, vr1max) == 1)
5601 /* [ ( ] ) or [ ]( ) */
5602 if (*vr0type == VR_RANGE
5603 && vr1type == VR_RANGE)
5604 *vr0max = vr1max;
5605 else if (*vr0type == VR_ANTI_RANGE
5606 && vr1type == VR_ANTI_RANGE)
5607 *vr0min = vr1min;
5608 else if (*vr0type == VR_ANTI_RANGE
5609 && vr1type == VR_RANGE)
5611 if (TREE_CODE (vr1min) == INTEGER_CST)
5612 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5613 build_int_cst (TREE_TYPE (vr1min), 1));
5614 else
5615 goto give_up;
5617 else if (*vr0type == VR_RANGE
5618 && vr1type == VR_ANTI_RANGE)
5620 if (TREE_CODE (*vr0max) == INTEGER_CST)
5622 *vr0type = vr1type;
5623 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5624 build_int_cst (TREE_TYPE (*vr0max), 1));
5625 *vr0max = vr1max;
5627 else
5628 goto give_up;
5630 else
5631 gcc_unreachable ();
5633 else if ((operand_less_p (*vr0min, vr1max) == 1
5634 || operand_equal_p (*vr0min, vr1max, 0))
5635 && operand_less_p (vr1min, *vr0min) == 1
5636 && operand_less_p (vr1max, *vr0max) == 1)
5638 /* ( [ ) ] or ( )[ ] */
5639 if (*vr0type == VR_RANGE
5640 && vr1type == VR_RANGE)
5641 *vr0min = vr1min;
5642 else if (*vr0type == VR_ANTI_RANGE
5643 && vr1type == VR_ANTI_RANGE)
5644 *vr0max = vr1max;
5645 else if (*vr0type == VR_ANTI_RANGE
5646 && vr1type == VR_RANGE)
5648 if (TREE_CODE (vr1max) == INTEGER_CST)
5649 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5650 build_int_cst (TREE_TYPE (vr1max), 1));
5651 else
5652 goto give_up;
5654 else if (*vr0type == VR_RANGE
5655 && vr1type == VR_ANTI_RANGE)
5657 if (TREE_CODE (*vr0min) == INTEGER_CST)
5659 *vr0type = vr1type;
5660 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5661 build_int_cst (TREE_TYPE (*vr0min), 1));
5662 *vr0min = vr1min;
5664 else
5665 goto give_up;
5667 else
5668 gcc_unreachable ();
5670 else
5671 goto give_up;
5673 return;
5675 give_up:
5676 *vr0type = VR_VARYING;
5677 *vr0min = NULL_TREE;
5678 *vr0max = NULL_TREE;
5681 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5682 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5683 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5684 possible such range. The resulting range is not canonicalized. */
5686 static void
5687 intersect_ranges (enum value_range_kind *vr0type,
5688 tree *vr0min, tree *vr0max,
5689 enum value_range_kind vr1type,
5690 tree vr1min, tree vr1max)
5692 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5693 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5695 /* [] is vr0, () is vr1 in the following classification comments. */
5696 if (mineq && maxeq)
5698 /* [( )] */
5699 if (*vr0type == vr1type)
5700 /* Nothing to do for equal ranges. */
5702 else if ((*vr0type == VR_RANGE
5703 && vr1type == VR_ANTI_RANGE)
5704 || (*vr0type == VR_ANTI_RANGE
5705 && vr1type == VR_RANGE))
5707 /* For anti-range with range intersection the result is empty. */
5708 *vr0type = VR_UNDEFINED;
5709 *vr0min = NULL_TREE;
5710 *vr0max = NULL_TREE;
5712 else
5713 gcc_unreachable ();
5715 else if (operand_less_p (*vr0max, vr1min) == 1
5716 || operand_less_p (vr1max, *vr0min) == 1)
5718 /* [ ] ( ) or ( ) [ ]
5719 If the ranges have an empty intersection, the result of the
5720 intersect operation is the range for intersecting an
5721 anti-range with a range or empty when intersecting two ranges. */
5722 if (*vr0type == VR_RANGE
5723 && vr1type == VR_ANTI_RANGE)
5725 else if (*vr0type == VR_ANTI_RANGE
5726 && vr1type == VR_RANGE)
5728 *vr0type = vr1type;
5729 *vr0min = vr1min;
5730 *vr0max = vr1max;
5732 else if (*vr0type == VR_RANGE
5733 && vr1type == VR_RANGE)
5735 *vr0type = VR_UNDEFINED;
5736 *vr0min = NULL_TREE;
5737 *vr0max = NULL_TREE;
5739 else if (*vr0type == VR_ANTI_RANGE
5740 && vr1type == VR_ANTI_RANGE)
5742 /* If the anti-ranges are adjacent to each other merge them. */
5743 if (TREE_CODE (*vr0max) == INTEGER_CST
5744 && TREE_CODE (vr1min) == INTEGER_CST
5745 && operand_less_p (*vr0max, vr1min) == 1
5746 && integer_onep (int_const_binop (MINUS_EXPR,
5747 vr1min, *vr0max)))
5748 *vr0max = vr1max;
5749 else if (TREE_CODE (vr1max) == INTEGER_CST
5750 && TREE_CODE (*vr0min) == INTEGER_CST
5751 && operand_less_p (vr1max, *vr0min) == 1
5752 && integer_onep (int_const_binop (MINUS_EXPR,
5753 *vr0min, vr1max)))
5754 *vr0min = vr1min;
5755 /* Else arbitrarily take VR0. */
5758 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5759 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5761 /* [ ( ) ] or [( ) ] or [ ( )] */
5762 if (*vr0type == VR_RANGE
5763 && vr1type == VR_RANGE)
5765 /* If both are ranges the result is the inner one. */
5766 *vr0type = vr1type;
5767 *vr0min = vr1min;
5768 *vr0max = vr1max;
5770 else if (*vr0type == VR_RANGE
5771 && vr1type == VR_ANTI_RANGE)
5773 /* Choose the right gap if the left one is empty. */
5774 if (mineq)
5776 if (TREE_CODE (vr1max) != INTEGER_CST)
5777 *vr0min = vr1max;
5778 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5779 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5780 *vr0min
5781 = int_const_binop (MINUS_EXPR, vr1max,
5782 build_int_cst (TREE_TYPE (vr1max), -1));
5783 else
5784 *vr0min
5785 = int_const_binop (PLUS_EXPR, vr1max,
5786 build_int_cst (TREE_TYPE (vr1max), 1));
5788 /* Choose the left gap if the right one is empty. */
5789 else if (maxeq)
5791 if (TREE_CODE (vr1min) != INTEGER_CST)
5792 *vr0max = vr1min;
5793 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5794 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5795 *vr0max
5796 = int_const_binop (PLUS_EXPR, vr1min,
5797 build_int_cst (TREE_TYPE (vr1min), -1));
5798 else
5799 *vr0max
5800 = int_const_binop (MINUS_EXPR, vr1min,
5801 build_int_cst (TREE_TYPE (vr1min), 1));
5803 /* Choose the anti-range if the range is effectively varying. */
5804 else if (vrp_val_is_min (*vr0min)
5805 && vrp_val_is_max (*vr0max))
5807 *vr0type = vr1type;
5808 *vr0min = vr1min;
5809 *vr0max = vr1max;
5811 /* Else choose the range. */
5813 else if (*vr0type == VR_ANTI_RANGE
5814 && vr1type == VR_ANTI_RANGE)
5815 /* If both are anti-ranges the result is the outer one. */
5817 else if (*vr0type == VR_ANTI_RANGE
5818 && vr1type == VR_RANGE)
5820 /* The intersection is empty. */
5821 *vr0type = VR_UNDEFINED;
5822 *vr0min = NULL_TREE;
5823 *vr0max = NULL_TREE;
5825 else
5826 gcc_unreachable ();
5828 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5829 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5831 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5832 if (*vr0type == VR_RANGE
5833 && vr1type == VR_RANGE)
5834 /* Choose the inner range. */
5836 else if (*vr0type == VR_ANTI_RANGE
5837 && vr1type == VR_RANGE)
5839 /* Choose the right gap if the left is empty. */
5840 if (mineq)
5842 *vr0type = VR_RANGE;
5843 if (TREE_CODE (*vr0max) != INTEGER_CST)
5844 *vr0min = *vr0max;
5845 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5846 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5847 *vr0min
5848 = int_const_binop (MINUS_EXPR, *vr0max,
5849 build_int_cst (TREE_TYPE (*vr0max), -1));
5850 else
5851 *vr0min
5852 = int_const_binop (PLUS_EXPR, *vr0max,
5853 build_int_cst (TREE_TYPE (*vr0max), 1));
5854 *vr0max = vr1max;
5856 /* Choose the left gap if the right is empty. */
5857 else if (maxeq)
5859 *vr0type = VR_RANGE;
5860 if (TREE_CODE (*vr0min) != INTEGER_CST)
5861 *vr0max = *vr0min;
5862 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5863 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5864 *vr0max
5865 = int_const_binop (PLUS_EXPR, *vr0min,
5866 build_int_cst (TREE_TYPE (*vr0min), -1));
5867 else
5868 *vr0max
5869 = int_const_binop (MINUS_EXPR, *vr0min,
5870 build_int_cst (TREE_TYPE (*vr0min), 1));
5871 *vr0min = vr1min;
5873 /* Choose the anti-range if the range is effectively varying. */
5874 else if (vrp_val_is_min (vr1min)
5875 && vrp_val_is_max (vr1max))
5877 /* Choose the anti-range if it is ~[0,0], that range is special
5878 enough to special case when vr1's range is relatively wide.
5879 At least for types bigger than int - this covers pointers
5880 and arguments to functions like ctz. */
5881 else if (*vr0min == *vr0max
5882 && integer_zerop (*vr0min)
5883 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5884 >= TYPE_PRECISION (integer_type_node))
5885 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5886 && TREE_CODE (vr1max) == INTEGER_CST
5887 && TREE_CODE (vr1min) == INTEGER_CST
5888 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5889 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5891 /* Else choose the range. */
5892 else
5894 *vr0type = vr1type;
5895 *vr0min = vr1min;
5896 *vr0max = vr1max;
5899 else if (*vr0type == VR_ANTI_RANGE
5900 && vr1type == VR_ANTI_RANGE)
5902 /* If both are anti-ranges the result is the outer one. */
5903 *vr0type = vr1type;
5904 *vr0min = vr1min;
5905 *vr0max = vr1max;
5907 else if (vr1type == VR_ANTI_RANGE
5908 && *vr0type == VR_RANGE)
5910 /* The intersection is empty. */
5911 *vr0type = VR_UNDEFINED;
5912 *vr0min = NULL_TREE;
5913 *vr0max = NULL_TREE;
5915 else
5916 gcc_unreachable ();
5918 else if ((operand_less_p (vr1min, *vr0max) == 1
5919 || operand_equal_p (vr1min, *vr0max, 0))
5920 && operand_less_p (*vr0min, vr1min) == 1)
5922 /* [ ( ] ) or [ ]( ) */
5923 if (*vr0type == VR_ANTI_RANGE
5924 && vr1type == VR_ANTI_RANGE)
5925 *vr0max = vr1max;
5926 else if (*vr0type == VR_RANGE
5927 && vr1type == VR_RANGE)
5928 *vr0min = vr1min;
5929 else if (*vr0type == VR_RANGE
5930 && vr1type == VR_ANTI_RANGE)
5932 if (TREE_CODE (vr1min) == INTEGER_CST)
5933 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5934 build_int_cst (TREE_TYPE (vr1min), 1));
5935 else
5936 *vr0max = vr1min;
5938 else if (*vr0type == VR_ANTI_RANGE
5939 && vr1type == VR_RANGE)
5941 *vr0type = VR_RANGE;
5942 if (TREE_CODE (*vr0max) == INTEGER_CST)
5943 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5944 build_int_cst (TREE_TYPE (*vr0max), 1));
5945 else
5946 *vr0min = *vr0max;
5947 *vr0max = vr1max;
5949 else
5950 gcc_unreachable ();
5952 else if ((operand_less_p (*vr0min, vr1max) == 1
5953 || operand_equal_p (*vr0min, vr1max, 0))
5954 && operand_less_p (vr1min, *vr0min) == 1)
5956 /* ( [ ) ] or ( )[ ] */
5957 if (*vr0type == VR_ANTI_RANGE
5958 && vr1type == VR_ANTI_RANGE)
5959 *vr0min = vr1min;
5960 else if (*vr0type == VR_RANGE
5961 && vr1type == VR_RANGE)
5962 *vr0max = vr1max;
5963 else if (*vr0type == VR_RANGE
5964 && vr1type == VR_ANTI_RANGE)
5966 if (TREE_CODE (vr1max) == INTEGER_CST)
5967 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5968 build_int_cst (TREE_TYPE (vr1max), 1));
5969 else
5970 *vr0min = vr1max;
5972 else if (*vr0type == VR_ANTI_RANGE
5973 && vr1type == VR_RANGE)
5975 *vr0type = VR_RANGE;
5976 if (TREE_CODE (*vr0min) == INTEGER_CST)
5977 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5978 build_int_cst (TREE_TYPE (*vr0min), 1));
5979 else
5980 *vr0max = *vr0min;
5981 *vr0min = vr1min;
5983 else
5984 gcc_unreachable ();
5987 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
5988 result for the intersection. That's always a conservative
5989 correct estimate unless VR1 is a constant singleton range
5990 in which case we choose that. */
5991 if (vr1type == VR_RANGE
5992 && is_gimple_min_invariant (vr1min)
5993 && vrp_operand_equal_p (vr1min, vr1max))
5995 *vr0type = vr1type;
5996 *vr0min = vr1min;
5997 *vr0max = vr1max;
6002 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6003 in *VR0. This may not be the smallest possible such range. */
6005 void
6006 value_range::intersect_helper (value_range *vr0, const value_range *vr1)
6008 /* If either range is VR_VARYING the other one wins. */
6009 if (vr1->varying_p ())
6010 return;
6011 if (vr0->varying_p ())
6013 vr0->deep_copy (vr1);
6014 return;
6017 /* When either range is VR_UNDEFINED the resulting range is
6018 VR_UNDEFINED, too. */
6019 if (vr0->undefined_p ())
6020 return;
6021 if (vr1->undefined_p ())
6023 vr0->set_undefined ();
6024 return;
6027 /* Save the original vr0 so we can return it as conservative intersection
6028 result when our worker turns things to varying. */
6029 value_range saved (*vr0);
6031 value_range_kind vr0type = vr0->kind ();
6032 tree vr0min = vr0->min ();
6033 tree vr0max = vr0->max ();
6034 intersect_ranges (&vr0type, &vr0min, &vr0max,
6035 vr1->kind (), vr1->min (), vr1->max ());
6036 /* Make sure to canonicalize the result though as the inversion of a
6037 VR_RANGE can still be a VR_RANGE. */
6038 vr0->set_and_canonicalize (vr0type, vr0min, vr0max, vr0->m_equiv);
6039 /* If that failed, use the saved original VR0. */
6040 if (vr0->varying_p ())
6042 *vr0 = saved;
6043 return;
6045 /* If the result is VR_UNDEFINED there is no need to mess with
6046 the equivalencies. */
6047 if (vr0->undefined_p ())
6048 return;
6050 /* The resulting set of equivalences for range intersection is the union of
6051 the two sets. */
6052 if (vr0->m_equiv && vr1->m_equiv && vr0->m_equiv != vr1->m_equiv)
6053 bitmap_ior_into (vr0->m_equiv, vr1->m_equiv);
6054 else if (vr1->m_equiv && !vr0->m_equiv)
6056 /* All equivalence bitmaps are allocated from the same obstack. So
6057 we can use the obstack associated with VR to allocate vr0->equiv. */
6058 vr0->m_equiv = BITMAP_ALLOC (vr1->m_equiv->obstack);
6059 bitmap_copy (m_equiv, vr1->m_equiv);
6063 void
6064 value_range::intersect (const value_range *other)
6066 if (dump_file && (dump_flags & TDF_DETAILS))
6068 fprintf (dump_file, "Intersecting\n ");
6069 dump_value_range (dump_file, this);
6070 fprintf (dump_file, "\nand\n ");
6071 dump_value_range (dump_file, other);
6072 fprintf (dump_file, "\n");
6074 intersect_helper (this, other);
6075 if (dump_file && (dump_flags & TDF_DETAILS))
6077 fprintf (dump_file, "to\n ");
6078 dump_value_range (dump_file, this);
6079 fprintf (dump_file, "\n");
6083 /* Meet operation for value ranges. Given two value ranges VR0 and
6084 VR1, store in VR0 a range that contains both VR0 and VR1. This
6085 may not be the smallest possible such range. */
6087 void
6088 value_range_base::union_ (const value_range_base *other)
6090 if (other->undefined_p ())
6092 /* this already has the resulting range. */
6093 return;
6096 if (this->undefined_p ())
6098 *this = *other;
6099 return;
6102 if (this->varying_p ())
6104 /* Nothing to do. VR0 already has the resulting range. */
6105 return;
6108 if (other->varying_p ())
6110 this->set_varying ();
6111 return;
6114 value_range saved (*this);
6115 value_range_kind vr0type = this->kind ();
6116 tree vr0min = this->min ();
6117 tree vr0max = this->max ();
6118 union_ranges (&vr0type, &vr0min, &vr0max,
6119 other->kind (), other->min (), other->max ());
6120 *this = value_range_base (vr0type, vr0min, vr0max);
6121 if (this->varying_p ())
6123 /* Failed to find an efficient meet. Before giving up and setting
6124 the result to VARYING, see if we can at least derive a useful
6125 anti-range. */
6126 if (range_includes_zero_p (&saved) == 0
6127 && range_includes_zero_p (other) == 0)
6129 tree zero = build_int_cst (saved.type (), 0);
6130 *this = value_range_base (VR_ANTI_RANGE, zero, zero);
6131 return;
6134 this->set_varying ();
6135 return;
6137 this->set_and_canonicalize (this->kind (), this->min (), this->max ());
6140 /* Meet operation for value ranges. Given two value ranges VR0 and
6141 VR1, store in VR0 a range that contains both VR0 and VR1. This
6142 may not be the smallest possible such range. */
6144 void
6145 value_range::union_helper (value_range *vr0, const value_range *vr1)
6147 if (vr1->undefined_p ())
6149 /* VR0 already has the resulting range. */
6150 return;
6153 if (vr0->undefined_p ())
6155 vr0->deep_copy (vr1);
6156 return;
6159 if (vr0->varying_p ())
6161 /* Nothing to do. VR0 already has the resulting range. */
6162 return;
6165 if (vr1->varying_p ())
6167 vr0->set_varying ();
6168 return;
6171 value_range saved (*vr0);
6172 value_range_kind vr0type = vr0->kind ();
6173 tree vr0min = vr0->min ();
6174 tree vr0max = vr0->max ();
6175 union_ranges (&vr0type, &vr0min, &vr0max,
6176 vr1->kind (), vr1->min (), vr1->max ());
6177 *vr0 = value_range (vr0type, vr0min, vr0max);
6178 if (vr0->varying_p ())
6180 /* Failed to find an efficient meet. Before giving up and setting
6181 the result to VARYING, see if we can at least derive a useful
6182 anti-range. */
6183 if (range_includes_zero_p (&saved) == 0
6184 && range_includes_zero_p (vr1) == 0)
6186 set_value_range_to_nonnull (vr0, saved.type ());
6188 /* Since this meet operation did not result from the meeting of
6189 two equivalent names, VR0 cannot have any equivalences. */
6190 if (vr0->m_equiv)
6191 bitmap_clear (vr0->m_equiv);
6192 return;
6195 vr0->set_varying ();
6196 return;
6198 vr0->set_and_canonicalize (vr0->kind (), vr0->min (), vr0->max (),
6199 vr0->equiv ());
6200 if (vr0->varying_p ())
6201 return;
6203 /* The resulting set of equivalences is always the intersection of
6204 the two sets. */
6205 if (vr0->m_equiv && vr1->m_equiv && vr0->m_equiv != vr1->m_equiv)
6206 bitmap_and_into (vr0->m_equiv, vr1->m_equiv);
6207 else if (vr0->m_equiv && !vr1->m_equiv)
6208 bitmap_clear (vr0->m_equiv);
6211 void
6212 value_range::union_ (const value_range *other)
6214 if (dump_file && (dump_flags & TDF_DETAILS))
6216 fprintf (dump_file, "Meeting\n ");
6217 dump_value_range (dump_file, this);
6218 fprintf (dump_file, "\nand\n ");
6219 dump_value_range (dump_file, other);
6220 fprintf (dump_file, "\n");
6222 union_helper (this, other);
6223 if (dump_file && (dump_flags & TDF_DETAILS))
6225 fprintf (dump_file, "to\n ");
6226 dump_value_range (dump_file, this);
6227 fprintf (dump_file, "\n");
6231 /* Visit all arguments for PHI node PHI that flow through executable
6232 edges. If a valid value range can be derived from all the incoming
6233 value ranges, set a new range for the LHS of PHI. */
6235 enum ssa_prop_result
6236 vrp_prop::visit_phi (gphi *phi)
6238 tree lhs = PHI_RESULT (phi);
6239 value_range vr_result;
6240 extract_range_from_phi_node (phi, &vr_result);
6241 if (update_value_range (lhs, &vr_result))
6243 if (dump_file && (dump_flags & TDF_DETAILS))
6245 fprintf (dump_file, "Found new range for ");
6246 print_generic_expr (dump_file, lhs);
6247 fprintf (dump_file, ": ");
6248 dump_value_range (dump_file, &vr_result);
6249 fprintf (dump_file, "\n");
6252 if (vr_result.varying_p ())
6253 return SSA_PROP_VARYING;
6255 return SSA_PROP_INTERESTING;
6258 /* Nothing changed, don't add outgoing edges. */
6259 return SSA_PROP_NOT_INTERESTING;
6262 class vrp_folder : public substitute_and_fold_engine
6264 public:
6265 tree get_value (tree) FINAL OVERRIDE;
6266 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6267 bool fold_predicate_in (gimple_stmt_iterator *);
6269 class vr_values *vr_values;
6271 /* Delegators. */
6272 tree vrp_evaluate_conditional (tree_code code, tree op0,
6273 tree op1, gimple *stmt)
6274 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6275 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6276 { return vr_values->simplify_stmt_using_ranges (gsi); }
6277 tree op_with_constant_singleton_value_range (tree op)
6278 { return vr_values->op_with_constant_singleton_value_range (op); }
6281 /* If the statement pointed by SI has a predicate whose value can be
6282 computed using the value range information computed by VRP, compute
6283 its value and return true. Otherwise, return false. */
6285 bool
6286 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6288 bool assignment_p = false;
6289 tree val;
6290 gimple *stmt = gsi_stmt (*si);
6292 if (is_gimple_assign (stmt)
6293 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6295 assignment_p = true;
6296 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6297 gimple_assign_rhs1 (stmt),
6298 gimple_assign_rhs2 (stmt),
6299 stmt);
6301 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6302 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6303 gimple_cond_lhs (cond_stmt),
6304 gimple_cond_rhs (cond_stmt),
6305 stmt);
6306 else
6307 return false;
6309 if (val)
6311 if (assignment_p)
6312 val = fold_convert (gimple_expr_type (stmt), val);
6314 if (dump_file)
6316 fprintf (dump_file, "Folding predicate ");
6317 print_gimple_expr (dump_file, stmt, 0);
6318 fprintf (dump_file, " to ");
6319 print_generic_expr (dump_file, val);
6320 fprintf (dump_file, "\n");
6323 if (is_gimple_assign (stmt))
6324 gimple_assign_set_rhs_from_tree (si, val);
6325 else
6327 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6328 gcond *cond_stmt = as_a <gcond *> (stmt);
6329 if (integer_zerop (val))
6330 gimple_cond_make_false (cond_stmt);
6331 else if (integer_onep (val))
6332 gimple_cond_make_true (cond_stmt);
6333 else
6334 gcc_unreachable ();
6337 return true;
6340 return false;
6343 /* Callback for substitute_and_fold folding the stmt at *SI. */
6345 bool
6346 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6348 if (fold_predicate_in (si))
6349 return true;
6351 return simplify_stmt_using_ranges (si);
6354 /* If OP has a value range with a single constant value return that,
6355 otherwise return NULL_TREE. This returns OP itself if OP is a
6356 constant.
6358 Implemented as a pure wrapper right now, but this will change. */
6360 tree
6361 vrp_folder::get_value (tree op)
6363 return op_with_constant_singleton_value_range (op);
6366 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6367 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6368 BB. If no such ASSERT_EXPR is found, return OP. */
6370 static tree
6371 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6373 imm_use_iterator imm_iter;
6374 gimple *use_stmt;
6375 use_operand_p use_p;
6377 if (TREE_CODE (op) == SSA_NAME)
6379 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6381 use_stmt = USE_STMT (use_p);
6382 if (use_stmt != stmt
6383 && gimple_assign_single_p (use_stmt)
6384 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6385 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6386 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6387 return gimple_assign_lhs (use_stmt);
6390 return op;
6393 /* A hack. */
6394 static class vr_values *x_vr_values;
6396 /* A trivial wrapper so that we can present the generic jump threading
6397 code with a simple API for simplifying statements. STMT is the
6398 statement we want to simplify, WITHIN_STMT provides the location
6399 for any overflow warnings. */
6401 static tree
6402 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6403 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6404 basic_block bb)
6406 /* First see if the conditional is in the hash table. */
6407 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6408 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6409 return cached_lhs;
6411 vr_values *vr_values = x_vr_values;
6412 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6414 tree op0 = gimple_cond_lhs (cond_stmt);
6415 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6417 tree op1 = gimple_cond_rhs (cond_stmt);
6418 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6420 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6421 op0, op1, within_stmt);
6424 /* We simplify a switch statement by trying to determine which case label
6425 will be taken. If we are successful then we return the corresponding
6426 CASE_LABEL_EXPR. */
6427 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6429 tree op = gimple_switch_index (switch_stmt);
6430 if (TREE_CODE (op) != SSA_NAME)
6431 return NULL_TREE;
6433 op = lhs_of_dominating_assert (op, bb, stmt);
6435 const value_range *vr = vr_values->get_value_range (op);
6436 if (vr->undefined_p ()
6437 || vr->varying_p ()
6438 || vr->symbolic_p ())
6439 return NULL_TREE;
6441 if (vr->kind () == VR_RANGE)
6443 size_t i, j;
6444 /* Get the range of labels that contain a part of the operand's
6445 value range. */
6446 find_case_label_range (switch_stmt, vr->min (), vr->max (), &i, &j);
6448 /* Is there only one such label? */
6449 if (i == j)
6451 tree label = gimple_switch_label (switch_stmt, i);
6453 /* The i'th label will be taken only if the value range of the
6454 operand is entirely within the bounds of this label. */
6455 if (CASE_HIGH (label) != NULL_TREE
6456 ? (tree_int_cst_compare (CASE_LOW (label), vr->min ()) <= 0
6457 && tree_int_cst_compare (CASE_HIGH (label),
6458 vr->max ()) >= 0)
6459 : (tree_int_cst_equal (CASE_LOW (label), vr->min ())
6460 && tree_int_cst_equal (vr->min (), vr->max ())))
6461 return label;
6464 /* If there are no such labels then the default label will be
6465 taken. */
6466 if (i > j)
6467 return gimple_switch_label (switch_stmt, 0);
6470 if (vr->kind () == VR_ANTI_RANGE)
6472 unsigned n = gimple_switch_num_labels (switch_stmt);
6473 tree min_label = gimple_switch_label (switch_stmt, 1);
6474 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6476 /* The default label will be taken only if the anti-range of the
6477 operand is entirely outside the bounds of all the (non-default)
6478 case labels. */
6479 if (tree_int_cst_compare (vr->min (), CASE_LOW (min_label)) <= 0
6480 && (CASE_HIGH (max_label) != NULL_TREE
6481 ? tree_int_cst_compare (vr->max (),
6482 CASE_HIGH (max_label)) >= 0
6483 : tree_int_cst_compare (vr->max (),
6484 CASE_LOW (max_label)) >= 0))
6485 return gimple_switch_label (switch_stmt, 0);
6488 return NULL_TREE;
6491 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6493 tree lhs = gimple_assign_lhs (assign_stmt);
6494 if (TREE_CODE (lhs) == SSA_NAME
6495 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6496 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6497 && stmt_interesting_for_vrp (stmt))
6499 edge dummy_e;
6500 tree dummy_tree;
6501 value_range new_vr;
6502 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6503 &dummy_tree, &new_vr);
6504 tree singleton;
6505 if (new_vr.singleton_p (&singleton))
6506 return singleton;
6510 return NULL_TREE;
6513 class vrp_dom_walker : public dom_walker
6515 public:
6516 vrp_dom_walker (cdi_direction direction,
6517 class const_and_copies *const_and_copies,
6518 class avail_exprs_stack *avail_exprs_stack)
6519 : dom_walker (direction, REACHABLE_BLOCKS),
6520 m_const_and_copies (const_and_copies),
6521 m_avail_exprs_stack (avail_exprs_stack),
6522 m_dummy_cond (NULL) {}
6524 virtual edge before_dom_children (basic_block);
6525 virtual void after_dom_children (basic_block);
6527 class vr_values *vr_values;
6529 private:
6530 class const_and_copies *m_const_and_copies;
6531 class avail_exprs_stack *m_avail_exprs_stack;
6533 gcond *m_dummy_cond;
6537 /* Called before processing dominator children of BB. We want to look
6538 at ASSERT_EXPRs and record information from them in the appropriate
6539 tables.
6541 We could look at other statements here. It's not seen as likely
6542 to significantly increase the jump threads we discover. */
6544 edge
6545 vrp_dom_walker::before_dom_children (basic_block bb)
6547 gimple_stmt_iterator gsi;
6549 m_avail_exprs_stack->push_marker ();
6550 m_const_and_copies->push_marker ();
6551 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6553 gimple *stmt = gsi_stmt (gsi);
6554 if (gimple_assign_single_p (stmt)
6555 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6557 tree rhs1 = gimple_assign_rhs1 (stmt);
6558 tree cond = TREE_OPERAND (rhs1, 1);
6559 tree inverted = invert_truthvalue (cond);
6560 vec<cond_equivalence> p;
6561 p.create (3);
6562 record_conditions (&p, cond, inverted);
6563 for (unsigned int i = 0; i < p.length (); i++)
6564 m_avail_exprs_stack->record_cond (&p[i]);
6566 tree lhs = gimple_assign_lhs (stmt);
6567 m_const_and_copies->record_const_or_copy (lhs,
6568 TREE_OPERAND (rhs1, 0));
6569 p.release ();
6570 continue;
6572 break;
6574 return NULL;
6577 /* Called after processing dominator children of BB. This is where we
6578 actually call into the threader. */
6579 void
6580 vrp_dom_walker::after_dom_children (basic_block bb)
6582 if (!m_dummy_cond)
6583 m_dummy_cond = gimple_build_cond (NE_EXPR,
6584 integer_zero_node, integer_zero_node,
6585 NULL, NULL);
6587 x_vr_values = vr_values;
6588 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6589 m_avail_exprs_stack, NULL,
6590 simplify_stmt_for_jump_threading);
6591 x_vr_values = NULL;
6593 m_avail_exprs_stack->pop_to_marker ();
6594 m_const_and_copies->pop_to_marker ();
6597 /* Blocks which have more than one predecessor and more than
6598 one successor present jump threading opportunities, i.e.,
6599 when the block is reached from a specific predecessor, we
6600 may be able to determine which of the outgoing edges will
6601 be traversed. When this optimization applies, we are able
6602 to avoid conditionals at runtime and we may expose secondary
6603 optimization opportunities.
6605 This routine is effectively a driver for the generic jump
6606 threading code. It basically just presents the generic code
6607 with edges that may be suitable for jump threading.
6609 Unlike DOM, we do not iterate VRP if jump threading was successful.
6610 While iterating may expose new opportunities for VRP, it is expected
6611 those opportunities would be very limited and the compile time cost
6612 to expose those opportunities would be significant.
6614 As jump threading opportunities are discovered, they are registered
6615 for later realization. */
6617 static void
6618 identify_jump_threads (class vr_values *vr_values)
6620 /* Ugh. When substituting values earlier in this pass we can
6621 wipe the dominance information. So rebuild the dominator
6622 information as we need it within the jump threading code. */
6623 calculate_dominance_info (CDI_DOMINATORS);
6625 /* We do not allow VRP information to be used for jump threading
6626 across a back edge in the CFG. Otherwise it becomes too
6627 difficult to avoid eliminating loop exit tests. Of course
6628 EDGE_DFS_BACK is not accurate at this time so we have to
6629 recompute it. */
6630 mark_dfs_back_edges ();
6632 /* Allocate our unwinder stack to unwind any temporary equivalences
6633 that might be recorded. */
6634 const_and_copies *equiv_stack = new const_and_copies ();
6636 hash_table<expr_elt_hasher> *avail_exprs
6637 = new hash_table<expr_elt_hasher> (1024);
6638 avail_exprs_stack *avail_exprs_stack
6639 = new class avail_exprs_stack (avail_exprs);
6641 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6642 walker.vr_values = vr_values;
6643 walker.walk (cfun->cfg->x_entry_block_ptr);
6645 /* We do not actually update the CFG or SSA graphs at this point as
6646 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6647 handle ASSERT_EXPRs gracefully. */
6648 delete equiv_stack;
6649 delete avail_exprs;
6650 delete avail_exprs_stack;
6653 /* Traverse all the blocks folding conditionals with known ranges. */
6655 void
6656 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6658 size_t i;
6660 /* We have completed propagating through the lattice. */
6661 vr_values.set_lattice_propagation_complete ();
6663 if (dump_file)
6665 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6666 vr_values.dump_all_value_ranges (dump_file);
6667 fprintf (dump_file, "\n");
6670 /* Set value range to non pointer SSA_NAMEs. */
6671 for (i = 0; i < num_ssa_names; i++)
6673 tree name = ssa_name (i);
6674 if (!name)
6675 continue;
6677 const value_range *vr = get_value_range (name);
6678 if (!name || !vr->constant_p ())
6679 continue;
6681 if (POINTER_TYPE_P (TREE_TYPE (name))
6682 && range_includes_zero_p (vr) == 0)
6683 set_ptr_nonnull (name);
6684 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6685 set_range_info (name, *vr);
6688 /* If we're checking array refs, we want to merge information on
6689 the executability of each edge between vrp_folder and the
6690 check_array_bounds_dom_walker: each can clear the
6691 EDGE_EXECUTABLE flag on edges, in different ways.
6693 Hence, if we're going to call check_all_array_refs, set
6694 the flag on every edge now, rather than in
6695 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6696 it from some edges. */
6697 if (warn_array_bounds && warn_array_bounds_p)
6698 set_all_edges_as_executable (cfun);
6700 class vrp_folder vrp_folder;
6701 vrp_folder.vr_values = &vr_values;
6702 vrp_folder.substitute_and_fold ();
6704 if (warn_array_bounds && warn_array_bounds_p)
6705 check_all_array_refs ();
6708 /* Main entry point to VRP (Value Range Propagation). This pass is
6709 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6710 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6711 Programming Language Design and Implementation, pp. 67-78, 1995.
6712 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6714 This is essentially an SSA-CCP pass modified to deal with ranges
6715 instead of constants.
6717 While propagating ranges, we may find that two or more SSA name
6718 have equivalent, though distinct ranges. For instance,
6720 1 x_9 = p_3->a;
6721 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6722 3 if (p_4 == q_2)
6723 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6724 5 endif
6725 6 if (q_2)
6727 In the code above, pointer p_5 has range [q_2, q_2], but from the
6728 code we can also determine that p_5 cannot be NULL and, if q_2 had
6729 a non-varying range, p_5's range should also be compatible with it.
6731 These equivalences are created by two expressions: ASSERT_EXPR and
6732 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6733 result of another assertion, then we can use the fact that p_5 and
6734 p_4 are equivalent when evaluating p_5's range.
6736 Together with value ranges, we also propagate these equivalences
6737 between names so that we can take advantage of information from
6738 multiple ranges when doing final replacement. Note that this
6739 equivalency relation is transitive but not symmetric.
6741 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6742 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6743 in contexts where that assertion does not hold (e.g., in line 6).
6745 TODO, the main difference between this pass and Patterson's is that
6746 we do not propagate edge probabilities. We only compute whether
6747 edges can be taken or not. That is, instead of having a spectrum
6748 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6749 DON'T KNOW. In the future, it may be worthwhile to propagate
6750 probabilities to aid branch prediction. */
6752 static unsigned int
6753 execute_vrp (bool warn_array_bounds_p)
6756 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6757 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6758 scev_initialize ();
6760 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6761 Inserting assertions may split edges which will invalidate
6762 EDGE_DFS_BACK. */
6763 insert_range_assertions ();
6765 threadedge_initialize_values ();
6767 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6768 mark_dfs_back_edges ();
6770 class vrp_prop vrp_prop;
6771 vrp_prop.vrp_initialize ();
6772 vrp_prop.ssa_propagate ();
6773 vrp_prop.vrp_finalize (warn_array_bounds_p);
6775 /* We must identify jump threading opportunities before we release
6776 the datastructures built by VRP. */
6777 identify_jump_threads (&vrp_prop.vr_values);
6779 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6780 was set by a type conversion can often be rewritten to use the
6781 RHS of the type conversion.
6783 However, doing so inhibits jump threading through the comparison.
6784 So that transformation is not performed until after jump threading
6785 is complete. */
6786 basic_block bb;
6787 FOR_EACH_BB_FN (bb, cfun)
6789 gimple *last = last_stmt (bb);
6790 if (last && gimple_code (last) == GIMPLE_COND)
6791 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6794 free_numbers_of_iterations_estimates (cfun);
6796 /* ASSERT_EXPRs must be removed before finalizing jump threads
6797 as finalizing jump threads calls the CFG cleanup code which
6798 does not properly handle ASSERT_EXPRs. */
6799 remove_range_assertions ();
6801 /* If we exposed any new variables, go ahead and put them into
6802 SSA form now, before we handle jump threading. This simplifies
6803 interactions between rewriting of _DECL nodes into SSA form
6804 and rewriting SSA_NAME nodes into SSA form after block
6805 duplication and CFG manipulation. */
6806 update_ssa (TODO_update_ssa);
6808 /* We identified all the jump threading opportunities earlier, but could
6809 not transform the CFG at that time. This routine transforms the
6810 CFG and arranges for the dominator tree to be rebuilt if necessary.
6812 Note the SSA graph update will occur during the normal TODO
6813 processing by the pass manager. */
6814 thread_through_all_blocks (false);
6816 vrp_prop.vr_values.cleanup_edges_and_switches ();
6817 threadedge_finalize_values ();
6819 scev_finalize ();
6820 loop_optimizer_finalize ();
6821 return 0;
6824 namespace {
6826 const pass_data pass_data_vrp =
6828 GIMPLE_PASS, /* type */
6829 "vrp", /* name */
6830 OPTGROUP_NONE, /* optinfo_flags */
6831 TV_TREE_VRP, /* tv_id */
6832 PROP_ssa, /* properties_required */
6833 0, /* properties_provided */
6834 0, /* properties_destroyed */
6835 0, /* todo_flags_start */
6836 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6839 class pass_vrp : public gimple_opt_pass
6841 public:
6842 pass_vrp (gcc::context *ctxt)
6843 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6846 /* opt_pass methods: */
6847 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6848 void set_pass_param (unsigned int n, bool param)
6850 gcc_assert (n == 0);
6851 warn_array_bounds_p = param;
6853 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6854 virtual unsigned int execute (function *)
6855 { return execute_vrp (warn_array_bounds_p); }
6857 private:
6858 bool warn_array_bounds_p;
6859 }; // class pass_vrp
6861 } // anon namespace
6863 gimple_opt_pass *
6864 make_pass_vrp (gcc::context *ctxt)
6866 return new pass_vrp (ctxt);
6870 /* Worker for determine_value_range. */
6872 static void
6873 determine_value_range_1 (value_range *vr, tree expr)
6875 if (BINARY_CLASS_P (expr))
6877 value_range vr0, vr1;
6878 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6879 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6880 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6881 &vr0, &vr1);
6883 else if (UNARY_CLASS_P (expr))
6885 value_range vr0;
6886 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6887 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6888 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6890 else if (TREE_CODE (expr) == INTEGER_CST)
6891 set_value_range_to_value (vr, expr, NULL);
6892 else
6894 value_range_kind kind;
6895 wide_int min, max;
6896 /* For SSA names try to extract range info computed by VRP. Otherwise
6897 fall back to varying. */
6898 if (TREE_CODE (expr) == SSA_NAME
6899 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6900 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6901 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6902 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6903 else
6904 vr->set_varying ();
6908 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6909 the determined range type. */
6911 value_range_kind
6912 determine_value_range (tree expr, wide_int *min, wide_int *max)
6914 value_range vr;
6915 determine_value_range_1 (&vr, expr);
6916 if (vr.constant_p ())
6918 *min = wi::to_wide (vr.min ());
6919 *max = wi::to_wide (vr.max ());
6920 return vr.kind ();
6923 return VR_VARYING;