PR rtl-optimization/87817
[official-gcc.git] / gcc / tree-vrp.c
blobf498386e8eb0144712235163858542ae76b9ba24
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 set, but keep the equivalences in place. */
139 void
140 value_range::update (value_range_kind kind, tree min, tree max)
142 set (kind, min, max,
143 (kind != VR_UNDEFINED && kind != VR_VARYING) ? m_equiv : NULL);
146 /* Copy value_range in FROM into THIS while avoiding bitmap sharing.
148 Note: The code that avoids the bitmap sharing looks at the existing
149 this->m_equiv, so this function cannot be used to initalize an
150 object. Use the constructors for initialization. */
152 void
153 value_range::deep_copy (const value_range *from)
155 set (from->m_kind, from->min (), from->max (), from->m_equiv);
158 void
159 value_range::move (value_range *from)
161 set (from->m_kind, from->min (), from->max ());
162 m_equiv = from->m_equiv;
163 from->m_equiv = NULL;
166 /* Check the validity of the range. */
168 void
169 value_range_base::check ()
171 switch (m_kind)
173 case VR_RANGE:
174 case VR_ANTI_RANGE:
176 int cmp;
178 gcc_assert (m_min && m_max);
180 gcc_assert (!TREE_OVERFLOW_P (m_min) && !TREE_OVERFLOW_P (m_max));
182 /* Creating ~[-MIN, +MAX] is stupid because that would be
183 the empty set. */
184 if (INTEGRAL_TYPE_P (TREE_TYPE (m_min)) && m_kind == VR_ANTI_RANGE)
185 gcc_assert (!vrp_val_is_min (m_min) || !vrp_val_is_max (m_max));
187 cmp = compare_values (m_min, m_max);
188 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
189 break;
191 case VR_UNDEFINED:
192 case VR_VARYING:
193 gcc_assert (!min () && !max ());
194 break;
195 default:
196 gcc_unreachable ();
200 void
201 value_range::check ()
203 value_range_base::check ();
204 switch (m_kind)
206 case VR_UNDEFINED:
207 case VR_VARYING:
208 gcc_assert (!m_equiv || bitmap_empty_p (m_equiv));
209 default:;
213 /* Returns TRUE if THIS == OTHER. Ignores the equivalence bitmap if
214 IGNORE_EQUIVS is TRUE. */
216 bool
217 value_range::equal_p (const value_range &other, bool ignore_equivs) const
219 return (ignore_equivs_equal_p (other)
220 && (ignore_equivs
221 || vrp_bitmap_equal_p (m_equiv, other.m_equiv)));
224 /* Return equality while ignoring equivalence bitmap. */
226 bool
227 value_range_base::ignore_equivs_equal_p (const value_range_base &other) const
229 return (m_kind == other.m_kind
230 && vrp_operand_equal_p (m_min, other.m_min)
231 && vrp_operand_equal_p (m_max, other.m_max));
234 bool
235 value_range::operator== (const value_range &other) const
237 return equal_p (other, /*ignore_equivs=*/false);
240 bool
241 value_range::operator!= (const value_range &other) const
243 return !(*this == other);
246 /* Return TRUE if this is a symbolic range. */
248 bool
249 value_range_base::symbolic_p () const
251 return (!varying_p ()
252 && !undefined_p ()
253 && (!is_gimple_min_invariant (m_min)
254 || !is_gimple_min_invariant (m_max)));
257 /* NOTE: This is not the inverse of symbolic_p because the range
258 could also be varying or undefined. Ideally they should be inverse
259 of each other, with varying only applying to symbolics. Varying of
260 constants would be represented as [-MIN, +MAX]. */
262 bool
263 value_range_base::constant_p () const
265 return (!varying_p ()
266 && !undefined_p ()
267 && TREE_CODE (m_min) == INTEGER_CST
268 && TREE_CODE (m_max) == INTEGER_CST);
271 void
272 value_range_base::set_undefined ()
274 set (VR_UNDEFINED, NULL, NULL);
277 void
278 value_range::set_undefined ()
280 set (VR_UNDEFINED, NULL, NULL, NULL);
283 void
284 value_range_base::set_varying ()
286 set (VR_VARYING, NULL, NULL);
289 void
290 value_range::set_varying ()
292 set (VR_VARYING, NULL, NULL, NULL);
295 /* Return TRUE if it is possible that range contains VAL. */
297 bool
298 value_range_base::may_contain_p (tree val) const
300 if (varying_p ())
301 return true;
303 if (undefined_p ())
304 return true;
306 if (m_kind == VR_ANTI_RANGE)
308 int res = value_inside_range (val, min (), max ());
309 return res == 0 || res == -2;
311 return value_inside_range (val, min (), max ()) != 0;
314 void
315 value_range::equiv_clear ()
317 if (m_equiv)
318 bitmap_clear (m_equiv);
321 /* Add VAR and VAR's equivalence set (VAR_VR) to the equivalence
322 bitmap. If no equivalence table has been created, OBSTACK is the
323 obstack to use (NULL for the default obstack).
325 This is the central point where equivalence processing can be
326 turned on/off. */
328 void
329 value_range::equiv_add (const_tree var,
330 const value_range *var_vr,
331 bitmap_obstack *obstack)
333 if (!m_equiv)
334 m_equiv = BITMAP_ALLOC (obstack);
335 unsigned ver = SSA_NAME_VERSION (var);
336 bitmap_set_bit (m_equiv, ver);
337 if (var_vr && var_vr->m_equiv)
338 bitmap_ior_into (m_equiv, var_vr->m_equiv);
341 /* If range is a singleton, place it in RESULT and return TRUE.
342 Note: A singleton can be any gimple invariant, not just constants.
343 So, [&x, &x] counts as a singleton. */
345 bool
346 value_range_base::singleton_p (tree *result) const
348 if (m_kind == VR_RANGE
349 && vrp_operand_equal_p (min (), max ())
350 && is_gimple_min_invariant (min ()))
352 if (result)
353 *result = min ();
354 return true;
356 return false;
359 tree
360 value_range_base::type () const
362 /* Types are only valid for VR_RANGE and VR_ANTI_RANGE, which are
363 known to have non-zero min/max. */
364 gcc_assert (min ());
365 return TREE_TYPE (min ());
368 void
369 value_range_base::dump (FILE *file) const
371 if (undefined_p ())
372 fprintf (file, "UNDEFINED");
373 else if (m_kind == VR_RANGE || m_kind == VR_ANTI_RANGE)
375 tree ttype = type ();
377 print_generic_expr (file, ttype);
378 fprintf (file, " ");
380 fprintf (file, "%s[", (m_kind == VR_ANTI_RANGE) ? "~" : "");
382 if (INTEGRAL_TYPE_P (ttype)
383 && !TYPE_UNSIGNED (ttype)
384 && vrp_val_is_min (min ())
385 && TYPE_PRECISION (ttype) != 1)
386 fprintf (file, "-INF");
387 else
388 print_generic_expr (file, min ());
390 fprintf (file, ", ");
392 if (INTEGRAL_TYPE_P (ttype)
393 && vrp_val_is_max (max ())
394 && TYPE_PRECISION (ttype) != 1)
395 fprintf (file, "+INF");
396 else
397 print_generic_expr (file, max ());
399 fprintf (file, "]");
401 else if (varying_p ())
402 fprintf (file, "VARYING");
403 else
404 gcc_unreachable ();
407 void
408 value_range::dump (FILE *file) const
410 value_range_base::dump (file);
411 if ((m_kind == VR_RANGE || m_kind == VR_ANTI_RANGE)
412 && m_equiv)
414 bitmap_iterator bi;
415 unsigned i, c = 0;
417 fprintf (file, " EQUIVALENCES: { ");
419 EXECUTE_IF_SET_IN_BITMAP (m_equiv, 0, i, bi)
421 print_generic_expr (file, ssa_name (i));
422 fprintf (file, " ");
423 c++;
426 fprintf (file, "} (%u elements)", c);
430 void
431 dump_value_range (FILE *file, const value_range *vr)
433 if (!vr)
434 fprintf (file, "[]");
435 else
436 vr->dump (file);
439 void
440 dump_value_range (FILE *file, const value_range_base *vr)
442 if (!vr)
443 fprintf (file, "[]");
444 else
445 vr->dump (file);
448 DEBUG_FUNCTION void
449 debug (const value_range_base *vr)
451 dump_value_range (stderr, vr);
454 DEBUG_FUNCTION void
455 debug (const value_range_base &vr)
457 dump_value_range (stderr, &vr);
460 DEBUG_FUNCTION void
461 debug (const value_range *vr)
463 dump_value_range (stderr, vr);
466 DEBUG_FUNCTION void
467 debug (const value_range &vr)
469 dump_value_range (stderr, &vr);
472 /* Return true if the SSA name NAME is live on the edge E. */
474 static bool
475 live_on_edge (edge e, tree name)
477 return (live[e->dest->index]
478 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
481 /* Location information for ASSERT_EXPRs. Each instance of this
482 structure describes an ASSERT_EXPR for an SSA name. Since a single
483 SSA name may have more than one assertion associated with it, these
484 locations are kept in a linked list attached to the corresponding
485 SSA name. */
486 struct assert_locus
488 /* Basic block where the assertion would be inserted. */
489 basic_block bb;
491 /* Some assertions need to be inserted on an edge (e.g., assertions
492 generated by COND_EXPRs). In those cases, BB will be NULL. */
493 edge e;
495 /* Pointer to the statement that generated this assertion. */
496 gimple_stmt_iterator si;
498 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
499 enum tree_code comp_code;
501 /* Value being compared against. */
502 tree val;
504 /* Expression to compare. */
505 tree expr;
507 /* Next node in the linked list. */
508 assert_locus *next;
511 /* If bit I is present, it means that SSA name N_i has a list of
512 assertions that should be inserted in the IL. */
513 static bitmap need_assert_for;
515 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
516 holds a list of ASSERT_LOCUS_T nodes that describe where
517 ASSERT_EXPRs for SSA name N_I should be inserted. */
518 static assert_locus **asserts_for;
520 /* Return the maximum value for TYPE. */
522 tree
523 vrp_val_max (const_tree type)
525 if (!INTEGRAL_TYPE_P (type))
526 return NULL_TREE;
528 return TYPE_MAX_VALUE (type);
531 /* Return the minimum value for TYPE. */
533 tree
534 vrp_val_min (const_tree type)
536 if (!INTEGRAL_TYPE_P (type))
537 return NULL_TREE;
539 return TYPE_MIN_VALUE (type);
542 /* Return whether VAL is equal to the maximum value of its type.
543 We can't do a simple equality comparison with TYPE_MAX_VALUE because
544 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
545 is not == to the integer constant with the same value in the type. */
547 bool
548 vrp_val_is_max (const_tree val)
550 tree type_max = vrp_val_max (TREE_TYPE (val));
551 return (val == type_max
552 || (type_max != NULL_TREE
553 && operand_equal_p (val, type_max, 0)));
556 /* Return whether VAL is equal to the minimum value of its type. */
558 bool
559 vrp_val_is_min (const_tree val)
561 tree type_min = vrp_val_min (TREE_TYPE (val));
562 return (val == type_min
563 || (type_min != NULL_TREE
564 && operand_equal_p (val, type_min, 0)));
567 /* VR_TYPE describes a range with mininum value *MIN and maximum
568 value *MAX. Restrict the range to the set of values that have
569 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
570 return the new range type.
572 SGN gives the sign of the values described by the range. */
574 enum value_range_kind
575 intersect_range_with_nonzero_bits (enum value_range_kind vr_type,
576 wide_int *min, wide_int *max,
577 const wide_int &nonzero_bits,
578 signop sgn)
580 if (vr_type == VR_ANTI_RANGE)
582 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
583 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
584 to create an inclusive upper bound for A and an inclusive lower
585 bound for B. */
586 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
587 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
589 /* If the calculation of A_MAX wrapped, A is effectively empty
590 and A_MAX is the highest value that satisfies NONZERO_BITS.
591 Likewise if the calculation of B_MIN wrapped, B is effectively
592 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
593 bool a_empty = wi::ge_p (a_max, *min, sgn);
594 bool b_empty = wi::le_p (b_min, *max, sgn);
596 /* If both A and B are empty, there are no valid values. */
597 if (a_empty && b_empty)
598 return VR_UNDEFINED;
600 /* If exactly one of A or B is empty, return a VR_RANGE for the
601 other one. */
602 if (a_empty || b_empty)
604 *min = b_min;
605 *max = a_max;
606 gcc_checking_assert (wi::le_p (*min, *max, sgn));
607 return VR_RANGE;
610 /* Update the VR_ANTI_RANGE bounds. */
611 *min = a_max + 1;
612 *max = b_min - 1;
613 gcc_checking_assert (wi::le_p (*min, *max, sgn));
615 /* Now check whether the excluded range includes any values that
616 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
617 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
619 unsigned int precision = min->get_precision ();
620 *min = wi::min_value (precision, sgn);
621 *max = wi::max_value (precision, sgn);
622 vr_type = VR_RANGE;
625 if (vr_type == VR_RANGE)
627 *max = wi::round_down_for_mask (*max, nonzero_bits);
629 /* Check that the range contains at least one valid value. */
630 if (wi::gt_p (*min, *max, sgn))
631 return VR_UNDEFINED;
633 *min = wi::round_up_for_mask (*min, nonzero_bits);
634 gcc_checking_assert (wi::le_p (*min, *max, sgn));
636 return vr_type;
640 /* Set value range to the canonical form of {VRTYPE, MIN, MAX, EQUIV}.
641 This means adjusting VRTYPE, MIN and MAX representing the case of a
642 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
643 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
644 In corner cases where MAX+1 or MIN-1 wraps this will fall back
645 to varying.
646 This routine exists to ease canonicalization in the case where we
647 extract ranges from var + CST op limit. */
649 void
650 value_range_base::set_and_canonicalize (enum value_range_kind kind,
651 tree min, tree max)
653 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
654 if (kind == VR_UNDEFINED)
656 set_undefined ();
657 return;
659 else if (kind == VR_VARYING)
661 set_varying ();
662 return;
665 /* Nothing to canonicalize for symbolic ranges. */
666 if (TREE_CODE (min) != INTEGER_CST
667 || TREE_CODE (max) != INTEGER_CST)
669 set (kind, min, max);
670 return;
673 /* Wrong order for min and max, to swap them and the VR type we need
674 to adjust them. */
675 if (tree_int_cst_lt (max, min))
677 tree one, tmp;
679 /* For one bit precision if max < min, then the swapped
680 range covers all values, so for VR_RANGE it is varying and
681 for VR_ANTI_RANGE empty range, so drop to varying as well. */
682 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
684 set_varying ();
685 return;
688 one = build_int_cst (TREE_TYPE (min), 1);
689 tmp = int_const_binop (PLUS_EXPR, max, one);
690 max = int_const_binop (MINUS_EXPR, min, one);
691 min = tmp;
693 /* There's one corner case, if we had [C+1, C] before we now have
694 that again. But this represents an empty value range, so drop
695 to varying in this case. */
696 if (tree_int_cst_lt (max, min))
698 set_varying ();
699 return;
702 kind = kind == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
705 /* Anti-ranges that can be represented as ranges should be so. */
706 if (kind == VR_ANTI_RANGE)
708 /* For -fstrict-enums we may receive out-of-range ranges so consider
709 values < -INF and values > INF as -INF/INF as well. */
710 tree type = TREE_TYPE (min);
711 bool is_min = (INTEGRAL_TYPE_P (type)
712 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
713 bool is_max = (INTEGRAL_TYPE_P (type)
714 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
716 if (is_min && is_max)
718 /* We cannot deal with empty ranges, drop to varying.
719 ??? This could be VR_UNDEFINED instead. */
720 set_varying ();
721 return;
723 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
724 && (is_min || is_max))
726 /* Non-empty boolean ranges can always be represented
727 as a singleton range. */
728 if (is_min)
729 min = max = vrp_val_max (TREE_TYPE (min));
730 else
731 min = max = vrp_val_min (TREE_TYPE (min));
732 kind = VR_RANGE;
734 else if (is_min
735 /* As a special exception preserve non-null ranges. */
736 && !(TYPE_UNSIGNED (TREE_TYPE (min))
737 && integer_zerop (max)))
739 tree one = build_int_cst (TREE_TYPE (max), 1);
740 min = int_const_binop (PLUS_EXPR, max, one);
741 max = vrp_val_max (TREE_TYPE (max));
742 kind = VR_RANGE;
744 else if (is_max)
746 tree one = build_int_cst (TREE_TYPE (min), 1);
747 max = int_const_binop (MINUS_EXPR, min, one);
748 min = vrp_val_min (TREE_TYPE (min));
749 kind = VR_RANGE;
753 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
754 to make sure VRP iteration terminates, otherwise we can get into
755 oscillations. */
757 set (kind, min, max);
760 void
761 value_range::set_and_canonicalize (enum value_range_kind kind,
762 tree min, tree max, bitmap equiv)
764 value_range_base::set_and_canonicalize (kind, min, max);
765 if (this->kind () == VR_RANGE || this->kind () == VR_ANTI_RANGE)
766 set_equiv (equiv);
767 else
768 equiv_clear ();
771 void
772 value_range_base::set (tree val)
774 gcc_assert (TREE_CODE (val) == SSA_NAME || is_gimple_min_invariant (val));
775 if (TREE_OVERFLOW_P (val))
776 val = drop_tree_overflow (val);
777 set (VR_RANGE, val, val);
780 void
781 value_range::set (tree val)
783 gcc_assert (TREE_CODE (val) == SSA_NAME || is_gimple_min_invariant (val));
784 if (TREE_OVERFLOW_P (val))
785 val = drop_tree_overflow (val);
786 set (VR_RANGE, val, val, NULL);
789 /* Set value range VR to a non-NULL range of type TYPE. */
791 void
792 value_range_base::set_nonnull (tree type)
794 tree zero = build_int_cst (type, 0);
795 set (VR_ANTI_RANGE, zero, zero);
798 void
799 value_range::set_nonnull (tree type)
801 tree zero = build_int_cst (type, 0);
802 set (VR_ANTI_RANGE, zero, zero, NULL);
805 /* Set value range VR to a NULL range of type TYPE. */
807 void
808 value_range_base::set_null (tree type)
810 set (build_int_cst (type, 0));
813 void
814 value_range::set_null (tree type)
816 set (build_int_cst (type, 0));
819 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
821 bool
822 vrp_operand_equal_p (const_tree val1, const_tree val2)
824 if (val1 == val2)
825 return true;
826 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
827 return false;
828 return true;
831 /* Return true, if the bitmaps B1 and B2 are equal. */
833 bool
834 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
836 return (b1 == b2
837 || ((!b1 || bitmap_empty_p (b1))
838 && (!b2 || bitmap_empty_p (b2)))
839 || (b1 && b2
840 && bitmap_equal_p (b1, b2)));
843 /* Return true if VR is [0, 0]. */
845 static inline bool
846 range_is_null (const value_range_base *vr)
848 return vr->zero_p ();
851 static inline bool
852 range_is_nonnull (const value_range_base *vr)
854 return (vr->kind () == VR_ANTI_RANGE
855 && vr->min () == vr->max ()
856 && integer_zerop (vr->min ()));
859 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
860 a singleton. */
862 bool
863 range_int_cst_p (const value_range_base *vr)
865 return (vr->kind () == VR_RANGE
866 && TREE_CODE (vr->min ()) == INTEGER_CST
867 && TREE_CODE (vr->max ()) == INTEGER_CST);
870 /* Return true if VR is a INTEGER_CST singleton. */
872 bool
873 range_int_cst_singleton_p (const value_range_base *vr)
875 return (range_int_cst_p (vr)
876 && tree_int_cst_equal (vr->min (), vr->max ()));
879 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
880 otherwise. We only handle additive operations and set NEG to true if the
881 symbol is negated and INV to the invariant part, if any. */
883 tree
884 get_single_symbol (tree t, bool *neg, tree *inv)
886 bool neg_;
887 tree inv_;
889 *inv = NULL_TREE;
890 *neg = false;
892 if (TREE_CODE (t) == PLUS_EXPR
893 || TREE_CODE (t) == POINTER_PLUS_EXPR
894 || TREE_CODE (t) == MINUS_EXPR)
896 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
898 neg_ = (TREE_CODE (t) == MINUS_EXPR);
899 inv_ = TREE_OPERAND (t, 0);
900 t = TREE_OPERAND (t, 1);
902 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
904 neg_ = false;
905 inv_ = TREE_OPERAND (t, 1);
906 t = TREE_OPERAND (t, 0);
908 else
909 return NULL_TREE;
911 else
913 neg_ = false;
914 inv_ = NULL_TREE;
917 if (TREE_CODE (t) == NEGATE_EXPR)
919 t = TREE_OPERAND (t, 0);
920 neg_ = !neg_;
923 if (TREE_CODE (t) != SSA_NAME)
924 return NULL_TREE;
926 if (inv_ && TREE_OVERFLOW_P (inv_))
927 inv_ = drop_tree_overflow (inv_);
929 *neg = neg_;
930 *inv = inv_;
931 return t;
934 /* The reverse operation: build a symbolic expression with TYPE
935 from symbol SYM, negated according to NEG, and invariant INV. */
937 static tree
938 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
940 const bool pointer_p = POINTER_TYPE_P (type);
941 tree t = sym;
943 if (neg)
944 t = build1 (NEGATE_EXPR, type, t);
946 if (integer_zerop (inv))
947 return t;
949 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
952 /* Return
953 1 if VAL < VAL2
954 0 if !(VAL < VAL2)
955 -2 if those are incomparable. */
957 operand_less_p (tree val, tree val2)
959 /* LT is folded faster than GE and others. Inline the common case. */
960 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
961 return tree_int_cst_lt (val, val2);
962 else
964 tree tcmp;
966 fold_defer_overflow_warnings ();
968 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
970 fold_undefer_and_ignore_overflow_warnings ();
972 if (!tcmp
973 || TREE_CODE (tcmp) != INTEGER_CST)
974 return -2;
976 if (!integer_zerop (tcmp))
977 return 1;
980 return 0;
983 /* Compare two values VAL1 and VAL2. Return
985 -2 if VAL1 and VAL2 cannot be compared at compile-time,
986 -1 if VAL1 < VAL2,
987 0 if VAL1 == VAL2,
988 +1 if VAL1 > VAL2, and
989 +2 if VAL1 != VAL2
991 This is similar to tree_int_cst_compare but supports pointer values
992 and values that cannot be compared at compile time.
994 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
995 true if the return value is only valid if we assume that signed
996 overflow is undefined. */
999 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1001 if (val1 == val2)
1002 return 0;
1004 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1005 both integers. */
1006 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1007 == POINTER_TYPE_P (TREE_TYPE (val2)));
1009 /* Convert the two values into the same type. This is needed because
1010 sizetype causes sign extension even for unsigned types. */
1011 val2 = fold_convert (TREE_TYPE (val1), val2);
1012 STRIP_USELESS_TYPE_CONVERSION (val2);
1014 const bool overflow_undefined
1015 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1016 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1017 tree inv1, inv2;
1018 bool neg1, neg2;
1019 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1020 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1022 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1023 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1024 if (sym1 && sym2)
1026 /* Both values must use the same name with the same sign. */
1027 if (sym1 != sym2 || neg1 != neg2)
1028 return -2;
1030 /* [-]NAME + CST == [-]NAME + CST. */
1031 if (inv1 == inv2)
1032 return 0;
1034 /* If overflow is defined we cannot simplify more. */
1035 if (!overflow_undefined)
1036 return -2;
1038 if (strict_overflow_p != NULL
1039 /* Symbolic range building sets TREE_NO_WARNING to declare
1040 that overflow doesn't happen. */
1041 && (!inv1 || !TREE_NO_WARNING (val1))
1042 && (!inv2 || !TREE_NO_WARNING (val2)))
1043 *strict_overflow_p = true;
1045 if (!inv1)
1046 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1047 if (!inv2)
1048 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1050 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
1051 TYPE_SIGN (TREE_TYPE (val1)));
1054 const bool cst1 = is_gimple_min_invariant (val1);
1055 const bool cst2 = is_gimple_min_invariant (val2);
1057 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1058 it might be possible to say something depending on the constants. */
1059 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1061 if (!overflow_undefined)
1062 return -2;
1064 if (strict_overflow_p != NULL
1065 /* Symbolic range building sets TREE_NO_WARNING to declare
1066 that overflow doesn't happen. */
1067 && (!sym1 || !TREE_NO_WARNING (val1))
1068 && (!sym2 || !TREE_NO_WARNING (val2)))
1069 *strict_overflow_p = true;
1071 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1072 tree cst = cst1 ? val1 : val2;
1073 tree inv = cst1 ? inv2 : inv1;
1075 /* Compute the difference between the constants. If it overflows or
1076 underflows, this means that we can trivially compare the NAME with
1077 it and, consequently, the two values with each other. */
1078 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
1079 if (wi::cmp (0, wi::to_wide (inv), sgn)
1080 != wi::cmp (diff, wi::to_wide (cst), sgn))
1082 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
1083 return cst1 ? res : -res;
1086 return -2;
1089 /* We cannot say anything more for non-constants. */
1090 if (!cst1 || !cst2)
1091 return -2;
1093 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1095 /* We cannot compare overflowed values. */
1096 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1097 return -2;
1099 if (TREE_CODE (val1) == INTEGER_CST
1100 && TREE_CODE (val2) == INTEGER_CST)
1101 return tree_int_cst_compare (val1, val2);
1103 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
1105 if (known_eq (wi::to_poly_widest (val1),
1106 wi::to_poly_widest (val2)))
1107 return 0;
1108 if (known_lt (wi::to_poly_widest (val1),
1109 wi::to_poly_widest (val2)))
1110 return -1;
1111 if (known_gt (wi::to_poly_widest (val1),
1112 wi::to_poly_widest (val2)))
1113 return 1;
1116 return -2;
1118 else
1120 tree t;
1122 /* First see if VAL1 and VAL2 are not the same. */
1123 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1124 return 0;
1126 /* If VAL1 is a lower address than VAL2, return -1. */
1127 if (operand_less_p (val1, val2) == 1)
1128 return -1;
1130 /* If VAL1 is a higher address than VAL2, return +1. */
1131 if (operand_less_p (val2, val1) == 1)
1132 return 1;
1134 /* If VAL1 is different than VAL2, return +2.
1135 For integer constants we either have already returned -1 or 1
1136 or they are equivalent. We still might succeed in proving
1137 something about non-trivial operands. */
1138 if (TREE_CODE (val1) != INTEGER_CST
1139 || TREE_CODE (val2) != INTEGER_CST)
1141 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1142 if (t && integer_onep (t))
1143 return 2;
1146 return -2;
1150 /* Compare values like compare_values_warnv. */
1153 compare_values (tree val1, tree val2)
1155 bool sop;
1156 return compare_values_warnv (val1, val2, &sop);
1160 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1161 0 if VAL is not inside [MIN, MAX],
1162 -2 if we cannot tell either way.
1164 Benchmark compile/20001226-1.c compilation time after changing this
1165 function. */
1168 value_inside_range (tree val, tree min, tree max)
1170 int cmp1, cmp2;
1172 cmp1 = operand_less_p (val, min);
1173 if (cmp1 == -2)
1174 return -2;
1175 if (cmp1 == 1)
1176 return 0;
1178 cmp2 = operand_less_p (max, val);
1179 if (cmp2 == -2)
1180 return -2;
1182 return !cmp2;
1186 /* Return TRUE if *VR includes the value zero. */
1188 bool
1189 range_includes_zero_p (const value_range_base *vr)
1191 if (vr->varying_p () || vr->undefined_p ())
1192 return true;
1193 tree zero = build_int_cst (vr->type (), 0);
1194 return vr->may_contain_p (zero);
1197 /* If *VR has a value range that is a single constant value return that,
1198 otherwise return NULL_TREE.
1200 ?? This actually returns TRUE for [&x, &x], so perhaps "constant"
1201 is not the best name. */
1203 tree
1204 value_range_constant_singleton (const value_range_base *vr)
1206 tree result = NULL;
1207 if (vr->singleton_p (&result))
1208 return result;
1209 return NULL;
1212 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
1214 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
1216 Return TRUE if VR was a constant range and we were able to compute
1217 the bit masks. */
1219 bool
1220 vrp_set_zero_nonzero_bits (const tree expr_type,
1221 const value_range_base *vr,
1222 wide_int *may_be_nonzero,
1223 wide_int *must_be_nonzero)
1225 if (!range_int_cst_p (vr))
1227 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1228 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1229 return false;
1231 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
1232 wi::to_wide (vr->min ()),
1233 wi::to_wide (vr->max ()),
1234 *may_be_nonzero, *must_be_nonzero);
1235 return true;
1238 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1239 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1240 false otherwise. If *AR can be represented with a single range
1241 *VR1 will be VR_UNDEFINED. */
1243 static bool
1244 ranges_from_anti_range (const value_range_base *ar,
1245 value_range_base *vr0, value_range_base *vr1)
1247 tree type = ar->type ();
1249 vr0->set_undefined ();
1250 vr1->set_undefined ();
1252 /* As a future improvement, we could handle ~[0, A] as: [-INF, -1] U
1253 [A+1, +INF]. Not sure if this helps in practice, though. */
1255 if (ar->kind () != VR_ANTI_RANGE
1256 || TREE_CODE (ar->min ()) != INTEGER_CST
1257 || TREE_CODE (ar->max ()) != INTEGER_CST
1258 || !vrp_val_min (type)
1259 || !vrp_val_max (type))
1260 return false;
1262 if (!vrp_val_is_min (ar->min ()))
1263 *vr0 = value_range (VR_RANGE,
1264 vrp_val_min (type),
1265 wide_int_to_tree (type, wi::to_wide (ar->min ()) - 1));
1266 if (!vrp_val_is_max (ar->max ()))
1267 *vr1 = value_range (VR_RANGE,
1268 wide_int_to_tree (type, wi::to_wide (ar->max ()) + 1),
1269 vrp_val_max (type));
1270 if (vr0->undefined_p ())
1272 *vr0 = *vr1;
1273 vr1->set_undefined ();
1276 return !vr0->undefined_p ();
1279 /* Extract the components of a value range into a pair of wide ints in
1280 [WMIN, WMAX].
1282 If the value range is anything but a VR_*RANGE of constants, the
1283 resulting wide ints are set to [-MIN, +MAX] for the type. */
1285 static void inline
1286 extract_range_into_wide_ints (const value_range_base *vr,
1287 signop sign, unsigned prec,
1288 wide_int &wmin, wide_int &wmax)
1290 gcc_assert (vr->kind () != VR_ANTI_RANGE || vr->symbolic_p ());
1291 if (range_int_cst_p (vr))
1293 wmin = wi::to_wide (vr->min ());
1294 wmax = wi::to_wide (vr->max ());
1296 else
1298 wmin = wi::min_value (prec, sign);
1299 wmax = wi::max_value (prec, sign);
1303 /* Value range wrapper for wide_int_range_multiplicative_op:
1305 *VR = *VR0 .CODE. *VR1. */
1307 static void
1308 extract_range_from_multiplicative_op (value_range_base *vr,
1309 enum tree_code code,
1310 const value_range_base *vr0,
1311 const value_range_base *vr1)
1313 gcc_assert (code == MULT_EXPR
1314 || code == TRUNC_DIV_EXPR
1315 || code == FLOOR_DIV_EXPR
1316 || code == CEIL_DIV_EXPR
1317 || code == EXACT_DIV_EXPR
1318 || code == ROUND_DIV_EXPR
1319 || code == RSHIFT_EXPR
1320 || code == LSHIFT_EXPR);
1321 gcc_assert (vr0->kind () == VR_RANGE
1322 && vr0->kind () == vr1->kind ());
1324 tree type = vr0->type ();
1325 wide_int res_lb, res_ub;
1326 wide_int vr0_lb = wi::to_wide (vr0->min ());
1327 wide_int vr0_ub = wi::to_wide (vr0->max ());
1328 wide_int vr1_lb = wi::to_wide (vr1->min ());
1329 wide_int vr1_ub = wi::to_wide (vr1->max ());
1330 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1331 unsigned prec = TYPE_PRECISION (type);
1333 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1334 code, TYPE_SIGN (type), prec,
1335 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1336 overflow_undefined))
1337 vr->set_and_canonicalize (VR_RANGE,
1338 wide_int_to_tree (type, res_lb),
1339 wide_int_to_tree (type, res_ub));
1340 else
1341 vr->set_varying ();
1344 /* If BOUND will include a symbolic bound, adjust it accordingly,
1345 otherwise leave it as is.
1347 CODE is the original operation that combined the bounds (PLUS_EXPR
1348 or MINUS_EXPR).
1350 TYPE is the type of the original operation.
1352 SYM_OPn is the symbolic for OPn if it has a symbolic.
1354 NEG_OPn is TRUE if the OPn was negated. */
1356 static void
1357 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1358 tree sym_op0, tree sym_op1,
1359 bool neg_op0, bool neg_op1)
1361 bool minus_p = (code == MINUS_EXPR);
1362 /* If the result bound is constant, we're done; otherwise, build the
1363 symbolic lower bound. */
1364 if (sym_op0 == sym_op1)
1366 else if (sym_op0)
1367 bound = build_symbolic_expr (type, sym_op0,
1368 neg_op0, bound);
1369 else if (sym_op1)
1371 /* We may not negate if that might introduce
1372 undefined overflow. */
1373 if (!minus_p
1374 || neg_op1
1375 || TYPE_OVERFLOW_WRAPS (type))
1376 bound = build_symbolic_expr (type, sym_op1,
1377 neg_op1 ^ minus_p, bound);
1378 else
1379 bound = NULL_TREE;
1383 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1384 int bound according to CODE. CODE is the operation combining the
1385 bound (either a PLUS_EXPR or a MINUS_EXPR).
1387 TYPE is the type of the combine operation.
1389 WI is the wide int to store the result.
1391 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1392 if over/underflow occurred. */
1394 static void
1395 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1396 tree type, tree op0, tree op1)
1398 bool minus_p = (code == MINUS_EXPR);
1399 const signop sgn = TYPE_SIGN (type);
1400 const unsigned int prec = TYPE_PRECISION (type);
1402 /* Combine the bounds, if any. */
1403 if (op0 && op1)
1405 if (minus_p)
1406 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1407 else
1408 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1410 else if (op0)
1411 wi = wi::to_wide (op0);
1412 else if (op1)
1414 if (minus_p)
1415 wi = wi::neg (wi::to_wide (op1), &ovf);
1416 else
1417 wi = wi::to_wide (op1);
1419 else
1420 wi = wi::shwi (0, prec);
1423 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1424 put the result in VR.
1426 TYPE is the type of the range.
1428 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1429 occurred while originally calculating WMIN or WMAX. -1 indicates
1430 underflow. +1 indicates overflow. 0 indicates neither. */
1432 static void
1433 set_value_range_with_overflow (value_range_kind &kind, tree &min, tree &max,
1434 tree type,
1435 const wide_int &wmin, const wide_int &wmax,
1436 wi::overflow_type min_ovf,
1437 wi::overflow_type max_ovf)
1439 const signop sgn = TYPE_SIGN (type);
1440 const unsigned int prec = TYPE_PRECISION (type);
1442 /* For one bit precision if max < min, then the swapped
1443 range covers all values. */
1444 if (prec == 1 && wi::lt_p (wmax, wmin, sgn))
1446 kind = VR_VARYING;
1447 return;
1450 if (TYPE_OVERFLOW_WRAPS (type))
1452 /* If overflow wraps, truncate the values and adjust the
1453 range kind and bounds appropriately. */
1454 wide_int tmin = wide_int::from (wmin, prec, sgn);
1455 wide_int tmax = wide_int::from (wmax, prec, sgn);
1456 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1458 /* If the limits are swapped, we wrapped around and cover
1459 the entire range. We have a similar check at the end of
1460 extract_range_from_binary_expr. */
1461 if (wi::gt_p (tmin, tmax, sgn))
1462 kind = VR_VARYING;
1463 else
1465 kind = VR_RANGE;
1466 /* No overflow or both overflow or underflow. The
1467 range kind stays VR_RANGE. */
1468 min = wide_int_to_tree (type, tmin);
1469 max = wide_int_to_tree (type, tmax);
1471 return;
1473 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1474 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1476 /* Min underflow or max overflow. The range kind
1477 changes to VR_ANTI_RANGE. */
1478 bool covers = false;
1479 wide_int tem = tmin;
1480 tmin = tmax + 1;
1481 if (wi::cmp (tmin, tmax, sgn) < 0)
1482 covers = true;
1483 tmax = tem - 1;
1484 if (wi::cmp (tmax, tem, sgn) > 0)
1485 covers = true;
1486 /* If the anti-range would cover nothing, drop to varying.
1487 Likewise if the anti-range bounds are outside of the
1488 types values. */
1489 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1491 kind = VR_VARYING;
1492 return;
1494 kind = VR_ANTI_RANGE;
1495 min = wide_int_to_tree (type, tmin);
1496 max = wide_int_to_tree (type, tmax);
1497 return;
1499 else
1501 /* Other underflow and/or overflow, drop to VR_VARYING. */
1502 kind = VR_VARYING;
1503 return;
1506 else
1508 /* If overflow does not wrap, saturate to the types min/max
1509 value. */
1510 wide_int type_min = wi::min_value (prec, sgn);
1511 wide_int type_max = wi::max_value (prec, sgn);
1512 kind = VR_RANGE;
1513 if (min_ovf == wi::OVF_UNDERFLOW)
1514 min = wide_int_to_tree (type, type_min);
1515 else if (min_ovf == wi::OVF_OVERFLOW)
1516 min = wide_int_to_tree (type, type_max);
1517 else
1518 min = wide_int_to_tree (type, wmin);
1520 if (max_ovf == wi::OVF_UNDERFLOW)
1521 max = wide_int_to_tree (type, type_min);
1522 else if (max_ovf == wi::OVF_OVERFLOW)
1523 max = wide_int_to_tree (type, type_max);
1524 else
1525 max = wide_int_to_tree (type, wmax);
1529 /* Extract range information from a binary operation CODE based on
1530 the ranges of each of its operands *VR0 and *VR1 with resulting
1531 type EXPR_TYPE. The resulting range is stored in *VR. */
1533 void
1534 extract_range_from_binary_expr (value_range_base *vr,
1535 enum tree_code code, tree expr_type,
1536 const value_range_base *vr0_,
1537 const value_range_base *vr1_)
1539 signop sign = TYPE_SIGN (expr_type);
1540 unsigned int prec = TYPE_PRECISION (expr_type);
1541 value_range_base vr0 = *vr0_, vr1 = *vr1_;
1542 value_range_base vrtem0, vrtem1;
1543 enum value_range_kind type;
1544 tree min = NULL_TREE, max = NULL_TREE;
1545 int cmp;
1547 if (!INTEGRAL_TYPE_P (expr_type)
1548 && !POINTER_TYPE_P (expr_type))
1550 vr->set_varying ();
1551 return;
1554 /* Not all binary expressions can be applied to ranges in a
1555 meaningful way. Handle only arithmetic operations. */
1556 if (code != PLUS_EXPR
1557 && code != MINUS_EXPR
1558 && code != POINTER_PLUS_EXPR
1559 && code != MULT_EXPR
1560 && code != TRUNC_DIV_EXPR
1561 && code != FLOOR_DIV_EXPR
1562 && code != CEIL_DIV_EXPR
1563 && code != EXACT_DIV_EXPR
1564 && code != ROUND_DIV_EXPR
1565 && code != TRUNC_MOD_EXPR
1566 && code != RSHIFT_EXPR
1567 && code != LSHIFT_EXPR
1568 && code != MIN_EXPR
1569 && code != MAX_EXPR
1570 && code != BIT_AND_EXPR
1571 && code != BIT_IOR_EXPR
1572 && code != BIT_XOR_EXPR)
1574 vr->set_varying ();
1575 return;
1578 /* If both ranges are UNDEFINED, so is the result. */
1579 if (vr0.undefined_p () && vr1.undefined_p ())
1581 vr->set_undefined ();
1582 return;
1584 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1585 code. At some point we may want to special-case operations that
1586 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1587 operand. */
1588 else if (vr0.undefined_p ())
1589 vr0.set_varying ();
1590 else if (vr1.undefined_p ())
1591 vr1.set_varying ();
1593 /* We get imprecise results from ranges_from_anti_range when
1594 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1595 range, but then we also need to hack up vrp_union. It's just
1596 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1597 if (code == EXACT_DIV_EXPR && range_is_nonnull (&vr0))
1599 vr->set_nonnull (expr_type);
1600 return;
1603 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1604 and express ~[] op X as ([]' op X) U ([]'' op X). */
1605 if (vr0.kind () == VR_ANTI_RANGE
1606 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1608 extract_range_from_binary_expr (vr, code, expr_type, &vrtem0, vr1_);
1609 if (!vrtem1.undefined_p ())
1611 value_range_base vrres;
1612 extract_range_from_binary_expr (&vrres, code, expr_type,
1613 &vrtem1, vr1_);
1614 vr->union_ (&vrres);
1616 return;
1618 /* Likewise for X op ~[]. */
1619 if (vr1.kind () == VR_ANTI_RANGE
1620 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1622 extract_range_from_binary_expr (vr, code, expr_type, vr0_, &vrtem0);
1623 if (!vrtem1.undefined_p ())
1625 value_range_base vrres;
1626 extract_range_from_binary_expr (&vrres, code, expr_type,
1627 vr0_, &vrtem1);
1628 vr->union_ (&vrres);
1630 return;
1633 /* The type of the resulting value range defaults to VR0.TYPE. */
1634 type = vr0.kind ();
1636 /* Refuse to operate on VARYING ranges, ranges of different kinds
1637 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1638 because we may be able to derive a useful range even if one of
1639 the operands is VR_VARYING or symbolic range. Similarly for
1640 divisions, MIN/MAX and PLUS/MINUS.
1642 TODO, we may be able to derive anti-ranges in some cases. */
1643 if (code != BIT_AND_EXPR
1644 && code != BIT_IOR_EXPR
1645 && code != TRUNC_DIV_EXPR
1646 && code != FLOOR_DIV_EXPR
1647 && code != CEIL_DIV_EXPR
1648 && code != EXACT_DIV_EXPR
1649 && code != ROUND_DIV_EXPR
1650 && code != TRUNC_MOD_EXPR
1651 && code != MIN_EXPR
1652 && code != MAX_EXPR
1653 && code != PLUS_EXPR
1654 && code != MINUS_EXPR
1655 && code != RSHIFT_EXPR
1656 && code != POINTER_PLUS_EXPR
1657 && (vr0.varying_p ()
1658 || vr1.varying_p ()
1659 || vr0.kind () != vr1.kind ()
1660 || vr0.symbolic_p ()
1661 || vr1.symbolic_p ()))
1663 vr->set_varying ();
1664 return;
1667 /* Now evaluate the expression to determine the new range. */
1668 if (POINTER_TYPE_P (expr_type))
1670 if (code == MIN_EXPR || code == MAX_EXPR)
1672 /* For MIN/MAX expressions with pointers, we only care about
1673 nullness, if both are non null, then the result is nonnull.
1674 If both are null, then the result is null. Otherwise they
1675 are varying. */
1676 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1677 vr->set_nonnull (expr_type);
1678 else if (range_is_null (&vr0) && range_is_null (&vr1))
1679 vr->set_null (expr_type);
1680 else
1681 vr->set_varying ();
1683 else if (code == POINTER_PLUS_EXPR)
1685 /* For pointer types, we are really only interested in asserting
1686 whether the expression evaluates to non-NULL. */
1687 if (!range_includes_zero_p (&vr0)
1688 || !range_includes_zero_p (&vr1))
1689 vr->set_nonnull (expr_type);
1690 else if (range_is_null (&vr0) && range_is_null (&vr1))
1691 vr->set_null (expr_type);
1692 else
1693 vr->set_varying ();
1695 else if (code == BIT_AND_EXPR)
1697 /* For pointer types, we are really only interested in asserting
1698 whether the expression evaluates to non-NULL. */
1699 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1700 vr->set_nonnull (expr_type);
1701 else if (range_is_null (&vr0) || range_is_null (&vr1))
1702 vr->set_null (expr_type);
1703 else
1704 vr->set_varying ();
1706 else
1707 vr->set_varying ();
1709 return;
1712 /* For integer ranges, apply the operation to each end of the
1713 range and see what we end up with. */
1714 if (code == PLUS_EXPR || code == MINUS_EXPR)
1716 /* This will normalize things such that calculating
1717 [0,0] - VR_VARYING is not dropped to varying, but is
1718 calculated as [MIN+1, MAX]. */
1719 if (vr0.varying_p ())
1720 vr0.set (VR_RANGE, vrp_val_min (expr_type), vrp_val_max (expr_type));
1721 if (vr1.varying_p ())
1722 vr1.set (VR_RANGE, vrp_val_min (expr_type), vrp_val_max (expr_type));
1724 const bool minus_p = (code == MINUS_EXPR);
1725 tree min_op0 = vr0.min ();
1726 tree min_op1 = minus_p ? vr1.max () : vr1.min ();
1727 tree max_op0 = vr0.max ();
1728 tree max_op1 = minus_p ? vr1.min () : vr1.max ();
1729 tree sym_min_op0 = NULL_TREE;
1730 tree sym_min_op1 = NULL_TREE;
1731 tree sym_max_op0 = NULL_TREE;
1732 tree sym_max_op1 = NULL_TREE;
1733 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1735 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1737 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1738 single-symbolic ranges, try to compute the precise resulting range,
1739 but only if we know that this resulting range will also be constant
1740 or single-symbolic. */
1741 if (vr0.kind () == VR_RANGE && vr1.kind () == VR_RANGE
1742 && (TREE_CODE (min_op0) == INTEGER_CST
1743 || (sym_min_op0
1744 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1745 && (TREE_CODE (min_op1) == INTEGER_CST
1746 || (sym_min_op1
1747 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1748 && (!(sym_min_op0 && sym_min_op1)
1749 || (sym_min_op0 == sym_min_op1
1750 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1751 && (TREE_CODE (max_op0) == INTEGER_CST
1752 || (sym_max_op0
1753 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1754 && (TREE_CODE (max_op1) == INTEGER_CST
1755 || (sym_max_op1
1756 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1757 && (!(sym_max_op0 && sym_max_op1)
1758 || (sym_max_op0 == sym_max_op1
1759 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1761 wide_int wmin, wmax;
1762 wi::overflow_type min_ovf = wi::OVF_NONE;
1763 wi::overflow_type max_ovf = wi::OVF_NONE;
1765 /* Build the bounds. */
1766 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1767 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1769 /* If we have overflow for the constant part and the resulting
1770 range will be symbolic, drop to VR_VARYING. */
1771 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1772 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1774 vr->set_varying ();
1775 return;
1778 /* Adjust the range for possible overflow. */
1779 min = NULL_TREE;
1780 max = NULL_TREE;
1781 set_value_range_with_overflow (type, min, max, expr_type,
1782 wmin, wmax, min_ovf, max_ovf);
1783 if (type == VR_VARYING)
1785 vr->set_varying ();
1786 return;
1789 /* Build the symbolic bounds if needed. */
1790 adjust_symbolic_bound (min, code, expr_type,
1791 sym_min_op0, sym_min_op1,
1792 neg_min_op0, neg_min_op1);
1793 adjust_symbolic_bound (max, code, expr_type,
1794 sym_max_op0, sym_max_op1,
1795 neg_max_op0, neg_max_op1);
1797 else
1799 /* For other cases, for example if we have a PLUS_EXPR with two
1800 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1801 to compute a precise range for such a case.
1802 ??? General even mixed range kind operations can be expressed
1803 by for example transforming ~[3, 5] + [1, 2] to range-only
1804 operations and a union primitive:
1805 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1806 [-INF+1, 4] U [6, +INF(OVF)]
1807 though usually the union is not exactly representable with
1808 a single range or anti-range as the above is
1809 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1810 but one could use a scheme similar to equivalences for this. */
1811 vr->set_varying ();
1812 return;
1815 else if (code == MIN_EXPR
1816 || code == MAX_EXPR)
1818 wide_int wmin, wmax;
1819 wide_int vr0_min, vr0_max;
1820 wide_int vr1_min, vr1_max;
1821 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1822 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1823 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1824 vr0_min, vr0_max, vr1_min, vr1_max))
1825 vr->set (VR_RANGE, wide_int_to_tree (expr_type, wmin),
1826 wide_int_to_tree (expr_type, wmax));
1827 else
1828 vr->set_varying ();
1829 return;
1831 else if (code == MULT_EXPR)
1833 if (!range_int_cst_p (&vr0)
1834 || !range_int_cst_p (&vr1))
1836 vr->set_varying ();
1837 return;
1839 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1840 return;
1842 else if (code == RSHIFT_EXPR
1843 || code == LSHIFT_EXPR)
1845 if (range_int_cst_p (&vr1)
1846 && !wide_int_range_shift_undefined_p
1847 (TYPE_SIGN (TREE_TYPE (vr1.min ())),
1848 prec,
1849 wi::to_wide (vr1.min ()),
1850 wi::to_wide (vr1.max ())))
1852 if (code == RSHIFT_EXPR)
1854 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1855 useful ranges just from the shift count. E.g.
1856 x >> 63 for signed 64-bit x is always [-1, 0]. */
1857 if (vr0.kind () != VR_RANGE || vr0.symbolic_p ())
1858 vr0.set (VR_RANGE, vrp_val_min (expr_type),
1859 vrp_val_max (expr_type));
1860 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1861 return;
1863 else if (code == LSHIFT_EXPR
1864 && range_int_cst_p (&vr0))
1866 wide_int res_lb, res_ub;
1867 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1868 wi::to_wide (vr0.min ()),
1869 wi::to_wide (vr0.max ()),
1870 wi::to_wide (vr1.min ()),
1871 wi::to_wide (vr1.max ()),
1872 TYPE_OVERFLOW_UNDEFINED (expr_type)))
1874 min = wide_int_to_tree (expr_type, res_lb);
1875 max = wide_int_to_tree (expr_type, res_ub);
1876 vr->set_and_canonicalize (VR_RANGE, min, max);
1877 return;
1881 vr->set_varying ();
1882 return;
1884 else if (code == TRUNC_DIV_EXPR
1885 || code == FLOOR_DIV_EXPR
1886 || code == CEIL_DIV_EXPR
1887 || code == EXACT_DIV_EXPR
1888 || code == ROUND_DIV_EXPR)
1890 wide_int dividend_min, dividend_max, divisor_min, divisor_max;
1891 wide_int wmin, wmax, extra_min, extra_max;
1892 bool extra_range_p;
1894 /* Special case explicit division by zero as undefined. */
1895 if (range_is_null (&vr1))
1897 vr->set_undefined ();
1898 return;
1901 /* First, normalize ranges into constants we can handle. Note
1902 that VR_ANTI_RANGE's of constants were already normalized
1903 before arriving here.
1905 NOTE: As a future improvement, we may be able to do better
1906 with mixed symbolic (anti-)ranges like [0, A]. See note in
1907 ranges_from_anti_range. */
1908 extract_range_into_wide_ints (&vr0, sign, prec,
1909 dividend_min, dividend_max);
1910 extract_range_into_wide_ints (&vr1, sign, prec,
1911 divisor_min, divisor_max);
1912 if (!wide_int_range_div (wmin, wmax, code, sign, prec,
1913 dividend_min, dividend_max,
1914 divisor_min, divisor_max,
1915 TYPE_OVERFLOW_UNDEFINED (expr_type),
1916 extra_range_p, extra_min, extra_max))
1918 vr->set_undefined ();
1919 return;
1921 vr->set (VR_RANGE, wide_int_to_tree (expr_type, wmin),
1922 wide_int_to_tree (expr_type, wmax));
1923 if (extra_range_p)
1925 value_range_base
1926 extra_range (VR_RANGE, wide_int_to_tree (expr_type, extra_min),
1927 wide_int_to_tree (expr_type, extra_max));
1928 vr->union_ (&extra_range);
1930 return;
1932 else if (code == TRUNC_MOD_EXPR)
1934 if (range_is_null (&vr1))
1936 vr->set_undefined ();
1937 return;
1939 wide_int wmin, wmax, tmp;
1940 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1941 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1942 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1943 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1944 vr0_min, vr0_max, vr1_min, vr1_max);
1945 min = wide_int_to_tree (expr_type, wmin);
1946 max = wide_int_to_tree (expr_type, wmax);
1947 vr->set (VR_RANGE, min, max);
1948 return;
1950 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1952 wide_int may_be_nonzero0, may_be_nonzero1;
1953 wide_int must_be_nonzero0, must_be_nonzero1;
1954 wide_int wmin, wmax;
1955 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1956 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1957 &may_be_nonzero0, &must_be_nonzero0);
1958 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1959 &may_be_nonzero1, &must_be_nonzero1);
1960 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1961 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1962 if (code == BIT_AND_EXPR)
1964 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1965 vr0_min, vr0_max,
1966 vr1_min, vr1_max,
1967 must_be_nonzero0,
1968 may_be_nonzero0,
1969 must_be_nonzero1,
1970 may_be_nonzero1))
1972 min = wide_int_to_tree (expr_type, wmin);
1973 max = wide_int_to_tree (expr_type, wmax);
1974 vr->set (VR_RANGE, min, max);
1976 else
1977 vr->set_varying ();
1978 return;
1980 else if (code == BIT_IOR_EXPR)
1982 if (wide_int_range_bit_ior (wmin, wmax, sign,
1983 vr0_min, vr0_max,
1984 vr1_min, vr1_max,
1985 must_be_nonzero0,
1986 may_be_nonzero0,
1987 must_be_nonzero1,
1988 may_be_nonzero1))
1990 min = wide_int_to_tree (expr_type, wmin);
1991 max = wide_int_to_tree (expr_type, wmax);
1992 vr->set (VR_RANGE, min, max);
1994 else
1995 vr->set_varying ();
1996 return;
1998 else if (code == BIT_XOR_EXPR)
2000 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
2001 must_be_nonzero0,
2002 may_be_nonzero0,
2003 must_be_nonzero1,
2004 may_be_nonzero1))
2006 min = wide_int_to_tree (expr_type, wmin);
2007 max = wide_int_to_tree (expr_type, wmax);
2008 vr->set (VR_RANGE, min, max);
2010 else
2011 vr->set_varying ();
2012 return;
2015 else
2016 gcc_unreachable ();
2018 /* If either MIN or MAX overflowed, then set the resulting range to
2019 VARYING. */
2020 if (min == NULL_TREE
2021 || TREE_OVERFLOW_P (min)
2022 || max == NULL_TREE
2023 || TREE_OVERFLOW_P (max))
2025 vr->set_varying ();
2026 return;
2029 /* We punt for [-INF, +INF].
2030 We learn nothing when we have INF on both sides.
2031 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2032 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2034 vr->set_varying ();
2035 return;
2038 cmp = compare_values (min, max);
2039 if (cmp == -2 || cmp == 1)
2041 /* If the new range has its limits swapped around (MIN > MAX),
2042 then the operation caused one of them to wrap around, mark
2043 the new range VARYING. */
2044 vr->set_varying ();
2046 else
2047 vr->set (type, min, max);
2050 /* Extract range information from a unary operation CODE based on
2051 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2052 The resulting range is stored in *VR. */
2054 void
2055 extract_range_from_unary_expr (value_range_base *vr,
2056 enum tree_code code, tree type,
2057 const value_range_base *vr0_, tree op0_type)
2059 signop sign = TYPE_SIGN (type);
2060 unsigned int prec = TYPE_PRECISION (type);
2061 value_range_base vr0 = *vr0_;
2062 value_range_base vrtem0, vrtem1;
2064 /* VRP only operates on integral and pointer types. */
2065 if (!(INTEGRAL_TYPE_P (op0_type)
2066 || POINTER_TYPE_P (op0_type))
2067 || !(INTEGRAL_TYPE_P (type)
2068 || POINTER_TYPE_P (type)))
2070 vr->set_varying ();
2071 return;
2074 /* If VR0 is UNDEFINED, so is the result. */
2075 if (vr0.undefined_p ())
2077 vr->set_undefined ();
2078 return;
2081 /* Handle operations that we express in terms of others. */
2082 if (code == PAREN_EXPR)
2084 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2085 *vr = vr0;
2086 return;
2088 else if (code == NEGATE_EXPR)
2090 /* -X is simply 0 - X, so re-use existing code that also handles
2091 anti-ranges fine. */
2092 value_range_base zero;
2093 zero.set (build_int_cst (type, 0));
2094 extract_range_from_binary_expr (vr, MINUS_EXPR, type, &zero, &vr0);
2095 return;
2097 else if (code == BIT_NOT_EXPR)
2099 /* ~X is simply -1 - X, so re-use existing code that also handles
2100 anti-ranges fine. */
2101 value_range_base minusone;
2102 minusone.set (build_int_cst (type, -1));
2103 extract_range_from_binary_expr (vr, MINUS_EXPR, type, &minusone, &vr0);
2104 return;
2107 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2108 and express op ~[] as (op []') U (op []''). */
2109 if (vr0.kind () == VR_ANTI_RANGE
2110 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2112 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2113 if (!vrtem1.undefined_p ())
2115 value_range_base vrres;
2116 extract_range_from_unary_expr (&vrres, code, type,
2117 &vrtem1, op0_type);
2118 vr->union_ (&vrres);
2120 return;
2123 if (CONVERT_EXPR_CODE_P (code))
2125 tree inner_type = op0_type;
2126 tree outer_type = type;
2128 /* If the expression involves a pointer, we are only interested in
2129 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).
2131 This may lose precision when converting (char *)~[0,2] to
2132 int, because we'll forget that the pointer can also not be 1
2133 or 2. In practice we don't care, as this is some idiot
2134 storing a magic constant to a pointer. */
2135 if (POINTER_TYPE_P (type) || POINTER_TYPE_P (op0_type))
2137 if (!range_includes_zero_p (&vr0))
2138 vr->set_nonnull (type);
2139 else if (range_is_null (&vr0))
2140 vr->set_null (type);
2141 else
2142 vr->set_varying ();
2143 return;
2146 /* The POINTER_TYPE_P code above will have dealt with all
2147 pointer anti-ranges. Any remaining anti-ranges at this point
2148 will be integer conversions from SSA names that will be
2149 normalized into VARYING. For instance: ~[x_55, x_55]. */
2150 gcc_assert (vr0.kind () != VR_ANTI_RANGE
2151 || TREE_CODE (vr0.min ()) != INTEGER_CST);
2153 /* NOTES: Previously we were returning VARYING for all symbolics, but
2154 we can do better by treating them as [-MIN, +MAX]. For
2155 example, converting [SYM, SYM] from INT to LONG UNSIGNED,
2156 we can return: ~[0x8000000, 0xffffffff7fffffff].
2158 We were also failing to convert ~[0,0] from char* to unsigned,
2159 instead choosing to return VR_VARYING. Now we return ~[0,0]. */
2160 wide_int vr0_min, vr0_max, wmin, wmax;
2161 signop inner_sign = TYPE_SIGN (inner_type);
2162 signop outer_sign = TYPE_SIGN (outer_type);
2163 unsigned inner_prec = TYPE_PRECISION (inner_type);
2164 unsigned outer_prec = TYPE_PRECISION (outer_type);
2165 extract_range_into_wide_ints (&vr0, inner_sign, inner_prec,
2166 vr0_min, vr0_max);
2167 if (wide_int_range_convert (wmin, wmax,
2168 inner_sign, inner_prec,
2169 outer_sign, outer_prec,
2170 vr0_min, vr0_max))
2172 tree min = wide_int_to_tree (outer_type, wmin);
2173 tree max = wide_int_to_tree (outer_type, wmax);
2174 vr->set_and_canonicalize (VR_RANGE, min, max);
2176 else
2177 vr->set_varying ();
2178 return;
2180 else if (code == ABS_EXPR)
2182 wide_int wmin, wmax;
2183 wide_int vr0_min, vr0_max;
2184 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
2185 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
2186 TYPE_OVERFLOW_UNDEFINED (type)))
2187 vr->set (VR_RANGE, wide_int_to_tree (type, wmin),
2188 wide_int_to_tree (type, wmax));
2189 else
2190 vr->set_varying ();
2191 return;
2194 /* For unhandled operations fall back to varying. */
2195 vr->set_varying ();
2196 return;
2199 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2200 create a new SSA name N and return the assertion assignment
2201 'N = ASSERT_EXPR <V, V OP W>'. */
2203 static gimple *
2204 build_assert_expr_for (tree cond, tree v)
2206 tree a;
2207 gassign *assertion;
2209 gcc_assert (TREE_CODE (v) == SSA_NAME
2210 && COMPARISON_CLASS_P (cond));
2212 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2213 assertion = gimple_build_assign (NULL_TREE, a);
2215 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2216 operand of the ASSERT_EXPR. Create it so the new name and the old one
2217 are registered in the replacement table so that we can fix the SSA web
2218 after adding all the ASSERT_EXPRs. */
2219 tree new_def = create_new_def_for (v, assertion, NULL);
2220 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2221 given we have to be able to fully propagate those out to re-create
2222 valid SSA when removing the asserts. */
2223 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2224 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2226 return assertion;
2230 /* Return false if EXPR is a predicate expression involving floating
2231 point values. */
2233 static inline bool
2234 fp_predicate (gimple *stmt)
2236 GIMPLE_CHECK (stmt, GIMPLE_COND);
2238 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2241 /* If the range of values taken by OP can be inferred after STMT executes,
2242 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2243 describes the inferred range. Return true if a range could be
2244 inferred. */
2246 bool
2247 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2249 *val_p = NULL_TREE;
2250 *comp_code_p = ERROR_MARK;
2252 /* Do not attempt to infer anything in names that flow through
2253 abnormal edges. */
2254 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2255 return false;
2257 /* If STMT is the last statement of a basic block with no normal
2258 successors, there is no point inferring anything about any of its
2259 operands. We would not be able to find a proper insertion point
2260 for the assertion, anyway. */
2261 if (stmt_ends_bb_p (stmt))
2263 edge_iterator ei;
2264 edge e;
2266 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2267 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2268 break;
2269 if (e == NULL)
2270 return false;
2273 if (infer_nonnull_range (stmt, op))
2275 *val_p = build_int_cst (TREE_TYPE (op), 0);
2276 *comp_code_p = NE_EXPR;
2277 return true;
2280 return false;
2284 void dump_asserts_for (FILE *, tree);
2285 void debug_asserts_for (tree);
2286 void dump_all_asserts (FILE *);
2287 void debug_all_asserts (void);
2289 /* Dump all the registered assertions for NAME to FILE. */
2291 void
2292 dump_asserts_for (FILE *file, tree name)
2294 assert_locus *loc;
2296 fprintf (file, "Assertions to be inserted for ");
2297 print_generic_expr (file, name);
2298 fprintf (file, "\n");
2300 loc = asserts_for[SSA_NAME_VERSION (name)];
2301 while (loc)
2303 fprintf (file, "\t");
2304 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2305 fprintf (file, "\n\tBB #%d", loc->bb->index);
2306 if (loc->e)
2308 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2309 loc->e->dest->index);
2310 dump_edge_info (file, loc->e, dump_flags, 0);
2312 fprintf (file, "\n\tPREDICATE: ");
2313 print_generic_expr (file, loc->expr);
2314 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2315 print_generic_expr (file, loc->val);
2316 fprintf (file, "\n\n");
2317 loc = loc->next;
2320 fprintf (file, "\n");
2324 /* Dump all the registered assertions for NAME to stderr. */
2326 DEBUG_FUNCTION void
2327 debug_asserts_for (tree name)
2329 dump_asserts_for (stderr, name);
2333 /* Dump all the registered assertions for all the names to FILE. */
2335 void
2336 dump_all_asserts (FILE *file)
2338 unsigned i;
2339 bitmap_iterator bi;
2341 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2342 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2343 dump_asserts_for (file, ssa_name (i));
2344 fprintf (file, "\n");
2348 /* Dump all the registered assertions for all the names to stderr. */
2350 DEBUG_FUNCTION void
2351 debug_all_asserts (void)
2353 dump_all_asserts (stderr);
2356 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2358 static void
2359 add_assert_info (vec<assert_info> &asserts,
2360 tree name, tree expr, enum tree_code comp_code, tree val)
2362 assert_info info;
2363 info.comp_code = comp_code;
2364 info.name = name;
2365 if (TREE_OVERFLOW_P (val))
2366 val = drop_tree_overflow (val);
2367 info.val = val;
2368 info.expr = expr;
2369 asserts.safe_push (info);
2370 if (dump_enabled_p ())
2371 dump_printf (MSG_NOTE | MSG_PRIORITY_INTERNALS,
2372 "Adding assert for %T from %T %s %T\n",
2373 name, expr, op_symbol_code (comp_code), val);
2376 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2377 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2378 E->DEST, then register this location as a possible insertion point
2379 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2381 BB, E and SI provide the exact insertion point for the new
2382 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2383 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2384 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2385 must not be NULL. */
2387 static void
2388 register_new_assert_for (tree name, tree expr,
2389 enum tree_code comp_code,
2390 tree val,
2391 basic_block bb,
2392 edge e,
2393 gimple_stmt_iterator si)
2395 assert_locus *n, *loc, *last_loc;
2396 basic_block dest_bb;
2398 gcc_checking_assert (bb == NULL || e == NULL);
2400 if (e == NULL)
2401 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2402 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2404 /* Never build an assert comparing against an integer constant with
2405 TREE_OVERFLOW set. This confuses our undefined overflow warning
2406 machinery. */
2407 if (TREE_OVERFLOW_P (val))
2408 val = drop_tree_overflow (val);
2410 /* The new assertion A will be inserted at BB or E. We need to
2411 determine if the new location is dominated by a previously
2412 registered location for A. If we are doing an edge insertion,
2413 assume that A will be inserted at E->DEST. Note that this is not
2414 necessarily true.
2416 If E is a critical edge, it will be split. But even if E is
2417 split, the new block will dominate the same set of blocks that
2418 E->DEST dominates.
2420 The reverse, however, is not true, blocks dominated by E->DEST
2421 will not be dominated by the new block created to split E. So,
2422 if the insertion location is on a critical edge, we will not use
2423 the new location to move another assertion previously registered
2424 at a block dominated by E->DEST. */
2425 dest_bb = (bb) ? bb : e->dest;
2427 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2428 VAL at a block dominating DEST_BB, then we don't need to insert a new
2429 one. Similarly, if the same assertion already exists at a block
2430 dominated by DEST_BB and the new location is not on a critical
2431 edge, then update the existing location for the assertion (i.e.,
2432 move the assertion up in the dominance tree).
2434 Note, this is implemented as a simple linked list because there
2435 should not be more than a handful of assertions registered per
2436 name. If this becomes a performance problem, a table hashed by
2437 COMP_CODE and VAL could be implemented. */
2438 loc = asserts_for[SSA_NAME_VERSION (name)];
2439 last_loc = loc;
2440 while (loc)
2442 if (loc->comp_code == comp_code
2443 && (loc->val == val
2444 || operand_equal_p (loc->val, val, 0))
2445 && (loc->expr == expr
2446 || operand_equal_p (loc->expr, expr, 0)))
2448 /* If E is not a critical edge and DEST_BB
2449 dominates the existing location for the assertion, move
2450 the assertion up in the dominance tree by updating its
2451 location information. */
2452 if ((e == NULL || !EDGE_CRITICAL_P (e))
2453 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2455 loc->bb = dest_bb;
2456 loc->e = e;
2457 loc->si = si;
2458 return;
2462 /* Update the last node of the list and move to the next one. */
2463 last_loc = loc;
2464 loc = loc->next;
2467 /* If we didn't find an assertion already registered for
2468 NAME COMP_CODE VAL, add a new one at the end of the list of
2469 assertions associated with NAME. */
2470 n = XNEW (struct assert_locus);
2471 n->bb = dest_bb;
2472 n->e = e;
2473 n->si = si;
2474 n->comp_code = comp_code;
2475 n->val = val;
2476 n->expr = expr;
2477 n->next = NULL;
2479 if (last_loc)
2480 last_loc->next = n;
2481 else
2482 asserts_for[SSA_NAME_VERSION (name)] = n;
2484 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2487 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2488 Extract a suitable test code and value and store them into *CODE_P and
2489 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2491 If no extraction was possible, return FALSE, otherwise return TRUE.
2493 If INVERT is true, then we invert the result stored into *CODE_P. */
2495 static bool
2496 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2497 tree cond_op0, tree cond_op1,
2498 bool invert, enum tree_code *code_p,
2499 tree *val_p)
2501 enum tree_code comp_code;
2502 tree val;
2504 /* Otherwise, we have a comparison of the form NAME COMP VAL
2505 or VAL COMP NAME. */
2506 if (name == cond_op1)
2508 /* If the predicate is of the form VAL COMP NAME, flip
2509 COMP around because we need to register NAME as the
2510 first operand in the predicate. */
2511 comp_code = swap_tree_comparison (cond_code);
2512 val = cond_op0;
2514 else if (name == cond_op0)
2516 /* The comparison is of the form NAME COMP VAL, so the
2517 comparison code remains unchanged. */
2518 comp_code = cond_code;
2519 val = cond_op1;
2521 else
2522 gcc_unreachable ();
2524 /* Invert the comparison code as necessary. */
2525 if (invert)
2526 comp_code = invert_tree_comparison (comp_code, 0);
2528 /* VRP only handles integral and pointer types. */
2529 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2530 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2531 return false;
2533 /* Do not register always-false predicates.
2534 FIXME: this works around a limitation in fold() when dealing with
2535 enumerations. Given 'enum { N1, N2 } x;', fold will not
2536 fold 'if (x > N2)' to 'if (0)'. */
2537 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2538 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2540 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2541 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2543 if (comp_code == GT_EXPR
2544 && (!max
2545 || compare_values (val, max) == 0))
2546 return false;
2548 if (comp_code == LT_EXPR
2549 && (!min
2550 || compare_values (val, min) == 0))
2551 return false;
2553 *code_p = comp_code;
2554 *val_p = val;
2555 return true;
2558 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2559 (otherwise return VAL). VAL and MASK must be zero-extended for
2560 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2561 (to transform signed values into unsigned) and at the end xor
2562 SGNBIT back. */
2564 static wide_int
2565 masked_increment (const wide_int &val_in, const wide_int &mask,
2566 const wide_int &sgnbit, unsigned int prec)
2568 wide_int bit = wi::one (prec), res;
2569 unsigned int i;
2571 wide_int val = val_in ^ sgnbit;
2572 for (i = 0; i < prec; i++, bit += bit)
2574 res = mask;
2575 if ((res & bit) == 0)
2576 continue;
2577 res = bit - 1;
2578 res = wi::bit_and_not (val + bit, res);
2579 res &= mask;
2580 if (wi::gtu_p (res, val))
2581 return res ^ sgnbit;
2583 return val ^ sgnbit;
2586 /* Helper for overflow_comparison_p
2588 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2589 OP1's defining statement to see if it ultimately has the form
2590 OP0 CODE (OP0 PLUS INTEGER_CST)
2592 If so, return TRUE indicating this is an overflow test and store into
2593 *NEW_CST an updated constant that can be used in a narrowed range test.
2595 REVERSED indicates if the comparison was originally:
2597 OP1 CODE' OP0.
2599 This affects how we build the updated constant. */
2601 static bool
2602 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2603 bool follow_assert_exprs, bool reversed, tree *new_cst)
2605 /* See if this is a relational operation between two SSA_NAMES with
2606 unsigned, overflow wrapping values. If so, check it more deeply. */
2607 if ((code == LT_EXPR || code == LE_EXPR
2608 || code == GE_EXPR || code == GT_EXPR)
2609 && TREE_CODE (op0) == SSA_NAME
2610 && TREE_CODE (op1) == SSA_NAME
2611 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2612 && TYPE_UNSIGNED (TREE_TYPE (op0))
2613 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2615 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2617 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2618 if (follow_assert_exprs)
2620 while (gimple_assign_single_p (op1_def)
2621 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2623 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2624 if (TREE_CODE (op1) != SSA_NAME)
2625 break;
2626 op1_def = SSA_NAME_DEF_STMT (op1);
2630 /* Now look at the defining statement of OP1 to see if it adds
2631 or subtracts a nonzero constant from another operand. */
2632 if (op1_def
2633 && is_gimple_assign (op1_def)
2634 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2635 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2636 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2638 tree target = gimple_assign_rhs1 (op1_def);
2640 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2641 for one where TARGET appears on the RHS. */
2642 if (follow_assert_exprs)
2644 /* Now see if that "other operand" is op0, following the chain
2645 of ASSERT_EXPRs if necessary. */
2646 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2647 while (op0 != target
2648 && gimple_assign_single_p (op0_def)
2649 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2651 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2652 if (TREE_CODE (op0) != SSA_NAME)
2653 break;
2654 op0_def = SSA_NAME_DEF_STMT (op0);
2658 /* If we did not find our target SSA_NAME, then this is not
2659 an overflow test. */
2660 if (op0 != target)
2661 return false;
2663 tree type = TREE_TYPE (op0);
2664 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2665 tree inc = gimple_assign_rhs2 (op1_def);
2666 if (reversed)
2667 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2668 else
2669 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2670 return true;
2673 return false;
2676 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2677 OP1's defining statement to see if it ultimately has the form
2678 OP0 CODE (OP0 PLUS INTEGER_CST)
2680 If so, return TRUE indicating this is an overflow test and store into
2681 *NEW_CST an updated constant that can be used in a narrowed range test.
2683 These statements are left as-is in the IL to facilitate discovery of
2684 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2685 the alternate range representation is often useful within VRP. */
2687 bool
2688 overflow_comparison_p (tree_code code, tree name, tree val,
2689 bool use_equiv_p, tree *new_cst)
2691 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2692 return true;
2693 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2694 use_equiv_p, true, new_cst);
2698 /* Try to register an edge assertion for SSA name NAME on edge E for
2699 the condition COND contributing to the conditional jump pointed to by BSI.
2700 Invert the condition COND if INVERT is true. */
2702 static void
2703 register_edge_assert_for_2 (tree name, edge e,
2704 enum tree_code cond_code,
2705 tree cond_op0, tree cond_op1, bool invert,
2706 vec<assert_info> &asserts)
2708 tree val;
2709 enum tree_code comp_code;
2711 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2712 cond_op0,
2713 cond_op1,
2714 invert, &comp_code, &val))
2715 return;
2717 /* Queue the assert. */
2718 tree x;
2719 if (overflow_comparison_p (comp_code, name, val, false, &x))
2721 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2722 ? GT_EXPR : LE_EXPR);
2723 add_assert_info (asserts, name, name, new_code, x);
2725 add_assert_info (asserts, name, name, comp_code, val);
2727 /* In the case of NAME <= CST and NAME being defined as
2728 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2729 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2730 This catches range and anti-range tests. */
2731 if ((comp_code == LE_EXPR
2732 || comp_code == GT_EXPR)
2733 && TREE_CODE (val) == INTEGER_CST
2734 && TYPE_UNSIGNED (TREE_TYPE (val)))
2736 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2737 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2739 /* Extract CST2 from the (optional) addition. */
2740 if (is_gimple_assign (def_stmt)
2741 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2743 name2 = gimple_assign_rhs1 (def_stmt);
2744 cst2 = gimple_assign_rhs2 (def_stmt);
2745 if (TREE_CODE (name2) == SSA_NAME
2746 && TREE_CODE (cst2) == INTEGER_CST)
2747 def_stmt = SSA_NAME_DEF_STMT (name2);
2750 /* Extract NAME2 from the (optional) sign-changing cast. */
2751 if (gimple_assign_cast_p (def_stmt))
2753 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2754 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2755 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2756 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2757 name3 = gimple_assign_rhs1 (def_stmt);
2760 /* If name3 is used later, create an ASSERT_EXPR for it. */
2761 if (name3 != NULL_TREE
2762 && TREE_CODE (name3) == SSA_NAME
2763 && (cst2 == NULL_TREE
2764 || TREE_CODE (cst2) == INTEGER_CST)
2765 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2767 tree tmp;
2769 /* Build an expression for the range test. */
2770 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2771 if (cst2 != NULL_TREE)
2772 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2773 add_assert_info (asserts, name3, tmp, comp_code, val);
2776 /* If name2 is used later, create an ASSERT_EXPR for it. */
2777 if (name2 != NULL_TREE
2778 && TREE_CODE (name2) == SSA_NAME
2779 && TREE_CODE (cst2) == INTEGER_CST
2780 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2782 tree tmp;
2784 /* Build an expression for the range test. */
2785 tmp = name2;
2786 if (TREE_TYPE (name) != TREE_TYPE (name2))
2787 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2788 if (cst2 != NULL_TREE)
2789 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2790 add_assert_info (asserts, name2, tmp, comp_code, val);
2794 /* In the case of post-in/decrement tests like if (i++) ... and uses
2795 of the in/decremented value on the edge the extra name we want to
2796 assert for is not on the def chain of the name compared. Instead
2797 it is in the set of use stmts.
2798 Similar cases happen for conversions that were simplified through
2799 fold_{sign_changed,widened}_comparison. */
2800 if ((comp_code == NE_EXPR
2801 || comp_code == EQ_EXPR)
2802 && TREE_CODE (val) == INTEGER_CST)
2804 imm_use_iterator ui;
2805 gimple *use_stmt;
2806 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2808 if (!is_gimple_assign (use_stmt))
2809 continue;
2811 /* Cut off to use-stmts that are dominating the predecessor. */
2812 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2813 continue;
2815 tree name2 = gimple_assign_lhs (use_stmt);
2816 if (TREE_CODE (name2) != SSA_NAME)
2817 continue;
2819 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2820 tree cst;
2821 if (code == PLUS_EXPR
2822 || code == MINUS_EXPR)
2824 cst = gimple_assign_rhs2 (use_stmt);
2825 if (TREE_CODE (cst) != INTEGER_CST)
2826 continue;
2827 cst = int_const_binop (code, val, cst);
2829 else if (CONVERT_EXPR_CODE_P (code))
2831 /* For truncating conversions we cannot record
2832 an inequality. */
2833 if (comp_code == NE_EXPR
2834 && (TYPE_PRECISION (TREE_TYPE (name2))
2835 < TYPE_PRECISION (TREE_TYPE (name))))
2836 continue;
2837 cst = fold_convert (TREE_TYPE (name2), val);
2839 else
2840 continue;
2842 if (TREE_OVERFLOW_P (cst))
2843 cst = drop_tree_overflow (cst);
2844 add_assert_info (asserts, name2, name2, comp_code, cst);
2848 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2849 && TREE_CODE (val) == INTEGER_CST)
2851 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2852 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2853 tree val2 = NULL_TREE;
2854 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2855 wide_int mask = wi::zero (prec);
2856 unsigned int nprec = prec;
2857 enum tree_code rhs_code = ERROR_MARK;
2859 if (is_gimple_assign (def_stmt))
2860 rhs_code = gimple_assign_rhs_code (def_stmt);
2862 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2863 assert that A != CST1 -+ CST2. */
2864 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2865 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2867 tree op0 = gimple_assign_rhs1 (def_stmt);
2868 tree op1 = gimple_assign_rhs2 (def_stmt);
2869 if (TREE_CODE (op0) == SSA_NAME
2870 && TREE_CODE (op1) == INTEGER_CST)
2872 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2873 ? MINUS_EXPR : PLUS_EXPR);
2874 op1 = int_const_binop (reverse_op, val, op1);
2875 if (TREE_OVERFLOW (op1))
2876 op1 = drop_tree_overflow (op1);
2877 add_assert_info (asserts, op0, op0, comp_code, op1);
2881 /* Add asserts for NAME cmp CST and NAME being defined
2882 as NAME = (int) NAME2. */
2883 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2884 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2885 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2886 && gimple_assign_cast_p (def_stmt))
2888 name2 = gimple_assign_rhs1 (def_stmt);
2889 if (CONVERT_EXPR_CODE_P (rhs_code)
2890 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2891 && TYPE_UNSIGNED (TREE_TYPE (name2))
2892 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2893 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2894 || !tree_int_cst_equal (val,
2895 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2897 tree tmp, cst;
2898 enum tree_code new_comp_code = comp_code;
2900 cst = fold_convert (TREE_TYPE (name2),
2901 TYPE_MIN_VALUE (TREE_TYPE (val)));
2902 /* Build an expression for the range test. */
2903 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2904 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2905 fold_convert (TREE_TYPE (name2), val));
2906 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2908 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2909 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2910 build_int_cst (TREE_TYPE (name2), 1));
2912 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2916 /* Add asserts for NAME cmp CST and NAME being defined as
2917 NAME = NAME2 >> CST2.
2919 Extract CST2 from the right shift. */
2920 if (rhs_code == RSHIFT_EXPR)
2922 name2 = gimple_assign_rhs1 (def_stmt);
2923 cst2 = gimple_assign_rhs2 (def_stmt);
2924 if (TREE_CODE (name2) == SSA_NAME
2925 && tree_fits_uhwi_p (cst2)
2926 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2927 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2928 && type_has_mode_precision_p (TREE_TYPE (val)))
2930 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2931 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2934 if (val2 != NULL_TREE
2935 && TREE_CODE (val2) == INTEGER_CST
2936 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2937 TREE_TYPE (val),
2938 val2, cst2), val))
2940 enum tree_code new_comp_code = comp_code;
2941 tree tmp, new_val;
2943 tmp = name2;
2944 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2946 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2948 tree type = build_nonstandard_integer_type (prec, 1);
2949 tmp = build1 (NOP_EXPR, type, name2);
2950 val2 = fold_convert (type, val2);
2952 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2953 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2954 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2956 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2958 wide_int minval
2959 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2960 new_val = val2;
2961 if (minval == wi::to_wide (new_val))
2962 new_val = NULL_TREE;
2964 else
2966 wide_int maxval
2967 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2968 mask |= wi::to_wide (val2);
2969 if (wi::eq_p (mask, maxval))
2970 new_val = NULL_TREE;
2971 else
2972 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2975 if (new_val)
2976 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2979 /* Add asserts for NAME cmp CST and NAME being defined as
2980 NAME = NAME2 & CST2.
2982 Extract CST2 from the and.
2984 Also handle
2985 NAME = (unsigned) NAME2;
2986 casts where NAME's type is unsigned and has smaller precision
2987 than NAME2's type as if it was NAME = NAME2 & MASK. */
2988 names[0] = NULL_TREE;
2989 names[1] = NULL_TREE;
2990 cst2 = NULL_TREE;
2991 if (rhs_code == BIT_AND_EXPR
2992 || (CONVERT_EXPR_CODE_P (rhs_code)
2993 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2994 && TYPE_UNSIGNED (TREE_TYPE (val))
2995 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2996 > prec))
2998 name2 = gimple_assign_rhs1 (def_stmt);
2999 if (rhs_code == BIT_AND_EXPR)
3000 cst2 = gimple_assign_rhs2 (def_stmt);
3001 else
3003 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3004 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3006 if (TREE_CODE (name2) == SSA_NAME
3007 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3008 && TREE_CODE (cst2) == INTEGER_CST
3009 && !integer_zerop (cst2)
3010 && (nprec > 1
3011 || TYPE_UNSIGNED (TREE_TYPE (val))))
3013 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3014 if (gimple_assign_cast_p (def_stmt2))
3016 names[1] = gimple_assign_rhs1 (def_stmt2);
3017 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3018 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3019 || (TYPE_PRECISION (TREE_TYPE (name2))
3020 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3021 names[1] = NULL_TREE;
3023 names[0] = name2;
3026 if (names[0] || names[1])
3028 wide_int minv, maxv, valv, cst2v;
3029 wide_int tem, sgnbit;
3030 bool valid_p = false, valn, cst2n;
3031 enum tree_code ccode = comp_code;
3033 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3034 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3035 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3036 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3037 /* If CST2 doesn't have most significant bit set,
3038 but VAL is negative, we have comparison like
3039 if ((x & 0x123) > -4) (always true). Just give up. */
3040 if (!cst2n && valn)
3041 ccode = ERROR_MARK;
3042 if (cst2n)
3043 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3044 else
3045 sgnbit = wi::zero (nprec);
3046 minv = valv & cst2v;
3047 switch (ccode)
3049 case EQ_EXPR:
3050 /* Minimum unsigned value for equality is VAL & CST2
3051 (should be equal to VAL, otherwise we probably should
3052 have folded the comparison into false) and
3053 maximum unsigned value is VAL | ~CST2. */
3054 maxv = valv | ~cst2v;
3055 valid_p = true;
3056 break;
3058 case NE_EXPR:
3059 tem = valv | ~cst2v;
3060 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3061 if (valv == 0)
3063 cst2n = false;
3064 sgnbit = wi::zero (nprec);
3065 goto gt_expr;
3067 /* If (VAL | ~CST2) is all ones, handle it as
3068 (X & CST2) < VAL. */
3069 if (tem == -1)
3071 cst2n = false;
3072 valn = false;
3073 sgnbit = wi::zero (nprec);
3074 goto lt_expr;
3076 if (!cst2n && wi::neg_p (cst2v))
3077 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3078 if (sgnbit != 0)
3080 if (valv == sgnbit)
3082 cst2n = true;
3083 valn = true;
3084 goto gt_expr;
3086 if (tem == wi::mask (nprec - 1, false, nprec))
3088 cst2n = true;
3089 goto lt_expr;
3091 if (!cst2n)
3092 sgnbit = wi::zero (nprec);
3094 break;
3096 case GE_EXPR:
3097 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3098 is VAL and maximum unsigned value is ~0. For signed
3099 comparison, if CST2 doesn't have most significant bit
3100 set, handle it similarly. If CST2 has MSB set,
3101 the minimum is the same, and maximum is ~0U/2. */
3102 if (minv != valv)
3104 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3105 VAL. */
3106 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3107 if (minv == valv)
3108 break;
3110 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3111 valid_p = true;
3112 break;
3114 case GT_EXPR:
3115 gt_expr:
3116 /* Find out smallest MINV where MINV > VAL
3117 && (MINV & CST2) == MINV, if any. If VAL is signed and
3118 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3119 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3120 if (minv == valv)
3121 break;
3122 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3123 valid_p = true;
3124 break;
3126 case LE_EXPR:
3127 /* Minimum unsigned value for <= is 0 and maximum
3128 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3129 Otherwise, find smallest VAL2 where VAL2 > VAL
3130 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3131 as maximum.
3132 For signed comparison, if CST2 doesn't have most
3133 significant bit set, handle it similarly. If CST2 has
3134 MSB set, the maximum is the same and minimum is INT_MIN. */
3135 if (minv == valv)
3136 maxv = valv;
3137 else
3139 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3140 if (maxv == valv)
3141 break;
3142 maxv -= 1;
3144 maxv |= ~cst2v;
3145 minv = sgnbit;
3146 valid_p = true;
3147 break;
3149 case LT_EXPR:
3150 lt_expr:
3151 /* Minimum unsigned value for < is 0 and maximum
3152 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3153 Otherwise, find smallest VAL2 where VAL2 > VAL
3154 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3155 as maximum.
3156 For signed comparison, if CST2 doesn't have most
3157 significant bit set, handle it similarly. If CST2 has
3158 MSB set, the maximum is the same and minimum is INT_MIN. */
3159 if (minv == valv)
3161 if (valv == sgnbit)
3162 break;
3163 maxv = valv;
3165 else
3167 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3168 if (maxv == valv)
3169 break;
3171 maxv -= 1;
3172 maxv |= ~cst2v;
3173 minv = sgnbit;
3174 valid_p = true;
3175 break;
3177 default:
3178 break;
3180 if (valid_p
3181 && (maxv - minv) != -1)
3183 tree tmp, new_val, type;
3184 int i;
3186 for (i = 0; i < 2; i++)
3187 if (names[i])
3189 wide_int maxv2 = maxv;
3190 tmp = names[i];
3191 type = TREE_TYPE (names[i]);
3192 if (!TYPE_UNSIGNED (type))
3194 type = build_nonstandard_integer_type (nprec, 1);
3195 tmp = build1 (NOP_EXPR, type, names[i]);
3197 if (minv != 0)
3199 tmp = build2 (PLUS_EXPR, type, tmp,
3200 wide_int_to_tree (type, -minv));
3201 maxv2 = maxv - minv;
3203 new_val = wide_int_to_tree (type, maxv2);
3204 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3211 /* OP is an operand of a truth value expression which is known to have
3212 a particular value. Register any asserts for OP and for any
3213 operands in OP's defining statement.
3215 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3216 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3218 static void
3219 register_edge_assert_for_1 (tree op, enum tree_code code,
3220 edge e, vec<assert_info> &asserts)
3222 gimple *op_def;
3223 tree val;
3224 enum tree_code rhs_code;
3226 /* We only care about SSA_NAMEs. */
3227 if (TREE_CODE (op) != SSA_NAME)
3228 return;
3230 /* We know that OP will have a zero or nonzero value. */
3231 val = build_int_cst (TREE_TYPE (op), 0);
3232 add_assert_info (asserts, op, op, code, val);
3234 /* Now look at how OP is set. If it's set from a comparison,
3235 a truth operation or some bit operations, then we may be able
3236 to register information about the operands of that assignment. */
3237 op_def = SSA_NAME_DEF_STMT (op);
3238 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3239 return;
3241 rhs_code = gimple_assign_rhs_code (op_def);
3243 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3245 bool invert = (code == EQ_EXPR ? true : false);
3246 tree op0 = gimple_assign_rhs1 (op_def);
3247 tree op1 = gimple_assign_rhs2 (op_def);
3249 if (TREE_CODE (op0) == SSA_NAME)
3250 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3251 if (TREE_CODE (op1) == SSA_NAME)
3252 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3254 else if ((code == NE_EXPR
3255 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3256 || (code == EQ_EXPR
3257 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3259 /* Recurse on each operand. */
3260 tree op0 = gimple_assign_rhs1 (op_def);
3261 tree op1 = gimple_assign_rhs2 (op_def);
3262 if (TREE_CODE (op0) == SSA_NAME
3263 && has_single_use (op0))
3264 register_edge_assert_for_1 (op0, code, e, asserts);
3265 if (TREE_CODE (op1) == SSA_NAME
3266 && has_single_use (op1))
3267 register_edge_assert_for_1 (op1, code, e, asserts);
3269 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3270 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3272 /* Recurse, flipping CODE. */
3273 code = invert_tree_comparison (code, false);
3274 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3276 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3278 /* Recurse through the copy. */
3279 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3281 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3283 /* Recurse through the type conversion, unless it is a narrowing
3284 conversion or conversion from non-integral type. */
3285 tree rhs = gimple_assign_rhs1 (op_def);
3286 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3287 && (TYPE_PRECISION (TREE_TYPE (rhs))
3288 <= TYPE_PRECISION (TREE_TYPE (op))))
3289 register_edge_assert_for_1 (rhs, code, e, asserts);
3293 /* Check if comparison
3294 NAME COND_OP INTEGER_CST
3295 has a form of
3296 (X & 11...100..0) COND_OP XX...X00...0
3297 Such comparison can yield assertions like
3298 X >= XX...X00...0
3299 X <= XX...X11...1
3300 in case of COND_OP being EQ_EXPR or
3301 X < XX...X00...0
3302 X > XX...X11...1
3303 in case of NE_EXPR. */
3305 static bool
3306 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3307 tree *new_name, tree *low, enum tree_code *low_code,
3308 tree *high, enum tree_code *high_code)
3310 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3312 if (!is_gimple_assign (def_stmt)
3313 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3314 return false;
3316 tree t = gimple_assign_rhs1 (def_stmt);
3317 tree maskt = gimple_assign_rhs2 (def_stmt);
3318 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3319 return false;
3321 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3322 wide_int inv_mask = ~mask;
3323 /* Must have been removed by now so don't bother optimizing. */
3324 if (mask == 0 || inv_mask == 0)
3325 return false;
3327 /* Assume VALT is INTEGER_CST. */
3328 wi::tree_to_wide_ref val = wi::to_wide (valt);
3330 if ((inv_mask & (inv_mask + 1)) != 0
3331 || (val & mask) != val)
3332 return false;
3334 bool is_range = cond_code == EQ_EXPR;
3336 tree type = TREE_TYPE (t);
3337 wide_int min = wi::min_value (type),
3338 max = wi::max_value (type);
3340 if (is_range)
3342 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3343 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3345 else
3347 /* We can still generate assertion if one of alternatives
3348 is known to always be false. */
3349 if (val == min)
3351 *low_code = (enum tree_code) 0;
3352 *high_code = GT_EXPR;
3354 else if ((val | inv_mask) == max)
3356 *low_code = LT_EXPR;
3357 *high_code = (enum tree_code) 0;
3359 else
3360 return false;
3363 *new_name = t;
3364 *low = wide_int_to_tree (type, val);
3365 *high = wide_int_to_tree (type, val | inv_mask);
3367 return true;
3370 /* Try to register an edge assertion for SSA name NAME on edge E for
3371 the condition COND contributing to the conditional jump pointed to by
3372 SI. */
3374 void
3375 register_edge_assert_for (tree name, edge e,
3376 enum tree_code cond_code, tree cond_op0,
3377 tree cond_op1, vec<assert_info> &asserts)
3379 tree val;
3380 enum tree_code comp_code;
3381 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3383 /* Do not attempt to infer anything in names that flow through
3384 abnormal edges. */
3385 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3386 return;
3388 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3389 cond_op0, cond_op1,
3390 is_else_edge,
3391 &comp_code, &val))
3392 return;
3394 /* Register ASSERT_EXPRs for name. */
3395 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3396 cond_op1, is_else_edge, asserts);
3399 /* If COND is effectively an equality test of an SSA_NAME against
3400 the value zero or one, then we may be able to assert values
3401 for SSA_NAMEs which flow into COND. */
3403 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3404 statement of NAME we can assert both operands of the BIT_AND_EXPR
3405 have nonzero value. */
3406 if (((comp_code == EQ_EXPR && integer_onep (val))
3407 || (comp_code == NE_EXPR && integer_zerop (val))))
3409 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3411 if (is_gimple_assign (def_stmt)
3412 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3414 tree op0 = gimple_assign_rhs1 (def_stmt);
3415 tree op1 = gimple_assign_rhs2 (def_stmt);
3416 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3417 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3421 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3422 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3423 have zero value. */
3424 if (((comp_code == EQ_EXPR && integer_zerop (val))
3425 || (comp_code == NE_EXPR && integer_onep (val))))
3427 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3429 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3430 necessarily zero value, or if type-precision is one. */
3431 if (is_gimple_assign (def_stmt)
3432 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3433 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3434 || comp_code == EQ_EXPR)))
3436 tree op0 = gimple_assign_rhs1 (def_stmt);
3437 tree op1 = gimple_assign_rhs2 (def_stmt);
3438 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3439 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3443 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3444 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3445 && TREE_CODE (val) == INTEGER_CST)
3447 enum tree_code low_code, high_code;
3448 tree low, high;
3449 if (is_masked_range_test (name, val, comp_code, &name, &low,
3450 &low_code, &high, &high_code))
3452 if (low_code != ERROR_MARK)
3453 register_edge_assert_for_2 (name, e, low_code, name,
3454 low, /*invert*/false, asserts);
3455 if (high_code != ERROR_MARK)
3456 register_edge_assert_for_2 (name, e, high_code, name,
3457 high, /*invert*/false, asserts);
3462 /* Finish found ASSERTS for E and register them at GSI. */
3464 static void
3465 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3466 vec<assert_info> &asserts)
3468 for (unsigned i = 0; i < asserts.length (); ++i)
3469 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3470 reachable from E. */
3471 if (live_on_edge (e, asserts[i].name))
3472 register_new_assert_for (asserts[i].name, asserts[i].expr,
3473 asserts[i].comp_code, asserts[i].val,
3474 NULL, e, gsi);
3479 /* Determine whether the outgoing edges of BB should receive an
3480 ASSERT_EXPR for each of the operands of BB's LAST statement.
3481 The last statement of BB must be a COND_EXPR.
3483 If any of the sub-graphs rooted at BB have an interesting use of
3484 the predicate operands, an assert location node is added to the
3485 list of assertions for the corresponding operands. */
3487 static void
3488 find_conditional_asserts (basic_block bb, gcond *last)
3490 gimple_stmt_iterator bsi;
3491 tree op;
3492 edge_iterator ei;
3493 edge e;
3494 ssa_op_iter iter;
3496 bsi = gsi_for_stmt (last);
3498 /* Look for uses of the operands in each of the sub-graphs
3499 rooted at BB. We need to check each of the outgoing edges
3500 separately, so that we know what kind of ASSERT_EXPR to
3501 insert. */
3502 FOR_EACH_EDGE (e, ei, bb->succs)
3504 if (e->dest == bb)
3505 continue;
3507 /* Register the necessary assertions for each operand in the
3508 conditional predicate. */
3509 auto_vec<assert_info, 8> asserts;
3510 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3511 register_edge_assert_for (op, e,
3512 gimple_cond_code (last),
3513 gimple_cond_lhs (last),
3514 gimple_cond_rhs (last), asserts);
3515 finish_register_edge_assert_for (e, bsi, asserts);
3519 struct case_info
3521 tree expr;
3522 basic_block bb;
3525 /* Compare two case labels sorting first by the destination bb index
3526 and then by the case value. */
3528 static int
3529 compare_case_labels (const void *p1, const void *p2)
3531 const struct case_info *ci1 = (const struct case_info *) p1;
3532 const struct case_info *ci2 = (const struct case_info *) p2;
3533 int idx1 = ci1->bb->index;
3534 int idx2 = ci2->bb->index;
3536 if (idx1 < idx2)
3537 return -1;
3538 else if (idx1 == idx2)
3540 /* Make sure the default label is first in a group. */
3541 if (!CASE_LOW (ci1->expr))
3542 return -1;
3543 else if (!CASE_LOW (ci2->expr))
3544 return 1;
3545 else
3546 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3547 CASE_LOW (ci2->expr));
3549 else
3550 return 1;
3553 /* Determine whether the outgoing edges of BB should receive an
3554 ASSERT_EXPR for each of the operands of BB's LAST statement.
3555 The last statement of BB must be a SWITCH_EXPR.
3557 If any of the sub-graphs rooted at BB have an interesting use of
3558 the predicate operands, an assert location node is added to the
3559 list of assertions for the corresponding operands. */
3561 static void
3562 find_switch_asserts (basic_block bb, gswitch *last)
3564 gimple_stmt_iterator bsi;
3565 tree op;
3566 edge e;
3567 struct case_info *ci;
3568 size_t n = gimple_switch_num_labels (last);
3569 #if GCC_VERSION >= 4000
3570 unsigned int idx;
3571 #else
3572 /* Work around GCC 3.4 bug (PR 37086). */
3573 volatile unsigned int idx;
3574 #endif
3576 bsi = gsi_for_stmt (last);
3577 op = gimple_switch_index (last);
3578 if (TREE_CODE (op) != SSA_NAME)
3579 return;
3581 /* Build a vector of case labels sorted by destination label. */
3582 ci = XNEWVEC (struct case_info, n);
3583 for (idx = 0; idx < n; ++idx)
3585 ci[idx].expr = gimple_switch_label (last, idx);
3586 ci[idx].bb = label_to_block (cfun, CASE_LABEL (ci[idx].expr));
3588 edge default_edge = find_edge (bb, ci[0].bb);
3589 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3591 for (idx = 0; idx < n; ++idx)
3593 tree min, max;
3594 tree cl = ci[idx].expr;
3595 basic_block cbb = ci[idx].bb;
3597 min = CASE_LOW (cl);
3598 max = CASE_HIGH (cl);
3600 /* If there are multiple case labels with the same destination
3601 we need to combine them to a single value range for the edge. */
3602 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3604 /* Skip labels until the last of the group. */
3605 do {
3606 ++idx;
3607 } while (idx < n && cbb == ci[idx].bb);
3608 --idx;
3610 /* Pick up the maximum of the case label range. */
3611 if (CASE_HIGH (ci[idx].expr))
3612 max = CASE_HIGH (ci[idx].expr);
3613 else
3614 max = CASE_LOW (ci[idx].expr);
3617 /* Can't extract a useful assertion out of a range that includes the
3618 default label. */
3619 if (min == NULL_TREE)
3620 continue;
3622 /* Find the edge to register the assert expr on. */
3623 e = find_edge (bb, cbb);
3625 /* Register the necessary assertions for the operand in the
3626 SWITCH_EXPR. */
3627 auto_vec<assert_info, 8> asserts;
3628 register_edge_assert_for (op, e,
3629 max ? GE_EXPR : EQ_EXPR,
3630 op, fold_convert (TREE_TYPE (op), min),
3631 asserts);
3632 if (max)
3633 register_edge_assert_for (op, e, LE_EXPR, op,
3634 fold_convert (TREE_TYPE (op), max),
3635 asserts);
3636 finish_register_edge_assert_for (e, bsi, asserts);
3639 XDELETEVEC (ci);
3641 if (!live_on_edge (default_edge, op))
3642 return;
3644 /* Now register along the default label assertions that correspond to the
3645 anti-range of each label. */
3646 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3647 if (insertion_limit == 0)
3648 return;
3650 /* We can't do this if the default case shares a label with another case. */
3651 tree default_cl = gimple_switch_default_label (last);
3652 for (idx = 1; idx < n; idx++)
3654 tree min, max;
3655 tree cl = gimple_switch_label (last, idx);
3656 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3657 continue;
3659 min = CASE_LOW (cl);
3660 max = CASE_HIGH (cl);
3662 /* Combine contiguous case ranges to reduce the number of assertions
3663 to insert. */
3664 for (idx = idx + 1; idx < n; idx++)
3666 tree next_min, next_max;
3667 tree next_cl = gimple_switch_label (last, idx);
3668 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3669 break;
3671 next_min = CASE_LOW (next_cl);
3672 next_max = CASE_HIGH (next_cl);
3674 wide_int difference = (wi::to_wide (next_min)
3675 - wi::to_wide (max ? max : min));
3676 if (wi::eq_p (difference, 1))
3677 max = next_max ? next_max : next_min;
3678 else
3679 break;
3681 idx--;
3683 if (max == NULL_TREE)
3685 /* Register the assertion OP != MIN. */
3686 auto_vec<assert_info, 8> asserts;
3687 min = fold_convert (TREE_TYPE (op), min);
3688 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3689 asserts);
3690 finish_register_edge_assert_for (default_edge, bsi, asserts);
3692 else
3694 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3695 which will give OP the anti-range ~[MIN,MAX]. */
3696 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3697 min = fold_convert (TREE_TYPE (uop), min);
3698 max = fold_convert (TREE_TYPE (uop), max);
3700 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3701 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3702 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3703 NULL, default_edge, bsi);
3706 if (--insertion_limit == 0)
3707 break;
3712 /* Traverse all the statements in block BB looking for statements that
3713 may generate useful assertions for the SSA names in their operand.
3714 If a statement produces a useful assertion A for name N_i, then the
3715 list of assertions already generated for N_i is scanned to
3716 determine if A is actually needed.
3718 If N_i already had the assertion A at a location dominating the
3719 current location, then nothing needs to be done. Otherwise, the
3720 new location for A is recorded instead.
3722 1- For every statement S in BB, all the variables used by S are
3723 added to bitmap FOUND_IN_SUBGRAPH.
3725 2- If statement S uses an operand N in a way that exposes a known
3726 value range for N, then if N was not already generated by an
3727 ASSERT_EXPR, create a new assert location for N. For instance,
3728 if N is a pointer and the statement dereferences it, we can
3729 assume that N is not NULL.
3731 3- COND_EXPRs are a special case of #2. We can derive range
3732 information from the predicate but need to insert different
3733 ASSERT_EXPRs for each of the sub-graphs rooted at the
3734 conditional block. If the last statement of BB is a conditional
3735 expression of the form 'X op Y', then
3737 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3739 b) If the conditional is the only entry point to the sub-graph
3740 corresponding to the THEN_CLAUSE, recurse into it. On
3741 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3742 an ASSERT_EXPR is added for the corresponding variable.
3744 c) Repeat step (b) on the ELSE_CLAUSE.
3746 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3748 For instance,
3750 if (a == 9)
3751 b = a;
3752 else
3753 b = c + 1;
3755 In this case, an assertion on the THEN clause is useful to
3756 determine that 'a' is always 9 on that edge. However, an assertion
3757 on the ELSE clause would be unnecessary.
3759 4- If BB does not end in a conditional expression, then we recurse
3760 into BB's dominator children.
3762 At the end of the recursive traversal, every SSA name will have a
3763 list of locations where ASSERT_EXPRs should be added. When a new
3764 location for name N is found, it is registered by calling
3765 register_new_assert_for. That function keeps track of all the
3766 registered assertions to prevent adding unnecessary assertions.
3767 For instance, if a pointer P_4 is dereferenced more than once in a
3768 dominator tree, only the location dominating all the dereference of
3769 P_4 will receive an ASSERT_EXPR. */
3771 static void
3772 find_assert_locations_1 (basic_block bb, sbitmap live)
3774 gimple *last;
3776 last = last_stmt (bb);
3778 /* If BB's last statement is a conditional statement involving integer
3779 operands, determine if we need to add ASSERT_EXPRs. */
3780 if (last
3781 && gimple_code (last) == GIMPLE_COND
3782 && !fp_predicate (last)
3783 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3784 find_conditional_asserts (bb, as_a <gcond *> (last));
3786 /* If BB's last statement is a switch statement involving integer
3787 operands, determine if we need to add ASSERT_EXPRs. */
3788 if (last
3789 && gimple_code (last) == GIMPLE_SWITCH
3790 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3791 find_switch_asserts (bb, as_a <gswitch *> (last));
3793 /* Traverse all the statements in BB marking used names and looking
3794 for statements that may infer assertions for their used operands. */
3795 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3796 gsi_prev (&si))
3798 gimple *stmt;
3799 tree op;
3800 ssa_op_iter i;
3802 stmt = gsi_stmt (si);
3804 if (is_gimple_debug (stmt))
3805 continue;
3807 /* See if we can derive an assertion for any of STMT's operands. */
3808 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3810 tree value;
3811 enum tree_code comp_code;
3813 /* If op is not live beyond this stmt, do not bother to insert
3814 asserts for it. */
3815 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3816 continue;
3818 /* If OP is used in such a way that we can infer a value
3819 range for it, and we don't find a previous assertion for
3820 it, create a new assertion location node for OP. */
3821 if (infer_value_range (stmt, op, &comp_code, &value))
3823 /* If we are able to infer a nonzero value range for OP,
3824 then walk backwards through the use-def chain to see if OP
3825 was set via a typecast.
3827 If so, then we can also infer a nonzero value range
3828 for the operand of the NOP_EXPR. */
3829 if (comp_code == NE_EXPR && integer_zerop (value))
3831 tree t = op;
3832 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3834 while (is_gimple_assign (def_stmt)
3835 && CONVERT_EXPR_CODE_P
3836 (gimple_assign_rhs_code (def_stmt))
3837 && TREE_CODE
3838 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3839 && POINTER_TYPE_P
3840 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3842 t = gimple_assign_rhs1 (def_stmt);
3843 def_stmt = SSA_NAME_DEF_STMT (t);
3845 /* Note we want to register the assert for the
3846 operand of the NOP_EXPR after SI, not after the
3847 conversion. */
3848 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3849 register_new_assert_for (t, t, comp_code, value,
3850 bb, NULL, si);
3854 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3858 /* Update live. */
3859 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3860 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3861 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3862 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3865 /* Traverse all PHI nodes in BB, updating live. */
3866 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3867 gsi_next (&si))
3869 use_operand_p arg_p;
3870 ssa_op_iter i;
3871 gphi *phi = si.phi ();
3872 tree res = gimple_phi_result (phi);
3874 if (virtual_operand_p (res))
3875 continue;
3877 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3879 tree arg = USE_FROM_PTR (arg_p);
3880 if (TREE_CODE (arg) == SSA_NAME)
3881 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3884 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3888 /* Do an RPO walk over the function computing SSA name liveness
3889 on-the-fly and deciding on assert expressions to insert. */
3891 static void
3892 find_assert_locations (void)
3894 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3895 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3896 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3897 int rpo_cnt, i;
3899 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3900 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3901 for (i = 0; i < rpo_cnt; ++i)
3902 bb_rpo[rpo[i]] = i;
3904 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3905 the order we compute liveness and insert asserts we otherwise
3906 fail to insert asserts into the loop latch. */
3907 loop_p loop;
3908 FOR_EACH_LOOP (loop, 0)
3910 i = loop->latch->index;
3911 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3912 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3913 !gsi_end_p (gsi); gsi_next (&gsi))
3915 gphi *phi = gsi.phi ();
3916 if (virtual_operand_p (gimple_phi_result (phi)))
3917 continue;
3918 tree arg = gimple_phi_arg_def (phi, j);
3919 if (TREE_CODE (arg) == SSA_NAME)
3921 if (live[i] == NULL)
3923 live[i] = sbitmap_alloc (num_ssa_names);
3924 bitmap_clear (live[i]);
3926 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3931 for (i = rpo_cnt - 1; i >= 0; --i)
3933 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3934 edge e;
3935 edge_iterator ei;
3937 if (!live[rpo[i]])
3939 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
3940 bitmap_clear (live[rpo[i]]);
3943 /* Process BB and update the live information with uses in
3944 this block. */
3945 find_assert_locations_1 (bb, live[rpo[i]]);
3947 /* Merge liveness into the predecessor blocks and free it. */
3948 if (!bitmap_empty_p (live[rpo[i]]))
3950 int pred_rpo = i;
3951 FOR_EACH_EDGE (e, ei, bb->preds)
3953 int pred = e->src->index;
3954 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3955 continue;
3957 if (!live[pred])
3959 live[pred] = sbitmap_alloc (num_ssa_names);
3960 bitmap_clear (live[pred]);
3962 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
3964 if (bb_rpo[pred] < pred_rpo)
3965 pred_rpo = bb_rpo[pred];
3968 /* Record the RPO number of the last visited block that needs
3969 live information from this block. */
3970 last_rpo[rpo[i]] = pred_rpo;
3972 else
3974 sbitmap_free (live[rpo[i]]);
3975 live[rpo[i]] = NULL;
3978 /* We can free all successors live bitmaps if all their
3979 predecessors have been visited already. */
3980 FOR_EACH_EDGE (e, ei, bb->succs)
3981 if (last_rpo[e->dest->index] == i
3982 && live[e->dest->index])
3984 sbitmap_free (live[e->dest->index]);
3985 live[e->dest->index] = NULL;
3989 XDELETEVEC (rpo);
3990 XDELETEVEC (bb_rpo);
3991 XDELETEVEC (last_rpo);
3992 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
3993 if (live[i])
3994 sbitmap_free (live[i]);
3995 XDELETEVEC (live);
3998 /* Create an ASSERT_EXPR for NAME and insert it in the location
3999 indicated by LOC. Return true if we made any edge insertions. */
4001 static bool
4002 process_assert_insertions_for (tree name, assert_locus *loc)
4004 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4005 gimple *stmt;
4006 tree cond;
4007 gimple *assert_stmt;
4008 edge_iterator ei;
4009 edge e;
4011 /* If we have X <=> X do not insert an assert expr for that. */
4012 if (loc->expr == loc->val)
4013 return false;
4015 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4016 assert_stmt = build_assert_expr_for (cond, name);
4017 if (loc->e)
4019 /* We have been asked to insert the assertion on an edge. This
4020 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4021 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4022 || (gimple_code (gsi_stmt (loc->si))
4023 == GIMPLE_SWITCH));
4025 gsi_insert_on_edge (loc->e, assert_stmt);
4026 return true;
4029 /* If the stmt iterator points at the end then this is an insertion
4030 at the beginning of a block. */
4031 if (gsi_end_p (loc->si))
4033 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4034 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4035 return false;
4038 /* Otherwise, we can insert right after LOC->SI iff the
4039 statement must not be the last statement in the block. */
4040 stmt = gsi_stmt (loc->si);
4041 if (!stmt_ends_bb_p (stmt))
4043 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4044 return false;
4047 /* If STMT must be the last statement in BB, we can only insert new
4048 assertions on the non-abnormal edge out of BB. Note that since
4049 STMT is not control flow, there may only be one non-abnormal/eh edge
4050 out of BB. */
4051 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4052 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4054 gsi_insert_on_edge (e, assert_stmt);
4055 return true;
4058 gcc_unreachable ();
4061 /* Qsort helper for sorting assert locations. If stable is true, don't
4062 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4063 on the other side some pointers might be NULL. */
4065 template <bool stable>
4066 static int
4067 compare_assert_loc (const void *pa, const void *pb)
4069 assert_locus * const a = *(assert_locus * const *)pa;
4070 assert_locus * const b = *(assert_locus * const *)pb;
4072 /* If stable, some asserts might be optimized away already, sort
4073 them last. */
4074 if (stable)
4076 if (a == NULL)
4077 return b != NULL;
4078 else if (b == NULL)
4079 return -1;
4082 if (a->e == NULL && b->e != NULL)
4083 return 1;
4084 else if (a->e != NULL && b->e == NULL)
4085 return -1;
4087 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4088 no need to test both a->e and b->e. */
4090 /* Sort after destination index. */
4091 if (a->e == NULL)
4093 else if (a->e->dest->index > b->e->dest->index)
4094 return 1;
4095 else if (a->e->dest->index < b->e->dest->index)
4096 return -1;
4098 /* Sort after comp_code. */
4099 if (a->comp_code > b->comp_code)
4100 return 1;
4101 else if (a->comp_code < b->comp_code)
4102 return -1;
4104 hashval_t ha, hb;
4106 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4107 uses DECL_UID of the VAR_DECL, so sorting might differ between
4108 -g and -g0. When doing the removal of redundant assert exprs
4109 and commonization to successors, this does not matter, but for
4110 the final sort needs to be stable. */
4111 if (stable)
4113 ha = 0;
4114 hb = 0;
4116 else
4118 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4119 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4122 /* Break the tie using hashing and source/bb index. */
4123 if (ha == hb)
4124 return (a->e != NULL
4125 ? a->e->src->index - b->e->src->index
4126 : a->bb->index - b->bb->index);
4127 return ha > hb ? 1 : -1;
4130 /* Process all the insertions registered for every name N_i registered
4131 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4132 found in ASSERTS_FOR[i]. */
4134 static void
4135 process_assert_insertions (void)
4137 unsigned i;
4138 bitmap_iterator bi;
4139 bool update_edges_p = false;
4140 int num_asserts = 0;
4142 if (dump_file && (dump_flags & TDF_DETAILS))
4143 dump_all_asserts (dump_file);
4145 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4147 assert_locus *loc = asserts_for[i];
4148 gcc_assert (loc);
4150 auto_vec<assert_locus *, 16> asserts;
4151 for (; loc; loc = loc->next)
4152 asserts.safe_push (loc);
4153 asserts.qsort (compare_assert_loc<false>);
4155 /* Push down common asserts to successors and remove redundant ones. */
4156 unsigned ecnt = 0;
4157 assert_locus *common = NULL;
4158 unsigned commonj = 0;
4159 for (unsigned j = 0; j < asserts.length (); ++j)
4161 loc = asserts[j];
4162 if (! loc->e)
4163 common = NULL;
4164 else if (! common
4165 || loc->e->dest != common->e->dest
4166 || loc->comp_code != common->comp_code
4167 || ! operand_equal_p (loc->val, common->val, 0)
4168 || ! operand_equal_p (loc->expr, common->expr, 0))
4170 commonj = j;
4171 common = loc;
4172 ecnt = 1;
4174 else if (loc->e == asserts[j-1]->e)
4176 /* Remove duplicate asserts. */
4177 if (commonj == j - 1)
4179 commonj = j;
4180 common = loc;
4182 free (asserts[j-1]);
4183 asserts[j-1] = NULL;
4185 else
4187 ecnt++;
4188 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4190 /* We have the same assertion on all incoming edges of a BB.
4191 Insert it at the beginning of that block. */
4192 loc->bb = loc->e->dest;
4193 loc->e = NULL;
4194 loc->si = gsi_none ();
4195 common = NULL;
4196 /* Clear asserts commoned. */
4197 for (; commonj != j; ++commonj)
4198 if (asserts[commonj])
4200 free (asserts[commonj]);
4201 asserts[commonj] = NULL;
4207 /* The asserts vector sorting above might be unstable for
4208 -fcompare-debug, sort again to ensure a stable sort. */
4209 asserts.qsort (compare_assert_loc<true>);
4210 for (unsigned j = 0; j < asserts.length (); ++j)
4212 loc = asserts[j];
4213 if (! loc)
4214 break;
4215 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4216 num_asserts++;
4217 free (loc);
4221 if (update_edges_p)
4222 gsi_commit_edge_inserts ();
4224 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4225 num_asserts);
4229 /* Traverse the flowgraph looking for conditional jumps to insert range
4230 expressions. These range expressions are meant to provide information
4231 to optimizations that need to reason in terms of value ranges. They
4232 will not be expanded into RTL. For instance, given:
4234 x = ...
4235 y = ...
4236 if (x < y)
4237 y = x - 2;
4238 else
4239 x = y + 3;
4241 this pass will transform the code into:
4243 x = ...
4244 y = ...
4245 if (x < y)
4247 x = ASSERT_EXPR <x, x < y>
4248 y = x - 2
4250 else
4252 y = ASSERT_EXPR <y, x >= y>
4253 x = y + 3
4256 The idea is that once copy and constant propagation have run, other
4257 optimizations will be able to determine what ranges of values can 'x'
4258 take in different paths of the code, simply by checking the reaching
4259 definition of 'x'. */
4261 static void
4262 insert_range_assertions (void)
4264 need_assert_for = BITMAP_ALLOC (NULL);
4265 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4267 calculate_dominance_info (CDI_DOMINATORS);
4269 find_assert_locations ();
4270 if (!bitmap_empty_p (need_assert_for))
4272 process_assert_insertions ();
4273 update_ssa (TODO_update_ssa_no_phi);
4276 if (dump_file && (dump_flags & TDF_DETAILS))
4278 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4279 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4282 free (asserts_for);
4283 BITMAP_FREE (need_assert_for);
4286 class vrp_prop : public ssa_propagation_engine
4288 public:
4289 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4290 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4292 void vrp_initialize (void);
4293 void vrp_finalize (bool);
4294 void check_all_array_refs (void);
4295 void check_array_ref (location_t, tree, bool);
4296 void check_mem_ref (location_t, tree, bool);
4297 void search_for_addr_array (tree, location_t);
4299 class vr_values vr_values;
4300 /* Temporary delegator to minimize code churn. */
4301 value_range *get_value_range (const_tree op)
4302 { return vr_values.get_value_range (op); }
4303 void set_defs_to_varying (gimple *stmt)
4304 { return vr_values.set_defs_to_varying (stmt); }
4305 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4306 tree *output_p, value_range *vr)
4307 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4308 bool update_value_range (const_tree op, value_range *vr)
4309 { return vr_values.update_value_range (op, vr); }
4310 void extract_range_basic (value_range *vr, gimple *stmt)
4311 { vr_values.extract_range_basic (vr, stmt); }
4312 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4313 { vr_values.extract_range_from_phi_node (phi, vr); }
4315 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4316 and "struct" hacks. If VRP can determine that the
4317 array subscript is a constant, check if it is outside valid
4318 range. If the array subscript is a RANGE, warn if it is
4319 non-overlapping with valid range.
4320 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4322 void
4323 vrp_prop::check_array_ref (location_t location, tree ref,
4324 bool ignore_off_by_one)
4326 const value_range *vr = NULL;
4327 tree low_sub, up_sub;
4328 tree low_bound, up_bound, up_bound_p1;
4330 if (TREE_NO_WARNING (ref))
4331 return;
4333 low_sub = up_sub = TREE_OPERAND (ref, 1);
4334 up_bound = array_ref_up_bound (ref);
4336 if (!up_bound
4337 || TREE_CODE (up_bound) != INTEGER_CST
4338 || (warn_array_bounds < 2
4339 && array_at_struct_end_p (ref)))
4341 /* Accesses to trailing arrays via pointers may access storage
4342 beyond the types array bounds. For such arrays, or for flexible
4343 array members, as well as for other arrays of an unknown size,
4344 replace the upper bound with a more permissive one that assumes
4345 the size of the largest object is PTRDIFF_MAX. */
4346 tree eltsize = array_ref_element_size (ref);
4348 if (TREE_CODE (eltsize) != INTEGER_CST
4349 || integer_zerop (eltsize))
4351 up_bound = NULL_TREE;
4352 up_bound_p1 = NULL_TREE;
4354 else
4356 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4357 tree arg = TREE_OPERAND (ref, 0);
4358 poly_int64 off;
4360 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4361 maxbound = wide_int_to_tree (sizetype,
4362 wi::sub (wi::to_wide (maxbound),
4363 off));
4364 else
4365 maxbound = fold_convert (sizetype, maxbound);
4367 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4369 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4370 build_int_cst (ptrdiff_type_node, 1));
4373 else
4374 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4375 build_int_cst (TREE_TYPE (up_bound), 1));
4377 low_bound = array_ref_low_bound (ref);
4379 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4381 bool warned = false;
4383 /* Empty array. */
4384 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4385 warned = warning_at (location, OPT_Warray_bounds,
4386 "array subscript %E is above array bounds of %qT",
4387 low_bound, artype);
4389 if (TREE_CODE (low_sub) == SSA_NAME)
4391 vr = get_value_range (low_sub);
4392 if (!vr->undefined_p () && !vr->varying_p ())
4394 low_sub = vr->kind () == VR_RANGE ? vr->max () : vr->min ();
4395 up_sub = vr->kind () == VR_RANGE ? vr->min () : vr->max ();
4399 if (vr && vr->kind () == VR_ANTI_RANGE)
4401 if (up_bound
4402 && TREE_CODE (up_sub) == INTEGER_CST
4403 && (ignore_off_by_one
4404 ? tree_int_cst_lt (up_bound, up_sub)
4405 : tree_int_cst_le (up_bound, up_sub))
4406 && TREE_CODE (low_sub) == INTEGER_CST
4407 && tree_int_cst_le (low_sub, low_bound))
4408 warned = warning_at (location, OPT_Warray_bounds,
4409 "array subscript [%E, %E] is outside "
4410 "array bounds of %qT",
4411 low_sub, up_sub, artype);
4413 else if (up_bound
4414 && TREE_CODE (up_sub) == INTEGER_CST
4415 && (ignore_off_by_one
4416 ? !tree_int_cst_le (up_sub, up_bound_p1)
4417 : !tree_int_cst_le (up_sub, up_bound)))
4419 if (dump_file && (dump_flags & TDF_DETAILS))
4421 fprintf (dump_file, "Array bound warning for ");
4422 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4423 fprintf (dump_file, "\n");
4425 warned = warning_at (location, OPT_Warray_bounds,
4426 "array subscript %E is above array bounds of %qT",
4427 up_sub, artype);
4429 else if (TREE_CODE (low_sub) == INTEGER_CST
4430 && tree_int_cst_lt (low_sub, low_bound))
4432 if (dump_file && (dump_flags & TDF_DETAILS))
4434 fprintf (dump_file, "Array bound warning for ");
4435 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4436 fprintf (dump_file, "\n");
4438 warned = warning_at (location, OPT_Warray_bounds,
4439 "array subscript %E is below array bounds of %qT",
4440 low_sub, artype);
4443 if (warned)
4445 ref = TREE_OPERAND (ref, 0);
4447 if (DECL_P (ref))
4448 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4450 TREE_NO_WARNING (ref) = 1;
4454 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4455 references to string constants. If VRP can determine that the array
4456 subscript is a constant, check if it is outside valid range.
4457 If the array subscript is a RANGE, warn if it is non-overlapping
4458 with valid range.
4459 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4460 (used to allow one-past-the-end indices for code that takes
4461 the address of the just-past-the-end element of an array). */
4463 void
4464 vrp_prop::check_mem_ref (location_t location, tree ref,
4465 bool ignore_off_by_one)
4467 if (TREE_NO_WARNING (ref))
4468 return;
4470 tree arg = TREE_OPERAND (ref, 0);
4471 /* The constant and variable offset of the reference. */
4472 tree cstoff = TREE_OPERAND (ref, 1);
4473 tree varoff = NULL_TREE;
4475 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4477 /* The array or string constant bounds in bytes. Initially set
4478 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4479 determined. */
4480 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4482 /* The minimum and maximum intermediate offset. For a reference
4483 to be valid, not only does the final offset/subscript must be
4484 in bounds but all intermediate offsets should be as well.
4485 GCC may be able to deal gracefully with such out-of-bounds
4486 offsets so the checking is only enbaled at -Warray-bounds=2
4487 where it may help detect bugs in uses of the intermediate
4488 offsets that could otherwise not be detectable. */
4489 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4490 offset_int extrema[2] = { 0, wi::abs (ioff) };
4492 /* The range of the byte offset into the reference. */
4493 offset_int offrange[2] = { 0, 0 };
4495 const value_range *vr = NULL;
4497 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4498 The loop computes the the range of the final offset for expressions
4499 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4500 in some range. */
4501 while (TREE_CODE (arg) == SSA_NAME)
4503 gimple *def = SSA_NAME_DEF_STMT (arg);
4504 if (!is_gimple_assign (def))
4505 break;
4507 tree_code code = gimple_assign_rhs_code (def);
4508 if (code == POINTER_PLUS_EXPR)
4510 arg = gimple_assign_rhs1 (def);
4511 varoff = gimple_assign_rhs2 (def);
4513 else if (code == ASSERT_EXPR)
4515 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4516 continue;
4518 else
4519 return;
4521 /* VAROFF should always be a SSA_NAME here (and not even
4522 INTEGER_CST) but there's no point in taking chances. */
4523 if (TREE_CODE (varoff) != SSA_NAME)
4524 break;
4526 vr = get_value_range (varoff);
4527 if (!vr || vr->undefined_p () || vr->varying_p ())
4528 break;
4530 if (!vr->constant_p ())
4531 break;
4533 if (vr->kind () == VR_RANGE)
4535 if (tree_int_cst_lt (vr->min (), vr->max ()))
4537 offset_int min
4538 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min ()));
4539 offset_int max
4540 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max ()));
4541 if (min < max)
4543 offrange[0] += min;
4544 offrange[1] += max;
4546 else
4548 offrange[0] += max;
4549 offrange[1] += min;
4552 else
4554 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4555 to OFFRANGE. */
4556 offrange[0] += arrbounds[0];
4557 offrange[1] += arrbounds[1];
4560 else
4562 /* For an anti-range, analogously to the above, conservatively
4563 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4564 offrange[0] += arrbounds[0];
4565 offrange[1] += arrbounds[1];
4568 /* Keep track of the minimum and maximum offset. */
4569 if (offrange[1] < 0 && offrange[1] < extrema[0])
4570 extrema[0] = offrange[1];
4571 if (offrange[0] > 0 && offrange[0] > extrema[1])
4572 extrema[1] = offrange[0];
4574 if (offrange[0] < arrbounds[0])
4575 offrange[0] = arrbounds[0];
4577 if (offrange[1] > arrbounds[1])
4578 offrange[1] = arrbounds[1];
4581 if (TREE_CODE (arg) == ADDR_EXPR)
4583 arg = TREE_OPERAND (arg, 0);
4584 if (TREE_CODE (arg) != STRING_CST
4585 && TREE_CODE (arg) != VAR_DECL)
4586 return;
4588 else
4589 return;
4591 /* The type of the object being referred to. It can be an array,
4592 string literal, or a non-array type when the MEM_REF represents
4593 a reference/subscript via a pointer to an object that is not
4594 an element of an array. References to members of structs and
4595 unions are excluded because MEM_REF doesn't make it possible
4596 to identify the member where the reference originated.
4597 Incomplete types are excluded as well because their size is
4598 not known. */
4599 tree reftype = TREE_TYPE (arg);
4600 if (POINTER_TYPE_P (reftype)
4601 || !COMPLETE_TYPE_P (reftype)
4602 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4603 || RECORD_OR_UNION_TYPE_P (reftype))
4604 return;
4606 offset_int eltsize;
4607 if (TREE_CODE (reftype) == ARRAY_TYPE)
4609 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4611 if (tree dom = TYPE_DOMAIN (reftype))
4613 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4614 if (array_at_struct_end_p (arg)
4615 || !bnds[0] || !bnds[1])
4617 arrbounds[0] = 0;
4618 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4620 else
4622 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4623 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4626 else
4628 arrbounds[0] = 0;
4629 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4632 if (TREE_CODE (ref) == MEM_REF)
4634 /* For MEM_REF determine a tighter bound of the non-array
4635 element type. */
4636 tree eltype = TREE_TYPE (reftype);
4637 while (TREE_CODE (eltype) == ARRAY_TYPE)
4638 eltype = TREE_TYPE (eltype);
4639 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4642 else
4644 eltsize = 1;
4645 arrbounds[0] = 0;
4646 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4649 offrange[0] += ioff;
4650 offrange[1] += ioff;
4652 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4653 is set (when taking the address of the one-past-last element
4654 of an array) but always use the stricter bound in diagnostics. */
4655 offset_int ubound = arrbounds[1];
4656 if (ignore_off_by_one)
4657 ubound += 1;
4659 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4661 /* Treat a reference to a non-array object as one to an array
4662 of a single element. */
4663 if (TREE_CODE (reftype) != ARRAY_TYPE)
4664 reftype = build_array_type_nelts (reftype, 1);
4666 if (TREE_CODE (ref) == MEM_REF)
4668 /* Extract the element type out of MEM_REF and use its size
4669 to compute the index to print in the diagnostic; arrays
4670 in MEM_REF don't mean anything. */
4671 tree type = TREE_TYPE (ref);
4672 while (TREE_CODE (type) == ARRAY_TYPE)
4673 type = TREE_TYPE (type);
4674 tree size = TYPE_SIZE_UNIT (type);
4675 offrange[0] = offrange[0] / wi::to_offset (size);
4676 offrange[1] = offrange[1] / wi::to_offset (size);
4678 else
4680 /* For anything other than MEM_REF, compute the index to
4681 print in the diagnostic as the offset over element size. */
4682 offrange[0] = offrange[0] / eltsize;
4683 offrange[1] = offrange[1] / eltsize;
4686 bool warned;
4687 if (offrange[0] == offrange[1])
4688 warned = warning_at (location, OPT_Warray_bounds,
4689 "array subscript %wi is outside array bounds "
4690 "of %qT",
4691 offrange[0].to_shwi (), reftype);
4692 else
4693 warned = warning_at (location, OPT_Warray_bounds,
4694 "array subscript [%wi, %wi] is outside "
4695 "array bounds of %qT",
4696 offrange[0].to_shwi (),
4697 offrange[1].to_shwi (), reftype);
4698 if (warned && DECL_P (arg))
4699 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4701 TREE_NO_WARNING (ref) = 1;
4702 return;
4705 if (warn_array_bounds < 2)
4706 return;
4708 /* At level 2 check also intermediate offsets. */
4709 int i = 0;
4710 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4712 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4714 warning_at (location, OPT_Warray_bounds,
4715 "intermediate array offset %wi is outside array bounds "
4716 "of %qT",
4717 tmpidx, reftype);
4718 TREE_NO_WARNING (ref) = 1;
4722 /* Searches if the expr T, located at LOCATION computes
4723 address of an ARRAY_REF, and call check_array_ref on it. */
4725 void
4726 vrp_prop::search_for_addr_array (tree t, location_t location)
4728 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4731 if (TREE_CODE (t) == ARRAY_REF)
4732 check_array_ref (location, t, true /*ignore_off_by_one*/);
4733 else if (TREE_CODE (t) == MEM_REF)
4734 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4736 t = TREE_OPERAND (t, 0);
4738 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4740 if (TREE_CODE (t) != MEM_REF
4741 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4742 || TREE_NO_WARNING (t))
4743 return;
4745 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4746 tree low_bound, up_bound, el_sz;
4747 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4748 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4749 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4750 return;
4752 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4753 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4754 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4755 if (!low_bound
4756 || TREE_CODE (low_bound) != INTEGER_CST
4757 || !up_bound
4758 || TREE_CODE (up_bound) != INTEGER_CST
4759 || !el_sz
4760 || TREE_CODE (el_sz) != INTEGER_CST)
4761 return;
4763 offset_int idx;
4764 if (!mem_ref_offset (t).is_constant (&idx))
4765 return;
4767 bool warned = false;
4768 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4769 if (idx < 0)
4771 if (dump_file && (dump_flags & TDF_DETAILS))
4773 fprintf (dump_file, "Array bound warning for ");
4774 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4775 fprintf (dump_file, "\n");
4777 warned = warning_at (location, OPT_Warray_bounds,
4778 "array subscript %wi is below "
4779 "array bounds of %qT",
4780 idx.to_shwi (), TREE_TYPE (tem));
4782 else if (idx > (wi::to_offset (up_bound)
4783 - wi::to_offset (low_bound) + 1))
4785 if (dump_file && (dump_flags & TDF_DETAILS))
4787 fprintf (dump_file, "Array bound warning for ");
4788 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4789 fprintf (dump_file, "\n");
4791 warned = warning_at (location, OPT_Warray_bounds,
4792 "array subscript %wu is above "
4793 "array bounds of %qT",
4794 idx.to_uhwi (), TREE_TYPE (tem));
4797 if (warned)
4799 if (DECL_P (t))
4800 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4802 TREE_NO_WARNING (t) = 1;
4806 /* walk_tree() callback that checks if *TP is
4807 an ARRAY_REF inside an ADDR_EXPR (in which an array
4808 subscript one outside the valid range is allowed). Call
4809 check_array_ref for each ARRAY_REF found. The location is
4810 passed in DATA. */
4812 static tree
4813 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4815 tree t = *tp;
4816 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4817 location_t location;
4819 if (EXPR_HAS_LOCATION (t))
4820 location = EXPR_LOCATION (t);
4821 else
4822 location = gimple_location (wi->stmt);
4824 *walk_subtree = TRUE;
4826 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4827 if (TREE_CODE (t) == ARRAY_REF)
4828 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4829 else if (TREE_CODE (t) == MEM_REF)
4830 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4831 else if (TREE_CODE (t) == ADDR_EXPR)
4833 vrp_prop->search_for_addr_array (t, location);
4834 *walk_subtree = FALSE;
4837 return NULL_TREE;
4840 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4841 to walk over all statements of all reachable BBs and call
4842 check_array_bounds on them. */
4844 class check_array_bounds_dom_walker : public dom_walker
4846 public:
4847 check_array_bounds_dom_walker (vrp_prop *prop)
4848 : dom_walker (CDI_DOMINATORS,
4849 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4850 flags, so that we can merge in information on
4851 non-executable edges from vrp_folder . */
4852 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4853 m_prop (prop) {}
4854 ~check_array_bounds_dom_walker () {}
4856 edge before_dom_children (basic_block) FINAL OVERRIDE;
4858 private:
4859 vrp_prop *m_prop;
4862 /* Implementation of dom_walker::before_dom_children.
4864 Walk over all statements of BB and call check_array_bounds on them,
4865 and determine if there's a unique successor edge. */
4867 edge
4868 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4870 gimple_stmt_iterator si;
4871 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4873 gimple *stmt = gsi_stmt (si);
4874 struct walk_stmt_info wi;
4875 if (!gimple_has_location (stmt)
4876 || is_gimple_debug (stmt))
4877 continue;
4879 memset (&wi, 0, sizeof (wi));
4881 wi.info = m_prop;
4883 walk_gimple_op (stmt, check_array_bounds, &wi);
4886 /* Determine if there's a unique successor edge, and if so, return
4887 that back to dom_walker, ensuring that we don't visit blocks that
4888 became unreachable during the VRP propagation
4889 (PR tree-optimization/83312). */
4890 return find_taken_edge (bb, NULL_TREE);
4893 /* Walk over all statements of all reachable BBs and call check_array_bounds
4894 on them. */
4896 void
4897 vrp_prop::check_all_array_refs ()
4899 check_array_bounds_dom_walker w (this);
4900 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4903 /* Return true if all imm uses of VAR are either in STMT, or
4904 feed (optionally through a chain of single imm uses) GIMPLE_COND
4905 in basic block COND_BB. */
4907 static bool
4908 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4910 use_operand_p use_p, use2_p;
4911 imm_use_iterator iter;
4913 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4914 if (USE_STMT (use_p) != stmt)
4916 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4917 if (is_gimple_debug (use_stmt))
4918 continue;
4919 while (is_gimple_assign (use_stmt)
4920 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4921 && single_imm_use (gimple_assign_lhs (use_stmt),
4922 &use2_p, &use_stmt2))
4923 use_stmt = use_stmt2;
4924 if (gimple_code (use_stmt) != GIMPLE_COND
4925 || gimple_bb (use_stmt) != cond_bb)
4926 return false;
4928 return true;
4931 /* Handle
4932 _4 = x_3 & 31;
4933 if (_4 != 0)
4934 goto <bb 6>;
4935 else
4936 goto <bb 7>;
4937 <bb 6>:
4938 __builtin_unreachable ();
4939 <bb 7>:
4940 x_5 = ASSERT_EXPR <x_3, ...>;
4941 If x_3 has no other immediate uses (checked by caller),
4942 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4943 from the non-zero bitmask. */
4945 void
4946 maybe_set_nonzero_bits (edge e, tree var)
4948 basic_block cond_bb = e->src;
4949 gimple *stmt = last_stmt (cond_bb);
4950 tree cst;
4952 if (stmt == NULL
4953 || gimple_code (stmt) != GIMPLE_COND
4954 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
4955 ? EQ_EXPR : NE_EXPR)
4956 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
4957 || !integer_zerop (gimple_cond_rhs (stmt)))
4958 return;
4960 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
4961 if (!is_gimple_assign (stmt)
4962 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4963 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
4964 return;
4965 if (gimple_assign_rhs1 (stmt) != var)
4967 gimple *stmt2;
4969 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
4970 return;
4971 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
4972 if (!gimple_assign_cast_p (stmt2)
4973 || gimple_assign_rhs1 (stmt2) != var
4974 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
4975 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
4976 != TYPE_PRECISION (TREE_TYPE (var))))
4977 return;
4979 cst = gimple_assign_rhs2 (stmt);
4980 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
4981 wi::to_wide (cst)));
4984 /* Convert range assertion expressions into the implied copies and
4985 copy propagate away the copies. Doing the trivial copy propagation
4986 here avoids the need to run the full copy propagation pass after
4987 VRP.
4989 FIXME, this will eventually lead to copy propagation removing the
4990 names that had useful range information attached to them. For
4991 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4992 then N_i will have the range [3, +INF].
4994 However, by converting the assertion into the implied copy
4995 operation N_i = N_j, we will then copy-propagate N_j into the uses
4996 of N_i and lose the range information. We may want to hold on to
4997 ASSERT_EXPRs a little while longer as the ranges could be used in
4998 things like jump threading.
5000 The problem with keeping ASSERT_EXPRs around is that passes after
5001 VRP need to handle them appropriately.
5003 Another approach would be to make the range information a first
5004 class property of the SSA_NAME so that it can be queried from
5005 any pass. This is made somewhat more complex by the need for
5006 multiple ranges to be associated with one SSA_NAME. */
5008 static void
5009 remove_range_assertions (void)
5011 basic_block bb;
5012 gimple_stmt_iterator si;
5013 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5014 a basic block preceeded by GIMPLE_COND branching to it and
5015 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5016 int is_unreachable;
5018 /* Note that the BSI iterator bump happens at the bottom of the
5019 loop and no bump is necessary if we're removing the statement
5020 referenced by the current BSI. */
5021 FOR_EACH_BB_FN (bb, cfun)
5022 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5024 gimple *stmt = gsi_stmt (si);
5026 if (is_gimple_assign (stmt)
5027 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5029 tree lhs = gimple_assign_lhs (stmt);
5030 tree rhs = gimple_assign_rhs1 (stmt);
5031 tree var;
5033 var = ASSERT_EXPR_VAR (rhs);
5035 if (TREE_CODE (var) == SSA_NAME
5036 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5037 && SSA_NAME_RANGE_INFO (lhs))
5039 if (is_unreachable == -1)
5041 is_unreachable = 0;
5042 if (single_pred_p (bb)
5043 && assert_unreachable_fallthru_edge_p
5044 (single_pred_edge (bb)))
5045 is_unreachable = 1;
5047 /* Handle
5048 if (x_7 >= 10 && x_7 < 20)
5049 __builtin_unreachable ();
5050 x_8 = ASSERT_EXPR <x_7, ...>;
5051 if the only uses of x_7 are in the ASSERT_EXPR and
5052 in the condition. In that case, we can copy the
5053 range info from x_8 computed in this pass also
5054 for x_7. */
5055 if (is_unreachable
5056 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5057 single_pred (bb)))
5059 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5060 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5061 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5062 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5066 /* Propagate the RHS into every use of the LHS. For SSA names
5067 also propagate abnormals as it merely restores the original
5068 IL in this case (an replace_uses_by would assert). */
5069 if (TREE_CODE (var) == SSA_NAME)
5071 imm_use_iterator iter;
5072 use_operand_p use_p;
5073 gimple *use_stmt;
5074 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5075 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5076 SET_USE (use_p, var);
5078 else
5079 replace_uses_by (lhs, var);
5081 /* And finally, remove the copy, it is not needed. */
5082 gsi_remove (&si, true);
5083 release_defs (stmt);
5085 else
5087 if (!is_gimple_debug (gsi_stmt (si)))
5088 is_unreachable = 0;
5089 gsi_next (&si);
5094 /* Return true if STMT is interesting for VRP. */
5096 bool
5097 stmt_interesting_for_vrp (gimple *stmt)
5099 if (gimple_code (stmt) == GIMPLE_PHI)
5101 tree res = gimple_phi_result (stmt);
5102 return (!virtual_operand_p (res)
5103 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5104 || POINTER_TYPE_P (TREE_TYPE (res))));
5106 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5108 tree lhs = gimple_get_lhs (stmt);
5110 /* In general, assignments with virtual operands are not useful
5111 for deriving ranges, with the obvious exception of calls to
5112 builtin functions. */
5113 if (lhs && TREE_CODE (lhs) == SSA_NAME
5114 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5115 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5116 && (is_gimple_call (stmt)
5117 || !gimple_vuse (stmt)))
5118 return true;
5119 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5120 switch (gimple_call_internal_fn (stmt))
5122 case IFN_ADD_OVERFLOW:
5123 case IFN_SUB_OVERFLOW:
5124 case IFN_MUL_OVERFLOW:
5125 case IFN_ATOMIC_COMPARE_EXCHANGE:
5126 /* These internal calls return _Complex integer type,
5127 but are interesting to VRP nevertheless. */
5128 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5129 return true;
5130 break;
5131 default:
5132 break;
5135 else if (gimple_code (stmt) == GIMPLE_COND
5136 || gimple_code (stmt) == GIMPLE_SWITCH)
5137 return true;
5139 return false;
5142 /* Initialization required by ssa_propagate engine. */
5144 void
5145 vrp_prop::vrp_initialize ()
5147 basic_block bb;
5149 FOR_EACH_BB_FN (bb, cfun)
5151 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5152 gsi_next (&si))
5154 gphi *phi = si.phi ();
5155 if (!stmt_interesting_for_vrp (phi))
5157 tree lhs = PHI_RESULT (phi);
5158 get_value_range (lhs)->set_varying ();
5159 prop_set_simulate_again (phi, false);
5161 else
5162 prop_set_simulate_again (phi, true);
5165 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5166 gsi_next (&si))
5168 gimple *stmt = gsi_stmt (si);
5170 /* If the statement is a control insn, then we do not
5171 want to avoid simulating the statement once. Failure
5172 to do so means that those edges will never get added. */
5173 if (stmt_ends_bb_p (stmt))
5174 prop_set_simulate_again (stmt, true);
5175 else if (!stmt_interesting_for_vrp (stmt))
5177 set_defs_to_varying (stmt);
5178 prop_set_simulate_again (stmt, false);
5180 else
5181 prop_set_simulate_again (stmt, true);
5186 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5187 that includes the value VAL. The search is restricted to the range
5188 [START_IDX, n - 1] where n is the size of VEC.
5190 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5191 returned.
5193 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5194 it is placed in IDX and false is returned.
5196 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5197 returned. */
5199 bool
5200 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5202 size_t n = gimple_switch_num_labels (stmt);
5203 size_t low, high;
5205 /* Find case label for minimum of the value range or the next one.
5206 At each iteration we are searching in [low, high - 1]. */
5208 for (low = start_idx, high = n; high != low; )
5210 tree t;
5211 int cmp;
5212 /* Note that i != high, so we never ask for n. */
5213 size_t i = (high + low) / 2;
5214 t = gimple_switch_label (stmt, i);
5216 /* Cache the result of comparing CASE_LOW and val. */
5217 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5219 if (cmp == 0)
5221 /* Ranges cannot be empty. */
5222 *idx = i;
5223 return true;
5225 else if (cmp > 0)
5226 high = i;
5227 else
5229 low = i + 1;
5230 if (CASE_HIGH (t) != NULL
5231 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5233 *idx = i;
5234 return true;
5239 *idx = high;
5240 return false;
5243 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5244 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5245 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5246 then MAX_IDX < MIN_IDX.
5247 Returns true if the default label is not needed. */
5249 bool
5250 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5251 size_t *max_idx)
5253 size_t i, j;
5254 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5255 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5257 if (i == j
5258 && min_take_default
5259 && max_take_default)
5261 /* Only the default case label reached.
5262 Return an empty range. */
5263 *min_idx = 1;
5264 *max_idx = 0;
5265 return false;
5267 else
5269 bool take_default = min_take_default || max_take_default;
5270 tree low, high;
5271 size_t k;
5273 if (max_take_default)
5274 j--;
5276 /* If the case label range is continuous, we do not need
5277 the default case label. Verify that. */
5278 high = CASE_LOW (gimple_switch_label (stmt, i));
5279 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5280 high = CASE_HIGH (gimple_switch_label (stmt, i));
5281 for (k = i + 1; k <= j; ++k)
5283 low = CASE_LOW (gimple_switch_label (stmt, k));
5284 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5286 take_default = true;
5287 break;
5289 high = low;
5290 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5291 high = CASE_HIGH (gimple_switch_label (stmt, k));
5294 *min_idx = i;
5295 *max_idx = j;
5296 return !take_default;
5300 /* Evaluate statement STMT. If the statement produces a useful range,
5301 return SSA_PROP_INTERESTING and record the SSA name with the
5302 interesting range into *OUTPUT_P.
5304 If STMT is a conditional branch and we can determine its truth
5305 value, the taken edge is recorded in *TAKEN_EDGE_P.
5307 If STMT produces a varying value, return SSA_PROP_VARYING. */
5309 enum ssa_prop_result
5310 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5312 tree lhs = gimple_get_lhs (stmt);
5313 value_range vr;
5314 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5316 if (*output_p)
5318 if (update_value_range (*output_p, &vr))
5320 if (dump_file && (dump_flags & TDF_DETAILS))
5322 fprintf (dump_file, "Found new range for ");
5323 print_generic_expr (dump_file, *output_p);
5324 fprintf (dump_file, ": ");
5325 dump_value_range (dump_file, &vr);
5326 fprintf (dump_file, "\n");
5329 if (vr.varying_p ())
5330 return SSA_PROP_VARYING;
5332 return SSA_PROP_INTERESTING;
5334 return SSA_PROP_NOT_INTERESTING;
5337 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5338 switch (gimple_call_internal_fn (stmt))
5340 case IFN_ADD_OVERFLOW:
5341 case IFN_SUB_OVERFLOW:
5342 case IFN_MUL_OVERFLOW:
5343 case IFN_ATOMIC_COMPARE_EXCHANGE:
5344 /* These internal calls return _Complex integer type,
5345 which VRP does not track, but the immediate uses
5346 thereof might be interesting. */
5347 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5349 imm_use_iterator iter;
5350 use_operand_p use_p;
5351 enum ssa_prop_result res = SSA_PROP_VARYING;
5353 get_value_range (lhs)->set_varying ();
5355 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5357 gimple *use_stmt = USE_STMT (use_p);
5358 if (!is_gimple_assign (use_stmt))
5359 continue;
5360 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5361 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5362 continue;
5363 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5364 tree use_lhs = gimple_assign_lhs (use_stmt);
5365 if (TREE_CODE (rhs1) != rhs_code
5366 || TREE_OPERAND (rhs1, 0) != lhs
5367 || TREE_CODE (use_lhs) != SSA_NAME
5368 || !stmt_interesting_for_vrp (use_stmt)
5369 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5370 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5371 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5372 continue;
5374 /* If there is a change in the value range for any of the
5375 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5376 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5377 or IMAGPART_EXPR immediate uses, but none of them have
5378 a change in their value ranges, return
5379 SSA_PROP_NOT_INTERESTING. If there are no
5380 {REAL,IMAG}PART_EXPR uses at all,
5381 return SSA_PROP_VARYING. */
5382 value_range new_vr;
5383 extract_range_basic (&new_vr, use_stmt);
5384 const value_range *old_vr = get_value_range (use_lhs);
5385 if (*old_vr != new_vr)
5386 res = SSA_PROP_INTERESTING;
5387 else
5388 res = SSA_PROP_NOT_INTERESTING;
5389 new_vr.equiv_clear ();
5390 if (res == SSA_PROP_INTERESTING)
5392 *output_p = lhs;
5393 return res;
5397 return res;
5399 break;
5400 default:
5401 break;
5404 /* All other statements produce nothing of interest for VRP, so mark
5405 their outputs varying and prevent further simulation. */
5406 set_defs_to_varying (stmt);
5408 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5411 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5412 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5413 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5414 possible such range. The resulting range is not canonicalized. */
5416 static void
5417 union_ranges (enum value_range_kind *vr0type,
5418 tree *vr0min, tree *vr0max,
5419 enum value_range_kind vr1type,
5420 tree vr1min, tree vr1max)
5422 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5423 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5425 /* [] is vr0, () is vr1 in the following classification comments. */
5426 if (mineq && maxeq)
5428 /* [( )] */
5429 if (*vr0type == vr1type)
5430 /* Nothing to do for equal ranges. */
5432 else if ((*vr0type == VR_RANGE
5433 && vr1type == VR_ANTI_RANGE)
5434 || (*vr0type == VR_ANTI_RANGE
5435 && vr1type == VR_RANGE))
5437 /* For anti-range with range union the result is varying. */
5438 goto give_up;
5440 else
5441 gcc_unreachable ();
5443 else if (operand_less_p (*vr0max, vr1min) == 1
5444 || operand_less_p (vr1max, *vr0min) == 1)
5446 /* [ ] ( ) or ( ) [ ]
5447 If the ranges have an empty intersection, result of the union
5448 operation is the anti-range or if both are anti-ranges
5449 it covers all. */
5450 if (*vr0type == VR_ANTI_RANGE
5451 && vr1type == VR_ANTI_RANGE)
5452 goto give_up;
5453 else if (*vr0type == VR_ANTI_RANGE
5454 && vr1type == VR_RANGE)
5456 else if (*vr0type == VR_RANGE
5457 && vr1type == VR_ANTI_RANGE)
5459 *vr0type = vr1type;
5460 *vr0min = vr1min;
5461 *vr0max = vr1max;
5463 else if (*vr0type == VR_RANGE
5464 && vr1type == VR_RANGE)
5466 /* The result is the convex hull of both ranges. */
5467 if (operand_less_p (*vr0max, vr1min) == 1)
5469 /* If the result can be an anti-range, create one. */
5470 if (TREE_CODE (*vr0max) == INTEGER_CST
5471 && TREE_CODE (vr1min) == INTEGER_CST
5472 && vrp_val_is_min (*vr0min)
5473 && vrp_val_is_max (vr1max))
5475 tree min = int_const_binop (PLUS_EXPR,
5476 *vr0max,
5477 build_int_cst (TREE_TYPE (*vr0max), 1));
5478 tree max = int_const_binop (MINUS_EXPR,
5479 vr1min,
5480 build_int_cst (TREE_TYPE (vr1min), 1));
5481 if (!operand_less_p (max, min))
5483 *vr0type = VR_ANTI_RANGE;
5484 *vr0min = min;
5485 *vr0max = max;
5487 else
5488 *vr0max = vr1max;
5490 else
5491 *vr0max = vr1max;
5493 else
5495 /* If the result can be an anti-range, create one. */
5496 if (TREE_CODE (vr1max) == INTEGER_CST
5497 && TREE_CODE (*vr0min) == INTEGER_CST
5498 && vrp_val_is_min (vr1min)
5499 && vrp_val_is_max (*vr0max))
5501 tree min = int_const_binop (PLUS_EXPR,
5502 vr1max,
5503 build_int_cst (TREE_TYPE (vr1max), 1));
5504 tree max = int_const_binop (MINUS_EXPR,
5505 *vr0min,
5506 build_int_cst (TREE_TYPE (*vr0min), 1));
5507 if (!operand_less_p (max, min))
5509 *vr0type = VR_ANTI_RANGE;
5510 *vr0min = min;
5511 *vr0max = max;
5513 else
5514 *vr0min = vr1min;
5516 else
5517 *vr0min = vr1min;
5520 else
5521 gcc_unreachable ();
5523 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5524 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5526 /* [ ( ) ] or [( ) ] or [ ( )] */
5527 if (*vr0type == VR_RANGE
5528 && vr1type == VR_RANGE)
5530 else if (*vr0type == VR_ANTI_RANGE
5531 && vr1type == VR_ANTI_RANGE)
5533 *vr0type = vr1type;
5534 *vr0min = vr1min;
5535 *vr0max = vr1max;
5537 else if (*vr0type == VR_ANTI_RANGE
5538 && vr1type == VR_RANGE)
5540 /* Arbitrarily choose the right or left gap. */
5541 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5542 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5543 build_int_cst (TREE_TYPE (vr1min), 1));
5544 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5545 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5546 build_int_cst (TREE_TYPE (vr1max), 1));
5547 else
5548 goto give_up;
5550 else if (*vr0type == VR_RANGE
5551 && vr1type == VR_ANTI_RANGE)
5552 /* The result covers everything. */
5553 goto give_up;
5554 else
5555 gcc_unreachable ();
5557 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5558 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5560 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5561 if (*vr0type == VR_RANGE
5562 && vr1type == VR_RANGE)
5564 *vr0type = vr1type;
5565 *vr0min = vr1min;
5566 *vr0max = vr1max;
5568 else if (*vr0type == VR_ANTI_RANGE
5569 && vr1type == VR_ANTI_RANGE)
5571 else if (*vr0type == VR_RANGE
5572 && vr1type == VR_ANTI_RANGE)
5574 *vr0type = VR_ANTI_RANGE;
5575 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5577 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5578 build_int_cst (TREE_TYPE (*vr0min), 1));
5579 *vr0min = vr1min;
5581 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5583 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5584 build_int_cst (TREE_TYPE (*vr0max), 1));
5585 *vr0max = vr1max;
5587 else
5588 goto give_up;
5590 else if (*vr0type == VR_ANTI_RANGE
5591 && vr1type == VR_RANGE)
5592 /* The result covers everything. */
5593 goto give_up;
5594 else
5595 gcc_unreachable ();
5597 else if ((operand_less_p (vr1min, *vr0max) == 1
5598 || operand_equal_p (vr1min, *vr0max, 0))
5599 && operand_less_p (*vr0min, vr1min) == 1
5600 && operand_less_p (*vr0max, vr1max) == 1)
5602 /* [ ( ] ) or [ ]( ) */
5603 if (*vr0type == VR_RANGE
5604 && vr1type == VR_RANGE)
5605 *vr0max = vr1max;
5606 else if (*vr0type == VR_ANTI_RANGE
5607 && vr1type == VR_ANTI_RANGE)
5608 *vr0min = vr1min;
5609 else if (*vr0type == VR_ANTI_RANGE
5610 && vr1type == VR_RANGE)
5612 if (TREE_CODE (vr1min) == INTEGER_CST)
5613 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5614 build_int_cst (TREE_TYPE (vr1min), 1));
5615 else
5616 goto give_up;
5618 else if (*vr0type == VR_RANGE
5619 && vr1type == VR_ANTI_RANGE)
5621 if (TREE_CODE (*vr0max) == INTEGER_CST)
5623 *vr0type = vr1type;
5624 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5625 build_int_cst (TREE_TYPE (*vr0max), 1));
5626 *vr0max = vr1max;
5628 else
5629 goto give_up;
5631 else
5632 gcc_unreachable ();
5634 else if ((operand_less_p (*vr0min, vr1max) == 1
5635 || operand_equal_p (*vr0min, vr1max, 0))
5636 && operand_less_p (vr1min, *vr0min) == 1
5637 && operand_less_p (vr1max, *vr0max) == 1)
5639 /* ( [ ) ] or ( )[ ] */
5640 if (*vr0type == VR_RANGE
5641 && vr1type == VR_RANGE)
5642 *vr0min = vr1min;
5643 else if (*vr0type == VR_ANTI_RANGE
5644 && vr1type == VR_ANTI_RANGE)
5645 *vr0max = vr1max;
5646 else if (*vr0type == VR_ANTI_RANGE
5647 && vr1type == VR_RANGE)
5649 if (TREE_CODE (vr1max) == INTEGER_CST)
5650 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5651 build_int_cst (TREE_TYPE (vr1max), 1));
5652 else
5653 goto give_up;
5655 else if (*vr0type == VR_RANGE
5656 && vr1type == VR_ANTI_RANGE)
5658 if (TREE_CODE (*vr0min) == INTEGER_CST)
5660 *vr0type = vr1type;
5661 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5662 build_int_cst (TREE_TYPE (*vr0min), 1));
5663 *vr0min = vr1min;
5665 else
5666 goto give_up;
5668 else
5669 gcc_unreachable ();
5671 else
5672 goto give_up;
5674 return;
5676 give_up:
5677 *vr0type = VR_VARYING;
5678 *vr0min = NULL_TREE;
5679 *vr0max = NULL_TREE;
5682 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5683 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5684 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5685 possible such range. The resulting range is not canonicalized. */
5687 static void
5688 intersect_ranges (enum value_range_kind *vr0type,
5689 tree *vr0min, tree *vr0max,
5690 enum value_range_kind vr1type,
5691 tree vr1min, tree vr1max)
5693 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5694 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5696 /* [] is vr0, () is vr1 in the following classification comments. */
5697 if (mineq && maxeq)
5699 /* [( )] */
5700 if (*vr0type == vr1type)
5701 /* Nothing to do for equal ranges. */
5703 else if ((*vr0type == VR_RANGE
5704 && vr1type == VR_ANTI_RANGE)
5705 || (*vr0type == VR_ANTI_RANGE
5706 && vr1type == VR_RANGE))
5708 /* For anti-range with range intersection the result is empty. */
5709 *vr0type = VR_UNDEFINED;
5710 *vr0min = NULL_TREE;
5711 *vr0max = NULL_TREE;
5713 else
5714 gcc_unreachable ();
5716 else if (operand_less_p (*vr0max, vr1min) == 1
5717 || operand_less_p (vr1max, *vr0min) == 1)
5719 /* [ ] ( ) or ( ) [ ]
5720 If the ranges have an empty intersection, the result of the
5721 intersect operation is the range for intersecting an
5722 anti-range with a range or empty when intersecting two ranges. */
5723 if (*vr0type == VR_RANGE
5724 && vr1type == VR_ANTI_RANGE)
5726 else if (*vr0type == VR_ANTI_RANGE
5727 && vr1type == VR_RANGE)
5729 *vr0type = vr1type;
5730 *vr0min = vr1min;
5731 *vr0max = vr1max;
5733 else if (*vr0type == VR_RANGE
5734 && vr1type == VR_RANGE)
5736 *vr0type = VR_UNDEFINED;
5737 *vr0min = NULL_TREE;
5738 *vr0max = NULL_TREE;
5740 else if (*vr0type == VR_ANTI_RANGE
5741 && vr1type == VR_ANTI_RANGE)
5743 /* If the anti-ranges are adjacent to each other merge them. */
5744 if (TREE_CODE (*vr0max) == INTEGER_CST
5745 && TREE_CODE (vr1min) == INTEGER_CST
5746 && operand_less_p (*vr0max, vr1min) == 1
5747 && integer_onep (int_const_binop (MINUS_EXPR,
5748 vr1min, *vr0max)))
5749 *vr0max = vr1max;
5750 else if (TREE_CODE (vr1max) == INTEGER_CST
5751 && TREE_CODE (*vr0min) == INTEGER_CST
5752 && operand_less_p (vr1max, *vr0min) == 1
5753 && integer_onep (int_const_binop (MINUS_EXPR,
5754 *vr0min, vr1max)))
5755 *vr0min = vr1min;
5756 /* Else arbitrarily take VR0. */
5759 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5760 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5762 /* [ ( ) ] or [( ) ] or [ ( )] */
5763 if (*vr0type == VR_RANGE
5764 && vr1type == VR_RANGE)
5766 /* If both are ranges the result is the inner one. */
5767 *vr0type = vr1type;
5768 *vr0min = vr1min;
5769 *vr0max = vr1max;
5771 else if (*vr0type == VR_RANGE
5772 && vr1type == VR_ANTI_RANGE)
5774 /* Choose the right gap if the left one is empty. */
5775 if (mineq)
5777 if (TREE_CODE (vr1max) != INTEGER_CST)
5778 *vr0min = vr1max;
5779 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5780 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5781 *vr0min
5782 = int_const_binop (MINUS_EXPR, vr1max,
5783 build_int_cst (TREE_TYPE (vr1max), -1));
5784 else
5785 *vr0min
5786 = int_const_binop (PLUS_EXPR, vr1max,
5787 build_int_cst (TREE_TYPE (vr1max), 1));
5789 /* Choose the left gap if the right one is empty. */
5790 else if (maxeq)
5792 if (TREE_CODE (vr1min) != INTEGER_CST)
5793 *vr0max = vr1min;
5794 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5795 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5796 *vr0max
5797 = int_const_binop (PLUS_EXPR, vr1min,
5798 build_int_cst (TREE_TYPE (vr1min), -1));
5799 else
5800 *vr0max
5801 = int_const_binop (MINUS_EXPR, vr1min,
5802 build_int_cst (TREE_TYPE (vr1min), 1));
5804 /* Choose the anti-range if the range is effectively varying. */
5805 else if (vrp_val_is_min (*vr0min)
5806 && vrp_val_is_max (*vr0max))
5808 *vr0type = vr1type;
5809 *vr0min = vr1min;
5810 *vr0max = vr1max;
5812 /* Else choose the range. */
5814 else if (*vr0type == VR_ANTI_RANGE
5815 && vr1type == VR_ANTI_RANGE)
5816 /* If both are anti-ranges the result is the outer one. */
5818 else if (*vr0type == VR_ANTI_RANGE
5819 && vr1type == VR_RANGE)
5821 /* The intersection is empty. */
5822 *vr0type = VR_UNDEFINED;
5823 *vr0min = NULL_TREE;
5824 *vr0max = NULL_TREE;
5826 else
5827 gcc_unreachable ();
5829 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5830 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5832 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5833 if (*vr0type == VR_RANGE
5834 && vr1type == VR_RANGE)
5835 /* Choose the inner range. */
5837 else if (*vr0type == VR_ANTI_RANGE
5838 && vr1type == VR_RANGE)
5840 /* Choose the right gap if the left is empty. */
5841 if (mineq)
5843 *vr0type = VR_RANGE;
5844 if (TREE_CODE (*vr0max) != INTEGER_CST)
5845 *vr0min = *vr0max;
5846 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5847 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5848 *vr0min
5849 = int_const_binop (MINUS_EXPR, *vr0max,
5850 build_int_cst (TREE_TYPE (*vr0max), -1));
5851 else
5852 *vr0min
5853 = int_const_binop (PLUS_EXPR, *vr0max,
5854 build_int_cst (TREE_TYPE (*vr0max), 1));
5855 *vr0max = vr1max;
5857 /* Choose the left gap if the right is empty. */
5858 else if (maxeq)
5860 *vr0type = VR_RANGE;
5861 if (TREE_CODE (*vr0min) != INTEGER_CST)
5862 *vr0max = *vr0min;
5863 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5864 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5865 *vr0max
5866 = int_const_binop (PLUS_EXPR, *vr0min,
5867 build_int_cst (TREE_TYPE (*vr0min), -1));
5868 else
5869 *vr0max
5870 = int_const_binop (MINUS_EXPR, *vr0min,
5871 build_int_cst (TREE_TYPE (*vr0min), 1));
5872 *vr0min = vr1min;
5874 /* Choose the anti-range if the range is effectively varying. */
5875 else if (vrp_val_is_min (vr1min)
5876 && vrp_val_is_max (vr1max))
5878 /* Choose the anti-range if it is ~[0,0], that range is special
5879 enough to special case when vr1's range is relatively wide.
5880 At least for types bigger than int - this covers pointers
5881 and arguments to functions like ctz. */
5882 else if (*vr0min == *vr0max
5883 && integer_zerop (*vr0min)
5884 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5885 >= TYPE_PRECISION (integer_type_node))
5886 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5887 && TREE_CODE (vr1max) == INTEGER_CST
5888 && TREE_CODE (vr1min) == INTEGER_CST
5889 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5890 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5892 /* Else choose the range. */
5893 else
5895 *vr0type = vr1type;
5896 *vr0min = vr1min;
5897 *vr0max = vr1max;
5900 else if (*vr0type == VR_ANTI_RANGE
5901 && vr1type == VR_ANTI_RANGE)
5903 /* If both are anti-ranges the result is the outer one. */
5904 *vr0type = vr1type;
5905 *vr0min = vr1min;
5906 *vr0max = vr1max;
5908 else if (vr1type == VR_ANTI_RANGE
5909 && *vr0type == VR_RANGE)
5911 /* The intersection is empty. */
5912 *vr0type = VR_UNDEFINED;
5913 *vr0min = NULL_TREE;
5914 *vr0max = NULL_TREE;
5916 else
5917 gcc_unreachable ();
5919 else if ((operand_less_p (vr1min, *vr0max) == 1
5920 || operand_equal_p (vr1min, *vr0max, 0))
5921 && operand_less_p (*vr0min, vr1min) == 1)
5923 /* [ ( ] ) or [ ]( ) */
5924 if (*vr0type == VR_ANTI_RANGE
5925 && vr1type == VR_ANTI_RANGE)
5926 *vr0max = vr1max;
5927 else if (*vr0type == VR_RANGE
5928 && vr1type == VR_RANGE)
5929 *vr0min = vr1min;
5930 else if (*vr0type == VR_RANGE
5931 && vr1type == VR_ANTI_RANGE)
5933 if (TREE_CODE (vr1min) == INTEGER_CST)
5934 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5935 build_int_cst (TREE_TYPE (vr1min), 1));
5936 else
5937 *vr0max = vr1min;
5939 else if (*vr0type == VR_ANTI_RANGE
5940 && vr1type == VR_RANGE)
5942 *vr0type = VR_RANGE;
5943 if (TREE_CODE (*vr0max) == INTEGER_CST)
5944 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5945 build_int_cst (TREE_TYPE (*vr0max), 1));
5946 else
5947 *vr0min = *vr0max;
5948 *vr0max = vr1max;
5950 else
5951 gcc_unreachable ();
5953 else if ((operand_less_p (*vr0min, vr1max) == 1
5954 || operand_equal_p (*vr0min, vr1max, 0))
5955 && operand_less_p (vr1min, *vr0min) == 1)
5957 /* ( [ ) ] or ( )[ ] */
5958 if (*vr0type == VR_ANTI_RANGE
5959 && vr1type == VR_ANTI_RANGE)
5960 *vr0min = vr1min;
5961 else if (*vr0type == VR_RANGE
5962 && vr1type == VR_RANGE)
5963 *vr0max = vr1max;
5964 else if (*vr0type == VR_RANGE
5965 && vr1type == VR_ANTI_RANGE)
5967 if (TREE_CODE (vr1max) == INTEGER_CST)
5968 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5969 build_int_cst (TREE_TYPE (vr1max), 1));
5970 else
5971 *vr0min = vr1max;
5973 else if (*vr0type == VR_ANTI_RANGE
5974 && vr1type == VR_RANGE)
5976 *vr0type = VR_RANGE;
5977 if (TREE_CODE (*vr0min) == INTEGER_CST)
5978 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5979 build_int_cst (TREE_TYPE (*vr0min), 1));
5980 else
5981 *vr0max = *vr0min;
5982 *vr0min = vr1min;
5984 else
5985 gcc_unreachable ();
5988 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
5989 result for the intersection. That's always a conservative
5990 correct estimate unless VR1 is a constant singleton range
5991 in which case we choose that. */
5992 if (vr1type == VR_RANGE
5993 && is_gimple_min_invariant (vr1min)
5994 && vrp_operand_equal_p (vr1min, vr1max))
5996 *vr0type = vr1type;
5997 *vr0min = vr1min;
5998 *vr0max = vr1max;
6003 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6004 in *VR0. This may not be the smallest possible such range. */
6006 void
6007 value_range::intersect_helper (value_range *vr0, const value_range *vr1)
6009 /* If either range is VR_VARYING the other one wins. */
6010 if (vr1->varying_p ())
6011 return;
6012 if (vr0->varying_p ())
6014 vr0->deep_copy (vr1);
6015 return;
6018 /* When either range is VR_UNDEFINED the resulting range is
6019 VR_UNDEFINED, too. */
6020 if (vr0->undefined_p ())
6021 return;
6022 if (vr1->undefined_p ())
6024 vr0->set_undefined ();
6025 return;
6028 value_range_kind vr0type = vr0->kind ();
6029 tree vr0min = vr0->min ();
6030 tree vr0max = vr0->max ();
6031 intersect_ranges (&vr0type, &vr0min, &vr0max,
6032 vr1->kind (), vr1->min (), vr1->max ());
6033 /* Make sure to canonicalize the result though as the inversion of a
6034 VR_RANGE can still be a VR_RANGE. Work on a temporary so we can
6035 fall back to vr0 when this turns things to varying. */
6036 value_range tem;
6037 tem.set_and_canonicalize (vr0type, vr0min, vr0max);
6038 /* If that failed, use the saved original VR0. */
6039 if (tem.varying_p ())
6040 return;
6041 vr0->update (tem.kind (), tem.min (), tem.max ());
6043 /* If the result is VR_UNDEFINED there is no need to mess with
6044 the equivalencies. */
6045 if (vr0->undefined_p ())
6046 return;
6048 /* The resulting set of equivalences for range intersection is the union of
6049 the two sets. */
6050 if (vr0->m_equiv && vr1->m_equiv && vr0->m_equiv != vr1->m_equiv)
6051 bitmap_ior_into (vr0->m_equiv, vr1->m_equiv);
6052 else if (vr1->m_equiv && !vr0->m_equiv)
6054 /* All equivalence bitmaps are allocated from the same obstack. So
6055 we can use the obstack associated with VR to allocate vr0->equiv. */
6056 vr0->m_equiv = BITMAP_ALLOC (vr1->m_equiv->obstack);
6057 bitmap_copy (m_equiv, vr1->m_equiv);
6061 void
6062 value_range::intersect (const value_range *other)
6064 if (dump_file && (dump_flags & TDF_DETAILS))
6066 fprintf (dump_file, "Intersecting\n ");
6067 dump_value_range (dump_file, this);
6068 fprintf (dump_file, "\nand\n ");
6069 dump_value_range (dump_file, other);
6070 fprintf (dump_file, "\n");
6072 intersect_helper (this, other);
6073 if (dump_file && (dump_flags & TDF_DETAILS))
6075 fprintf (dump_file, "to\n ");
6076 dump_value_range (dump_file, this);
6077 fprintf (dump_file, "\n");
6081 /* Helper for meet operation for value ranges. Given two value ranges VR0 and
6082 VR1, return a range that contains both VR0 and VR1. This may not be the
6083 smallest possible such range. */
6085 value_range_base
6086 value_range_base::union_helper (const value_range_base *vr0,
6087 const value_range_base *vr1)
6089 /* VR0 has the resulting range if VR1 is undefined or VR0 is varying. */
6090 if (vr1->undefined_p ()
6091 || vr0->varying_p ())
6092 return *vr0;
6094 /* VR1 has the resulting range if VR0 is undefined or VR1 is varying. */
6095 if (vr0->undefined_p ()
6096 || vr1->varying_p ())
6097 return *vr1;
6099 value_range_kind vr0type = vr0->kind ();
6100 tree vr0min = vr0->min ();
6101 tree vr0max = vr0->max ();
6102 union_ranges (&vr0type, &vr0min, &vr0max,
6103 vr1->kind (), vr1->min (), vr1->max ());
6105 /* Work on a temporary so we can still use vr0 when union returns varying. */
6106 value_range tem;
6107 tem.set_and_canonicalize (vr0type, vr0min, vr0max);
6109 /* Failed to find an efficient meet. Before giving up and setting
6110 the result to VARYING, see if we can at least derive a useful
6111 anti-range. */
6112 if (tem.varying_p ()
6113 && range_includes_zero_p (vr0) == 0
6114 && range_includes_zero_p (vr1) == 0)
6116 tem.set_nonnull (vr0->type ());
6117 return tem;
6120 return tem;
6124 /* Meet operation for value ranges. Given two value ranges VR0 and
6125 VR1, store in VR0 a range that contains both VR0 and VR1. This
6126 may not be the smallest possible such range. */
6128 void
6129 value_range_base::union_ (const value_range_base *other)
6131 if (dump_file && (dump_flags & TDF_DETAILS))
6133 fprintf (dump_file, "Meeting\n ");
6134 dump_value_range (dump_file, this);
6135 fprintf (dump_file, "\nand\n ");
6136 dump_value_range (dump_file, other);
6137 fprintf (dump_file, "\n");
6140 *this = union_helper (this, other);
6142 if (dump_file && (dump_flags & TDF_DETAILS))
6144 fprintf (dump_file, "to\n ");
6145 dump_value_range (dump_file, this);
6146 fprintf (dump_file, "\n");
6150 void
6151 value_range::union_ (const value_range *other)
6153 if (dump_file && (dump_flags & TDF_DETAILS))
6155 fprintf (dump_file, "Meeting\n ");
6156 dump_value_range (dump_file, this);
6157 fprintf (dump_file, "\nand\n ");
6158 dump_value_range (dump_file, other);
6159 fprintf (dump_file, "\n");
6162 /* If THIS is undefined we want to pick up equivalences from OTHER.
6163 Just special-case this here rather than trying to fixup after the fact. */
6164 if (this->undefined_p ())
6165 this->deep_copy (other);
6166 else
6168 value_range_base tem = union_helper (this, other);
6169 this->update (tem.kind (), tem.min (), tem.max ());
6171 /* The resulting set of equivalences is always the intersection of
6172 the two sets. */
6173 if (this->m_equiv && other->m_equiv && this->m_equiv != other->m_equiv)
6174 bitmap_and_into (this->m_equiv, other->m_equiv);
6175 else if (this->m_equiv && !other->m_equiv)
6176 bitmap_clear (this->m_equiv);
6179 if (dump_file && (dump_flags & TDF_DETAILS))
6181 fprintf (dump_file, "to\n ");
6182 dump_value_range (dump_file, this);
6183 fprintf (dump_file, "\n");
6187 /* Visit all arguments for PHI node PHI that flow through executable
6188 edges. If a valid value range can be derived from all the incoming
6189 value ranges, set a new range for the LHS of PHI. */
6191 enum ssa_prop_result
6192 vrp_prop::visit_phi (gphi *phi)
6194 tree lhs = PHI_RESULT (phi);
6195 value_range vr_result;
6196 extract_range_from_phi_node (phi, &vr_result);
6197 if (update_value_range (lhs, &vr_result))
6199 if (dump_file && (dump_flags & TDF_DETAILS))
6201 fprintf (dump_file, "Found new range for ");
6202 print_generic_expr (dump_file, lhs);
6203 fprintf (dump_file, ": ");
6204 dump_value_range (dump_file, &vr_result);
6205 fprintf (dump_file, "\n");
6208 if (vr_result.varying_p ())
6209 return SSA_PROP_VARYING;
6211 return SSA_PROP_INTERESTING;
6214 /* Nothing changed, don't add outgoing edges. */
6215 return SSA_PROP_NOT_INTERESTING;
6218 class vrp_folder : public substitute_and_fold_engine
6220 public:
6221 tree get_value (tree) FINAL OVERRIDE;
6222 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6223 bool fold_predicate_in (gimple_stmt_iterator *);
6225 class vr_values *vr_values;
6227 /* Delegators. */
6228 tree vrp_evaluate_conditional (tree_code code, tree op0,
6229 tree op1, gimple *stmt)
6230 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6231 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6232 { return vr_values->simplify_stmt_using_ranges (gsi); }
6233 tree op_with_constant_singleton_value_range (tree op)
6234 { return vr_values->op_with_constant_singleton_value_range (op); }
6237 /* If the statement pointed by SI has a predicate whose value can be
6238 computed using the value range information computed by VRP, compute
6239 its value and return true. Otherwise, return false. */
6241 bool
6242 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6244 bool assignment_p = false;
6245 tree val;
6246 gimple *stmt = gsi_stmt (*si);
6248 if (is_gimple_assign (stmt)
6249 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6251 assignment_p = true;
6252 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6253 gimple_assign_rhs1 (stmt),
6254 gimple_assign_rhs2 (stmt),
6255 stmt);
6257 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6258 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6259 gimple_cond_lhs (cond_stmt),
6260 gimple_cond_rhs (cond_stmt),
6261 stmt);
6262 else
6263 return false;
6265 if (val)
6267 if (assignment_p)
6268 val = fold_convert (gimple_expr_type (stmt), val);
6270 if (dump_file)
6272 fprintf (dump_file, "Folding predicate ");
6273 print_gimple_expr (dump_file, stmt, 0);
6274 fprintf (dump_file, " to ");
6275 print_generic_expr (dump_file, val);
6276 fprintf (dump_file, "\n");
6279 if (is_gimple_assign (stmt))
6280 gimple_assign_set_rhs_from_tree (si, val);
6281 else
6283 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6284 gcond *cond_stmt = as_a <gcond *> (stmt);
6285 if (integer_zerop (val))
6286 gimple_cond_make_false (cond_stmt);
6287 else if (integer_onep (val))
6288 gimple_cond_make_true (cond_stmt);
6289 else
6290 gcc_unreachable ();
6293 return true;
6296 return false;
6299 /* Callback for substitute_and_fold folding the stmt at *SI. */
6301 bool
6302 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6304 if (fold_predicate_in (si))
6305 return true;
6307 return simplify_stmt_using_ranges (si);
6310 /* If OP has a value range with a single constant value return that,
6311 otherwise return NULL_TREE. This returns OP itself if OP is a
6312 constant.
6314 Implemented as a pure wrapper right now, but this will change. */
6316 tree
6317 vrp_folder::get_value (tree op)
6319 return op_with_constant_singleton_value_range (op);
6322 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6323 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6324 BB. If no such ASSERT_EXPR is found, return OP. */
6326 static tree
6327 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6329 imm_use_iterator imm_iter;
6330 gimple *use_stmt;
6331 use_operand_p use_p;
6333 if (TREE_CODE (op) == SSA_NAME)
6335 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6337 use_stmt = USE_STMT (use_p);
6338 if (use_stmt != stmt
6339 && gimple_assign_single_p (use_stmt)
6340 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6341 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6342 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6343 return gimple_assign_lhs (use_stmt);
6346 return op;
6349 /* A hack. */
6350 static class vr_values *x_vr_values;
6352 /* A trivial wrapper so that we can present the generic jump threading
6353 code with a simple API for simplifying statements. STMT is the
6354 statement we want to simplify, WITHIN_STMT provides the location
6355 for any overflow warnings. */
6357 static tree
6358 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6359 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6360 basic_block bb)
6362 /* First see if the conditional is in the hash table. */
6363 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6364 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6365 return cached_lhs;
6367 vr_values *vr_values = x_vr_values;
6368 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6370 tree op0 = gimple_cond_lhs (cond_stmt);
6371 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6373 tree op1 = gimple_cond_rhs (cond_stmt);
6374 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6376 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6377 op0, op1, within_stmt);
6380 /* We simplify a switch statement by trying to determine which case label
6381 will be taken. If we are successful then we return the corresponding
6382 CASE_LABEL_EXPR. */
6383 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6385 tree op = gimple_switch_index (switch_stmt);
6386 if (TREE_CODE (op) != SSA_NAME)
6387 return NULL_TREE;
6389 op = lhs_of_dominating_assert (op, bb, stmt);
6391 const value_range *vr = vr_values->get_value_range (op);
6392 if (vr->undefined_p ()
6393 || vr->varying_p ()
6394 || vr->symbolic_p ())
6395 return NULL_TREE;
6397 if (vr->kind () == VR_RANGE)
6399 size_t i, j;
6400 /* Get the range of labels that contain a part of the operand's
6401 value range. */
6402 find_case_label_range (switch_stmt, vr->min (), vr->max (), &i, &j);
6404 /* Is there only one such label? */
6405 if (i == j)
6407 tree label = gimple_switch_label (switch_stmt, i);
6409 /* The i'th label will be taken only if the value range of the
6410 operand is entirely within the bounds of this label. */
6411 if (CASE_HIGH (label) != NULL_TREE
6412 ? (tree_int_cst_compare (CASE_LOW (label), vr->min ()) <= 0
6413 && tree_int_cst_compare (CASE_HIGH (label),
6414 vr->max ()) >= 0)
6415 : (tree_int_cst_equal (CASE_LOW (label), vr->min ())
6416 && tree_int_cst_equal (vr->min (), vr->max ())))
6417 return label;
6420 /* If there are no such labels then the default label will be
6421 taken. */
6422 if (i > j)
6423 return gimple_switch_label (switch_stmt, 0);
6426 if (vr->kind () == VR_ANTI_RANGE)
6428 unsigned n = gimple_switch_num_labels (switch_stmt);
6429 tree min_label = gimple_switch_label (switch_stmt, 1);
6430 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6432 /* The default label will be taken only if the anti-range of the
6433 operand is entirely outside the bounds of all the (non-default)
6434 case labels. */
6435 if (tree_int_cst_compare (vr->min (), CASE_LOW (min_label)) <= 0
6436 && (CASE_HIGH (max_label) != NULL_TREE
6437 ? tree_int_cst_compare (vr->max (),
6438 CASE_HIGH (max_label)) >= 0
6439 : tree_int_cst_compare (vr->max (),
6440 CASE_LOW (max_label)) >= 0))
6441 return gimple_switch_label (switch_stmt, 0);
6444 return NULL_TREE;
6447 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6449 tree lhs = gimple_assign_lhs (assign_stmt);
6450 if (TREE_CODE (lhs) == SSA_NAME
6451 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6452 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6453 && stmt_interesting_for_vrp (stmt))
6455 edge dummy_e;
6456 tree dummy_tree;
6457 value_range new_vr;
6458 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6459 &dummy_tree, &new_vr);
6460 tree singleton;
6461 if (new_vr.singleton_p (&singleton))
6462 return singleton;
6466 return NULL_TREE;
6469 class vrp_dom_walker : public dom_walker
6471 public:
6472 vrp_dom_walker (cdi_direction direction,
6473 class const_and_copies *const_and_copies,
6474 class avail_exprs_stack *avail_exprs_stack)
6475 : dom_walker (direction, REACHABLE_BLOCKS),
6476 m_const_and_copies (const_and_copies),
6477 m_avail_exprs_stack (avail_exprs_stack),
6478 m_dummy_cond (NULL) {}
6480 virtual edge before_dom_children (basic_block);
6481 virtual void after_dom_children (basic_block);
6483 class vr_values *vr_values;
6485 private:
6486 class const_and_copies *m_const_and_copies;
6487 class avail_exprs_stack *m_avail_exprs_stack;
6489 gcond *m_dummy_cond;
6493 /* Called before processing dominator children of BB. We want to look
6494 at ASSERT_EXPRs and record information from them in the appropriate
6495 tables.
6497 We could look at other statements here. It's not seen as likely
6498 to significantly increase the jump threads we discover. */
6500 edge
6501 vrp_dom_walker::before_dom_children (basic_block bb)
6503 gimple_stmt_iterator gsi;
6505 m_avail_exprs_stack->push_marker ();
6506 m_const_and_copies->push_marker ();
6507 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6509 gimple *stmt = gsi_stmt (gsi);
6510 if (gimple_assign_single_p (stmt)
6511 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6513 tree rhs1 = gimple_assign_rhs1 (stmt);
6514 tree cond = TREE_OPERAND (rhs1, 1);
6515 tree inverted = invert_truthvalue (cond);
6516 vec<cond_equivalence> p;
6517 p.create (3);
6518 record_conditions (&p, cond, inverted);
6519 for (unsigned int i = 0; i < p.length (); i++)
6520 m_avail_exprs_stack->record_cond (&p[i]);
6522 tree lhs = gimple_assign_lhs (stmt);
6523 m_const_and_copies->record_const_or_copy (lhs,
6524 TREE_OPERAND (rhs1, 0));
6525 p.release ();
6526 continue;
6528 break;
6530 return NULL;
6533 /* Called after processing dominator children of BB. This is where we
6534 actually call into the threader. */
6535 void
6536 vrp_dom_walker::after_dom_children (basic_block bb)
6538 if (!m_dummy_cond)
6539 m_dummy_cond = gimple_build_cond (NE_EXPR,
6540 integer_zero_node, integer_zero_node,
6541 NULL, NULL);
6543 x_vr_values = vr_values;
6544 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6545 m_avail_exprs_stack, NULL,
6546 simplify_stmt_for_jump_threading);
6547 x_vr_values = NULL;
6549 m_avail_exprs_stack->pop_to_marker ();
6550 m_const_and_copies->pop_to_marker ();
6553 /* Blocks which have more than one predecessor and more than
6554 one successor present jump threading opportunities, i.e.,
6555 when the block is reached from a specific predecessor, we
6556 may be able to determine which of the outgoing edges will
6557 be traversed. When this optimization applies, we are able
6558 to avoid conditionals at runtime and we may expose secondary
6559 optimization opportunities.
6561 This routine is effectively a driver for the generic jump
6562 threading code. It basically just presents the generic code
6563 with edges that may be suitable for jump threading.
6565 Unlike DOM, we do not iterate VRP if jump threading was successful.
6566 While iterating may expose new opportunities for VRP, it is expected
6567 those opportunities would be very limited and the compile time cost
6568 to expose those opportunities would be significant.
6570 As jump threading opportunities are discovered, they are registered
6571 for later realization. */
6573 static void
6574 identify_jump_threads (class vr_values *vr_values)
6576 /* Ugh. When substituting values earlier in this pass we can
6577 wipe the dominance information. So rebuild the dominator
6578 information as we need it within the jump threading code. */
6579 calculate_dominance_info (CDI_DOMINATORS);
6581 /* We do not allow VRP information to be used for jump threading
6582 across a back edge in the CFG. Otherwise it becomes too
6583 difficult to avoid eliminating loop exit tests. Of course
6584 EDGE_DFS_BACK is not accurate at this time so we have to
6585 recompute it. */
6586 mark_dfs_back_edges ();
6588 /* Allocate our unwinder stack to unwind any temporary equivalences
6589 that might be recorded. */
6590 const_and_copies *equiv_stack = new const_and_copies ();
6592 hash_table<expr_elt_hasher> *avail_exprs
6593 = new hash_table<expr_elt_hasher> (1024);
6594 avail_exprs_stack *avail_exprs_stack
6595 = new class avail_exprs_stack (avail_exprs);
6597 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6598 walker.vr_values = vr_values;
6599 walker.walk (cfun->cfg->x_entry_block_ptr);
6601 /* We do not actually update the CFG or SSA graphs at this point as
6602 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6603 handle ASSERT_EXPRs gracefully. */
6604 delete equiv_stack;
6605 delete avail_exprs;
6606 delete avail_exprs_stack;
6609 /* Traverse all the blocks folding conditionals with known ranges. */
6611 void
6612 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6614 size_t i;
6616 /* We have completed propagating through the lattice. */
6617 vr_values.set_lattice_propagation_complete ();
6619 if (dump_file)
6621 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6622 vr_values.dump_all_value_ranges (dump_file);
6623 fprintf (dump_file, "\n");
6626 /* Set value range to non pointer SSA_NAMEs. */
6627 for (i = 0; i < num_ssa_names; i++)
6629 tree name = ssa_name (i);
6630 if (!name)
6631 continue;
6633 const value_range *vr = get_value_range (name);
6634 if (!name || !vr->constant_p ())
6635 continue;
6637 if (POINTER_TYPE_P (TREE_TYPE (name))
6638 && range_includes_zero_p (vr) == 0)
6639 set_ptr_nonnull (name);
6640 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6641 set_range_info (name, *vr);
6644 /* If we're checking array refs, we want to merge information on
6645 the executability of each edge between vrp_folder and the
6646 check_array_bounds_dom_walker: each can clear the
6647 EDGE_EXECUTABLE flag on edges, in different ways.
6649 Hence, if we're going to call check_all_array_refs, set
6650 the flag on every edge now, rather than in
6651 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6652 it from some edges. */
6653 if (warn_array_bounds && warn_array_bounds_p)
6654 set_all_edges_as_executable (cfun);
6656 class vrp_folder vrp_folder;
6657 vrp_folder.vr_values = &vr_values;
6658 vrp_folder.substitute_and_fold ();
6660 if (warn_array_bounds && warn_array_bounds_p)
6661 check_all_array_refs ();
6664 /* Main entry point to VRP (Value Range Propagation). This pass is
6665 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6666 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6667 Programming Language Design and Implementation, pp. 67-78, 1995.
6668 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6670 This is essentially an SSA-CCP pass modified to deal with ranges
6671 instead of constants.
6673 While propagating ranges, we may find that two or more SSA name
6674 have equivalent, though distinct ranges. For instance,
6676 1 x_9 = p_3->a;
6677 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6678 3 if (p_4 == q_2)
6679 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6680 5 endif
6681 6 if (q_2)
6683 In the code above, pointer p_5 has range [q_2, q_2], but from the
6684 code we can also determine that p_5 cannot be NULL and, if q_2 had
6685 a non-varying range, p_5's range should also be compatible with it.
6687 These equivalences are created by two expressions: ASSERT_EXPR and
6688 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6689 result of another assertion, then we can use the fact that p_5 and
6690 p_4 are equivalent when evaluating p_5's range.
6692 Together with value ranges, we also propagate these equivalences
6693 between names so that we can take advantage of information from
6694 multiple ranges when doing final replacement. Note that this
6695 equivalency relation is transitive but not symmetric.
6697 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6698 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6699 in contexts where that assertion does not hold (e.g., in line 6).
6701 TODO, the main difference between this pass and Patterson's is that
6702 we do not propagate edge probabilities. We only compute whether
6703 edges can be taken or not. That is, instead of having a spectrum
6704 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6705 DON'T KNOW. In the future, it may be worthwhile to propagate
6706 probabilities to aid branch prediction. */
6708 static unsigned int
6709 execute_vrp (bool warn_array_bounds_p)
6712 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6713 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6714 scev_initialize ();
6716 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6717 Inserting assertions may split edges which will invalidate
6718 EDGE_DFS_BACK. */
6719 insert_range_assertions ();
6721 threadedge_initialize_values ();
6723 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6724 mark_dfs_back_edges ();
6726 class vrp_prop vrp_prop;
6727 vrp_prop.vrp_initialize ();
6728 vrp_prop.ssa_propagate ();
6729 vrp_prop.vrp_finalize (warn_array_bounds_p);
6731 /* We must identify jump threading opportunities before we release
6732 the datastructures built by VRP. */
6733 identify_jump_threads (&vrp_prop.vr_values);
6735 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6736 was set by a type conversion can often be rewritten to use the
6737 RHS of the type conversion.
6739 However, doing so inhibits jump threading through the comparison.
6740 So that transformation is not performed until after jump threading
6741 is complete. */
6742 basic_block bb;
6743 FOR_EACH_BB_FN (bb, cfun)
6745 gimple *last = last_stmt (bb);
6746 if (last && gimple_code (last) == GIMPLE_COND)
6747 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6750 free_numbers_of_iterations_estimates (cfun);
6752 /* ASSERT_EXPRs must be removed before finalizing jump threads
6753 as finalizing jump threads calls the CFG cleanup code which
6754 does not properly handle ASSERT_EXPRs. */
6755 remove_range_assertions ();
6757 /* If we exposed any new variables, go ahead and put them into
6758 SSA form now, before we handle jump threading. This simplifies
6759 interactions between rewriting of _DECL nodes into SSA form
6760 and rewriting SSA_NAME nodes into SSA form after block
6761 duplication and CFG manipulation. */
6762 update_ssa (TODO_update_ssa);
6764 /* We identified all the jump threading opportunities earlier, but could
6765 not transform the CFG at that time. This routine transforms the
6766 CFG and arranges for the dominator tree to be rebuilt if necessary.
6768 Note the SSA graph update will occur during the normal TODO
6769 processing by the pass manager. */
6770 thread_through_all_blocks (false);
6772 vrp_prop.vr_values.cleanup_edges_and_switches ();
6773 threadedge_finalize_values ();
6775 scev_finalize ();
6776 loop_optimizer_finalize ();
6777 return 0;
6780 namespace {
6782 const pass_data pass_data_vrp =
6784 GIMPLE_PASS, /* type */
6785 "vrp", /* name */
6786 OPTGROUP_NONE, /* optinfo_flags */
6787 TV_TREE_VRP, /* tv_id */
6788 PROP_ssa, /* properties_required */
6789 0, /* properties_provided */
6790 0, /* properties_destroyed */
6791 0, /* todo_flags_start */
6792 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6795 class pass_vrp : public gimple_opt_pass
6797 public:
6798 pass_vrp (gcc::context *ctxt)
6799 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6802 /* opt_pass methods: */
6803 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6804 void set_pass_param (unsigned int n, bool param)
6806 gcc_assert (n == 0);
6807 warn_array_bounds_p = param;
6809 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6810 virtual unsigned int execute (function *)
6811 { return execute_vrp (warn_array_bounds_p); }
6813 private:
6814 bool warn_array_bounds_p;
6815 }; // class pass_vrp
6817 } // anon namespace
6819 gimple_opt_pass *
6820 make_pass_vrp (gcc::context *ctxt)
6822 return new pass_vrp (ctxt);
6826 /* Worker for determine_value_range. */
6828 static void
6829 determine_value_range_1 (value_range_base *vr, tree expr)
6831 if (BINARY_CLASS_P (expr))
6833 value_range_base vr0, vr1;
6834 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6835 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6836 extract_range_from_binary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6837 &vr0, &vr1);
6839 else if (UNARY_CLASS_P (expr))
6841 value_range_base vr0;
6842 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6843 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6844 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6846 else if (TREE_CODE (expr) == INTEGER_CST)
6847 vr->set (expr);
6848 else
6850 value_range_kind kind;
6851 wide_int min, max;
6852 /* For SSA names try to extract range info computed by VRP. Otherwise
6853 fall back to varying. */
6854 if (TREE_CODE (expr) == SSA_NAME
6855 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6856 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6857 vr->set (kind, wide_int_to_tree (TREE_TYPE (expr), min),
6858 wide_int_to_tree (TREE_TYPE (expr), max));
6859 else
6860 vr->set_varying ();
6864 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6865 the determined range type. */
6867 value_range_kind
6868 determine_value_range (tree expr, wide_int *min, wide_int *max)
6870 value_range_base vr;
6871 determine_value_range_1 (&vr, expr);
6872 if (vr.constant_p ())
6874 *min = wi::to_wide (vr.min ());
6875 *max = wi::to_wide (vr.max ());
6876 return vr.kind ();
6879 return VR_VARYING;