c-format.c: suggest the correct format string to use (PR c/64955)
[official-gcc.git] / gcc / tree-vrp.c
blob44dfc84b268278d9e61efed59681c6cbe5266edf
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2016 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-ssa-loop-manip.h"
46 #include "tree-ssa-loop-niter.h"
47 #include "tree-ssa-loop.h"
48 #include "tree-into-ssa.h"
49 #include "tree-ssa.h"
50 #include "intl.h"
51 #include "cfgloop.h"
52 #include "tree-scalar-evolution.h"
53 #include "tree-ssa-propagate.h"
54 #include "tree-chrec.h"
55 #include "tree-ssa-threadupdate.h"
56 #include "tree-ssa-scopedtables.h"
57 #include "tree-ssa-threadedge.h"
58 #include "omp-low.h"
59 #include "target.h"
60 #include "case-cfn-macros.h"
61 #include "params.h"
62 #include "alloc-pool.h"
64 /* Range of values that can be associated with an SSA_NAME after VRP
65 has executed. */
66 struct value_range
68 /* Lattice value represented by this range. */
69 enum value_range_type type;
71 /* Minimum and maximum values represented by this range. These
72 values should be interpreted as follows:
74 - If TYPE is VR_UNDEFINED or VR_VARYING then MIN and MAX must
75 be NULL.
77 - If TYPE == VR_RANGE then MIN holds the minimum value and
78 MAX holds the maximum value of the range [MIN, MAX].
80 - If TYPE == ANTI_RANGE the variable is known to NOT
81 take any values in the range [MIN, MAX]. */
82 tree min;
83 tree max;
85 /* Set of SSA names whose value ranges are equivalent to this one.
86 This set is only valid when TYPE is VR_RANGE or VR_ANTI_RANGE. */
87 bitmap equiv;
90 #define VR_INITIALIZER { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL }
92 /* Allocation pools for tree-vrp allocations. */
93 static object_allocator<value_range> vrp_value_range_pool ("Tree VRP value ranges");
94 static bitmap_obstack vrp_equiv_obstack;
96 /* Set of SSA names found live during the RPO traversal of the function
97 for still active basic-blocks. */
98 static sbitmap *live;
100 /* Return true if the SSA name NAME is live on the edge E. */
102 static bool
103 live_on_edge (edge e, tree name)
105 return (live[e->dest->index]
106 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
109 /* Local functions. */
110 static int compare_values (tree val1, tree val2);
111 static int compare_values_warnv (tree val1, tree val2, bool *);
112 static void vrp_meet (value_range *, value_range *);
113 static void vrp_intersect_ranges (value_range *, value_range *);
114 static tree vrp_evaluate_conditional_warnv_with_ops (enum tree_code,
115 tree, tree, bool, bool *,
116 bool *);
118 /* Location information for ASSERT_EXPRs. Each instance of this
119 structure describes an ASSERT_EXPR for an SSA name. Since a single
120 SSA name may have more than one assertion associated with it, these
121 locations are kept in a linked list attached to the corresponding
122 SSA name. */
123 struct assert_locus
125 /* Basic block where the assertion would be inserted. */
126 basic_block bb;
128 /* Some assertions need to be inserted on an edge (e.g., assertions
129 generated by COND_EXPRs). In those cases, BB will be NULL. */
130 edge e;
132 /* Pointer to the statement that generated this assertion. */
133 gimple_stmt_iterator si;
135 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
136 enum tree_code comp_code;
138 /* Value being compared against. */
139 tree val;
141 /* Expression to compare. */
142 tree expr;
144 /* Next node in the linked list. */
145 assert_locus *next;
148 /* If bit I is present, it means that SSA name N_i has a list of
149 assertions that should be inserted in the IL. */
150 static bitmap need_assert_for;
152 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
153 holds a list of ASSERT_LOCUS_T nodes that describe where
154 ASSERT_EXPRs for SSA name N_I should be inserted. */
155 static assert_locus **asserts_for;
157 /* Value range array. After propagation, VR_VALUE[I] holds the range
158 of values that SSA name N_I may take. */
159 static unsigned num_vr_values;
160 static value_range **vr_value;
161 static bool values_propagated;
163 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
164 number of executable edges we saw the last time we visited the
165 node. */
166 static int *vr_phi_edge_counts;
168 struct switch_update {
169 gswitch *stmt;
170 tree vec;
173 static vec<edge> to_remove_edges;
174 static vec<switch_update> to_update_switch_stmts;
177 /* Return the maximum value for TYPE. */
179 static inline tree
180 vrp_val_max (const_tree type)
182 if (!INTEGRAL_TYPE_P (type))
183 return NULL_TREE;
185 return TYPE_MAX_VALUE (type);
188 /* Return the minimum value for TYPE. */
190 static inline tree
191 vrp_val_min (const_tree type)
193 if (!INTEGRAL_TYPE_P (type))
194 return NULL_TREE;
196 return TYPE_MIN_VALUE (type);
199 /* Return whether VAL is equal to the maximum value of its type. This
200 will be true for a positive overflow infinity. We can't do a
201 simple equality comparison with TYPE_MAX_VALUE because C typedefs
202 and Ada subtypes can produce types whose TYPE_MAX_VALUE is not ==
203 to the integer constant with the same value in the type. */
205 static inline bool
206 vrp_val_is_max (const_tree val)
208 tree type_max = vrp_val_max (TREE_TYPE (val));
209 return (val == type_max
210 || (type_max != NULL_TREE
211 && operand_equal_p (val, type_max, 0)));
214 /* Return whether VAL is equal to the minimum value of its type. This
215 will be true for a negative overflow infinity. */
217 static inline bool
218 vrp_val_is_min (const_tree val)
220 tree type_min = vrp_val_min (TREE_TYPE (val));
221 return (val == type_min
222 || (type_min != NULL_TREE
223 && operand_equal_p (val, type_min, 0)));
227 /* Return whether TYPE should use an overflow infinity distinct from
228 TYPE_{MIN,MAX}_VALUE. We use an overflow infinity value to
229 represent a signed overflow during VRP computations. An infinity
230 is distinct from a half-range, which will go from some number to
231 TYPE_{MIN,MAX}_VALUE. */
233 static inline bool
234 needs_overflow_infinity (const_tree type)
236 return INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type);
239 /* Return whether TYPE can support our overflow infinity
240 representation: we use the TREE_OVERFLOW flag, which only exists
241 for constants. If TYPE doesn't support this, we don't optimize
242 cases which would require signed overflow--we drop them to
243 VARYING. */
245 static inline bool
246 supports_overflow_infinity (const_tree type)
248 tree min = vrp_val_min (type), max = vrp_val_max (type);
249 gcc_checking_assert (needs_overflow_infinity (type));
250 return (min != NULL_TREE
251 && CONSTANT_CLASS_P (min)
252 && max != NULL_TREE
253 && CONSTANT_CLASS_P (max));
256 /* VAL is the maximum or minimum value of a type. Return a
257 corresponding overflow infinity. */
259 static inline tree
260 make_overflow_infinity (tree val)
262 gcc_checking_assert (val != NULL_TREE && CONSTANT_CLASS_P (val));
263 val = copy_node (val);
264 TREE_OVERFLOW (val) = 1;
265 return val;
268 /* Return a negative overflow infinity for TYPE. */
270 static inline tree
271 negative_overflow_infinity (tree type)
273 gcc_checking_assert (supports_overflow_infinity (type));
274 return make_overflow_infinity (vrp_val_min (type));
277 /* Return a positive overflow infinity for TYPE. */
279 static inline tree
280 positive_overflow_infinity (tree type)
282 gcc_checking_assert (supports_overflow_infinity (type));
283 return make_overflow_infinity (vrp_val_max (type));
286 /* Return whether VAL is a negative overflow infinity. */
288 static inline bool
289 is_negative_overflow_infinity (const_tree val)
291 return (TREE_OVERFLOW_P (val)
292 && needs_overflow_infinity (TREE_TYPE (val))
293 && vrp_val_is_min (val));
296 /* Return whether VAL is a positive overflow infinity. */
298 static inline bool
299 is_positive_overflow_infinity (const_tree val)
301 return (TREE_OVERFLOW_P (val)
302 && needs_overflow_infinity (TREE_TYPE (val))
303 && vrp_val_is_max (val));
306 /* Return whether VAL is a positive or negative overflow infinity. */
308 static inline bool
309 is_overflow_infinity (const_tree val)
311 return (TREE_OVERFLOW_P (val)
312 && needs_overflow_infinity (TREE_TYPE (val))
313 && (vrp_val_is_min (val) || vrp_val_is_max (val)));
316 /* Return whether STMT has a constant rhs that is_overflow_infinity. */
318 static inline bool
319 stmt_overflow_infinity (gimple *stmt)
321 if (is_gimple_assign (stmt)
322 && get_gimple_rhs_class (gimple_assign_rhs_code (stmt)) ==
323 GIMPLE_SINGLE_RHS)
324 return is_overflow_infinity (gimple_assign_rhs1 (stmt));
325 return false;
328 /* If VAL is now an overflow infinity, return VAL. Otherwise, return
329 the same value with TREE_OVERFLOW clear. This can be used to avoid
330 confusing a regular value with an overflow value. */
332 static inline tree
333 avoid_overflow_infinity (tree val)
335 if (!is_overflow_infinity (val))
336 return val;
338 if (vrp_val_is_max (val))
339 return vrp_val_max (TREE_TYPE (val));
340 else
342 gcc_checking_assert (vrp_val_is_min (val));
343 return vrp_val_min (TREE_TYPE (val));
348 /* Set value range VR to VR_UNDEFINED. */
350 static inline void
351 set_value_range_to_undefined (value_range *vr)
353 vr->type = VR_UNDEFINED;
354 vr->min = vr->max = NULL_TREE;
355 if (vr->equiv)
356 bitmap_clear (vr->equiv);
360 /* Set value range VR to VR_VARYING. */
362 static inline void
363 set_value_range_to_varying (value_range *vr)
365 vr->type = VR_VARYING;
366 vr->min = vr->max = NULL_TREE;
367 if (vr->equiv)
368 bitmap_clear (vr->equiv);
372 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
374 static void
375 set_value_range (value_range *vr, enum value_range_type t, tree min,
376 tree max, bitmap equiv)
378 /* Check the validity of the range. */
379 if (flag_checking
380 && (t == VR_RANGE || t == VR_ANTI_RANGE))
382 int cmp;
384 gcc_assert (min && max);
386 gcc_assert ((!TREE_OVERFLOW_P (min) || is_overflow_infinity (min))
387 && (!TREE_OVERFLOW_P (max) || is_overflow_infinity (max)));
389 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
390 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
392 cmp = compare_values (min, max);
393 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
395 if (needs_overflow_infinity (TREE_TYPE (min)))
396 gcc_assert (!is_overflow_infinity (min)
397 || !is_overflow_infinity (max));
400 if (flag_checking
401 && (t == VR_UNDEFINED || t == VR_VARYING))
403 gcc_assert (min == NULL_TREE && max == NULL_TREE);
404 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
407 vr->type = t;
408 vr->min = min;
409 vr->max = max;
411 /* Since updating the equivalence set involves deep copying the
412 bitmaps, only do it if absolutely necessary. */
413 if (vr->equiv == NULL
414 && equiv != NULL)
415 vr->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
417 if (equiv != vr->equiv)
419 if (equiv && !bitmap_empty_p (equiv))
420 bitmap_copy (vr->equiv, equiv);
421 else
422 bitmap_clear (vr->equiv);
427 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
428 This means adjusting T, MIN and MAX representing the case of a
429 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
430 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
431 In corner cases where MAX+1 or MIN-1 wraps this will fall back
432 to varying.
433 This routine exists to ease canonicalization in the case where we
434 extract ranges from var + CST op limit. */
436 static void
437 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
438 tree min, tree max, bitmap equiv)
440 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
441 if (t == VR_UNDEFINED)
443 set_value_range_to_undefined (vr);
444 return;
446 else if (t == VR_VARYING)
448 set_value_range_to_varying (vr);
449 return;
452 /* Nothing to canonicalize for symbolic ranges. */
453 if (TREE_CODE (min) != INTEGER_CST
454 || TREE_CODE (max) != INTEGER_CST)
456 set_value_range (vr, t, min, max, equiv);
457 return;
460 /* Wrong order for min and max, to swap them and the VR type we need
461 to adjust them. */
462 if (tree_int_cst_lt (max, min))
464 tree one, tmp;
466 /* For one bit precision if max < min, then the swapped
467 range covers all values, so for VR_RANGE it is varying and
468 for VR_ANTI_RANGE empty range, so drop to varying as well. */
469 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
471 set_value_range_to_varying (vr);
472 return;
475 one = build_int_cst (TREE_TYPE (min), 1);
476 tmp = int_const_binop (PLUS_EXPR, max, one);
477 max = int_const_binop (MINUS_EXPR, min, one);
478 min = tmp;
480 /* There's one corner case, if we had [C+1, C] before we now have
481 that again. But this represents an empty value range, so drop
482 to varying in this case. */
483 if (tree_int_cst_lt (max, min))
485 set_value_range_to_varying (vr);
486 return;
489 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
492 /* Anti-ranges that can be represented as ranges should be so. */
493 if (t == VR_ANTI_RANGE)
495 bool is_min = vrp_val_is_min (min);
496 bool is_max = vrp_val_is_max (max);
498 if (is_min && is_max)
500 /* We cannot deal with empty ranges, drop to varying.
501 ??? This could be VR_UNDEFINED instead. */
502 set_value_range_to_varying (vr);
503 return;
505 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
506 && (is_min || is_max))
508 /* Non-empty boolean ranges can always be represented
509 as a singleton range. */
510 if (is_min)
511 min = max = vrp_val_max (TREE_TYPE (min));
512 else
513 min = max = vrp_val_min (TREE_TYPE (min));
514 t = VR_RANGE;
516 else if (is_min
517 /* As a special exception preserve non-null ranges. */
518 && !(TYPE_UNSIGNED (TREE_TYPE (min))
519 && integer_zerop (max)))
521 tree one = build_int_cst (TREE_TYPE (max), 1);
522 min = int_const_binop (PLUS_EXPR, max, one);
523 max = vrp_val_max (TREE_TYPE (max));
524 t = VR_RANGE;
526 else if (is_max)
528 tree one = build_int_cst (TREE_TYPE (min), 1);
529 max = int_const_binop (MINUS_EXPR, min, one);
530 min = vrp_val_min (TREE_TYPE (min));
531 t = VR_RANGE;
535 /* Drop [-INF(OVF), +INF(OVF)] to varying. */
536 if (needs_overflow_infinity (TREE_TYPE (min))
537 && is_overflow_infinity (min)
538 && is_overflow_infinity (max))
540 set_value_range_to_varying (vr);
541 return;
544 set_value_range (vr, t, min, max, equiv);
547 /* Copy value range FROM into value range TO. */
549 static inline void
550 copy_value_range (value_range *to, value_range *from)
552 set_value_range (to, from->type, from->min, from->max, from->equiv);
555 /* Set value range VR to a single value. This function is only called
556 with values we get from statements, and exists to clear the
557 TREE_OVERFLOW flag so that we don't think we have an overflow
558 infinity when we shouldn't. */
560 static inline void
561 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
563 gcc_assert (is_gimple_min_invariant (val));
564 if (TREE_OVERFLOW_P (val))
565 val = drop_tree_overflow (val);
566 set_value_range (vr, VR_RANGE, val, val, equiv);
569 /* Set value range VR to a non-negative range of type TYPE.
570 OVERFLOW_INFINITY indicates whether to use an overflow infinity
571 rather than TYPE_MAX_VALUE; this should be true if we determine
572 that the range is nonnegative based on the assumption that signed
573 overflow does not occur. */
575 static inline void
576 set_value_range_to_nonnegative (value_range *vr, tree type,
577 bool overflow_infinity)
579 tree zero;
581 if (overflow_infinity && !supports_overflow_infinity (type))
583 set_value_range_to_varying (vr);
584 return;
587 zero = build_int_cst (type, 0);
588 set_value_range (vr, VR_RANGE, zero,
589 (overflow_infinity
590 ? positive_overflow_infinity (type)
591 : TYPE_MAX_VALUE (type)),
592 vr->equiv);
595 /* Set value range VR to a non-NULL range of type TYPE. */
597 static inline void
598 set_value_range_to_nonnull (value_range *vr, tree type)
600 tree zero = build_int_cst (type, 0);
601 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
605 /* Set value range VR to a NULL range of type TYPE. */
607 static inline void
608 set_value_range_to_null (value_range *vr, tree type)
610 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
614 /* Set value range VR to a range of a truthvalue of type TYPE. */
616 static inline void
617 set_value_range_to_truthvalue (value_range *vr, tree type)
619 if (TYPE_PRECISION (type) == 1)
620 set_value_range_to_varying (vr);
621 else
622 set_value_range (vr, VR_RANGE,
623 build_int_cst (type, 0), build_int_cst (type, 1),
624 vr->equiv);
628 /* If abs (min) < abs (max), set VR to [-max, max], if
629 abs (min) >= abs (max), set VR to [-min, min]. */
631 static void
632 abs_extent_range (value_range *vr, tree min, tree max)
634 int cmp;
636 gcc_assert (TREE_CODE (min) == INTEGER_CST);
637 gcc_assert (TREE_CODE (max) == INTEGER_CST);
638 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
639 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
640 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
641 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
642 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
644 set_value_range_to_varying (vr);
645 return;
647 cmp = compare_values (min, max);
648 if (cmp == -1)
649 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
650 else if (cmp == 0 || cmp == 1)
652 max = min;
653 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
655 else
657 set_value_range_to_varying (vr);
658 return;
660 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
664 /* Return value range information for VAR.
666 If we have no values ranges recorded (ie, VRP is not running), then
667 return NULL. Otherwise create an empty range if none existed for VAR. */
669 static value_range *
670 get_value_range (const_tree var)
672 static const value_range vr_const_varying
673 = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
674 value_range *vr;
675 tree sym;
676 unsigned ver = SSA_NAME_VERSION (var);
678 /* If we have no recorded ranges, then return NULL. */
679 if (! vr_value)
680 return NULL;
682 /* If we query the range for a new SSA name return an unmodifiable VARYING.
683 We should get here at most from the substitute-and-fold stage which
684 will never try to change values. */
685 if (ver >= num_vr_values)
686 return CONST_CAST (value_range *, &vr_const_varying);
688 vr = vr_value[ver];
689 if (vr)
690 return vr;
692 /* After propagation finished do not allocate new value-ranges. */
693 if (values_propagated)
694 return CONST_CAST (value_range *, &vr_const_varying);
696 /* Create a default value range. */
697 vr_value[ver] = vr = vrp_value_range_pool.allocate ();
698 memset (vr, 0, sizeof (*vr));
700 /* Defer allocating the equivalence set. */
701 vr->equiv = NULL;
703 /* If VAR is a default definition of a parameter, the variable can
704 take any value in VAR's type. */
705 if (SSA_NAME_IS_DEFAULT_DEF (var))
707 sym = SSA_NAME_VAR (var);
708 if (TREE_CODE (sym) == PARM_DECL)
710 /* Try to use the "nonnull" attribute to create ~[0, 0]
711 anti-ranges for pointers. Note that this is only valid with
712 default definitions of PARM_DECLs. */
713 if (POINTER_TYPE_P (TREE_TYPE (sym))
714 && nonnull_arg_p (sym))
715 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
716 else
717 set_value_range_to_varying (vr);
719 else if (TREE_CODE (sym) == RESULT_DECL
720 && DECL_BY_REFERENCE (sym))
721 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
724 return vr;
727 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
729 static inline bool
730 vrp_operand_equal_p (const_tree val1, const_tree val2)
732 if (val1 == val2)
733 return true;
734 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
735 return false;
736 return is_overflow_infinity (val1) == is_overflow_infinity (val2);
739 /* Return true, if the bitmaps B1 and B2 are equal. */
741 static inline bool
742 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
744 return (b1 == b2
745 || ((!b1 || bitmap_empty_p (b1))
746 && (!b2 || bitmap_empty_p (b2)))
747 || (b1 && b2
748 && bitmap_equal_p (b1, b2)));
751 /* Update the value range and equivalence set for variable VAR to
752 NEW_VR. Return true if NEW_VR is different from VAR's previous
753 value.
755 NOTE: This function assumes that NEW_VR is a temporary value range
756 object created for the sole purpose of updating VAR's range. The
757 storage used by the equivalence set from NEW_VR will be freed by
758 this function. Do not call update_value_range when NEW_VR
759 is the range object associated with another SSA name. */
761 static inline bool
762 update_value_range (const_tree var, value_range *new_vr)
764 value_range *old_vr;
765 bool is_new;
767 /* If there is a value-range on the SSA name from earlier analysis
768 factor that in. */
769 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
771 wide_int min, max;
772 value_range_type rtype = get_range_info (var, &min, &max);
773 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
775 value_range nr;
776 nr.type = rtype;
777 nr.min = wide_int_to_tree (TREE_TYPE (var), min);
778 nr.max = wide_int_to_tree (TREE_TYPE (var), max);
779 nr.equiv = NULL;
780 vrp_intersect_ranges (new_vr, &nr);
784 /* Update the value range, if necessary. */
785 old_vr = get_value_range (var);
786 is_new = old_vr->type != new_vr->type
787 || !vrp_operand_equal_p (old_vr->min, new_vr->min)
788 || !vrp_operand_equal_p (old_vr->max, new_vr->max)
789 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
791 if (is_new)
793 /* Do not allow transitions up the lattice. The following
794 is slightly more awkward than just new_vr->type < old_vr->type
795 because VR_RANGE and VR_ANTI_RANGE need to be considered
796 the same. We may not have is_new when transitioning to
797 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
798 called. */
799 if (new_vr->type == VR_UNDEFINED)
801 BITMAP_FREE (new_vr->equiv);
802 set_value_range_to_varying (old_vr);
803 set_value_range_to_varying (new_vr);
804 return true;
806 else
807 set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
808 new_vr->equiv);
811 BITMAP_FREE (new_vr->equiv);
813 return is_new;
817 /* Add VAR and VAR's equivalence set to EQUIV. This is the central
818 point where equivalence processing can be turned on/off. */
820 static void
821 add_equivalence (bitmap *equiv, const_tree var)
823 unsigned ver = SSA_NAME_VERSION (var);
824 value_range *vr = vr_value[ver];
826 if (*equiv == NULL)
827 *equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
828 bitmap_set_bit (*equiv, ver);
829 if (vr && vr->equiv)
830 bitmap_ior_into (*equiv, vr->equiv);
834 /* Return true if VR is ~[0, 0]. */
836 static inline bool
837 range_is_nonnull (value_range *vr)
839 return vr->type == VR_ANTI_RANGE
840 && integer_zerop (vr->min)
841 && integer_zerop (vr->max);
845 /* Return true if VR is [0, 0]. */
847 static inline bool
848 range_is_null (value_range *vr)
850 return vr->type == VR_RANGE
851 && integer_zerop (vr->min)
852 && integer_zerop (vr->max);
855 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
856 a singleton. */
858 static inline bool
859 range_int_cst_p (value_range *vr)
861 return (vr->type == VR_RANGE
862 && TREE_CODE (vr->max) == INTEGER_CST
863 && TREE_CODE (vr->min) == INTEGER_CST);
866 /* Return true if VR is a INTEGER_CST singleton. */
868 static inline bool
869 range_int_cst_singleton_p (value_range *vr)
871 return (range_int_cst_p (vr)
872 && !is_overflow_infinity (vr->min)
873 && !is_overflow_infinity (vr->max)
874 && tree_int_cst_equal (vr->min, vr->max));
877 /* Return true if value range VR involves at least one symbol. */
879 static inline bool
880 symbolic_range_p (value_range *vr)
882 return (!is_gimple_min_invariant (vr->min)
883 || !is_gimple_min_invariant (vr->max));
886 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
887 otherwise. We only handle additive operations and set NEG to true if the
888 symbol is negated and INV to the invariant part, if any. */
890 static tree
891 get_single_symbol (tree t, bool *neg, tree *inv)
893 bool neg_;
894 tree inv_;
896 if (TREE_CODE (t) == PLUS_EXPR
897 || TREE_CODE (t) == POINTER_PLUS_EXPR
898 || TREE_CODE (t) == MINUS_EXPR)
900 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
902 neg_ = (TREE_CODE (t) == MINUS_EXPR);
903 inv_ = TREE_OPERAND (t, 0);
904 t = TREE_OPERAND (t, 1);
906 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
908 neg_ = false;
909 inv_ = TREE_OPERAND (t, 1);
910 t = TREE_OPERAND (t, 0);
912 else
913 return NULL_TREE;
915 else
917 neg_ = false;
918 inv_ = NULL_TREE;
921 if (TREE_CODE (t) == NEGATE_EXPR)
923 t = TREE_OPERAND (t, 0);
924 neg_ = !neg_;
927 if (TREE_CODE (t) != SSA_NAME)
928 return NULL_TREE;
930 *neg = neg_;
931 *inv = inv_;
932 return t;
935 /* The reverse operation: build a symbolic expression with TYPE
936 from symbol SYM, negated according to NEG, and invariant INV. */
938 static tree
939 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
941 const bool pointer_p = POINTER_TYPE_P (type);
942 tree t = sym;
944 if (neg)
945 t = build1 (NEGATE_EXPR, type, t);
947 if (integer_zerop (inv))
948 return t;
950 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
953 /* Return true if value range VR involves exactly one symbol SYM. */
955 static bool
956 symbolic_range_based_on_p (value_range *vr, const_tree sym)
958 bool neg, min_has_symbol, max_has_symbol;
959 tree inv;
961 if (is_gimple_min_invariant (vr->min))
962 min_has_symbol = false;
963 else if (get_single_symbol (vr->min, &neg, &inv) == sym)
964 min_has_symbol = true;
965 else
966 return false;
968 if (is_gimple_min_invariant (vr->max))
969 max_has_symbol = false;
970 else if (get_single_symbol (vr->max, &neg, &inv) == sym)
971 max_has_symbol = true;
972 else
973 return false;
975 return (min_has_symbol || max_has_symbol);
978 /* Return true if value range VR uses an overflow infinity. */
980 static inline bool
981 overflow_infinity_range_p (value_range *vr)
983 return (vr->type == VR_RANGE
984 && (is_overflow_infinity (vr->min)
985 || is_overflow_infinity (vr->max)));
988 /* Return false if we can not make a valid comparison based on VR;
989 this will be the case if it uses an overflow infinity and overflow
990 is not undefined (i.e., -fno-strict-overflow is in effect).
991 Otherwise return true, and set *STRICT_OVERFLOW_P to true if VR
992 uses an overflow infinity. */
994 static bool
995 usable_range_p (value_range *vr, bool *strict_overflow_p)
997 gcc_assert (vr->type == VR_RANGE);
998 if (is_overflow_infinity (vr->min))
1000 *strict_overflow_p = true;
1001 if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->min)))
1002 return false;
1004 if (is_overflow_infinity (vr->max))
1006 *strict_overflow_p = true;
1007 if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->max)))
1008 return false;
1010 return true;
1013 /* Return true if the result of assignment STMT is know to be non-zero.
1014 If the return value is based on the assumption that signed overflow is
1015 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1016 *STRICT_OVERFLOW_P.*/
1018 static bool
1019 gimple_assign_nonzero_warnv_p (gimple *stmt, bool *strict_overflow_p)
1021 enum tree_code code = gimple_assign_rhs_code (stmt);
1022 switch (get_gimple_rhs_class (code))
1024 case GIMPLE_UNARY_RHS:
1025 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1026 gimple_expr_type (stmt),
1027 gimple_assign_rhs1 (stmt),
1028 strict_overflow_p);
1029 case GIMPLE_BINARY_RHS:
1030 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1031 gimple_expr_type (stmt),
1032 gimple_assign_rhs1 (stmt),
1033 gimple_assign_rhs2 (stmt),
1034 strict_overflow_p);
1035 case GIMPLE_TERNARY_RHS:
1036 return false;
1037 case GIMPLE_SINGLE_RHS:
1038 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
1039 strict_overflow_p);
1040 case GIMPLE_INVALID_RHS:
1041 gcc_unreachable ();
1042 default:
1043 gcc_unreachable ();
1047 /* Return true if STMT is known to compute a non-zero value.
1048 If the return value is based on the assumption that signed overflow is
1049 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1050 *STRICT_OVERFLOW_P.*/
1052 static bool
1053 gimple_stmt_nonzero_warnv_p (gimple *stmt, bool *strict_overflow_p)
1055 switch (gimple_code (stmt))
1057 case GIMPLE_ASSIGN:
1058 return gimple_assign_nonzero_warnv_p (stmt, strict_overflow_p);
1059 case GIMPLE_CALL:
1061 tree fndecl = gimple_call_fndecl (stmt);
1062 if (!fndecl) return false;
1063 if (flag_delete_null_pointer_checks && !flag_check_new
1064 && DECL_IS_OPERATOR_NEW (fndecl)
1065 && !TREE_NOTHROW (fndecl))
1066 return true;
1067 /* References are always non-NULL. */
1068 if (flag_delete_null_pointer_checks
1069 && TREE_CODE (TREE_TYPE (fndecl)) == REFERENCE_TYPE)
1070 return true;
1071 if (flag_delete_null_pointer_checks &&
1072 lookup_attribute ("returns_nonnull",
1073 TYPE_ATTRIBUTES (gimple_call_fntype (stmt))))
1074 return true;
1075 return gimple_alloca_call_p (stmt);
1077 default:
1078 gcc_unreachable ();
1082 /* Like tree_expr_nonzero_warnv_p, but this function uses value ranges
1083 obtained so far. */
1085 static bool
1086 vrp_stmt_computes_nonzero (gimple *stmt, bool *strict_overflow_p)
1088 if (gimple_stmt_nonzero_warnv_p (stmt, strict_overflow_p))
1089 return true;
1091 /* If we have an expression of the form &X->a, then the expression
1092 is nonnull if X is nonnull. */
1093 if (is_gimple_assign (stmt)
1094 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
1096 tree expr = gimple_assign_rhs1 (stmt);
1097 tree base = get_base_address (TREE_OPERAND (expr, 0));
1099 if (base != NULL_TREE
1100 && TREE_CODE (base) == MEM_REF
1101 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
1103 value_range *vr = get_value_range (TREE_OPERAND (base, 0));
1104 if (range_is_nonnull (vr))
1105 return true;
1109 return false;
1112 /* Returns true if EXPR is a valid value (as expected by compare_values) --
1113 a gimple invariant, or SSA_NAME +- CST. */
1115 static bool
1116 valid_value_p (tree expr)
1118 if (TREE_CODE (expr) == SSA_NAME)
1119 return true;
1121 if (TREE_CODE (expr) == PLUS_EXPR
1122 || TREE_CODE (expr) == MINUS_EXPR)
1123 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1124 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
1126 return is_gimple_min_invariant (expr);
1129 /* Return
1130 1 if VAL < VAL2
1131 0 if !(VAL < VAL2)
1132 -2 if those are incomparable. */
1133 static inline int
1134 operand_less_p (tree val, tree val2)
1136 /* LT is folded faster than GE and others. Inline the common case. */
1137 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
1138 return tree_int_cst_lt (val, val2);
1139 else
1141 tree tcmp;
1143 fold_defer_overflow_warnings ();
1145 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
1147 fold_undefer_and_ignore_overflow_warnings ();
1149 if (!tcmp
1150 || TREE_CODE (tcmp) != INTEGER_CST)
1151 return -2;
1153 if (!integer_zerop (tcmp))
1154 return 1;
1157 /* val >= val2, not considering overflow infinity. */
1158 if (is_negative_overflow_infinity (val))
1159 return is_negative_overflow_infinity (val2) ? 0 : 1;
1160 else if (is_positive_overflow_infinity (val2))
1161 return is_positive_overflow_infinity (val) ? 0 : 1;
1163 return 0;
1166 /* Compare two values VAL1 and VAL2. Return
1168 -2 if VAL1 and VAL2 cannot be compared at compile-time,
1169 -1 if VAL1 < VAL2,
1170 0 if VAL1 == VAL2,
1171 +1 if VAL1 > VAL2, and
1172 +2 if VAL1 != VAL2
1174 This is similar to tree_int_cst_compare but supports pointer values
1175 and values that cannot be compared at compile time.
1177 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1178 true if the return value is only valid if we assume that signed
1179 overflow is undefined. */
1181 static int
1182 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1184 if (val1 == val2)
1185 return 0;
1187 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1188 both integers. */
1189 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1190 == POINTER_TYPE_P (TREE_TYPE (val2)));
1192 /* Convert the two values into the same type. This is needed because
1193 sizetype causes sign extension even for unsigned types. */
1194 val2 = fold_convert (TREE_TYPE (val1), val2);
1195 STRIP_USELESS_TYPE_CONVERSION (val2);
1197 const bool overflow_undefined
1198 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1199 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1200 tree inv1, inv2;
1201 bool neg1, neg2;
1202 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1203 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1205 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1206 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1207 if (sym1 && sym2)
1209 /* Both values must use the same name with the same sign. */
1210 if (sym1 != sym2 || neg1 != neg2)
1211 return -2;
1213 /* [-]NAME + CST == [-]NAME + CST. */
1214 if (inv1 == inv2)
1215 return 0;
1217 /* If overflow is defined we cannot simplify more. */
1218 if (!overflow_undefined)
1219 return -2;
1221 if (strict_overflow_p != NULL
1222 && (!inv1 || !TREE_NO_WARNING (val1))
1223 && (!inv2 || !TREE_NO_WARNING (val2)))
1224 *strict_overflow_p = true;
1226 if (!inv1)
1227 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1228 if (!inv2)
1229 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1231 return compare_values_warnv (inv1, inv2, strict_overflow_p);
1234 const bool cst1 = is_gimple_min_invariant (val1);
1235 const bool cst2 = is_gimple_min_invariant (val2);
1237 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1238 it might be possible to say something depending on the constants. */
1239 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1241 if (!overflow_undefined)
1242 return -2;
1244 if (strict_overflow_p != NULL
1245 && (!sym1 || !TREE_NO_WARNING (val1))
1246 && (!sym2 || !TREE_NO_WARNING (val2)))
1247 *strict_overflow_p = true;
1249 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1250 tree cst = cst1 ? val1 : val2;
1251 tree inv = cst1 ? inv2 : inv1;
1253 /* Compute the difference between the constants. If it overflows or
1254 underflows, this means that we can trivially compare the NAME with
1255 it and, consequently, the two values with each other. */
1256 wide_int diff = wi::sub (cst, inv);
1257 if (wi::cmp (0, inv, sgn) != wi::cmp (diff, cst, sgn))
1259 const int res = wi::cmp (cst, inv, sgn);
1260 return cst1 ? res : -res;
1263 return -2;
1266 /* We cannot say anything more for non-constants. */
1267 if (!cst1 || !cst2)
1268 return -2;
1270 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1272 /* We cannot compare overflowed values, except for overflow
1273 infinities. */
1274 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1276 if (strict_overflow_p != NULL)
1277 *strict_overflow_p = true;
1278 if (is_negative_overflow_infinity (val1))
1279 return is_negative_overflow_infinity (val2) ? 0 : -1;
1280 else if (is_negative_overflow_infinity (val2))
1281 return 1;
1282 else if (is_positive_overflow_infinity (val1))
1283 return is_positive_overflow_infinity (val2) ? 0 : 1;
1284 else if (is_positive_overflow_infinity (val2))
1285 return -1;
1286 return -2;
1289 return tree_int_cst_compare (val1, val2);
1291 else
1293 tree t;
1295 /* First see if VAL1 and VAL2 are not the same. */
1296 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1297 return 0;
1299 /* If VAL1 is a lower address than VAL2, return -1. */
1300 if (operand_less_p (val1, val2) == 1)
1301 return -1;
1303 /* If VAL1 is a higher address than VAL2, return +1. */
1304 if (operand_less_p (val2, val1) == 1)
1305 return 1;
1307 /* If VAL1 is different than VAL2, return +2.
1308 For integer constants we either have already returned -1 or 1
1309 or they are equivalent. We still might succeed in proving
1310 something about non-trivial operands. */
1311 if (TREE_CODE (val1) != INTEGER_CST
1312 || TREE_CODE (val2) != INTEGER_CST)
1314 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1315 if (t && integer_onep (t))
1316 return 2;
1319 return -2;
1323 /* Compare values like compare_values_warnv, but treat comparisons of
1324 nonconstants which rely on undefined overflow as incomparable. */
1326 static int
1327 compare_values (tree val1, tree val2)
1329 bool sop;
1330 int ret;
1332 sop = false;
1333 ret = compare_values_warnv (val1, val2, &sop);
1334 if (sop
1335 && (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2)))
1336 ret = -2;
1337 return ret;
1341 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1342 0 if VAL is not inside [MIN, MAX],
1343 -2 if we cannot tell either way.
1345 Benchmark compile/20001226-1.c compilation time after changing this
1346 function. */
1348 static inline int
1349 value_inside_range (tree val, tree min, tree max)
1351 int cmp1, cmp2;
1353 cmp1 = operand_less_p (val, min);
1354 if (cmp1 == -2)
1355 return -2;
1356 if (cmp1 == 1)
1357 return 0;
1359 cmp2 = operand_less_p (max, val);
1360 if (cmp2 == -2)
1361 return -2;
1363 return !cmp2;
1367 /* Return true if value ranges VR0 and VR1 have a non-empty
1368 intersection.
1370 Benchmark compile/20001226-1.c compilation time after changing this
1371 function.
1374 static inline bool
1375 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
1377 /* The value ranges do not intersect if the maximum of the first range is
1378 less than the minimum of the second range or vice versa.
1379 When those relations are unknown, we can't do any better. */
1380 if (operand_less_p (vr0->max, vr1->min) != 0)
1381 return false;
1382 if (operand_less_p (vr1->max, vr0->min) != 0)
1383 return false;
1384 return true;
1388 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1389 include the value zero, -2 if we cannot tell. */
1391 static inline int
1392 range_includes_zero_p (tree min, tree max)
1394 tree zero = build_int_cst (TREE_TYPE (min), 0);
1395 return value_inside_range (zero, min, max);
1398 /* Return true if *VR is know to only contain nonnegative values. */
1400 static inline bool
1401 value_range_nonnegative_p (value_range *vr)
1403 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1404 which would return a useful value should be encoded as a
1405 VR_RANGE. */
1406 if (vr->type == VR_RANGE)
1408 int result = compare_values (vr->min, integer_zero_node);
1409 return (result == 0 || result == 1);
1412 return false;
1415 /* If *VR has a value rante that is a single constant value return that,
1416 otherwise return NULL_TREE. */
1418 static tree
1419 value_range_constant_singleton (value_range *vr)
1421 if (vr->type == VR_RANGE
1422 && operand_equal_p (vr->min, vr->max, 0)
1423 && is_gimple_min_invariant (vr->min))
1424 return vr->min;
1426 return NULL_TREE;
1429 /* If OP has a value range with a single constant value return that,
1430 otherwise return NULL_TREE. This returns OP itself if OP is a
1431 constant. */
1433 static tree
1434 op_with_constant_singleton_value_range (tree op)
1436 if (is_gimple_min_invariant (op))
1437 return op;
1439 if (TREE_CODE (op) != SSA_NAME)
1440 return NULL_TREE;
1442 return value_range_constant_singleton (get_value_range (op));
1445 /* Return true if op is in a boolean [0, 1] value-range. */
1447 static bool
1448 op_with_boolean_value_range_p (tree op)
1450 value_range *vr;
1452 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1453 return true;
1455 if (integer_zerop (op)
1456 || integer_onep (op))
1457 return true;
1459 if (TREE_CODE (op) != SSA_NAME)
1460 return false;
1462 vr = get_value_range (op);
1463 return (vr->type == VR_RANGE
1464 && integer_zerop (vr->min)
1465 && integer_onep (vr->max));
1468 /* Extract value range information from an ASSERT_EXPR EXPR and store
1469 it in *VR_P. */
1471 static void
1472 extract_range_from_assert (value_range *vr_p, tree expr)
1474 tree var, cond, limit, min, max, type;
1475 value_range *limit_vr;
1476 enum tree_code cond_code;
1478 var = ASSERT_EXPR_VAR (expr);
1479 cond = ASSERT_EXPR_COND (expr);
1481 gcc_assert (COMPARISON_CLASS_P (cond));
1483 /* Find VAR in the ASSERT_EXPR conditional. */
1484 if (var == TREE_OPERAND (cond, 0)
1485 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1486 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1488 /* If the predicate is of the form VAR COMP LIMIT, then we just
1489 take LIMIT from the RHS and use the same comparison code. */
1490 cond_code = TREE_CODE (cond);
1491 limit = TREE_OPERAND (cond, 1);
1492 cond = TREE_OPERAND (cond, 0);
1494 else
1496 /* If the predicate is of the form LIMIT COMP VAR, then we need
1497 to flip around the comparison code to create the proper range
1498 for VAR. */
1499 cond_code = swap_tree_comparison (TREE_CODE (cond));
1500 limit = TREE_OPERAND (cond, 0);
1501 cond = TREE_OPERAND (cond, 1);
1504 limit = avoid_overflow_infinity (limit);
1506 type = TREE_TYPE (var);
1507 gcc_assert (limit != var);
1509 /* For pointer arithmetic, we only keep track of pointer equality
1510 and inequality. */
1511 if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1513 set_value_range_to_varying (vr_p);
1514 return;
1517 /* If LIMIT is another SSA name and LIMIT has a range of its own,
1518 try to use LIMIT's range to avoid creating symbolic ranges
1519 unnecessarily. */
1520 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1522 /* LIMIT's range is only interesting if it has any useful information. */
1523 if (! limit_vr
1524 || limit_vr->type == VR_UNDEFINED
1525 || limit_vr->type == VR_VARYING
1526 || (symbolic_range_p (limit_vr)
1527 && ! (limit_vr->type == VR_RANGE
1528 && (limit_vr->min == limit_vr->max
1529 || operand_equal_p (limit_vr->min, limit_vr->max, 0)))))
1530 limit_vr = NULL;
1532 /* Initially, the new range has the same set of equivalences of
1533 VAR's range. This will be revised before returning the final
1534 value. Since assertions may be chained via mutually exclusive
1535 predicates, we will need to trim the set of equivalences before
1536 we are done. */
1537 gcc_assert (vr_p->equiv == NULL);
1538 add_equivalence (&vr_p->equiv, var);
1540 /* Extract a new range based on the asserted comparison for VAR and
1541 LIMIT's value range. Notice that if LIMIT has an anti-range, we
1542 will only use it for equality comparisons (EQ_EXPR). For any
1543 other kind of assertion, we cannot derive a range from LIMIT's
1544 anti-range that can be used to describe the new range. For
1545 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
1546 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
1547 no single range for x_2 that could describe LE_EXPR, so we might
1548 as well build the range [b_4, +INF] for it.
1549 One special case we handle is extracting a range from a
1550 range test encoded as (unsigned)var + CST <= limit. */
1551 if (TREE_CODE (cond) == NOP_EXPR
1552 || TREE_CODE (cond) == PLUS_EXPR)
1554 if (TREE_CODE (cond) == PLUS_EXPR)
1556 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (cond, 1)),
1557 TREE_OPERAND (cond, 1));
1558 max = int_const_binop (PLUS_EXPR, limit, min);
1559 cond = TREE_OPERAND (cond, 0);
1561 else
1563 min = build_int_cst (TREE_TYPE (var), 0);
1564 max = limit;
1567 /* Make sure to not set TREE_OVERFLOW on the final type
1568 conversion. We are willingly interpreting large positive
1569 unsigned values as negative signed values here. */
1570 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1571 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1573 /* We can transform a max, min range to an anti-range or
1574 vice-versa. Use set_and_canonicalize_value_range which does
1575 this for us. */
1576 if (cond_code == LE_EXPR)
1577 set_and_canonicalize_value_range (vr_p, VR_RANGE,
1578 min, max, vr_p->equiv);
1579 else if (cond_code == GT_EXPR)
1580 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1581 min, max, vr_p->equiv);
1582 else
1583 gcc_unreachable ();
1585 else if (cond_code == EQ_EXPR)
1587 enum value_range_type range_type;
1589 if (limit_vr)
1591 range_type = limit_vr->type;
1592 min = limit_vr->min;
1593 max = limit_vr->max;
1595 else
1597 range_type = VR_RANGE;
1598 min = limit;
1599 max = limit;
1602 set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1604 /* When asserting the equality VAR == LIMIT and LIMIT is another
1605 SSA name, the new range will also inherit the equivalence set
1606 from LIMIT. */
1607 if (TREE_CODE (limit) == SSA_NAME)
1608 add_equivalence (&vr_p->equiv, limit);
1610 else if (cond_code == NE_EXPR)
1612 /* As described above, when LIMIT's range is an anti-range and
1613 this assertion is an inequality (NE_EXPR), then we cannot
1614 derive anything from the anti-range. For instance, if
1615 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1616 not imply that VAR's range is [0, 0]. So, in the case of
1617 anti-ranges, we just assert the inequality using LIMIT and
1618 not its anti-range.
1620 If LIMIT_VR is a range, we can only use it to build a new
1621 anti-range if LIMIT_VR is a single-valued range. For
1622 instance, if LIMIT_VR is [0, 1], the predicate
1623 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1624 Rather, it means that for value 0 VAR should be ~[0, 0]
1625 and for value 1, VAR should be ~[1, 1]. We cannot
1626 represent these ranges.
1628 The only situation in which we can build a valid
1629 anti-range is when LIMIT_VR is a single-valued range
1630 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
1631 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
1632 if (limit_vr
1633 && limit_vr->type == VR_RANGE
1634 && compare_values (limit_vr->min, limit_vr->max) == 0)
1636 min = limit_vr->min;
1637 max = limit_vr->max;
1639 else
1641 /* In any other case, we cannot use LIMIT's range to build a
1642 valid anti-range. */
1643 min = max = limit;
1646 /* If MIN and MAX cover the whole range for their type, then
1647 just use the original LIMIT. */
1648 if (INTEGRAL_TYPE_P (type)
1649 && vrp_val_is_min (min)
1650 && vrp_val_is_max (max))
1651 min = max = limit;
1653 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1654 min, max, vr_p->equiv);
1656 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1658 min = TYPE_MIN_VALUE (type);
1660 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1661 max = limit;
1662 else
1664 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1665 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1666 LT_EXPR. */
1667 max = limit_vr->max;
1670 /* If the maximum value forces us to be out of bounds, simply punt.
1671 It would be pointless to try and do anything more since this
1672 all should be optimized away above us. */
1673 if ((cond_code == LT_EXPR
1674 && compare_values (max, min) == 0)
1675 || is_overflow_infinity (max))
1676 set_value_range_to_varying (vr_p);
1677 else
1679 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
1680 if (cond_code == LT_EXPR)
1682 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1683 && !TYPE_UNSIGNED (TREE_TYPE (max)))
1684 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1685 build_int_cst (TREE_TYPE (max), -1));
1686 else
1687 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1688 build_int_cst (TREE_TYPE (max), 1));
1689 if (EXPR_P (max))
1690 TREE_NO_WARNING (max) = 1;
1693 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1696 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1698 max = TYPE_MAX_VALUE (type);
1700 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1701 min = limit;
1702 else
1704 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1705 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1706 GT_EXPR. */
1707 min = limit_vr->min;
1710 /* If the minimum value forces us to be out of bounds, simply punt.
1711 It would be pointless to try and do anything more since this
1712 all should be optimized away above us. */
1713 if ((cond_code == GT_EXPR
1714 && compare_values (min, max) == 0)
1715 || is_overflow_infinity (min))
1716 set_value_range_to_varying (vr_p);
1717 else
1719 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
1720 if (cond_code == GT_EXPR)
1722 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1723 && !TYPE_UNSIGNED (TREE_TYPE (min)))
1724 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1725 build_int_cst (TREE_TYPE (min), -1));
1726 else
1727 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1728 build_int_cst (TREE_TYPE (min), 1));
1729 if (EXPR_P (min))
1730 TREE_NO_WARNING (min) = 1;
1733 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1736 else
1737 gcc_unreachable ();
1739 /* Finally intersect the new range with what we already know about var. */
1740 vrp_intersect_ranges (vr_p, get_value_range (var));
1744 /* Extract range information from SSA name VAR and store it in VR. If
1745 VAR has an interesting range, use it. Otherwise, create the
1746 range [VAR, VAR] and return it. This is useful in situations where
1747 we may have conditionals testing values of VARYING names. For
1748 instance,
1750 x_3 = y_5;
1751 if (x_3 > y_5)
1754 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1755 always false. */
1757 static void
1758 extract_range_from_ssa_name (value_range *vr, tree var)
1760 value_range *var_vr = get_value_range (var);
1762 if (var_vr->type != VR_VARYING)
1763 copy_value_range (vr, var_vr);
1764 else
1765 set_value_range (vr, VR_RANGE, var, var, NULL);
1767 add_equivalence (&vr->equiv, var);
1771 /* Wrapper around int_const_binop. If the operation overflows and we
1772 are not using wrapping arithmetic, then adjust the result to be
1773 -INF or +INF depending on CODE, VAL1 and VAL2. This can return
1774 NULL_TREE if we need to use an overflow infinity representation but
1775 the type does not support it. */
1777 static tree
1778 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
1780 tree res;
1782 res = int_const_binop (code, val1, val2);
1784 /* If we are using unsigned arithmetic, operate symbolically
1785 on -INF and +INF as int_const_binop only handles signed overflow. */
1786 if (TYPE_UNSIGNED (TREE_TYPE (val1)))
1788 int checkz = compare_values (res, val1);
1789 bool overflow = false;
1791 /* Ensure that res = val1 [+*] val2 >= val1
1792 or that res = val1 - val2 <= val1. */
1793 if ((code == PLUS_EXPR
1794 && !(checkz == 1 || checkz == 0))
1795 || (code == MINUS_EXPR
1796 && !(checkz == 0 || checkz == -1)))
1798 overflow = true;
1800 /* Checking for multiplication overflow is done by dividing the
1801 output of the multiplication by the first input of the
1802 multiplication. If the result of that division operation is
1803 not equal to the second input of the multiplication, then the
1804 multiplication overflowed. */
1805 else if (code == MULT_EXPR && !integer_zerop (val1))
1807 tree tmp = int_const_binop (TRUNC_DIV_EXPR,
1808 res,
1809 val1);
1810 int check = compare_values (tmp, val2);
1812 if (check != 0)
1813 overflow = true;
1816 if (overflow)
1818 res = copy_node (res);
1819 TREE_OVERFLOW (res) = 1;
1823 else if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (val1)))
1824 /* If the singed operation wraps then int_const_binop has done
1825 everything we want. */
1827 /* Signed division of -1/0 overflows and by the time it gets here
1828 returns NULL_TREE. */
1829 else if (!res)
1830 return NULL_TREE;
1831 else if ((TREE_OVERFLOW (res)
1832 && !TREE_OVERFLOW (val1)
1833 && !TREE_OVERFLOW (val2))
1834 || is_overflow_infinity (val1)
1835 || is_overflow_infinity (val2))
1837 /* If the operation overflowed but neither VAL1 nor VAL2 are
1838 overflown, return -INF or +INF depending on the operation
1839 and the combination of signs of the operands. */
1840 int sgn1 = tree_int_cst_sgn (val1);
1841 int sgn2 = tree_int_cst_sgn (val2);
1843 if (needs_overflow_infinity (TREE_TYPE (res))
1844 && !supports_overflow_infinity (TREE_TYPE (res)))
1845 return NULL_TREE;
1847 /* We have to punt on adding infinities of different signs,
1848 since we can't tell what the sign of the result should be.
1849 Likewise for subtracting infinities of the same sign. */
1850 if (((code == PLUS_EXPR && sgn1 != sgn2)
1851 || (code == MINUS_EXPR && sgn1 == sgn2))
1852 && is_overflow_infinity (val1)
1853 && is_overflow_infinity (val2))
1854 return NULL_TREE;
1856 /* Don't try to handle division or shifting of infinities. */
1857 if ((code == TRUNC_DIV_EXPR
1858 || code == FLOOR_DIV_EXPR
1859 || code == CEIL_DIV_EXPR
1860 || code == EXACT_DIV_EXPR
1861 || code == ROUND_DIV_EXPR
1862 || code == RSHIFT_EXPR)
1863 && (is_overflow_infinity (val1)
1864 || is_overflow_infinity (val2)))
1865 return NULL_TREE;
1867 /* Notice that we only need to handle the restricted set of
1868 operations handled by extract_range_from_binary_expr.
1869 Among them, only multiplication, addition and subtraction
1870 can yield overflow without overflown operands because we
1871 are working with integral types only... except in the
1872 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1873 for division too. */
1875 /* For multiplication, the sign of the overflow is given
1876 by the comparison of the signs of the operands. */
1877 if ((code == MULT_EXPR && sgn1 == sgn2)
1878 /* For addition, the operands must be of the same sign
1879 to yield an overflow. Its sign is therefore that
1880 of one of the operands, for example the first. For
1881 infinite operands X + -INF is negative, not positive. */
1882 || (code == PLUS_EXPR
1883 && (sgn1 >= 0
1884 ? !is_negative_overflow_infinity (val2)
1885 : is_positive_overflow_infinity (val2)))
1886 /* For subtraction, non-infinite operands must be of
1887 different signs to yield an overflow. Its sign is
1888 therefore that of the first operand or the opposite of
1889 that of the second operand. A first operand of 0 counts
1890 as positive here, for the corner case 0 - (-INF), which
1891 overflows, but must yield +INF. For infinite operands 0
1892 - INF is negative, not positive. */
1893 || (code == MINUS_EXPR
1894 && (sgn1 >= 0
1895 ? !is_positive_overflow_infinity (val2)
1896 : is_negative_overflow_infinity (val2)))
1897 /* We only get in here with positive shift count, so the
1898 overflow direction is the same as the sign of val1.
1899 Actually rshift does not overflow at all, but we only
1900 handle the case of shifting overflowed -INF and +INF. */
1901 || (code == RSHIFT_EXPR
1902 && sgn1 >= 0)
1903 /* For division, the only case is -INF / -1 = +INF. */
1904 || code == TRUNC_DIV_EXPR
1905 || code == FLOOR_DIV_EXPR
1906 || code == CEIL_DIV_EXPR
1907 || code == EXACT_DIV_EXPR
1908 || code == ROUND_DIV_EXPR)
1909 return (needs_overflow_infinity (TREE_TYPE (res))
1910 ? positive_overflow_infinity (TREE_TYPE (res))
1911 : TYPE_MAX_VALUE (TREE_TYPE (res)));
1912 else
1913 return (needs_overflow_infinity (TREE_TYPE (res))
1914 ? negative_overflow_infinity (TREE_TYPE (res))
1915 : TYPE_MIN_VALUE (TREE_TYPE (res)));
1918 return res;
1922 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1923 bitmask if some bit is unset, it means for all numbers in the range
1924 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1925 bitmask if some bit is set, it means for all numbers in the range
1926 the bit is 1, otherwise it might be 0 or 1. */
1928 static bool
1929 zero_nonzero_bits_from_vr (const tree expr_type,
1930 value_range *vr,
1931 wide_int *may_be_nonzero,
1932 wide_int *must_be_nonzero)
1934 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1935 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1936 if (!range_int_cst_p (vr)
1937 || is_overflow_infinity (vr->min)
1938 || is_overflow_infinity (vr->max))
1939 return false;
1941 if (range_int_cst_singleton_p (vr))
1943 *may_be_nonzero = vr->min;
1944 *must_be_nonzero = *may_be_nonzero;
1946 else if (tree_int_cst_sgn (vr->min) >= 0
1947 || tree_int_cst_sgn (vr->max) < 0)
1949 wide_int xor_mask = wi::bit_xor (vr->min, vr->max);
1950 *may_be_nonzero = wi::bit_or (vr->min, vr->max);
1951 *must_be_nonzero = wi::bit_and (vr->min, vr->max);
1952 if (xor_mask != 0)
1954 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1955 may_be_nonzero->get_precision ());
1956 *may_be_nonzero = *may_be_nonzero | mask;
1957 *must_be_nonzero = must_be_nonzero->and_not (mask);
1961 return true;
1964 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1965 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1966 false otherwise. If *AR can be represented with a single range
1967 *VR1 will be VR_UNDEFINED. */
1969 static bool
1970 ranges_from_anti_range (value_range *ar,
1971 value_range *vr0, value_range *vr1)
1973 tree type = TREE_TYPE (ar->min);
1975 vr0->type = VR_UNDEFINED;
1976 vr1->type = VR_UNDEFINED;
1978 if (ar->type != VR_ANTI_RANGE
1979 || TREE_CODE (ar->min) != INTEGER_CST
1980 || TREE_CODE (ar->max) != INTEGER_CST
1981 || !vrp_val_min (type)
1982 || !vrp_val_max (type))
1983 return false;
1985 if (!vrp_val_is_min (ar->min))
1987 vr0->type = VR_RANGE;
1988 vr0->min = vrp_val_min (type);
1989 vr0->max = wide_int_to_tree (type, wi::sub (ar->min, 1));
1991 if (!vrp_val_is_max (ar->max))
1993 vr1->type = VR_RANGE;
1994 vr1->min = wide_int_to_tree (type, wi::add (ar->max, 1));
1995 vr1->max = vrp_val_max (type);
1997 if (vr0->type == VR_UNDEFINED)
1999 *vr0 = *vr1;
2000 vr1->type = VR_UNDEFINED;
2003 return vr0->type != VR_UNDEFINED;
2006 /* Helper to extract a value-range *VR for a multiplicative operation
2007 *VR0 CODE *VR1. */
2009 static void
2010 extract_range_from_multiplicative_op_1 (value_range *vr,
2011 enum tree_code code,
2012 value_range *vr0, value_range *vr1)
2014 enum value_range_type type;
2015 tree val[4];
2016 size_t i;
2017 tree min, max;
2018 bool sop;
2019 int cmp;
2021 /* Multiplications, divisions and shifts are a bit tricky to handle,
2022 depending on the mix of signs we have in the two ranges, we
2023 need to operate on different values to get the minimum and
2024 maximum values for the new range. One approach is to figure
2025 out all the variations of range combinations and do the
2026 operations.
2028 However, this involves several calls to compare_values and it
2029 is pretty convoluted. It's simpler to do the 4 operations
2030 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
2031 MAX1) and then figure the smallest and largest values to form
2032 the new range. */
2033 gcc_assert (code == MULT_EXPR
2034 || code == TRUNC_DIV_EXPR
2035 || code == FLOOR_DIV_EXPR
2036 || code == CEIL_DIV_EXPR
2037 || code == EXACT_DIV_EXPR
2038 || code == ROUND_DIV_EXPR
2039 || code == RSHIFT_EXPR
2040 || code == LSHIFT_EXPR);
2041 gcc_assert ((vr0->type == VR_RANGE
2042 || (code == MULT_EXPR && vr0->type == VR_ANTI_RANGE))
2043 && vr0->type == vr1->type);
2045 type = vr0->type;
2047 /* Compute the 4 cross operations. */
2048 sop = false;
2049 val[0] = vrp_int_const_binop (code, vr0->min, vr1->min);
2050 if (val[0] == NULL_TREE)
2051 sop = true;
2053 if (vr1->max == vr1->min)
2054 val[1] = NULL_TREE;
2055 else
2057 val[1] = vrp_int_const_binop (code, vr0->min, vr1->max);
2058 if (val[1] == NULL_TREE)
2059 sop = true;
2062 if (vr0->max == vr0->min)
2063 val[2] = NULL_TREE;
2064 else
2066 val[2] = vrp_int_const_binop (code, vr0->max, vr1->min);
2067 if (val[2] == NULL_TREE)
2068 sop = true;
2071 if (vr0->min == vr0->max || vr1->min == vr1->max)
2072 val[3] = NULL_TREE;
2073 else
2075 val[3] = vrp_int_const_binop (code, vr0->max, vr1->max);
2076 if (val[3] == NULL_TREE)
2077 sop = true;
2080 if (sop)
2082 set_value_range_to_varying (vr);
2083 return;
2086 /* Set MIN to the minimum of VAL[i] and MAX to the maximum
2087 of VAL[i]. */
2088 min = val[0];
2089 max = val[0];
2090 for (i = 1; i < 4; i++)
2092 if (!is_gimple_min_invariant (min)
2093 || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2094 || !is_gimple_min_invariant (max)
2095 || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2096 break;
2098 if (val[i])
2100 if (!is_gimple_min_invariant (val[i])
2101 || (TREE_OVERFLOW (val[i])
2102 && !is_overflow_infinity (val[i])))
2104 /* If we found an overflowed value, set MIN and MAX
2105 to it so that we set the resulting range to
2106 VARYING. */
2107 min = max = val[i];
2108 break;
2111 if (compare_values (val[i], min) == -1)
2112 min = val[i];
2114 if (compare_values (val[i], max) == 1)
2115 max = val[i];
2119 /* If either MIN or MAX overflowed, then set the resulting range to
2120 VARYING. But we do accept an overflow infinity
2121 representation. */
2122 if (min == NULL_TREE
2123 || !is_gimple_min_invariant (min)
2124 || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2125 || max == NULL_TREE
2126 || !is_gimple_min_invariant (max)
2127 || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2129 set_value_range_to_varying (vr);
2130 return;
2133 /* We punt if:
2134 1) [-INF, +INF]
2135 2) [-INF, +-INF(OVF)]
2136 3) [+-INF(OVF), +INF]
2137 4) [+-INF(OVF), +-INF(OVF)]
2138 We learn nothing when we have INF and INF(OVF) on both sides.
2139 Note that we do accept [-INF, -INF] and [+INF, +INF] without
2140 overflow. */
2141 if ((vrp_val_is_min (min) || is_overflow_infinity (min))
2142 && (vrp_val_is_max (max) || is_overflow_infinity (max)))
2144 set_value_range_to_varying (vr);
2145 return;
2148 cmp = compare_values (min, max);
2149 if (cmp == -2 || cmp == 1)
2151 /* If the new range has its limits swapped around (MIN > MAX),
2152 then the operation caused one of them to wrap around, mark
2153 the new range VARYING. */
2154 set_value_range_to_varying (vr);
2156 else
2157 set_value_range (vr, type, min, max, NULL);
2160 /* Extract range information from a binary operation CODE based on
2161 the ranges of each of its operands *VR0 and *VR1 with resulting
2162 type EXPR_TYPE. The resulting range is stored in *VR. */
2164 static void
2165 extract_range_from_binary_expr_1 (value_range *vr,
2166 enum tree_code code, tree expr_type,
2167 value_range *vr0_, value_range *vr1_)
2169 value_range vr0 = *vr0_, vr1 = *vr1_;
2170 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2171 enum value_range_type type;
2172 tree min = NULL_TREE, max = NULL_TREE;
2173 int cmp;
2175 if (!INTEGRAL_TYPE_P (expr_type)
2176 && !POINTER_TYPE_P (expr_type))
2178 set_value_range_to_varying (vr);
2179 return;
2182 /* Not all binary expressions can be applied to ranges in a
2183 meaningful way. Handle only arithmetic operations. */
2184 if (code != PLUS_EXPR
2185 && code != MINUS_EXPR
2186 && code != POINTER_PLUS_EXPR
2187 && code != MULT_EXPR
2188 && code != TRUNC_DIV_EXPR
2189 && code != FLOOR_DIV_EXPR
2190 && code != CEIL_DIV_EXPR
2191 && code != EXACT_DIV_EXPR
2192 && code != ROUND_DIV_EXPR
2193 && code != TRUNC_MOD_EXPR
2194 && code != RSHIFT_EXPR
2195 && code != LSHIFT_EXPR
2196 && code != MIN_EXPR
2197 && code != MAX_EXPR
2198 && code != BIT_AND_EXPR
2199 && code != BIT_IOR_EXPR
2200 && code != BIT_XOR_EXPR)
2202 set_value_range_to_varying (vr);
2203 return;
2206 /* If both ranges are UNDEFINED, so is the result. */
2207 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
2209 set_value_range_to_undefined (vr);
2210 return;
2212 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
2213 code. At some point we may want to special-case operations that
2214 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
2215 operand. */
2216 else if (vr0.type == VR_UNDEFINED)
2217 set_value_range_to_varying (&vr0);
2218 else if (vr1.type == VR_UNDEFINED)
2219 set_value_range_to_varying (&vr1);
2221 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2222 and express ~[] op X as ([]' op X) U ([]'' op X). */
2223 if (vr0.type == VR_ANTI_RANGE
2224 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2226 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2227 if (vrtem1.type != VR_UNDEFINED)
2229 value_range vrres = VR_INITIALIZER;
2230 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2231 &vrtem1, vr1_);
2232 vrp_meet (vr, &vrres);
2234 return;
2236 /* Likewise for X op ~[]. */
2237 if (vr1.type == VR_ANTI_RANGE
2238 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2240 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2241 if (vrtem1.type != VR_UNDEFINED)
2243 value_range vrres = VR_INITIALIZER;
2244 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2245 vr0_, &vrtem1);
2246 vrp_meet (vr, &vrres);
2248 return;
2251 /* The type of the resulting value range defaults to VR0.TYPE. */
2252 type = vr0.type;
2254 /* Refuse to operate on VARYING ranges, ranges of different kinds
2255 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2256 because we may be able to derive a useful range even if one of
2257 the operands is VR_VARYING or symbolic range. Similarly for
2258 divisions, MIN/MAX and PLUS/MINUS.
2260 TODO, we may be able to derive anti-ranges in some cases. */
2261 if (code != BIT_AND_EXPR
2262 && code != BIT_IOR_EXPR
2263 && code != TRUNC_DIV_EXPR
2264 && code != FLOOR_DIV_EXPR
2265 && code != CEIL_DIV_EXPR
2266 && code != EXACT_DIV_EXPR
2267 && code != ROUND_DIV_EXPR
2268 && code != TRUNC_MOD_EXPR
2269 && code != MIN_EXPR
2270 && code != MAX_EXPR
2271 && code != PLUS_EXPR
2272 && code != MINUS_EXPR
2273 && code != RSHIFT_EXPR
2274 && (vr0.type == VR_VARYING
2275 || vr1.type == VR_VARYING
2276 || vr0.type != vr1.type
2277 || symbolic_range_p (&vr0)
2278 || symbolic_range_p (&vr1)))
2280 set_value_range_to_varying (vr);
2281 return;
2284 /* Now evaluate the expression to determine the new range. */
2285 if (POINTER_TYPE_P (expr_type))
2287 if (code == MIN_EXPR || code == MAX_EXPR)
2289 /* For MIN/MAX expressions with pointers, we only care about
2290 nullness, if both are non null, then the result is nonnull.
2291 If both are null, then the result is null. Otherwise they
2292 are varying. */
2293 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2294 set_value_range_to_nonnull (vr, expr_type);
2295 else if (range_is_null (&vr0) && range_is_null (&vr1))
2296 set_value_range_to_null (vr, expr_type);
2297 else
2298 set_value_range_to_varying (vr);
2300 else if (code == POINTER_PLUS_EXPR)
2302 /* For pointer types, we are really only interested in asserting
2303 whether the expression evaluates to non-NULL. */
2304 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2305 set_value_range_to_nonnull (vr, expr_type);
2306 else if (range_is_null (&vr0) && range_is_null (&vr1))
2307 set_value_range_to_null (vr, expr_type);
2308 else
2309 set_value_range_to_varying (vr);
2311 else if (code == BIT_AND_EXPR)
2313 /* For pointer types, we are really only interested in asserting
2314 whether the expression evaluates to non-NULL. */
2315 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2316 set_value_range_to_nonnull (vr, expr_type);
2317 else if (range_is_null (&vr0) || range_is_null (&vr1))
2318 set_value_range_to_null (vr, expr_type);
2319 else
2320 set_value_range_to_varying (vr);
2322 else
2323 set_value_range_to_varying (vr);
2325 return;
2328 /* For integer ranges, apply the operation to each end of the
2329 range and see what we end up with. */
2330 if (code == PLUS_EXPR || code == MINUS_EXPR)
2332 const bool minus_p = (code == MINUS_EXPR);
2333 tree min_op0 = vr0.min;
2334 tree min_op1 = minus_p ? vr1.max : vr1.min;
2335 tree max_op0 = vr0.max;
2336 tree max_op1 = minus_p ? vr1.min : vr1.max;
2337 tree sym_min_op0 = NULL_TREE;
2338 tree sym_min_op1 = NULL_TREE;
2339 tree sym_max_op0 = NULL_TREE;
2340 tree sym_max_op1 = NULL_TREE;
2341 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2343 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2344 single-symbolic ranges, try to compute the precise resulting range,
2345 but only if we know that this resulting range will also be constant
2346 or single-symbolic. */
2347 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2348 && (TREE_CODE (min_op0) == INTEGER_CST
2349 || (sym_min_op0
2350 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2351 && (TREE_CODE (min_op1) == INTEGER_CST
2352 || (sym_min_op1
2353 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2354 && (!(sym_min_op0 && sym_min_op1)
2355 || (sym_min_op0 == sym_min_op1
2356 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2357 && (TREE_CODE (max_op0) == INTEGER_CST
2358 || (sym_max_op0
2359 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2360 && (TREE_CODE (max_op1) == INTEGER_CST
2361 || (sym_max_op1
2362 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2363 && (!(sym_max_op0 && sym_max_op1)
2364 || (sym_max_op0 == sym_max_op1
2365 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2367 const signop sgn = TYPE_SIGN (expr_type);
2368 const unsigned int prec = TYPE_PRECISION (expr_type);
2369 wide_int type_min, type_max, wmin, wmax;
2370 int min_ovf = 0;
2371 int max_ovf = 0;
2373 /* Get the lower and upper bounds of the type. */
2374 if (TYPE_OVERFLOW_WRAPS (expr_type))
2376 type_min = wi::min_value (prec, sgn);
2377 type_max = wi::max_value (prec, sgn);
2379 else
2381 type_min = vrp_val_min (expr_type);
2382 type_max = vrp_val_max (expr_type);
2385 /* Combine the lower bounds, if any. */
2386 if (min_op0 && min_op1)
2388 if (minus_p)
2390 wmin = wi::sub (min_op0, min_op1);
2392 /* Check for overflow. */
2393 if (wi::cmp (0, min_op1, sgn)
2394 != wi::cmp (wmin, min_op0, sgn))
2395 min_ovf = wi::cmp (min_op0, min_op1, sgn);
2397 else
2399 wmin = wi::add (min_op0, min_op1);
2401 /* Check for overflow. */
2402 if (wi::cmp (min_op1, 0, sgn)
2403 != wi::cmp (wmin, min_op0, sgn))
2404 min_ovf = wi::cmp (min_op0, wmin, sgn);
2407 else if (min_op0)
2408 wmin = min_op0;
2409 else if (min_op1)
2410 wmin = minus_p ? wi::neg (min_op1) : min_op1;
2411 else
2412 wmin = wi::shwi (0, prec);
2414 /* Combine the upper bounds, if any. */
2415 if (max_op0 && max_op1)
2417 if (minus_p)
2419 wmax = wi::sub (max_op0, max_op1);
2421 /* Check for overflow. */
2422 if (wi::cmp (0, max_op1, sgn)
2423 != wi::cmp (wmax, max_op0, sgn))
2424 max_ovf = wi::cmp (max_op0, max_op1, sgn);
2426 else
2428 wmax = wi::add (max_op0, max_op1);
2430 if (wi::cmp (max_op1, 0, sgn)
2431 != wi::cmp (wmax, max_op0, sgn))
2432 max_ovf = wi::cmp (max_op0, wmax, sgn);
2435 else if (max_op0)
2436 wmax = max_op0;
2437 else if (max_op1)
2438 wmax = minus_p ? wi::neg (max_op1) : max_op1;
2439 else
2440 wmax = wi::shwi (0, prec);
2442 /* Check for type overflow. */
2443 if (min_ovf == 0)
2445 if (wi::cmp (wmin, type_min, sgn) == -1)
2446 min_ovf = -1;
2447 else if (wi::cmp (wmin, type_max, sgn) == 1)
2448 min_ovf = 1;
2450 if (max_ovf == 0)
2452 if (wi::cmp (wmax, type_min, sgn) == -1)
2453 max_ovf = -1;
2454 else if (wi::cmp (wmax, type_max, sgn) == 1)
2455 max_ovf = 1;
2458 /* If we have overflow for the constant part and the resulting
2459 range will be symbolic, drop to VR_VARYING. */
2460 if ((min_ovf && sym_min_op0 != sym_min_op1)
2461 || (max_ovf && sym_max_op0 != sym_max_op1))
2463 set_value_range_to_varying (vr);
2464 return;
2467 if (TYPE_OVERFLOW_WRAPS (expr_type))
2469 /* If overflow wraps, truncate the values and adjust the
2470 range kind and bounds appropriately. */
2471 wide_int tmin = wide_int::from (wmin, prec, sgn);
2472 wide_int tmax = wide_int::from (wmax, prec, sgn);
2473 if (min_ovf == max_ovf)
2475 /* No overflow or both overflow or underflow. The
2476 range kind stays VR_RANGE. */
2477 min = wide_int_to_tree (expr_type, tmin);
2478 max = wide_int_to_tree (expr_type, tmax);
2480 else if ((min_ovf == -1 && max_ovf == 0)
2481 || (max_ovf == 1 && min_ovf == 0))
2483 /* Min underflow or max overflow. The range kind
2484 changes to VR_ANTI_RANGE. */
2485 bool covers = false;
2486 wide_int tem = tmin;
2487 type = VR_ANTI_RANGE;
2488 tmin = tmax + 1;
2489 if (wi::cmp (tmin, tmax, sgn) < 0)
2490 covers = true;
2491 tmax = tem - 1;
2492 if (wi::cmp (tmax, tem, sgn) > 0)
2493 covers = true;
2494 /* If the anti-range would cover nothing, drop to varying.
2495 Likewise if the anti-range bounds are outside of the
2496 types values. */
2497 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2499 set_value_range_to_varying (vr);
2500 return;
2502 min = wide_int_to_tree (expr_type, tmin);
2503 max = wide_int_to_tree (expr_type, tmax);
2505 else
2507 /* Other underflow and/or overflow, drop to VR_VARYING. */
2508 set_value_range_to_varying (vr);
2509 return;
2512 else
2514 /* If overflow does not wrap, saturate to the types min/max
2515 value. */
2516 if (min_ovf == -1)
2518 if (needs_overflow_infinity (expr_type)
2519 && supports_overflow_infinity (expr_type))
2520 min = negative_overflow_infinity (expr_type);
2521 else
2522 min = wide_int_to_tree (expr_type, type_min);
2524 else if (min_ovf == 1)
2526 if (needs_overflow_infinity (expr_type)
2527 && supports_overflow_infinity (expr_type))
2528 min = positive_overflow_infinity (expr_type);
2529 else
2530 min = wide_int_to_tree (expr_type, type_max);
2532 else
2533 min = wide_int_to_tree (expr_type, wmin);
2535 if (max_ovf == -1)
2537 if (needs_overflow_infinity (expr_type)
2538 && supports_overflow_infinity (expr_type))
2539 max = negative_overflow_infinity (expr_type);
2540 else
2541 max = wide_int_to_tree (expr_type, type_min);
2543 else if (max_ovf == 1)
2545 if (needs_overflow_infinity (expr_type)
2546 && supports_overflow_infinity (expr_type))
2547 max = positive_overflow_infinity (expr_type);
2548 else
2549 max = wide_int_to_tree (expr_type, type_max);
2551 else
2552 max = wide_int_to_tree (expr_type, wmax);
2555 if (needs_overflow_infinity (expr_type)
2556 && supports_overflow_infinity (expr_type))
2558 if ((min_op0 && is_negative_overflow_infinity (min_op0))
2559 || (min_op1
2560 && (minus_p
2561 ? is_positive_overflow_infinity (min_op1)
2562 : is_negative_overflow_infinity (min_op1))))
2563 min = negative_overflow_infinity (expr_type);
2564 if ((max_op0 && is_positive_overflow_infinity (max_op0))
2565 || (max_op1
2566 && (minus_p
2567 ? is_negative_overflow_infinity (max_op1)
2568 : is_positive_overflow_infinity (max_op1))))
2569 max = positive_overflow_infinity (expr_type);
2572 /* If the result lower bound is constant, we're done;
2573 otherwise, build the symbolic lower bound. */
2574 if (sym_min_op0 == sym_min_op1)
2576 else if (sym_min_op0)
2577 min = build_symbolic_expr (expr_type, sym_min_op0,
2578 neg_min_op0, min);
2579 else if (sym_min_op1)
2580 min = build_symbolic_expr (expr_type, sym_min_op1,
2581 neg_min_op1 ^ minus_p, min);
2583 /* Likewise for the upper bound. */
2584 if (sym_max_op0 == sym_max_op1)
2586 else if (sym_max_op0)
2587 max = build_symbolic_expr (expr_type, sym_max_op0,
2588 neg_max_op0, max);
2589 else if (sym_max_op1)
2590 max = build_symbolic_expr (expr_type, sym_max_op1,
2591 neg_max_op1 ^ minus_p, max);
2593 else
2595 /* For other cases, for example if we have a PLUS_EXPR with two
2596 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2597 to compute a precise range for such a case.
2598 ??? General even mixed range kind operations can be expressed
2599 by for example transforming ~[3, 5] + [1, 2] to range-only
2600 operations and a union primitive:
2601 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2602 [-INF+1, 4] U [6, +INF(OVF)]
2603 though usually the union is not exactly representable with
2604 a single range or anti-range as the above is
2605 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2606 but one could use a scheme similar to equivalences for this. */
2607 set_value_range_to_varying (vr);
2608 return;
2611 else if (code == MIN_EXPR
2612 || code == MAX_EXPR)
2614 if (vr0.type == VR_RANGE
2615 && !symbolic_range_p (&vr0))
2617 type = VR_RANGE;
2618 if (vr1.type == VR_RANGE
2619 && !symbolic_range_p (&vr1))
2621 /* For operations that make the resulting range directly
2622 proportional to the original ranges, apply the operation to
2623 the same end of each range. */
2624 min = vrp_int_const_binop (code, vr0.min, vr1.min);
2625 max = vrp_int_const_binop (code, vr0.max, vr1.max);
2627 else if (code == MIN_EXPR)
2629 min = vrp_val_min (expr_type);
2630 max = vr0.max;
2632 else if (code == MAX_EXPR)
2634 min = vr0.min;
2635 max = vrp_val_max (expr_type);
2638 else if (vr1.type == VR_RANGE
2639 && !symbolic_range_p (&vr1))
2641 type = VR_RANGE;
2642 if (code == MIN_EXPR)
2644 min = vrp_val_min (expr_type);
2645 max = vr1.max;
2647 else if (code == MAX_EXPR)
2649 min = vr1.min;
2650 max = vrp_val_max (expr_type);
2653 else
2655 set_value_range_to_varying (vr);
2656 return;
2659 else if (code == MULT_EXPR)
2661 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2662 drop to varying. This test requires 2*prec bits if both
2663 operands are signed and 2*prec + 2 bits if either is not. */
2665 signop sign = TYPE_SIGN (expr_type);
2666 unsigned int prec = TYPE_PRECISION (expr_type);
2668 if (range_int_cst_p (&vr0)
2669 && range_int_cst_p (&vr1)
2670 && TYPE_OVERFLOW_WRAPS (expr_type))
2672 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2673 typedef generic_wide_int
2674 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2675 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2676 vrp_int size = sizem1 + 1;
2678 /* Extend the values using the sign of the result to PREC2.
2679 From here on out, everthing is just signed math no matter
2680 what the input types were. */
2681 vrp_int min0 = vrp_int_cst (vr0.min);
2682 vrp_int max0 = vrp_int_cst (vr0.max);
2683 vrp_int min1 = vrp_int_cst (vr1.min);
2684 vrp_int max1 = vrp_int_cst (vr1.max);
2685 /* Canonicalize the intervals. */
2686 if (sign == UNSIGNED)
2688 if (wi::ltu_p (size, min0 + max0))
2690 min0 -= size;
2691 max0 -= size;
2694 if (wi::ltu_p (size, min1 + max1))
2696 min1 -= size;
2697 max1 -= size;
2701 vrp_int prod0 = min0 * min1;
2702 vrp_int prod1 = min0 * max1;
2703 vrp_int prod2 = max0 * min1;
2704 vrp_int prod3 = max0 * max1;
2706 /* Sort the 4 products so that min is in prod0 and max is in
2707 prod3. */
2708 /* min0min1 > max0max1 */
2709 if (prod0 > prod3)
2710 std::swap (prod0, prod3);
2712 /* min0max1 > max0min1 */
2713 if (prod1 > prod2)
2714 std::swap (prod1, prod2);
2716 if (prod0 > prod1)
2717 std::swap (prod0, prod1);
2719 if (prod2 > prod3)
2720 std::swap (prod2, prod3);
2722 /* diff = max - min. */
2723 prod2 = prod3 - prod0;
2724 if (wi::geu_p (prod2, sizem1))
2726 /* the range covers all values. */
2727 set_value_range_to_varying (vr);
2728 return;
2731 /* The following should handle the wrapping and selecting
2732 VR_ANTI_RANGE for us. */
2733 min = wide_int_to_tree (expr_type, prod0);
2734 max = wide_int_to_tree (expr_type, prod3);
2735 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2736 return;
2739 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2740 drop to VR_VARYING. It would take more effort to compute a
2741 precise range for such a case. For example, if we have
2742 op0 == 65536 and op1 == 65536 with their ranges both being
2743 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2744 we cannot claim that the product is in ~[0,0]. Note that we
2745 are guaranteed to have vr0.type == vr1.type at this
2746 point. */
2747 if (vr0.type == VR_ANTI_RANGE
2748 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2750 set_value_range_to_varying (vr);
2751 return;
2754 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2755 return;
2757 else if (code == RSHIFT_EXPR
2758 || code == LSHIFT_EXPR)
2760 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2761 then drop to VR_VARYING. Outside of this range we get undefined
2762 behavior from the shift operation. We cannot even trust
2763 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2764 shifts, and the operation at the tree level may be widened. */
2765 if (range_int_cst_p (&vr1)
2766 && compare_tree_int (vr1.min, 0) >= 0
2767 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2769 if (code == RSHIFT_EXPR)
2771 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2772 useful ranges just from the shift count. E.g.
2773 x >> 63 for signed 64-bit x is always [-1, 0]. */
2774 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2776 vr0.type = type = VR_RANGE;
2777 vr0.min = vrp_val_min (expr_type);
2778 vr0.max = vrp_val_max (expr_type);
2780 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2781 return;
2783 /* We can map lshifts by constants to MULT_EXPR handling. */
2784 else if (code == LSHIFT_EXPR
2785 && range_int_cst_singleton_p (&vr1))
2787 bool saved_flag_wrapv;
2788 value_range vr1p = VR_INITIALIZER;
2789 vr1p.type = VR_RANGE;
2790 vr1p.min = (wide_int_to_tree
2791 (expr_type,
2792 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2793 TYPE_PRECISION (expr_type))));
2794 vr1p.max = vr1p.min;
2795 /* We have to use a wrapping multiply though as signed overflow
2796 on lshifts is implementation defined in C89. */
2797 saved_flag_wrapv = flag_wrapv;
2798 flag_wrapv = 1;
2799 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2800 &vr0, &vr1p);
2801 flag_wrapv = saved_flag_wrapv;
2802 return;
2804 else if (code == LSHIFT_EXPR
2805 && range_int_cst_p (&vr0))
2807 int prec = TYPE_PRECISION (expr_type);
2808 int overflow_pos = prec;
2809 int bound_shift;
2810 wide_int low_bound, high_bound;
2811 bool uns = TYPE_UNSIGNED (expr_type);
2812 bool in_bounds = false;
2814 if (!uns)
2815 overflow_pos -= 1;
2817 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2818 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2819 overflow. However, for that to happen, vr1.max needs to be
2820 zero, which means vr1 is a singleton range of zero, which
2821 means it should be handled by the previous LSHIFT_EXPR
2822 if-clause. */
2823 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2824 wide_int complement = ~(bound - 1);
2826 if (uns)
2828 low_bound = bound;
2829 high_bound = complement;
2830 if (wi::ltu_p (vr0.max, low_bound))
2832 /* [5, 6] << [1, 2] == [10, 24]. */
2833 /* We're shifting out only zeroes, the value increases
2834 monotonically. */
2835 in_bounds = true;
2837 else if (wi::ltu_p (high_bound, vr0.min))
2839 /* [0xffffff00, 0xffffffff] << [1, 2]
2840 == [0xfffffc00, 0xfffffffe]. */
2841 /* We're shifting out only ones, the value decreases
2842 monotonically. */
2843 in_bounds = true;
2846 else
2848 /* [-1, 1] << [1, 2] == [-4, 4]. */
2849 low_bound = complement;
2850 high_bound = bound;
2851 if (wi::lts_p (vr0.max, high_bound)
2852 && wi::lts_p (low_bound, vr0.min))
2854 /* For non-negative numbers, we're shifting out only
2855 zeroes, the value increases monotonically.
2856 For negative numbers, we're shifting out only ones, the
2857 value decreases monotomically. */
2858 in_bounds = true;
2862 if (in_bounds)
2864 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2865 return;
2869 set_value_range_to_varying (vr);
2870 return;
2872 else if (code == TRUNC_DIV_EXPR
2873 || code == FLOOR_DIV_EXPR
2874 || code == CEIL_DIV_EXPR
2875 || code == EXACT_DIV_EXPR
2876 || code == ROUND_DIV_EXPR)
2878 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2880 /* For division, if op1 has VR_RANGE but op0 does not, something
2881 can be deduced just from that range. Say [min, max] / [4, max]
2882 gives [min / 4, max / 4] range. */
2883 if (vr1.type == VR_RANGE
2884 && !symbolic_range_p (&vr1)
2885 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2887 vr0.type = type = VR_RANGE;
2888 vr0.min = vrp_val_min (expr_type);
2889 vr0.max = vrp_val_max (expr_type);
2891 else
2893 set_value_range_to_varying (vr);
2894 return;
2898 /* For divisions, if flag_non_call_exceptions is true, we must
2899 not eliminate a division by zero. */
2900 if (cfun->can_throw_non_call_exceptions
2901 && (vr1.type != VR_RANGE
2902 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2904 set_value_range_to_varying (vr);
2905 return;
2908 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2909 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2910 include 0. */
2911 if (vr0.type == VR_RANGE
2912 && (vr1.type != VR_RANGE
2913 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2915 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2916 int cmp;
2918 min = NULL_TREE;
2919 max = NULL_TREE;
2920 if (TYPE_UNSIGNED (expr_type)
2921 || value_range_nonnegative_p (&vr1))
2923 /* For unsigned division or when divisor is known
2924 to be non-negative, the range has to cover
2925 all numbers from 0 to max for positive max
2926 and all numbers from min to 0 for negative min. */
2927 cmp = compare_values (vr0.max, zero);
2928 if (cmp == -1)
2930 /* When vr0.max < 0, vr1.min != 0 and value
2931 ranges for dividend and divisor are available. */
2932 if (vr1.type == VR_RANGE
2933 && !symbolic_range_p (&vr0)
2934 && !symbolic_range_p (&vr1)
2935 && compare_values (vr1.min, zero) != 0)
2936 max = int_const_binop (code, vr0.max, vr1.min);
2937 else
2938 max = zero;
2940 else if (cmp == 0 || cmp == 1)
2941 max = vr0.max;
2942 else
2943 type = VR_VARYING;
2944 cmp = compare_values (vr0.min, zero);
2945 if (cmp == 1)
2947 /* For unsigned division when value ranges for dividend
2948 and divisor are available. */
2949 if (vr1.type == VR_RANGE
2950 && !symbolic_range_p (&vr0)
2951 && !symbolic_range_p (&vr1)
2952 && compare_values (vr1.max, zero) != 0)
2953 min = int_const_binop (code, vr0.min, vr1.max);
2954 else
2955 min = zero;
2957 else if (cmp == 0 || cmp == -1)
2958 min = vr0.min;
2959 else
2960 type = VR_VARYING;
2962 else
2964 /* Otherwise the range is -max .. max or min .. -min
2965 depending on which bound is bigger in absolute value,
2966 as the division can change the sign. */
2967 abs_extent_range (vr, vr0.min, vr0.max);
2968 return;
2970 if (type == VR_VARYING)
2972 set_value_range_to_varying (vr);
2973 return;
2976 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
2978 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2979 return;
2982 else if (code == TRUNC_MOD_EXPR)
2984 if (range_is_null (&vr1))
2986 set_value_range_to_undefined (vr);
2987 return;
2989 /* ABS (A % B) < ABS (B) and either
2990 0 <= A % B <= A or A <= A % B <= 0. */
2991 type = VR_RANGE;
2992 signop sgn = TYPE_SIGN (expr_type);
2993 unsigned int prec = TYPE_PRECISION (expr_type);
2994 wide_int wmin, wmax, tmp;
2995 wide_int zero = wi::zero (prec);
2996 wide_int one = wi::one (prec);
2997 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2999 wmax = wi::sub (vr1.max, one);
3000 if (sgn == SIGNED)
3002 tmp = wi::sub (wi::minus_one (prec), vr1.min);
3003 wmax = wi::smax (wmax, tmp);
3006 else
3008 wmax = wi::max_value (prec, sgn);
3009 /* X % INT_MIN may be INT_MAX. */
3010 if (sgn == UNSIGNED)
3011 wmax = wmax - one;
3014 if (sgn == UNSIGNED)
3015 wmin = zero;
3016 else
3018 wmin = -wmax;
3019 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
3021 tmp = vr0.min;
3022 if (wi::gts_p (tmp, zero))
3023 tmp = zero;
3024 wmin = wi::smax (wmin, tmp);
3028 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
3030 tmp = vr0.max;
3031 if (sgn == SIGNED && wi::neg_p (tmp))
3032 tmp = zero;
3033 wmax = wi::min (wmax, tmp, sgn);
3036 min = wide_int_to_tree (expr_type, wmin);
3037 max = wide_int_to_tree (expr_type, wmax);
3039 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
3041 bool int_cst_range0, int_cst_range1;
3042 wide_int may_be_nonzero0, may_be_nonzero1;
3043 wide_int must_be_nonzero0, must_be_nonzero1;
3045 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
3046 &may_be_nonzero0,
3047 &must_be_nonzero0);
3048 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
3049 &may_be_nonzero1,
3050 &must_be_nonzero1);
3052 type = VR_RANGE;
3053 if (code == BIT_AND_EXPR)
3055 min = wide_int_to_tree (expr_type,
3056 must_be_nonzero0 & must_be_nonzero1);
3057 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
3058 /* If both input ranges contain only negative values we can
3059 truncate the result range maximum to the minimum of the
3060 input range maxima. */
3061 if (int_cst_range0 && int_cst_range1
3062 && tree_int_cst_sgn (vr0.max) < 0
3063 && tree_int_cst_sgn (vr1.max) < 0)
3065 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3066 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3068 /* If either input range contains only non-negative values
3069 we can truncate the result range maximum to the respective
3070 maximum of the input range. */
3071 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
3072 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3073 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
3074 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3075 max = wide_int_to_tree (expr_type, wmax);
3076 cmp = compare_values (min, max);
3077 /* PR68217: In case of signed & sign-bit-CST should
3078 result in [-INF, 0] instead of [-INF, INF]. */
3079 if (cmp == -2 || cmp == 1)
3081 wide_int sign_bit
3082 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
3083 TYPE_PRECISION (expr_type));
3084 if (!TYPE_UNSIGNED (expr_type)
3085 && ((value_range_constant_singleton (&vr0)
3086 && !wi::cmps (vr0.min, sign_bit))
3087 || (value_range_constant_singleton (&vr1)
3088 && !wi::cmps (vr1.min, sign_bit))))
3090 min = TYPE_MIN_VALUE (expr_type);
3091 max = build_int_cst (expr_type, 0);
3095 else if (code == BIT_IOR_EXPR)
3097 max = wide_int_to_tree (expr_type,
3098 may_be_nonzero0 | may_be_nonzero1);
3099 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
3100 /* If the input ranges contain only positive values we can
3101 truncate the minimum of the result range to the maximum
3102 of the input range minima. */
3103 if (int_cst_range0 && int_cst_range1
3104 && tree_int_cst_sgn (vr0.min) >= 0
3105 && tree_int_cst_sgn (vr1.min) >= 0)
3107 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3108 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3110 /* If either input range contains only negative values
3111 we can truncate the minimum of the result range to the
3112 respective minimum range. */
3113 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
3114 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3115 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
3116 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3117 min = wide_int_to_tree (expr_type, wmin);
3119 else if (code == BIT_XOR_EXPR)
3121 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
3122 | ~(may_be_nonzero0 | may_be_nonzero1));
3123 wide_int result_one_bits
3124 = (must_be_nonzero0.and_not (may_be_nonzero1)
3125 | must_be_nonzero1.and_not (may_be_nonzero0));
3126 max = wide_int_to_tree (expr_type, ~result_zero_bits);
3127 min = wide_int_to_tree (expr_type, result_one_bits);
3128 /* If the range has all positive or all negative values the
3129 result is better than VARYING. */
3130 if (tree_int_cst_sgn (min) < 0
3131 || tree_int_cst_sgn (max) >= 0)
3133 else
3134 max = min = NULL_TREE;
3137 else
3138 gcc_unreachable ();
3140 /* If either MIN or MAX overflowed, then set the resulting range to
3141 VARYING. But we do accept an overflow infinity representation. */
3142 if (min == NULL_TREE
3143 || (TREE_OVERFLOW_P (min) && !is_overflow_infinity (min))
3144 || max == NULL_TREE
3145 || (TREE_OVERFLOW_P (max) && !is_overflow_infinity (max)))
3147 set_value_range_to_varying (vr);
3148 return;
3151 /* We punt if:
3152 1) [-INF, +INF]
3153 2) [-INF, +-INF(OVF)]
3154 3) [+-INF(OVF), +INF]
3155 4) [+-INF(OVF), +-INF(OVF)]
3156 We learn nothing when we have INF and INF(OVF) on both sides.
3157 Note that we do accept [-INF, -INF] and [+INF, +INF] without
3158 overflow. */
3159 if ((vrp_val_is_min (min) || is_overflow_infinity (min))
3160 && (vrp_val_is_max (max) || is_overflow_infinity (max)))
3162 set_value_range_to_varying (vr);
3163 return;
3166 cmp = compare_values (min, max);
3167 if (cmp == -2 || cmp == 1)
3169 /* If the new range has its limits swapped around (MIN > MAX),
3170 then the operation caused one of them to wrap around, mark
3171 the new range VARYING. */
3172 set_value_range_to_varying (vr);
3174 else
3175 set_value_range (vr, type, min, max, NULL);
3178 /* Extract range information from a binary expression OP0 CODE OP1 based on
3179 the ranges of each of its operands with resulting type EXPR_TYPE.
3180 The resulting range is stored in *VR. */
3182 static void
3183 extract_range_from_binary_expr (value_range *vr,
3184 enum tree_code code,
3185 tree expr_type, tree op0, tree op1)
3187 value_range vr0 = VR_INITIALIZER;
3188 value_range vr1 = VR_INITIALIZER;
3190 /* Get value ranges for each operand. For constant operands, create
3191 a new value range with the operand to simplify processing. */
3192 if (TREE_CODE (op0) == SSA_NAME)
3193 vr0 = *(get_value_range (op0));
3194 else if (is_gimple_min_invariant (op0))
3195 set_value_range_to_value (&vr0, op0, NULL);
3196 else
3197 set_value_range_to_varying (&vr0);
3199 if (TREE_CODE (op1) == SSA_NAME)
3200 vr1 = *(get_value_range (op1));
3201 else if (is_gimple_min_invariant (op1))
3202 set_value_range_to_value (&vr1, op1, NULL);
3203 else
3204 set_value_range_to_varying (&vr1);
3206 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3208 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3209 and based on the other operand, for example if it was deduced from a
3210 symbolic comparison. When a bound of the range of the first operand
3211 is invariant, we set the corresponding bound of the new range to INF
3212 in order to avoid recursing on the range of the second operand. */
3213 if (vr->type == VR_VARYING
3214 && (code == PLUS_EXPR || code == MINUS_EXPR)
3215 && TREE_CODE (op1) == SSA_NAME
3216 && vr0.type == VR_RANGE
3217 && symbolic_range_based_on_p (&vr0, op1))
3219 const bool minus_p = (code == MINUS_EXPR);
3220 value_range n_vr1 = VR_INITIALIZER;
3222 /* Try with VR0 and [-INF, OP1]. */
3223 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3224 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3226 /* Try with VR0 and [OP1, +INF]. */
3227 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3228 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3230 /* Try with VR0 and [OP1, OP1]. */
3231 else
3232 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3234 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3237 if (vr->type == VR_VARYING
3238 && (code == PLUS_EXPR || code == MINUS_EXPR)
3239 && TREE_CODE (op0) == SSA_NAME
3240 && vr1.type == VR_RANGE
3241 && symbolic_range_based_on_p (&vr1, op0))
3243 const bool minus_p = (code == MINUS_EXPR);
3244 value_range n_vr0 = VR_INITIALIZER;
3246 /* Try with [-INF, OP0] and VR1. */
3247 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3248 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3250 /* Try with [OP0, +INF] and VR1. */
3251 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3252 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3254 /* Try with [OP0, OP0] and VR1. */
3255 else
3256 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3258 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3262 /* Extract range information from a unary operation CODE based on
3263 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3264 The resulting range is stored in *VR. */
3266 static void
3267 extract_range_from_unary_expr_1 (value_range *vr,
3268 enum tree_code code, tree type,
3269 value_range *vr0_, tree op0_type)
3271 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3273 /* VRP only operates on integral and pointer types. */
3274 if (!(INTEGRAL_TYPE_P (op0_type)
3275 || POINTER_TYPE_P (op0_type))
3276 || !(INTEGRAL_TYPE_P (type)
3277 || POINTER_TYPE_P (type)))
3279 set_value_range_to_varying (vr);
3280 return;
3283 /* If VR0 is UNDEFINED, so is the result. */
3284 if (vr0.type == VR_UNDEFINED)
3286 set_value_range_to_undefined (vr);
3287 return;
3290 /* Handle operations that we express in terms of others. */
3291 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3293 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3294 copy_value_range (vr, &vr0);
3295 return;
3297 else if (code == NEGATE_EXPR)
3299 /* -X is simply 0 - X, so re-use existing code that also handles
3300 anti-ranges fine. */
3301 value_range zero = VR_INITIALIZER;
3302 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3303 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3304 return;
3306 else if (code == BIT_NOT_EXPR)
3308 /* ~X is simply -1 - X, so re-use existing code that also handles
3309 anti-ranges fine. */
3310 value_range minusone = VR_INITIALIZER;
3311 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3312 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3313 type, &minusone, &vr0);
3314 return;
3317 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3318 and express op ~[] as (op []') U (op []''). */
3319 if (vr0.type == VR_ANTI_RANGE
3320 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3322 extract_range_from_unary_expr_1 (vr, code, type, &vrtem0, op0_type);
3323 if (vrtem1.type != VR_UNDEFINED)
3325 value_range vrres = VR_INITIALIZER;
3326 extract_range_from_unary_expr_1 (&vrres, code, type,
3327 &vrtem1, op0_type);
3328 vrp_meet (vr, &vrres);
3330 return;
3333 if (CONVERT_EXPR_CODE_P (code))
3335 tree inner_type = op0_type;
3336 tree outer_type = type;
3338 /* If the expression evaluates to a pointer, we are only interested in
3339 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3340 if (POINTER_TYPE_P (type))
3342 if (range_is_nonnull (&vr0))
3343 set_value_range_to_nonnull (vr, type);
3344 else if (range_is_null (&vr0))
3345 set_value_range_to_null (vr, type);
3346 else
3347 set_value_range_to_varying (vr);
3348 return;
3351 /* If VR0 is varying and we increase the type precision, assume
3352 a full range for the following transformation. */
3353 if (vr0.type == VR_VARYING
3354 && INTEGRAL_TYPE_P (inner_type)
3355 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3357 vr0.type = VR_RANGE;
3358 vr0.min = TYPE_MIN_VALUE (inner_type);
3359 vr0.max = TYPE_MAX_VALUE (inner_type);
3362 /* If VR0 is a constant range or anti-range and the conversion is
3363 not truncating we can convert the min and max values and
3364 canonicalize the resulting range. Otherwise we can do the
3365 conversion if the size of the range is less than what the
3366 precision of the target type can represent and the range is
3367 not an anti-range. */
3368 if ((vr0.type == VR_RANGE
3369 || vr0.type == VR_ANTI_RANGE)
3370 && TREE_CODE (vr0.min) == INTEGER_CST
3371 && TREE_CODE (vr0.max) == INTEGER_CST
3372 && (!is_overflow_infinity (vr0.min)
3373 || (vr0.type == VR_RANGE
3374 && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3375 && needs_overflow_infinity (outer_type)
3376 && supports_overflow_infinity (outer_type)))
3377 && (!is_overflow_infinity (vr0.max)
3378 || (vr0.type == VR_RANGE
3379 && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3380 && needs_overflow_infinity (outer_type)
3381 && supports_overflow_infinity (outer_type)))
3382 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3383 || (vr0.type == VR_RANGE
3384 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3385 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3386 size_int (TYPE_PRECISION (outer_type)))))))
3388 tree new_min, new_max;
3389 if (is_overflow_infinity (vr0.min))
3390 new_min = negative_overflow_infinity (outer_type);
3391 else
3392 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3393 0, false);
3394 if (is_overflow_infinity (vr0.max))
3395 new_max = positive_overflow_infinity (outer_type);
3396 else
3397 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3398 0, false);
3399 set_and_canonicalize_value_range (vr, vr0.type,
3400 new_min, new_max, NULL);
3401 return;
3404 set_value_range_to_varying (vr);
3405 return;
3407 else if (code == ABS_EXPR)
3409 tree min, max;
3410 int cmp;
3412 /* Pass through vr0 in the easy cases. */
3413 if (TYPE_UNSIGNED (type)
3414 || value_range_nonnegative_p (&vr0))
3416 copy_value_range (vr, &vr0);
3417 return;
3420 /* For the remaining varying or symbolic ranges we can't do anything
3421 useful. */
3422 if (vr0.type == VR_VARYING
3423 || symbolic_range_p (&vr0))
3425 set_value_range_to_varying (vr);
3426 return;
3429 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3430 useful range. */
3431 if (!TYPE_OVERFLOW_UNDEFINED (type)
3432 && ((vr0.type == VR_RANGE
3433 && vrp_val_is_min (vr0.min))
3434 || (vr0.type == VR_ANTI_RANGE
3435 && !vrp_val_is_min (vr0.min))))
3437 set_value_range_to_varying (vr);
3438 return;
3441 /* ABS_EXPR may flip the range around, if the original range
3442 included negative values. */
3443 if (is_overflow_infinity (vr0.min))
3444 min = positive_overflow_infinity (type);
3445 else if (!vrp_val_is_min (vr0.min))
3446 min = fold_unary_to_constant (code, type, vr0.min);
3447 else if (!needs_overflow_infinity (type))
3448 min = TYPE_MAX_VALUE (type);
3449 else if (supports_overflow_infinity (type))
3450 min = positive_overflow_infinity (type);
3451 else
3453 set_value_range_to_varying (vr);
3454 return;
3457 if (is_overflow_infinity (vr0.max))
3458 max = positive_overflow_infinity (type);
3459 else if (!vrp_val_is_min (vr0.max))
3460 max = fold_unary_to_constant (code, type, vr0.max);
3461 else if (!needs_overflow_infinity (type))
3462 max = TYPE_MAX_VALUE (type);
3463 else if (supports_overflow_infinity (type)
3464 /* We shouldn't generate [+INF, +INF] as set_value_range
3465 doesn't like this and ICEs. */
3466 && !is_positive_overflow_infinity (min))
3467 max = positive_overflow_infinity (type);
3468 else
3470 set_value_range_to_varying (vr);
3471 return;
3474 cmp = compare_values (min, max);
3476 /* If a VR_ANTI_RANGEs contains zero, then we have
3477 ~[-INF, min(MIN, MAX)]. */
3478 if (vr0.type == VR_ANTI_RANGE)
3480 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3482 /* Take the lower of the two values. */
3483 if (cmp != 1)
3484 max = min;
3486 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3487 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3488 flag_wrapv is set and the original anti-range doesn't include
3489 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3490 if (TYPE_OVERFLOW_WRAPS (type))
3492 tree type_min_value = TYPE_MIN_VALUE (type);
3494 min = (vr0.min != type_min_value
3495 ? int_const_binop (PLUS_EXPR, type_min_value,
3496 build_int_cst (TREE_TYPE (type_min_value), 1))
3497 : type_min_value);
3499 else
3501 if (overflow_infinity_range_p (&vr0))
3502 min = negative_overflow_infinity (type);
3503 else
3504 min = TYPE_MIN_VALUE (type);
3507 else
3509 /* All else has failed, so create the range [0, INF], even for
3510 flag_wrapv since TYPE_MIN_VALUE is in the original
3511 anti-range. */
3512 vr0.type = VR_RANGE;
3513 min = build_int_cst (type, 0);
3514 if (needs_overflow_infinity (type))
3516 if (supports_overflow_infinity (type))
3517 max = positive_overflow_infinity (type);
3518 else
3520 set_value_range_to_varying (vr);
3521 return;
3524 else
3525 max = TYPE_MAX_VALUE (type);
3529 /* If the range contains zero then we know that the minimum value in the
3530 range will be zero. */
3531 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3533 if (cmp == 1)
3534 max = min;
3535 min = build_int_cst (type, 0);
3537 else
3539 /* If the range was reversed, swap MIN and MAX. */
3540 if (cmp == 1)
3541 std::swap (min, max);
3544 cmp = compare_values (min, max);
3545 if (cmp == -2 || cmp == 1)
3547 /* If the new range has its limits swapped around (MIN > MAX),
3548 then the operation caused one of them to wrap around, mark
3549 the new range VARYING. */
3550 set_value_range_to_varying (vr);
3552 else
3553 set_value_range (vr, vr0.type, min, max, NULL);
3554 return;
3557 /* For unhandled operations fall back to varying. */
3558 set_value_range_to_varying (vr);
3559 return;
3563 /* Extract range information from a unary expression CODE OP0 based on
3564 the range of its operand with resulting type TYPE.
3565 The resulting range is stored in *VR. */
3567 static void
3568 extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3569 tree type, tree op0)
3571 value_range vr0 = VR_INITIALIZER;
3573 /* Get value ranges for the operand. For constant operands, create
3574 a new value range with the operand to simplify processing. */
3575 if (TREE_CODE (op0) == SSA_NAME)
3576 vr0 = *(get_value_range (op0));
3577 else if (is_gimple_min_invariant (op0))
3578 set_value_range_to_value (&vr0, op0, NULL);
3579 else
3580 set_value_range_to_varying (&vr0);
3582 extract_range_from_unary_expr_1 (vr, code, type, &vr0, TREE_TYPE (op0));
3586 /* Extract range information from a conditional expression STMT based on
3587 the ranges of each of its operands and the expression code. */
3589 static void
3590 extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3592 tree op0, op1;
3593 value_range vr0 = VR_INITIALIZER;
3594 value_range vr1 = VR_INITIALIZER;
3596 /* Get value ranges for each operand. For constant operands, create
3597 a new value range with the operand to simplify processing. */
3598 op0 = gimple_assign_rhs2 (stmt);
3599 if (TREE_CODE (op0) == SSA_NAME)
3600 vr0 = *(get_value_range (op0));
3601 else if (is_gimple_min_invariant (op0))
3602 set_value_range_to_value (&vr0, op0, NULL);
3603 else
3604 set_value_range_to_varying (&vr0);
3606 op1 = gimple_assign_rhs3 (stmt);
3607 if (TREE_CODE (op1) == SSA_NAME)
3608 vr1 = *(get_value_range (op1));
3609 else if (is_gimple_min_invariant (op1))
3610 set_value_range_to_value (&vr1, op1, NULL);
3611 else
3612 set_value_range_to_varying (&vr1);
3614 /* The resulting value range is the union of the operand ranges */
3615 copy_value_range (vr, &vr0);
3616 vrp_meet (vr, &vr1);
3620 /* Extract range information from a comparison expression EXPR based
3621 on the range of its operand and the expression code. */
3623 static void
3624 extract_range_from_comparison (value_range *vr, enum tree_code code,
3625 tree type, tree op0, tree op1)
3627 bool sop = false;
3628 tree val;
3630 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3631 NULL);
3633 /* A disadvantage of using a special infinity as an overflow
3634 representation is that we lose the ability to record overflow
3635 when we don't have an infinity. So we have to ignore a result
3636 which relies on overflow. */
3638 if (val && !is_overflow_infinity (val) && !sop)
3640 /* Since this expression was found on the RHS of an assignment,
3641 its type may be different from _Bool. Convert VAL to EXPR's
3642 type. */
3643 val = fold_convert (type, val);
3644 if (is_gimple_min_invariant (val))
3645 set_value_range_to_value (vr, val, vr->equiv);
3646 else
3647 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3649 else
3650 /* The result of a comparison is always true or false. */
3651 set_value_range_to_truthvalue (vr, type);
3654 /* Helper function for simplify_internal_call_using_ranges and
3655 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3656 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3657 always overflow. Set *OVF to true if it is known to always
3658 overflow. */
3660 static bool
3661 check_for_binary_op_overflow (enum tree_code subcode, tree type,
3662 tree op0, tree op1, bool *ovf)
3664 value_range vr0 = VR_INITIALIZER;
3665 value_range vr1 = VR_INITIALIZER;
3666 if (TREE_CODE (op0) == SSA_NAME)
3667 vr0 = *get_value_range (op0);
3668 else if (TREE_CODE (op0) == INTEGER_CST)
3669 set_value_range_to_value (&vr0, op0, NULL);
3670 else
3671 set_value_range_to_varying (&vr0);
3673 if (TREE_CODE (op1) == SSA_NAME)
3674 vr1 = *get_value_range (op1);
3675 else if (TREE_CODE (op1) == INTEGER_CST)
3676 set_value_range_to_value (&vr1, op1, NULL);
3677 else
3678 set_value_range_to_varying (&vr1);
3680 if (!range_int_cst_p (&vr0)
3681 || TREE_OVERFLOW (vr0.min)
3682 || TREE_OVERFLOW (vr0.max))
3684 vr0.min = vrp_val_min (TREE_TYPE (op0));
3685 vr0.max = vrp_val_max (TREE_TYPE (op0));
3687 if (!range_int_cst_p (&vr1)
3688 || TREE_OVERFLOW (vr1.min)
3689 || TREE_OVERFLOW (vr1.max))
3691 vr1.min = vrp_val_min (TREE_TYPE (op1));
3692 vr1.max = vrp_val_max (TREE_TYPE (op1));
3694 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3695 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3696 if (arith_overflowed_p (subcode, type, vr0.max,
3697 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3698 return false;
3699 if (subcode == MULT_EXPR)
3701 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3702 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3703 return false;
3705 if (*ovf)
3707 /* So far we found that there is an overflow on the boundaries.
3708 That doesn't prove that there is an overflow even for all values
3709 in between the boundaries. For that compute widest_int range
3710 of the result and see if it doesn't overlap the range of
3711 type. */
3712 widest_int wmin, wmax;
3713 widest_int w[4];
3714 int i;
3715 w[0] = wi::to_widest (vr0.min);
3716 w[1] = wi::to_widest (vr0.max);
3717 w[2] = wi::to_widest (vr1.min);
3718 w[3] = wi::to_widest (vr1.max);
3719 for (i = 0; i < 4; i++)
3721 widest_int wt;
3722 switch (subcode)
3724 case PLUS_EXPR:
3725 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3726 break;
3727 case MINUS_EXPR:
3728 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3729 break;
3730 case MULT_EXPR:
3731 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3732 break;
3733 default:
3734 gcc_unreachable ();
3736 if (i == 0)
3738 wmin = wt;
3739 wmax = wt;
3741 else
3743 wmin = wi::smin (wmin, wt);
3744 wmax = wi::smax (wmax, wt);
3747 /* The result of op0 CODE op1 is known to be in range
3748 [wmin, wmax]. */
3749 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3750 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3751 /* If all values in [wmin, wmax] are smaller than
3752 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3753 the arithmetic operation will always overflow. */
3754 if (wmax < wtmin || wmin > wtmax)
3755 return true;
3756 return false;
3758 return true;
3761 /* Try to derive a nonnegative or nonzero range out of STMT relying
3762 primarily on generic routines in fold in conjunction with range data.
3763 Store the result in *VR */
3765 static void
3766 extract_range_basic (value_range *vr, gimple *stmt)
3768 bool sop = false;
3769 tree type = gimple_expr_type (stmt);
3771 if (is_gimple_call (stmt))
3773 tree arg;
3774 int mini, maxi, zerov = 0, prec;
3775 enum tree_code subcode = ERROR_MARK;
3776 combined_fn cfn = gimple_call_combined_fn (stmt);
3778 switch (cfn)
3780 case CFN_BUILT_IN_CONSTANT_P:
3781 /* If the call is __builtin_constant_p and the argument is a
3782 function parameter resolve it to false. This avoids bogus
3783 array bound warnings.
3784 ??? We could do this as early as inlining is finished. */
3785 arg = gimple_call_arg (stmt, 0);
3786 if (TREE_CODE (arg) == SSA_NAME
3787 && SSA_NAME_IS_DEFAULT_DEF (arg)
3788 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3789 && cfun->after_inlining)
3791 set_value_range_to_null (vr, type);
3792 return;
3794 break;
3795 /* Both __builtin_ffs* and __builtin_popcount return
3796 [0, prec]. */
3797 CASE_CFN_FFS:
3798 CASE_CFN_POPCOUNT:
3799 arg = gimple_call_arg (stmt, 0);
3800 prec = TYPE_PRECISION (TREE_TYPE (arg));
3801 mini = 0;
3802 maxi = prec;
3803 if (TREE_CODE (arg) == SSA_NAME)
3805 value_range *vr0 = get_value_range (arg);
3806 /* If arg is non-zero, then ffs or popcount
3807 are non-zero. */
3808 if (((vr0->type == VR_RANGE
3809 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3810 || (vr0->type == VR_ANTI_RANGE
3811 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3812 && !is_overflow_infinity (vr0->min)
3813 && !is_overflow_infinity (vr0->max))
3814 mini = 1;
3815 /* If some high bits are known to be zero,
3816 we can decrease the maximum. */
3817 if (vr0->type == VR_RANGE
3818 && TREE_CODE (vr0->max) == INTEGER_CST
3819 && !operand_less_p (vr0->min,
3820 build_zero_cst (TREE_TYPE (vr0->min)))
3821 && !is_overflow_infinity (vr0->max))
3822 maxi = tree_floor_log2 (vr0->max) + 1;
3824 goto bitop_builtin;
3825 /* __builtin_parity* returns [0, 1]. */
3826 CASE_CFN_PARITY:
3827 mini = 0;
3828 maxi = 1;
3829 goto bitop_builtin;
3830 /* __builtin_c[lt]z* return [0, prec-1], except for
3831 when the argument is 0, but that is undefined behavior.
3832 On many targets where the CLZ RTL or optab value is defined
3833 for 0 the value is prec, so include that in the range
3834 by default. */
3835 CASE_CFN_CLZ:
3836 arg = gimple_call_arg (stmt, 0);
3837 prec = TYPE_PRECISION (TREE_TYPE (arg));
3838 mini = 0;
3839 maxi = prec;
3840 if (optab_handler (clz_optab, TYPE_MODE (TREE_TYPE (arg)))
3841 != CODE_FOR_nothing
3842 && CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3843 zerov)
3844 /* Handle only the single common value. */
3845 && zerov != prec)
3846 /* Magic value to give up, unless vr0 proves
3847 arg is non-zero. */
3848 mini = -2;
3849 if (TREE_CODE (arg) == SSA_NAME)
3851 value_range *vr0 = get_value_range (arg);
3852 /* From clz of VR_RANGE minimum we can compute
3853 result maximum. */
3854 if (vr0->type == VR_RANGE
3855 && TREE_CODE (vr0->min) == INTEGER_CST
3856 && !is_overflow_infinity (vr0->min))
3858 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3859 if (maxi != prec)
3860 mini = 0;
3862 else if (vr0->type == VR_ANTI_RANGE
3863 && integer_zerop (vr0->min)
3864 && !is_overflow_infinity (vr0->min))
3866 maxi = prec - 1;
3867 mini = 0;
3869 if (mini == -2)
3870 break;
3871 /* From clz of VR_RANGE maximum we can compute
3872 result minimum. */
3873 if (vr0->type == VR_RANGE
3874 && TREE_CODE (vr0->max) == INTEGER_CST
3875 && !is_overflow_infinity (vr0->max))
3877 mini = prec - 1 - tree_floor_log2 (vr0->max);
3878 if (mini == prec)
3879 break;
3882 if (mini == -2)
3883 break;
3884 goto bitop_builtin;
3885 /* __builtin_ctz* return [0, prec-1], except for
3886 when the argument is 0, but that is undefined behavior.
3887 If there is a ctz optab for this mode and
3888 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3889 otherwise just assume 0 won't be seen. */
3890 CASE_CFN_CTZ:
3891 arg = gimple_call_arg (stmt, 0);
3892 prec = TYPE_PRECISION (TREE_TYPE (arg));
3893 mini = 0;
3894 maxi = prec - 1;
3895 if (optab_handler (ctz_optab, TYPE_MODE (TREE_TYPE (arg)))
3896 != CODE_FOR_nothing
3897 && CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3898 zerov))
3900 /* Handle only the two common values. */
3901 if (zerov == -1)
3902 mini = -1;
3903 else if (zerov == prec)
3904 maxi = prec;
3905 else
3906 /* Magic value to give up, unless vr0 proves
3907 arg is non-zero. */
3908 mini = -2;
3910 if (TREE_CODE (arg) == SSA_NAME)
3912 value_range *vr0 = get_value_range (arg);
3913 /* If arg is non-zero, then use [0, prec - 1]. */
3914 if (((vr0->type == VR_RANGE
3915 && integer_nonzerop (vr0->min))
3916 || (vr0->type == VR_ANTI_RANGE
3917 && integer_zerop (vr0->min)))
3918 && !is_overflow_infinity (vr0->min))
3920 mini = 0;
3921 maxi = prec - 1;
3923 /* If some high bits are known to be zero,
3924 we can decrease the result maximum. */
3925 if (vr0->type == VR_RANGE
3926 && TREE_CODE (vr0->max) == INTEGER_CST
3927 && !is_overflow_infinity (vr0->max))
3929 maxi = tree_floor_log2 (vr0->max);
3930 /* For vr0 [0, 0] give up. */
3931 if (maxi == -1)
3932 break;
3935 if (mini == -2)
3936 break;
3937 goto bitop_builtin;
3938 /* __builtin_clrsb* returns [0, prec-1]. */
3939 CASE_CFN_CLRSB:
3940 arg = gimple_call_arg (stmt, 0);
3941 prec = TYPE_PRECISION (TREE_TYPE (arg));
3942 mini = 0;
3943 maxi = prec - 1;
3944 goto bitop_builtin;
3945 bitop_builtin:
3946 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3947 build_int_cst (type, maxi), NULL);
3948 return;
3949 case CFN_UBSAN_CHECK_ADD:
3950 subcode = PLUS_EXPR;
3951 break;
3952 case CFN_UBSAN_CHECK_SUB:
3953 subcode = MINUS_EXPR;
3954 break;
3955 case CFN_UBSAN_CHECK_MUL:
3956 subcode = MULT_EXPR;
3957 break;
3958 case CFN_GOACC_DIM_SIZE:
3959 case CFN_GOACC_DIM_POS:
3960 /* Optimizing these two internal functions helps the loop
3961 optimizer eliminate outer comparisons. Size is [1,N]
3962 and pos is [0,N-1]. */
3964 bool is_pos = cfn == CFN_GOACC_DIM_POS;
3965 int axis = get_oacc_ifn_dim_arg (stmt);
3966 int size = get_oacc_fn_dim_size (current_function_decl, axis);
3968 if (!size)
3969 /* If it's dynamic, the backend might know a hardware
3970 limitation. */
3971 size = targetm.goacc.dim_limit (axis);
3973 tree type = TREE_TYPE (gimple_call_lhs (stmt));
3974 set_value_range (vr, VR_RANGE,
3975 build_int_cst (type, is_pos ? 0 : 1),
3976 size ? build_int_cst (type, size - is_pos)
3977 : vrp_val_max (type), NULL);
3979 return;
3980 default:
3981 break;
3983 if (subcode != ERROR_MARK)
3985 bool saved_flag_wrapv = flag_wrapv;
3986 /* Pretend the arithmetics is wrapping. If there is
3987 any overflow, we'll complain, but will actually do
3988 wrapping operation. */
3989 flag_wrapv = 1;
3990 extract_range_from_binary_expr (vr, subcode, type,
3991 gimple_call_arg (stmt, 0),
3992 gimple_call_arg (stmt, 1));
3993 flag_wrapv = saved_flag_wrapv;
3995 /* If for both arguments vrp_valueize returned non-NULL,
3996 this should have been already folded and if not, it
3997 wasn't folded because of overflow. Avoid removing the
3998 UBSAN_CHECK_* calls in that case. */
3999 if (vr->type == VR_RANGE
4000 && (vr->min == vr->max
4001 || operand_equal_p (vr->min, vr->max, 0)))
4002 set_value_range_to_varying (vr);
4003 return;
4006 /* Handle extraction of the two results (result of arithmetics and
4007 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
4008 internal function. */
4009 else if (is_gimple_assign (stmt)
4010 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
4011 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
4012 && INTEGRAL_TYPE_P (type))
4014 enum tree_code code = gimple_assign_rhs_code (stmt);
4015 tree op = gimple_assign_rhs1 (stmt);
4016 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
4018 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
4019 if (is_gimple_call (g) && gimple_call_internal_p (g))
4021 enum tree_code subcode = ERROR_MARK;
4022 switch (gimple_call_internal_fn (g))
4024 case IFN_ADD_OVERFLOW:
4025 subcode = PLUS_EXPR;
4026 break;
4027 case IFN_SUB_OVERFLOW:
4028 subcode = MINUS_EXPR;
4029 break;
4030 case IFN_MUL_OVERFLOW:
4031 subcode = MULT_EXPR;
4032 break;
4033 default:
4034 break;
4036 if (subcode != ERROR_MARK)
4038 tree op0 = gimple_call_arg (g, 0);
4039 tree op1 = gimple_call_arg (g, 1);
4040 if (code == IMAGPART_EXPR)
4042 bool ovf = false;
4043 if (check_for_binary_op_overflow (subcode, type,
4044 op0, op1, &ovf))
4045 set_value_range_to_value (vr,
4046 build_int_cst (type, ovf),
4047 NULL);
4048 else if (TYPE_PRECISION (type) == 1
4049 && !TYPE_UNSIGNED (type))
4050 set_value_range_to_varying (vr);
4051 else
4052 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
4053 build_int_cst (type, 1), NULL);
4055 else if (types_compatible_p (type, TREE_TYPE (op0))
4056 && types_compatible_p (type, TREE_TYPE (op1)))
4058 bool saved_flag_wrapv = flag_wrapv;
4059 /* Pretend the arithmetics is wrapping. If there is
4060 any overflow, IMAGPART_EXPR will be set. */
4061 flag_wrapv = 1;
4062 extract_range_from_binary_expr (vr, subcode, type,
4063 op0, op1);
4064 flag_wrapv = saved_flag_wrapv;
4066 else
4068 value_range vr0 = VR_INITIALIZER;
4069 value_range vr1 = VR_INITIALIZER;
4070 bool saved_flag_wrapv = flag_wrapv;
4071 /* Pretend the arithmetics is wrapping. If there is
4072 any overflow, IMAGPART_EXPR will be set. */
4073 flag_wrapv = 1;
4074 extract_range_from_unary_expr (&vr0, NOP_EXPR,
4075 type, op0);
4076 extract_range_from_unary_expr (&vr1, NOP_EXPR,
4077 type, op1);
4078 extract_range_from_binary_expr_1 (vr, subcode, type,
4079 &vr0, &vr1);
4080 flag_wrapv = saved_flag_wrapv;
4082 return;
4087 if (INTEGRAL_TYPE_P (type)
4088 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
4089 set_value_range_to_nonnegative (vr, type,
4090 sop || stmt_overflow_infinity (stmt));
4091 else if (vrp_stmt_computes_nonzero (stmt, &sop)
4092 && !sop)
4093 set_value_range_to_nonnull (vr, type);
4094 else
4095 set_value_range_to_varying (vr);
4099 /* Try to compute a useful range out of assignment STMT and store it
4100 in *VR. */
4102 static void
4103 extract_range_from_assignment (value_range *vr, gassign *stmt)
4105 enum tree_code code = gimple_assign_rhs_code (stmt);
4107 if (code == ASSERT_EXPR)
4108 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
4109 else if (code == SSA_NAME)
4110 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
4111 else if (TREE_CODE_CLASS (code) == tcc_binary)
4112 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
4113 gimple_expr_type (stmt),
4114 gimple_assign_rhs1 (stmt),
4115 gimple_assign_rhs2 (stmt));
4116 else if (TREE_CODE_CLASS (code) == tcc_unary)
4117 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
4118 gimple_expr_type (stmt),
4119 gimple_assign_rhs1 (stmt));
4120 else if (code == COND_EXPR)
4121 extract_range_from_cond_expr (vr, stmt);
4122 else if (TREE_CODE_CLASS (code) == tcc_comparison)
4123 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
4124 gimple_expr_type (stmt),
4125 gimple_assign_rhs1 (stmt),
4126 gimple_assign_rhs2 (stmt));
4127 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
4128 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
4129 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
4130 else
4131 set_value_range_to_varying (vr);
4133 if (vr->type == VR_VARYING)
4134 extract_range_basic (vr, stmt);
4137 /* Given a range VR, a LOOP and a variable VAR, determine whether it
4138 would be profitable to adjust VR using scalar evolution information
4139 for VAR. If so, update VR with the new limits. */
4141 static void
4142 adjust_range_with_scev (value_range *vr, struct loop *loop,
4143 gimple *stmt, tree var)
4145 tree init, step, chrec, tmin, tmax, min, max, type, tem;
4146 enum ev_direction dir;
4148 /* TODO. Don't adjust anti-ranges. An anti-range may provide
4149 better opportunities than a regular range, but I'm not sure. */
4150 if (vr->type == VR_ANTI_RANGE)
4151 return;
4153 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
4155 /* Like in PR19590, scev can return a constant function. */
4156 if (is_gimple_min_invariant (chrec))
4158 set_value_range_to_value (vr, chrec, vr->equiv);
4159 return;
4162 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
4163 return;
4165 init = initial_condition_in_loop_num (chrec, loop->num);
4166 tem = op_with_constant_singleton_value_range (init);
4167 if (tem)
4168 init = tem;
4169 step = evolution_part_in_loop_num (chrec, loop->num);
4170 tem = op_with_constant_singleton_value_range (step);
4171 if (tem)
4172 step = tem;
4174 /* If STEP is symbolic, we can't know whether INIT will be the
4175 minimum or maximum value in the range. Also, unless INIT is
4176 a simple expression, compare_values and possibly other functions
4177 in tree-vrp won't be able to handle it. */
4178 if (step == NULL_TREE
4179 || !is_gimple_min_invariant (step)
4180 || !valid_value_p (init))
4181 return;
4183 dir = scev_direction (chrec);
4184 if (/* Do not adjust ranges if we do not know whether the iv increases
4185 or decreases, ... */
4186 dir == EV_DIR_UNKNOWN
4187 /* ... or if it may wrap. */
4188 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
4189 get_chrec_loop (chrec), true))
4190 return;
4192 /* We use TYPE_MIN_VALUE and TYPE_MAX_VALUE here instead of
4193 negative_overflow_infinity and positive_overflow_infinity,
4194 because we have concluded that the loop probably does not
4195 wrap. */
4197 type = TREE_TYPE (var);
4198 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
4199 tmin = lower_bound_in_type (type, type);
4200 else
4201 tmin = TYPE_MIN_VALUE (type);
4202 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4203 tmax = upper_bound_in_type (type, type);
4204 else
4205 tmax = TYPE_MAX_VALUE (type);
4207 /* Try to use estimated number of iterations for the loop to constrain the
4208 final value in the evolution. */
4209 if (TREE_CODE (step) == INTEGER_CST
4210 && is_gimple_val (init)
4211 && (TREE_CODE (init) != SSA_NAME
4212 || get_value_range (init)->type == VR_RANGE))
4214 widest_int nit;
4216 /* We are only entering here for loop header PHI nodes, so using
4217 the number of latch executions is the correct thing to use. */
4218 if (max_loop_iterations (loop, &nit))
4220 value_range maxvr = VR_INITIALIZER;
4221 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4222 bool overflow;
4224 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4225 &overflow);
4226 /* If the multiplication overflowed we can't do a meaningful
4227 adjustment. Likewise if the result doesn't fit in the type
4228 of the induction variable. For a signed type we have to
4229 check whether the result has the expected signedness which
4230 is that of the step as number of iterations is unsigned. */
4231 if (!overflow
4232 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4233 && (sgn == UNSIGNED
4234 || wi::gts_p (wtmp, 0) == wi::gts_p (step, 0)))
4236 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4237 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4238 TREE_TYPE (init), init, tem);
4239 /* Likewise if the addition did. */
4240 if (maxvr.type == VR_RANGE)
4242 value_range initvr = VR_INITIALIZER;
4244 if (TREE_CODE (init) == SSA_NAME)
4245 initvr = *(get_value_range (init));
4246 else if (is_gimple_min_invariant (init))
4247 set_value_range_to_value (&initvr, init, NULL);
4248 else
4249 return;
4251 /* Check if init + nit * step overflows. Though we checked
4252 scev {init, step}_loop doesn't wrap, it is not enough
4253 because the loop may exit immediately. Overflow could
4254 happen in the plus expression in this case. */
4255 if ((dir == EV_DIR_DECREASES
4256 && (is_negative_overflow_infinity (maxvr.min)
4257 || compare_values (maxvr.min, initvr.min) != -1))
4258 || (dir == EV_DIR_GROWS
4259 && (is_positive_overflow_infinity (maxvr.max)
4260 || compare_values (maxvr.max, initvr.max) != 1)))
4261 return;
4263 tmin = maxvr.min;
4264 tmax = maxvr.max;
4270 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4272 min = tmin;
4273 max = tmax;
4275 /* For VARYING or UNDEFINED ranges, just about anything we get
4276 from scalar evolutions should be better. */
4278 if (dir == EV_DIR_DECREASES)
4279 max = init;
4280 else
4281 min = init;
4283 else if (vr->type == VR_RANGE)
4285 min = vr->min;
4286 max = vr->max;
4288 if (dir == EV_DIR_DECREASES)
4290 /* INIT is the maximum value. If INIT is lower than VR->MAX
4291 but no smaller than VR->MIN, set VR->MAX to INIT. */
4292 if (compare_values (init, max) == -1)
4293 max = init;
4295 /* According to the loop information, the variable does not
4296 overflow. If we think it does, probably because of an
4297 overflow due to arithmetic on a different INF value,
4298 reset now. */
4299 if (is_negative_overflow_infinity (min)
4300 || compare_values (min, tmin) == -1)
4301 min = tmin;
4304 else
4306 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4307 if (compare_values (init, min) == 1)
4308 min = init;
4310 if (is_positive_overflow_infinity (max)
4311 || compare_values (tmax, max) == -1)
4312 max = tmax;
4315 else
4316 return;
4318 /* If we just created an invalid range with the minimum
4319 greater than the maximum, we fail conservatively.
4320 This should happen only in unreachable
4321 parts of code, or for invalid programs. */
4322 if (compare_values (min, max) == 1
4323 || (is_negative_overflow_infinity (min)
4324 && is_positive_overflow_infinity (max)))
4325 return;
4327 /* Even for valid range info, sometimes overflow flag will leak in.
4328 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4329 drop them except for +-overflow_infinity which still need special
4330 handling in vrp pass. */
4331 if (TREE_OVERFLOW_P (min)
4332 && ! is_negative_overflow_infinity (min))
4333 min = drop_tree_overflow (min);
4334 if (TREE_OVERFLOW_P (max)
4335 && ! is_positive_overflow_infinity (max))
4336 max = drop_tree_overflow (max);
4338 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4342 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4344 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4345 all the values in the ranges.
4347 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4349 - Return NULL_TREE if it is not always possible to determine the
4350 value of the comparison.
4352 Also set *STRICT_OVERFLOW_P to indicate whether a range with an
4353 overflow infinity was used in the test. */
4356 static tree
4357 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4358 bool *strict_overflow_p)
4360 /* VARYING or UNDEFINED ranges cannot be compared. */
4361 if (vr0->type == VR_VARYING
4362 || vr0->type == VR_UNDEFINED
4363 || vr1->type == VR_VARYING
4364 || vr1->type == VR_UNDEFINED)
4365 return NULL_TREE;
4367 /* Anti-ranges need to be handled separately. */
4368 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4370 /* If both are anti-ranges, then we cannot compute any
4371 comparison. */
4372 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4373 return NULL_TREE;
4375 /* These comparisons are never statically computable. */
4376 if (comp == GT_EXPR
4377 || comp == GE_EXPR
4378 || comp == LT_EXPR
4379 || comp == LE_EXPR)
4380 return NULL_TREE;
4382 /* Equality can be computed only between a range and an
4383 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4384 if (vr0->type == VR_RANGE)
4386 /* To simplify processing, make VR0 the anti-range. */
4387 value_range *tmp = vr0;
4388 vr0 = vr1;
4389 vr1 = tmp;
4392 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4394 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4395 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4396 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4398 return NULL_TREE;
4401 if (!usable_range_p (vr0, strict_overflow_p)
4402 || !usable_range_p (vr1, strict_overflow_p))
4403 return NULL_TREE;
4405 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4406 operands around and change the comparison code. */
4407 if (comp == GT_EXPR || comp == GE_EXPR)
4409 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4410 std::swap (vr0, vr1);
4413 if (comp == EQ_EXPR)
4415 /* Equality may only be computed if both ranges represent
4416 exactly one value. */
4417 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4418 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4420 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4421 strict_overflow_p);
4422 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4423 strict_overflow_p);
4424 if (cmp_min == 0 && cmp_max == 0)
4425 return boolean_true_node;
4426 else if (cmp_min != -2 && cmp_max != -2)
4427 return boolean_false_node;
4429 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4430 else if (compare_values_warnv (vr0->min, vr1->max,
4431 strict_overflow_p) == 1
4432 || compare_values_warnv (vr1->min, vr0->max,
4433 strict_overflow_p) == 1)
4434 return boolean_false_node;
4436 return NULL_TREE;
4438 else if (comp == NE_EXPR)
4440 int cmp1, cmp2;
4442 /* If VR0 is completely to the left or completely to the right
4443 of VR1, they are always different. Notice that we need to
4444 make sure that both comparisons yield similar results to
4445 avoid comparing values that cannot be compared at
4446 compile-time. */
4447 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4448 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4449 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4450 return boolean_true_node;
4452 /* If VR0 and VR1 represent a single value and are identical,
4453 return false. */
4454 else if (compare_values_warnv (vr0->min, vr0->max,
4455 strict_overflow_p) == 0
4456 && compare_values_warnv (vr1->min, vr1->max,
4457 strict_overflow_p) == 0
4458 && compare_values_warnv (vr0->min, vr1->min,
4459 strict_overflow_p) == 0
4460 && compare_values_warnv (vr0->max, vr1->max,
4461 strict_overflow_p) == 0)
4462 return boolean_false_node;
4464 /* Otherwise, they may or may not be different. */
4465 else
4466 return NULL_TREE;
4468 else if (comp == LT_EXPR || comp == LE_EXPR)
4470 int tst;
4472 /* If VR0 is to the left of VR1, return true. */
4473 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4474 if ((comp == LT_EXPR && tst == -1)
4475 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4477 if (overflow_infinity_range_p (vr0)
4478 || overflow_infinity_range_p (vr1))
4479 *strict_overflow_p = true;
4480 return boolean_true_node;
4483 /* If VR0 is to the right of VR1, return false. */
4484 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4485 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4486 || (comp == LE_EXPR && tst == 1))
4488 if (overflow_infinity_range_p (vr0)
4489 || overflow_infinity_range_p (vr1))
4490 *strict_overflow_p = true;
4491 return boolean_false_node;
4494 /* Otherwise, we don't know. */
4495 return NULL_TREE;
4498 gcc_unreachable ();
4502 /* Given a value range VR, a value VAL and a comparison code COMP, return
4503 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4504 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4505 always returns false. Return NULL_TREE if it is not always
4506 possible to determine the value of the comparison. Also set
4507 *STRICT_OVERFLOW_P to indicate whether a range with an overflow
4508 infinity was used in the test. */
4510 static tree
4511 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4512 bool *strict_overflow_p)
4514 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4515 return NULL_TREE;
4517 /* Anti-ranges need to be handled separately. */
4518 if (vr->type == VR_ANTI_RANGE)
4520 /* For anti-ranges, the only predicates that we can compute at
4521 compile time are equality and inequality. */
4522 if (comp == GT_EXPR
4523 || comp == GE_EXPR
4524 || comp == LT_EXPR
4525 || comp == LE_EXPR)
4526 return NULL_TREE;
4528 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4529 if (value_inside_range (val, vr->min, vr->max) == 1)
4530 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4532 return NULL_TREE;
4535 if (!usable_range_p (vr, strict_overflow_p))
4536 return NULL_TREE;
4538 if (comp == EQ_EXPR)
4540 /* EQ_EXPR may only be computed if VR represents exactly
4541 one value. */
4542 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4544 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4545 if (cmp == 0)
4546 return boolean_true_node;
4547 else if (cmp == -1 || cmp == 1 || cmp == 2)
4548 return boolean_false_node;
4550 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4551 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4552 return boolean_false_node;
4554 return NULL_TREE;
4556 else if (comp == NE_EXPR)
4558 /* If VAL is not inside VR, then they are always different. */
4559 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4560 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4561 return boolean_true_node;
4563 /* If VR represents exactly one value equal to VAL, then return
4564 false. */
4565 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4566 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4567 return boolean_false_node;
4569 /* Otherwise, they may or may not be different. */
4570 return NULL_TREE;
4572 else if (comp == LT_EXPR || comp == LE_EXPR)
4574 int tst;
4576 /* If VR is to the left of VAL, return true. */
4577 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4578 if ((comp == LT_EXPR && tst == -1)
4579 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4581 if (overflow_infinity_range_p (vr))
4582 *strict_overflow_p = true;
4583 return boolean_true_node;
4586 /* If VR is to the right of VAL, return false. */
4587 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4588 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4589 || (comp == LE_EXPR && tst == 1))
4591 if (overflow_infinity_range_p (vr))
4592 *strict_overflow_p = true;
4593 return boolean_false_node;
4596 /* Otherwise, we don't know. */
4597 return NULL_TREE;
4599 else if (comp == GT_EXPR || comp == GE_EXPR)
4601 int tst;
4603 /* If VR is to the right of VAL, return true. */
4604 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4605 if ((comp == GT_EXPR && tst == 1)
4606 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4608 if (overflow_infinity_range_p (vr))
4609 *strict_overflow_p = true;
4610 return boolean_true_node;
4613 /* If VR is to the left of VAL, return false. */
4614 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4615 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4616 || (comp == GE_EXPR && tst == -1))
4618 if (overflow_infinity_range_p (vr))
4619 *strict_overflow_p = true;
4620 return boolean_false_node;
4623 /* Otherwise, we don't know. */
4624 return NULL_TREE;
4627 gcc_unreachable ();
4631 /* Debugging dumps. */
4633 void dump_value_range (FILE *, value_range *);
4634 void debug_value_range (value_range *);
4635 void dump_all_value_ranges (FILE *);
4636 void debug_all_value_ranges (void);
4637 void dump_vr_equiv (FILE *, bitmap);
4638 void debug_vr_equiv (bitmap);
4641 /* Dump value range VR to FILE. */
4643 void
4644 dump_value_range (FILE *file, value_range *vr)
4646 if (vr == NULL)
4647 fprintf (file, "[]");
4648 else if (vr->type == VR_UNDEFINED)
4649 fprintf (file, "UNDEFINED");
4650 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4652 tree type = TREE_TYPE (vr->min);
4654 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4656 if (is_negative_overflow_infinity (vr->min))
4657 fprintf (file, "-INF(OVF)");
4658 else if (INTEGRAL_TYPE_P (type)
4659 && !TYPE_UNSIGNED (type)
4660 && vrp_val_is_min (vr->min))
4661 fprintf (file, "-INF");
4662 else
4663 print_generic_expr (file, vr->min, 0);
4665 fprintf (file, ", ");
4667 if (is_positive_overflow_infinity (vr->max))
4668 fprintf (file, "+INF(OVF)");
4669 else if (INTEGRAL_TYPE_P (type)
4670 && vrp_val_is_max (vr->max))
4671 fprintf (file, "+INF");
4672 else
4673 print_generic_expr (file, vr->max, 0);
4675 fprintf (file, "]");
4677 if (vr->equiv)
4679 bitmap_iterator bi;
4680 unsigned i, c = 0;
4682 fprintf (file, " EQUIVALENCES: { ");
4684 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4686 print_generic_expr (file, ssa_name (i), 0);
4687 fprintf (file, " ");
4688 c++;
4691 fprintf (file, "} (%u elements)", c);
4694 else if (vr->type == VR_VARYING)
4695 fprintf (file, "VARYING");
4696 else
4697 fprintf (file, "INVALID RANGE");
4701 /* Dump value range VR to stderr. */
4703 DEBUG_FUNCTION void
4704 debug_value_range (value_range *vr)
4706 dump_value_range (stderr, vr);
4707 fprintf (stderr, "\n");
4711 /* Dump value ranges of all SSA_NAMEs to FILE. */
4713 void
4714 dump_all_value_ranges (FILE *file)
4716 size_t i;
4718 for (i = 0; i < num_vr_values; i++)
4720 if (vr_value[i])
4722 print_generic_expr (file, ssa_name (i), 0);
4723 fprintf (file, ": ");
4724 dump_value_range (file, vr_value[i]);
4725 fprintf (file, "\n");
4729 fprintf (file, "\n");
4733 /* Dump all value ranges to stderr. */
4735 DEBUG_FUNCTION void
4736 debug_all_value_ranges (void)
4738 dump_all_value_ranges (stderr);
4742 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4743 create a new SSA name N and return the assertion assignment
4744 'N = ASSERT_EXPR <V, V OP W>'. */
4746 static gimple *
4747 build_assert_expr_for (tree cond, tree v)
4749 tree a;
4750 gassign *assertion;
4752 gcc_assert (TREE_CODE (v) == SSA_NAME
4753 && COMPARISON_CLASS_P (cond));
4755 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4756 assertion = gimple_build_assign (NULL_TREE, a);
4758 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4759 operand of the ASSERT_EXPR. Create it so the new name and the old one
4760 are registered in the replacement table so that we can fix the SSA web
4761 after adding all the ASSERT_EXPRs. */
4762 create_new_def_for (v, assertion, NULL);
4764 return assertion;
4768 /* Return false if EXPR is a predicate expression involving floating
4769 point values. */
4771 static inline bool
4772 fp_predicate (gimple *stmt)
4774 GIMPLE_CHECK (stmt, GIMPLE_COND);
4776 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4779 /* If the range of values taken by OP can be inferred after STMT executes,
4780 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4781 describes the inferred range. Return true if a range could be
4782 inferred. */
4784 static bool
4785 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4787 *val_p = NULL_TREE;
4788 *comp_code_p = ERROR_MARK;
4790 /* Do not attempt to infer anything in names that flow through
4791 abnormal edges. */
4792 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4793 return false;
4795 /* Similarly, don't infer anything from statements that may throw
4796 exceptions. ??? Relax this requirement? */
4797 if (stmt_could_throw_p (stmt))
4798 return false;
4800 /* If STMT is the last statement of a basic block with no normal
4801 successors, there is no point inferring anything about any of its
4802 operands. We would not be able to find a proper insertion point
4803 for the assertion, anyway. */
4804 if (stmt_ends_bb_p (stmt))
4806 edge_iterator ei;
4807 edge e;
4809 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4810 if (!(e->flags & EDGE_ABNORMAL))
4811 break;
4812 if (e == NULL)
4813 return false;
4816 if (infer_nonnull_range (stmt, op))
4818 *val_p = build_int_cst (TREE_TYPE (op), 0);
4819 *comp_code_p = NE_EXPR;
4820 return true;
4823 return false;
4827 void dump_asserts_for (FILE *, tree);
4828 void debug_asserts_for (tree);
4829 void dump_all_asserts (FILE *);
4830 void debug_all_asserts (void);
4832 /* Dump all the registered assertions for NAME to FILE. */
4834 void
4835 dump_asserts_for (FILE *file, tree name)
4837 assert_locus *loc;
4839 fprintf (file, "Assertions to be inserted for ");
4840 print_generic_expr (file, name, 0);
4841 fprintf (file, "\n");
4843 loc = asserts_for[SSA_NAME_VERSION (name)];
4844 while (loc)
4846 fprintf (file, "\t");
4847 print_gimple_stmt (file, gsi_stmt (loc->si), 0, 0);
4848 fprintf (file, "\n\tBB #%d", loc->bb->index);
4849 if (loc->e)
4851 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4852 loc->e->dest->index);
4853 dump_edge_info (file, loc->e, dump_flags, 0);
4855 fprintf (file, "\n\tPREDICATE: ");
4856 print_generic_expr (file, loc->expr, 0);
4857 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4858 print_generic_expr (file, loc->val, 0);
4859 fprintf (file, "\n\n");
4860 loc = loc->next;
4863 fprintf (file, "\n");
4867 /* Dump all the registered assertions for NAME to stderr. */
4869 DEBUG_FUNCTION void
4870 debug_asserts_for (tree name)
4872 dump_asserts_for (stderr, name);
4876 /* Dump all the registered assertions for all the names to FILE. */
4878 void
4879 dump_all_asserts (FILE *file)
4881 unsigned i;
4882 bitmap_iterator bi;
4884 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4885 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4886 dump_asserts_for (file, ssa_name (i));
4887 fprintf (file, "\n");
4891 /* Dump all the registered assertions for all the names to stderr. */
4893 DEBUG_FUNCTION void
4894 debug_all_asserts (void)
4896 dump_all_asserts (stderr);
4900 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4901 'EXPR COMP_CODE VAL' at a location that dominates block BB or
4902 E->DEST, then register this location as a possible insertion point
4903 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4905 BB, E and SI provide the exact insertion point for the new
4906 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
4907 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4908 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4909 must not be NULL. */
4911 static void
4912 register_new_assert_for (tree name, tree expr,
4913 enum tree_code comp_code,
4914 tree val,
4915 basic_block bb,
4916 edge e,
4917 gimple_stmt_iterator si)
4919 assert_locus *n, *loc, *last_loc;
4920 basic_block dest_bb;
4922 gcc_checking_assert (bb == NULL || e == NULL);
4924 if (e == NULL)
4925 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4926 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4928 /* Never build an assert comparing against an integer constant with
4929 TREE_OVERFLOW set. This confuses our undefined overflow warning
4930 machinery. */
4931 if (TREE_OVERFLOW_P (val))
4932 val = drop_tree_overflow (val);
4934 /* The new assertion A will be inserted at BB or E. We need to
4935 determine if the new location is dominated by a previously
4936 registered location for A. If we are doing an edge insertion,
4937 assume that A will be inserted at E->DEST. Note that this is not
4938 necessarily true.
4940 If E is a critical edge, it will be split. But even if E is
4941 split, the new block will dominate the same set of blocks that
4942 E->DEST dominates.
4944 The reverse, however, is not true, blocks dominated by E->DEST
4945 will not be dominated by the new block created to split E. So,
4946 if the insertion location is on a critical edge, we will not use
4947 the new location to move another assertion previously registered
4948 at a block dominated by E->DEST. */
4949 dest_bb = (bb) ? bb : e->dest;
4951 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4952 VAL at a block dominating DEST_BB, then we don't need to insert a new
4953 one. Similarly, if the same assertion already exists at a block
4954 dominated by DEST_BB and the new location is not on a critical
4955 edge, then update the existing location for the assertion (i.e.,
4956 move the assertion up in the dominance tree).
4958 Note, this is implemented as a simple linked list because there
4959 should not be more than a handful of assertions registered per
4960 name. If this becomes a performance problem, a table hashed by
4961 COMP_CODE and VAL could be implemented. */
4962 loc = asserts_for[SSA_NAME_VERSION (name)];
4963 last_loc = loc;
4964 while (loc)
4966 if (loc->comp_code == comp_code
4967 && (loc->val == val
4968 || operand_equal_p (loc->val, val, 0))
4969 && (loc->expr == expr
4970 || operand_equal_p (loc->expr, expr, 0)))
4972 /* If E is not a critical edge and DEST_BB
4973 dominates the existing location for the assertion, move
4974 the assertion up in the dominance tree by updating its
4975 location information. */
4976 if ((e == NULL || !EDGE_CRITICAL_P (e))
4977 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4979 loc->bb = dest_bb;
4980 loc->e = e;
4981 loc->si = si;
4982 return;
4986 /* Update the last node of the list and move to the next one. */
4987 last_loc = loc;
4988 loc = loc->next;
4991 /* If we didn't find an assertion already registered for
4992 NAME COMP_CODE VAL, add a new one at the end of the list of
4993 assertions associated with NAME. */
4994 n = XNEW (struct assert_locus);
4995 n->bb = dest_bb;
4996 n->e = e;
4997 n->si = si;
4998 n->comp_code = comp_code;
4999 n->val = val;
5000 n->expr = expr;
5001 n->next = NULL;
5003 if (last_loc)
5004 last_loc->next = n;
5005 else
5006 asserts_for[SSA_NAME_VERSION (name)] = n;
5008 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
5011 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
5012 Extract a suitable test code and value and store them into *CODE_P and
5013 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
5015 If no extraction was possible, return FALSE, otherwise return TRUE.
5017 If INVERT is true, then we invert the result stored into *CODE_P. */
5019 static bool
5020 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
5021 tree cond_op0, tree cond_op1,
5022 bool invert, enum tree_code *code_p,
5023 tree *val_p)
5025 enum tree_code comp_code;
5026 tree val;
5028 /* Otherwise, we have a comparison of the form NAME COMP VAL
5029 or VAL COMP NAME. */
5030 if (name == cond_op1)
5032 /* If the predicate is of the form VAL COMP NAME, flip
5033 COMP around because we need to register NAME as the
5034 first operand in the predicate. */
5035 comp_code = swap_tree_comparison (cond_code);
5036 val = cond_op0;
5038 else if (name == cond_op0)
5040 /* The comparison is of the form NAME COMP VAL, so the
5041 comparison code remains unchanged. */
5042 comp_code = cond_code;
5043 val = cond_op1;
5045 else
5046 gcc_unreachable ();
5048 /* Invert the comparison code as necessary. */
5049 if (invert)
5050 comp_code = invert_tree_comparison (comp_code, 0);
5052 /* VRP only handles integral and pointer types. */
5053 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
5054 && ! POINTER_TYPE_P (TREE_TYPE (val)))
5055 return false;
5057 /* Do not register always-false predicates.
5058 FIXME: this works around a limitation in fold() when dealing with
5059 enumerations. Given 'enum { N1, N2 } x;', fold will not
5060 fold 'if (x > N2)' to 'if (0)'. */
5061 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
5062 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
5064 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
5065 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
5067 if (comp_code == GT_EXPR
5068 && (!max
5069 || compare_values (val, max) == 0))
5070 return false;
5072 if (comp_code == LT_EXPR
5073 && (!min
5074 || compare_values (val, min) == 0))
5075 return false;
5077 *code_p = comp_code;
5078 *val_p = val;
5079 return true;
5082 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
5083 (otherwise return VAL). VAL and MASK must be zero-extended for
5084 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
5085 (to transform signed values into unsigned) and at the end xor
5086 SGNBIT back. */
5088 static wide_int
5089 masked_increment (const wide_int &val_in, const wide_int &mask,
5090 const wide_int &sgnbit, unsigned int prec)
5092 wide_int bit = wi::one (prec), res;
5093 unsigned int i;
5095 wide_int val = val_in ^ sgnbit;
5096 for (i = 0; i < prec; i++, bit += bit)
5098 res = mask;
5099 if ((res & bit) == 0)
5100 continue;
5101 res = bit - 1;
5102 res = (val + bit).and_not (res);
5103 res &= mask;
5104 if (wi::gtu_p (res, val))
5105 return res ^ sgnbit;
5107 return val ^ sgnbit;
5110 /* Try to register an edge assertion for SSA name NAME on edge E for
5111 the condition COND contributing to the conditional jump pointed to by BSI.
5112 Invert the condition COND if INVERT is true. */
5114 static void
5115 register_edge_assert_for_2 (tree name, edge e, gimple_stmt_iterator bsi,
5116 enum tree_code cond_code,
5117 tree cond_op0, tree cond_op1, bool invert)
5119 tree val;
5120 enum tree_code comp_code;
5122 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5123 cond_op0,
5124 cond_op1,
5125 invert, &comp_code, &val))
5126 return;
5128 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5129 reachable from E. */
5130 if (live_on_edge (e, name))
5131 register_new_assert_for (name, name, comp_code, val, NULL, e, bsi);
5133 /* In the case of NAME <= CST and NAME being defined as
5134 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5135 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
5136 This catches range and anti-range tests. */
5137 if ((comp_code == LE_EXPR
5138 || comp_code == GT_EXPR)
5139 && TREE_CODE (val) == INTEGER_CST
5140 && TYPE_UNSIGNED (TREE_TYPE (val)))
5142 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5143 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5145 /* Extract CST2 from the (optional) addition. */
5146 if (is_gimple_assign (def_stmt)
5147 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5149 name2 = gimple_assign_rhs1 (def_stmt);
5150 cst2 = gimple_assign_rhs2 (def_stmt);
5151 if (TREE_CODE (name2) == SSA_NAME
5152 && TREE_CODE (cst2) == INTEGER_CST)
5153 def_stmt = SSA_NAME_DEF_STMT (name2);
5156 /* Extract NAME2 from the (optional) sign-changing cast. */
5157 if (gimple_assign_cast_p (def_stmt))
5159 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5160 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5161 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5162 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5163 name3 = gimple_assign_rhs1 (def_stmt);
5166 /* If name3 is used later, create an ASSERT_EXPR for it. */
5167 if (name3 != NULL_TREE
5168 && TREE_CODE (name3) == SSA_NAME
5169 && (cst2 == NULL_TREE
5170 || TREE_CODE (cst2) == INTEGER_CST)
5171 && INTEGRAL_TYPE_P (TREE_TYPE (name3))
5172 && live_on_edge (e, name3))
5174 tree tmp;
5176 /* Build an expression for the range test. */
5177 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5178 if (cst2 != NULL_TREE)
5179 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5181 if (dump_file)
5183 fprintf (dump_file, "Adding assert for ");
5184 print_generic_expr (dump_file, name3, 0);
5185 fprintf (dump_file, " from ");
5186 print_generic_expr (dump_file, tmp, 0);
5187 fprintf (dump_file, "\n");
5190 register_new_assert_for (name3, tmp, comp_code, val, NULL, e, bsi);
5193 /* If name2 is used later, create an ASSERT_EXPR for it. */
5194 if (name2 != NULL_TREE
5195 && TREE_CODE (name2) == SSA_NAME
5196 && TREE_CODE (cst2) == INTEGER_CST
5197 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5198 && live_on_edge (e, name2))
5200 tree tmp;
5202 /* Build an expression for the range test. */
5203 tmp = name2;
5204 if (TREE_TYPE (name) != TREE_TYPE (name2))
5205 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5206 if (cst2 != NULL_TREE)
5207 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5209 if (dump_file)
5211 fprintf (dump_file, "Adding assert for ");
5212 print_generic_expr (dump_file, name2, 0);
5213 fprintf (dump_file, " from ");
5214 print_generic_expr (dump_file, tmp, 0);
5215 fprintf (dump_file, "\n");
5218 register_new_assert_for (name2, tmp, comp_code, val, NULL, e, bsi);
5222 /* In the case of post-in/decrement tests like if (i++) ... and uses
5223 of the in/decremented value on the edge the extra name we want to
5224 assert for is not on the def chain of the name compared. Instead
5225 it is in the set of use stmts.
5226 Similar cases happen for conversions that were simplified through
5227 fold_{sign_changed,widened}_comparison. */
5228 if ((comp_code == NE_EXPR
5229 || comp_code == EQ_EXPR)
5230 && TREE_CODE (val) == INTEGER_CST)
5232 imm_use_iterator ui;
5233 gimple *use_stmt;
5234 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5236 if (!is_gimple_assign (use_stmt))
5237 continue;
5239 /* Cut off to use-stmts that are dominating the predecessor. */
5240 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5241 continue;
5243 tree name2 = gimple_assign_lhs (use_stmt);
5244 if (TREE_CODE (name2) != SSA_NAME
5245 || !live_on_edge (e, name2))
5246 continue;
5248 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5249 tree cst;
5250 if (code == PLUS_EXPR
5251 || code == MINUS_EXPR)
5253 cst = gimple_assign_rhs2 (use_stmt);
5254 if (TREE_CODE (cst) != INTEGER_CST)
5255 continue;
5256 cst = int_const_binop (code, val, cst);
5258 else if (CONVERT_EXPR_CODE_P (code))
5260 /* For truncating conversions we cannot record
5261 an inequality. */
5262 if (comp_code == NE_EXPR
5263 && (TYPE_PRECISION (TREE_TYPE (name2))
5264 < TYPE_PRECISION (TREE_TYPE (name))))
5265 continue;
5266 cst = fold_convert (TREE_TYPE (name2), val);
5268 else
5269 continue;
5271 if (TREE_OVERFLOW_P (cst))
5272 cst = drop_tree_overflow (cst);
5273 register_new_assert_for (name2, name2, comp_code, cst,
5274 NULL, e, bsi);
5278 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5279 && TREE_CODE (val) == INTEGER_CST)
5281 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5282 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5283 tree val2 = NULL_TREE;
5284 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5285 wide_int mask = wi::zero (prec);
5286 unsigned int nprec = prec;
5287 enum tree_code rhs_code = ERROR_MARK;
5289 if (is_gimple_assign (def_stmt))
5290 rhs_code = gimple_assign_rhs_code (def_stmt);
5292 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5293 assert that A != CST1 -+ CST2. */
5294 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5295 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5297 tree op0 = gimple_assign_rhs1 (def_stmt);
5298 tree op1 = gimple_assign_rhs2 (def_stmt);
5299 if (TREE_CODE (op0) == SSA_NAME
5300 && TREE_CODE (op1) == INTEGER_CST
5301 && live_on_edge (e, op0))
5303 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5304 ? MINUS_EXPR : PLUS_EXPR);
5305 op1 = int_const_binop (reverse_op, val, op1);
5306 if (TREE_OVERFLOW (op1))
5307 op1 = drop_tree_overflow (op1);
5308 register_new_assert_for (op0, op0, comp_code, op1, NULL, e, bsi);
5312 /* Add asserts for NAME cmp CST and NAME being defined
5313 as NAME = (int) NAME2. */
5314 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5315 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5316 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5317 && gimple_assign_cast_p (def_stmt))
5319 name2 = gimple_assign_rhs1 (def_stmt);
5320 if (CONVERT_EXPR_CODE_P (rhs_code)
5321 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5322 && TYPE_UNSIGNED (TREE_TYPE (name2))
5323 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5324 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5325 || !tree_int_cst_equal (val,
5326 TYPE_MIN_VALUE (TREE_TYPE (val))))
5327 && live_on_edge (e, name2))
5329 tree tmp, cst;
5330 enum tree_code new_comp_code = comp_code;
5332 cst = fold_convert (TREE_TYPE (name2),
5333 TYPE_MIN_VALUE (TREE_TYPE (val)));
5334 /* Build an expression for the range test. */
5335 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5336 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5337 fold_convert (TREE_TYPE (name2), val));
5338 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5340 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5341 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5342 build_int_cst (TREE_TYPE (name2), 1));
5345 if (dump_file)
5347 fprintf (dump_file, "Adding assert for ");
5348 print_generic_expr (dump_file, name2, 0);
5349 fprintf (dump_file, " from ");
5350 print_generic_expr (dump_file, tmp, 0);
5351 fprintf (dump_file, "\n");
5354 register_new_assert_for (name2, tmp, new_comp_code, cst, NULL,
5355 e, bsi);
5359 /* Add asserts for NAME cmp CST and NAME being defined as
5360 NAME = NAME2 >> CST2.
5362 Extract CST2 from the right shift. */
5363 if (rhs_code == RSHIFT_EXPR)
5365 name2 = gimple_assign_rhs1 (def_stmt);
5366 cst2 = gimple_assign_rhs2 (def_stmt);
5367 if (TREE_CODE (name2) == SSA_NAME
5368 && tree_fits_uhwi_p (cst2)
5369 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5370 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5371 && prec == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (val)))
5372 && live_on_edge (e, name2))
5374 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5375 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5378 if (val2 != NULL_TREE
5379 && TREE_CODE (val2) == INTEGER_CST
5380 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5381 TREE_TYPE (val),
5382 val2, cst2), val))
5384 enum tree_code new_comp_code = comp_code;
5385 tree tmp, new_val;
5387 tmp = name2;
5388 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5390 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5392 tree type = build_nonstandard_integer_type (prec, 1);
5393 tmp = build1 (NOP_EXPR, type, name2);
5394 val2 = fold_convert (type, val2);
5396 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5397 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5398 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5400 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5402 wide_int minval
5403 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5404 new_val = val2;
5405 if (minval == new_val)
5406 new_val = NULL_TREE;
5408 else
5410 wide_int maxval
5411 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5412 mask |= val2;
5413 if (mask == maxval)
5414 new_val = NULL_TREE;
5415 else
5416 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5419 if (new_val)
5421 if (dump_file)
5423 fprintf (dump_file, "Adding assert for ");
5424 print_generic_expr (dump_file, name2, 0);
5425 fprintf (dump_file, " from ");
5426 print_generic_expr (dump_file, tmp, 0);
5427 fprintf (dump_file, "\n");
5430 register_new_assert_for (name2, tmp, new_comp_code, new_val,
5431 NULL, e, bsi);
5435 /* Add asserts for NAME cmp CST and NAME being defined as
5436 NAME = NAME2 & CST2.
5438 Extract CST2 from the and.
5440 Also handle
5441 NAME = (unsigned) NAME2;
5442 casts where NAME's type is unsigned and has smaller precision
5443 than NAME2's type as if it was NAME = NAME2 & MASK. */
5444 names[0] = NULL_TREE;
5445 names[1] = NULL_TREE;
5446 cst2 = NULL_TREE;
5447 if (rhs_code == BIT_AND_EXPR
5448 || (CONVERT_EXPR_CODE_P (rhs_code)
5449 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5450 && TYPE_UNSIGNED (TREE_TYPE (val))
5451 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5452 > prec))
5454 name2 = gimple_assign_rhs1 (def_stmt);
5455 if (rhs_code == BIT_AND_EXPR)
5456 cst2 = gimple_assign_rhs2 (def_stmt);
5457 else
5459 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5460 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5462 if (TREE_CODE (name2) == SSA_NAME
5463 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5464 && TREE_CODE (cst2) == INTEGER_CST
5465 && !integer_zerop (cst2)
5466 && (nprec > 1
5467 || TYPE_UNSIGNED (TREE_TYPE (val))))
5469 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5470 if (gimple_assign_cast_p (def_stmt2))
5472 names[1] = gimple_assign_rhs1 (def_stmt2);
5473 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5474 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5475 || (TYPE_PRECISION (TREE_TYPE (name2))
5476 != TYPE_PRECISION (TREE_TYPE (names[1])))
5477 || !live_on_edge (e, names[1]))
5478 names[1] = NULL_TREE;
5480 if (live_on_edge (e, name2))
5481 names[0] = name2;
5484 if (names[0] || names[1])
5486 wide_int minv, maxv, valv, cst2v;
5487 wide_int tem, sgnbit;
5488 bool valid_p = false, valn, cst2n;
5489 enum tree_code ccode = comp_code;
5491 valv = wide_int::from (val, nprec, UNSIGNED);
5492 cst2v = wide_int::from (cst2, nprec, UNSIGNED);
5493 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5494 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5495 /* If CST2 doesn't have most significant bit set,
5496 but VAL is negative, we have comparison like
5497 if ((x & 0x123) > -4) (always true). Just give up. */
5498 if (!cst2n && valn)
5499 ccode = ERROR_MARK;
5500 if (cst2n)
5501 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5502 else
5503 sgnbit = wi::zero (nprec);
5504 minv = valv & cst2v;
5505 switch (ccode)
5507 case EQ_EXPR:
5508 /* Minimum unsigned value for equality is VAL & CST2
5509 (should be equal to VAL, otherwise we probably should
5510 have folded the comparison into false) and
5511 maximum unsigned value is VAL | ~CST2. */
5512 maxv = valv | ~cst2v;
5513 valid_p = true;
5514 break;
5516 case NE_EXPR:
5517 tem = valv | ~cst2v;
5518 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5519 if (valv == 0)
5521 cst2n = false;
5522 sgnbit = wi::zero (nprec);
5523 goto gt_expr;
5525 /* If (VAL | ~CST2) is all ones, handle it as
5526 (X & CST2) < VAL. */
5527 if (tem == -1)
5529 cst2n = false;
5530 valn = false;
5531 sgnbit = wi::zero (nprec);
5532 goto lt_expr;
5534 if (!cst2n && wi::neg_p (cst2v))
5535 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5536 if (sgnbit != 0)
5538 if (valv == sgnbit)
5540 cst2n = true;
5541 valn = true;
5542 goto gt_expr;
5544 if (tem == wi::mask (nprec - 1, false, nprec))
5546 cst2n = true;
5547 goto lt_expr;
5549 if (!cst2n)
5550 sgnbit = wi::zero (nprec);
5552 break;
5554 case GE_EXPR:
5555 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5556 is VAL and maximum unsigned value is ~0. For signed
5557 comparison, if CST2 doesn't have most significant bit
5558 set, handle it similarly. If CST2 has MSB set,
5559 the minimum is the same, and maximum is ~0U/2. */
5560 if (minv != valv)
5562 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5563 VAL. */
5564 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5565 if (minv == valv)
5566 break;
5568 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5569 valid_p = true;
5570 break;
5572 case GT_EXPR:
5573 gt_expr:
5574 /* Find out smallest MINV where MINV > VAL
5575 && (MINV & CST2) == MINV, if any. If VAL is signed and
5576 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5577 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5578 if (minv == valv)
5579 break;
5580 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5581 valid_p = true;
5582 break;
5584 case LE_EXPR:
5585 /* Minimum unsigned value for <= is 0 and maximum
5586 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5587 Otherwise, find smallest VAL2 where VAL2 > VAL
5588 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5589 as maximum.
5590 For signed comparison, if CST2 doesn't have most
5591 significant bit set, handle it similarly. If CST2 has
5592 MSB set, the maximum is the same and minimum is INT_MIN. */
5593 if (minv == valv)
5594 maxv = valv;
5595 else
5597 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5598 if (maxv == valv)
5599 break;
5600 maxv -= 1;
5602 maxv |= ~cst2v;
5603 minv = sgnbit;
5604 valid_p = true;
5605 break;
5607 case LT_EXPR:
5608 lt_expr:
5609 /* Minimum unsigned value for < is 0 and maximum
5610 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5611 Otherwise, find smallest VAL2 where VAL2 > VAL
5612 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5613 as maximum.
5614 For signed comparison, if CST2 doesn't have most
5615 significant bit set, handle it similarly. If CST2 has
5616 MSB set, the maximum is the same and minimum is INT_MIN. */
5617 if (minv == valv)
5619 if (valv == sgnbit)
5620 break;
5621 maxv = valv;
5623 else
5625 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5626 if (maxv == valv)
5627 break;
5629 maxv -= 1;
5630 maxv |= ~cst2v;
5631 minv = sgnbit;
5632 valid_p = true;
5633 break;
5635 default:
5636 break;
5638 if (valid_p
5639 && (maxv - minv) != -1)
5641 tree tmp, new_val, type;
5642 int i;
5644 for (i = 0; i < 2; i++)
5645 if (names[i])
5647 wide_int maxv2 = maxv;
5648 tmp = names[i];
5649 type = TREE_TYPE (names[i]);
5650 if (!TYPE_UNSIGNED (type))
5652 type = build_nonstandard_integer_type (nprec, 1);
5653 tmp = build1 (NOP_EXPR, type, names[i]);
5655 if (minv != 0)
5657 tmp = build2 (PLUS_EXPR, type, tmp,
5658 wide_int_to_tree (type, -minv));
5659 maxv2 = maxv - minv;
5661 new_val = wide_int_to_tree (type, maxv2);
5663 if (dump_file)
5665 fprintf (dump_file, "Adding assert for ");
5666 print_generic_expr (dump_file, names[i], 0);
5667 fprintf (dump_file, " from ");
5668 print_generic_expr (dump_file, tmp, 0);
5669 fprintf (dump_file, "\n");
5672 register_new_assert_for (names[i], tmp, LE_EXPR,
5673 new_val, NULL, e, bsi);
5680 /* OP is an operand of a truth value expression which is known to have
5681 a particular value. Register any asserts for OP and for any
5682 operands in OP's defining statement.
5684 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5685 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5687 static void
5688 register_edge_assert_for_1 (tree op, enum tree_code code,
5689 edge e, gimple_stmt_iterator bsi)
5691 gimple *op_def;
5692 tree val;
5693 enum tree_code rhs_code;
5695 /* We only care about SSA_NAMEs. */
5696 if (TREE_CODE (op) != SSA_NAME)
5697 return;
5699 /* We know that OP will have a zero or nonzero value. If OP is used
5700 more than once go ahead and register an assert for OP. */
5701 if (live_on_edge (e, op))
5703 val = build_int_cst (TREE_TYPE (op), 0);
5704 register_new_assert_for (op, op, code, val, NULL, e, bsi);
5707 /* Now look at how OP is set. If it's set from a comparison,
5708 a truth operation or some bit operations, then we may be able
5709 to register information about the operands of that assignment. */
5710 op_def = SSA_NAME_DEF_STMT (op);
5711 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5712 return;
5714 rhs_code = gimple_assign_rhs_code (op_def);
5716 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5718 bool invert = (code == EQ_EXPR ? true : false);
5719 tree op0 = gimple_assign_rhs1 (op_def);
5720 tree op1 = gimple_assign_rhs2 (op_def);
5722 if (TREE_CODE (op0) == SSA_NAME)
5723 register_edge_assert_for_2 (op0, e, bsi, rhs_code, op0, op1, invert);
5724 if (TREE_CODE (op1) == SSA_NAME)
5725 register_edge_assert_for_2 (op1, e, bsi, rhs_code, op0, op1, invert);
5727 else if ((code == NE_EXPR
5728 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5729 || (code == EQ_EXPR
5730 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5732 /* Recurse on each operand. */
5733 tree op0 = gimple_assign_rhs1 (op_def);
5734 tree op1 = gimple_assign_rhs2 (op_def);
5735 if (TREE_CODE (op0) == SSA_NAME
5736 && has_single_use (op0))
5737 register_edge_assert_for_1 (op0, code, e, bsi);
5738 if (TREE_CODE (op1) == SSA_NAME
5739 && has_single_use (op1))
5740 register_edge_assert_for_1 (op1, code, e, bsi);
5742 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5743 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5745 /* Recurse, flipping CODE. */
5746 code = invert_tree_comparison (code, false);
5747 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, bsi);
5749 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5751 /* Recurse through the copy. */
5752 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, bsi);
5754 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5756 /* Recurse through the type conversion, unless it is a narrowing
5757 conversion or conversion from non-integral type. */
5758 tree rhs = gimple_assign_rhs1 (op_def);
5759 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5760 && (TYPE_PRECISION (TREE_TYPE (rhs))
5761 <= TYPE_PRECISION (TREE_TYPE (op))))
5762 register_edge_assert_for_1 (rhs, code, e, bsi);
5766 /* Try to register an edge assertion for SSA name NAME on edge E for
5767 the condition COND contributing to the conditional jump pointed to by
5768 SI. */
5770 static void
5771 register_edge_assert_for (tree name, edge e, gimple_stmt_iterator si,
5772 enum tree_code cond_code, tree cond_op0,
5773 tree cond_op1)
5775 tree val;
5776 enum tree_code comp_code;
5777 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5779 /* Do not attempt to infer anything in names that flow through
5780 abnormal edges. */
5781 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5782 return;
5784 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5785 cond_op0, cond_op1,
5786 is_else_edge,
5787 &comp_code, &val))
5788 return;
5790 /* Register ASSERT_EXPRs for name. */
5791 register_edge_assert_for_2 (name, e, si, cond_code, cond_op0,
5792 cond_op1, is_else_edge);
5795 /* If COND is effectively an equality test of an SSA_NAME against
5796 the value zero or one, then we may be able to assert values
5797 for SSA_NAMEs which flow into COND. */
5799 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5800 statement of NAME we can assert both operands of the BIT_AND_EXPR
5801 have nonzero value. */
5802 if (((comp_code == EQ_EXPR && integer_onep (val))
5803 || (comp_code == NE_EXPR && integer_zerop (val))))
5805 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5807 if (is_gimple_assign (def_stmt)
5808 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5810 tree op0 = gimple_assign_rhs1 (def_stmt);
5811 tree op1 = gimple_assign_rhs2 (def_stmt);
5812 register_edge_assert_for_1 (op0, NE_EXPR, e, si);
5813 register_edge_assert_for_1 (op1, NE_EXPR, e, si);
5817 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5818 statement of NAME we can assert both operands of the BIT_IOR_EXPR
5819 have zero value. */
5820 if (((comp_code == EQ_EXPR && integer_zerop (val))
5821 || (comp_code == NE_EXPR && integer_onep (val))))
5823 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5825 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5826 necessarily zero value, or if type-precision is one. */
5827 if (is_gimple_assign (def_stmt)
5828 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5829 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5830 || comp_code == EQ_EXPR)))
5832 tree op0 = gimple_assign_rhs1 (def_stmt);
5833 tree op1 = gimple_assign_rhs2 (def_stmt);
5834 register_edge_assert_for_1 (op0, EQ_EXPR, e, si);
5835 register_edge_assert_for_1 (op1, EQ_EXPR, e, si);
5841 /* Determine whether the outgoing edges of BB should receive an
5842 ASSERT_EXPR for each of the operands of BB's LAST statement.
5843 The last statement of BB must be a COND_EXPR.
5845 If any of the sub-graphs rooted at BB have an interesting use of
5846 the predicate operands, an assert location node is added to the
5847 list of assertions for the corresponding operands. */
5849 static void
5850 find_conditional_asserts (basic_block bb, gcond *last)
5852 gimple_stmt_iterator bsi;
5853 tree op;
5854 edge_iterator ei;
5855 edge e;
5856 ssa_op_iter iter;
5858 bsi = gsi_for_stmt (last);
5860 /* Look for uses of the operands in each of the sub-graphs
5861 rooted at BB. We need to check each of the outgoing edges
5862 separately, so that we know what kind of ASSERT_EXPR to
5863 insert. */
5864 FOR_EACH_EDGE (e, ei, bb->succs)
5866 if (e->dest == bb)
5867 continue;
5869 /* Register the necessary assertions for each operand in the
5870 conditional predicate. */
5871 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5872 register_edge_assert_for (op, e, bsi,
5873 gimple_cond_code (last),
5874 gimple_cond_lhs (last),
5875 gimple_cond_rhs (last));
5879 struct case_info
5881 tree expr;
5882 basic_block bb;
5885 /* Compare two case labels sorting first by the destination bb index
5886 and then by the case value. */
5888 static int
5889 compare_case_labels (const void *p1, const void *p2)
5891 const struct case_info *ci1 = (const struct case_info *) p1;
5892 const struct case_info *ci2 = (const struct case_info *) p2;
5893 int idx1 = ci1->bb->index;
5894 int idx2 = ci2->bb->index;
5896 if (idx1 < idx2)
5897 return -1;
5898 else if (idx1 == idx2)
5900 /* Make sure the default label is first in a group. */
5901 if (!CASE_LOW (ci1->expr))
5902 return -1;
5903 else if (!CASE_LOW (ci2->expr))
5904 return 1;
5905 else
5906 return tree_int_cst_compare (CASE_LOW (ci1->expr),
5907 CASE_LOW (ci2->expr));
5909 else
5910 return 1;
5913 /* Determine whether the outgoing edges of BB should receive an
5914 ASSERT_EXPR for each of the operands of BB's LAST statement.
5915 The last statement of BB must be a SWITCH_EXPR.
5917 If any of the sub-graphs rooted at BB have an interesting use of
5918 the predicate operands, an assert location node is added to the
5919 list of assertions for the corresponding operands. */
5921 static void
5922 find_switch_asserts (basic_block bb, gswitch *last)
5924 gimple_stmt_iterator bsi;
5925 tree op;
5926 edge e;
5927 struct case_info *ci;
5928 size_t n = gimple_switch_num_labels (last);
5929 #if GCC_VERSION >= 4000
5930 unsigned int idx;
5931 #else
5932 /* Work around GCC 3.4 bug (PR 37086). */
5933 volatile unsigned int idx;
5934 #endif
5936 bsi = gsi_for_stmt (last);
5937 op = gimple_switch_index (last);
5938 if (TREE_CODE (op) != SSA_NAME)
5939 return;
5941 /* Build a vector of case labels sorted by destination label. */
5942 ci = XNEWVEC (struct case_info, n);
5943 for (idx = 0; idx < n; ++idx)
5945 ci[idx].expr = gimple_switch_label (last, idx);
5946 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
5948 edge default_edge = find_edge (bb, ci[0].bb);
5949 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
5951 for (idx = 0; idx < n; ++idx)
5953 tree min, max;
5954 tree cl = ci[idx].expr;
5955 basic_block cbb = ci[idx].bb;
5957 min = CASE_LOW (cl);
5958 max = CASE_HIGH (cl);
5960 /* If there are multiple case labels with the same destination
5961 we need to combine them to a single value range for the edge. */
5962 if (idx + 1 < n && cbb == ci[idx + 1].bb)
5964 /* Skip labels until the last of the group. */
5965 do {
5966 ++idx;
5967 } while (idx < n && cbb == ci[idx].bb);
5968 --idx;
5970 /* Pick up the maximum of the case label range. */
5971 if (CASE_HIGH (ci[idx].expr))
5972 max = CASE_HIGH (ci[idx].expr);
5973 else
5974 max = CASE_LOW (ci[idx].expr);
5977 /* Can't extract a useful assertion out of a range that includes the
5978 default label. */
5979 if (min == NULL_TREE)
5980 continue;
5982 /* Find the edge to register the assert expr on. */
5983 e = find_edge (bb, cbb);
5985 /* Register the necessary assertions for the operand in the
5986 SWITCH_EXPR. */
5987 register_edge_assert_for (op, e, bsi,
5988 max ? GE_EXPR : EQ_EXPR,
5989 op, fold_convert (TREE_TYPE (op), min));
5990 if (max)
5991 register_edge_assert_for (op, e, bsi, LE_EXPR, op,
5992 fold_convert (TREE_TYPE (op), max));
5995 XDELETEVEC (ci);
5997 if (!live_on_edge (default_edge, op))
5998 return;
6000 /* Now register along the default label assertions that correspond to the
6001 anti-range of each label. */
6002 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
6003 for (idx = 1; idx < n; idx++)
6005 tree min, max;
6006 tree cl = gimple_switch_label (last, idx);
6008 min = CASE_LOW (cl);
6009 max = CASE_HIGH (cl);
6011 /* Combine contiguous case ranges to reduce the number of assertions
6012 to insert. */
6013 for (idx = idx + 1; idx < n; idx++)
6015 tree next_min, next_max;
6016 tree next_cl = gimple_switch_label (last, idx);
6018 next_min = CASE_LOW (next_cl);
6019 next_max = CASE_HIGH (next_cl);
6021 wide_int difference = wi::sub (next_min, max ? max : min);
6022 if (wi::eq_p (difference, 1))
6023 max = next_max ? next_max : next_min;
6024 else
6025 break;
6027 idx--;
6029 if (max == NULL_TREE)
6031 /* Register the assertion OP != MIN. */
6032 min = fold_convert (TREE_TYPE (op), min);
6033 register_edge_assert_for (op, default_edge, bsi, NE_EXPR, op, min);
6035 else
6037 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6038 which will give OP the anti-range ~[MIN,MAX]. */
6039 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6040 min = fold_convert (TREE_TYPE (uop), min);
6041 max = fold_convert (TREE_TYPE (uop), max);
6043 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6044 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6045 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6046 NULL, default_edge, bsi);
6049 if (--insertion_limit == 0)
6050 break;
6055 /* Traverse all the statements in block BB looking for statements that
6056 may generate useful assertions for the SSA names in their operand.
6057 If a statement produces a useful assertion A for name N_i, then the
6058 list of assertions already generated for N_i is scanned to
6059 determine if A is actually needed.
6061 If N_i already had the assertion A at a location dominating the
6062 current location, then nothing needs to be done. Otherwise, the
6063 new location for A is recorded instead.
6065 1- For every statement S in BB, all the variables used by S are
6066 added to bitmap FOUND_IN_SUBGRAPH.
6068 2- If statement S uses an operand N in a way that exposes a known
6069 value range for N, then if N was not already generated by an
6070 ASSERT_EXPR, create a new assert location for N. For instance,
6071 if N is a pointer and the statement dereferences it, we can
6072 assume that N is not NULL.
6074 3- COND_EXPRs are a special case of #2. We can derive range
6075 information from the predicate but need to insert different
6076 ASSERT_EXPRs for each of the sub-graphs rooted at the
6077 conditional block. If the last statement of BB is a conditional
6078 expression of the form 'X op Y', then
6080 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6082 b) If the conditional is the only entry point to the sub-graph
6083 corresponding to the THEN_CLAUSE, recurse into it. On
6084 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6085 an ASSERT_EXPR is added for the corresponding variable.
6087 c) Repeat step (b) on the ELSE_CLAUSE.
6089 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6091 For instance,
6093 if (a == 9)
6094 b = a;
6095 else
6096 b = c + 1;
6098 In this case, an assertion on the THEN clause is useful to
6099 determine that 'a' is always 9 on that edge. However, an assertion
6100 on the ELSE clause would be unnecessary.
6102 4- If BB does not end in a conditional expression, then we recurse
6103 into BB's dominator children.
6105 At the end of the recursive traversal, every SSA name will have a
6106 list of locations where ASSERT_EXPRs should be added. When a new
6107 location for name N is found, it is registered by calling
6108 register_new_assert_for. That function keeps track of all the
6109 registered assertions to prevent adding unnecessary assertions.
6110 For instance, if a pointer P_4 is dereferenced more than once in a
6111 dominator tree, only the location dominating all the dereference of
6112 P_4 will receive an ASSERT_EXPR. */
6114 static void
6115 find_assert_locations_1 (basic_block bb, sbitmap live)
6117 gimple *last;
6119 last = last_stmt (bb);
6121 /* If BB's last statement is a conditional statement involving integer
6122 operands, determine if we need to add ASSERT_EXPRs. */
6123 if (last
6124 && gimple_code (last) == GIMPLE_COND
6125 && !fp_predicate (last)
6126 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6127 find_conditional_asserts (bb, as_a <gcond *> (last));
6129 /* If BB's last statement is a switch statement involving integer
6130 operands, determine if we need to add ASSERT_EXPRs. */
6131 if (last
6132 && gimple_code (last) == GIMPLE_SWITCH
6133 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6134 find_switch_asserts (bb, as_a <gswitch *> (last));
6136 /* Traverse all the statements in BB marking used names and looking
6137 for statements that may infer assertions for their used operands. */
6138 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6139 gsi_prev (&si))
6141 gimple *stmt;
6142 tree op;
6143 ssa_op_iter i;
6145 stmt = gsi_stmt (si);
6147 if (is_gimple_debug (stmt))
6148 continue;
6150 /* See if we can derive an assertion for any of STMT's operands. */
6151 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6153 tree value;
6154 enum tree_code comp_code;
6156 /* If op is not live beyond this stmt, do not bother to insert
6157 asserts for it. */
6158 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6159 continue;
6161 /* If OP is used in such a way that we can infer a value
6162 range for it, and we don't find a previous assertion for
6163 it, create a new assertion location node for OP. */
6164 if (infer_value_range (stmt, op, &comp_code, &value))
6166 /* If we are able to infer a nonzero value range for OP,
6167 then walk backwards through the use-def chain to see if OP
6168 was set via a typecast.
6170 If so, then we can also infer a nonzero value range
6171 for the operand of the NOP_EXPR. */
6172 if (comp_code == NE_EXPR && integer_zerop (value))
6174 tree t = op;
6175 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6177 while (is_gimple_assign (def_stmt)
6178 && CONVERT_EXPR_CODE_P
6179 (gimple_assign_rhs_code (def_stmt))
6180 && TREE_CODE
6181 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6182 && POINTER_TYPE_P
6183 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6185 t = gimple_assign_rhs1 (def_stmt);
6186 def_stmt = SSA_NAME_DEF_STMT (t);
6188 /* Note we want to register the assert for the
6189 operand of the NOP_EXPR after SI, not after the
6190 conversion. */
6191 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6192 register_new_assert_for (t, t, comp_code, value,
6193 bb, NULL, si);
6197 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6201 /* Update live. */
6202 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6203 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6204 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6205 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6208 /* Traverse all PHI nodes in BB, updating live. */
6209 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6210 gsi_next (&si))
6212 use_operand_p arg_p;
6213 ssa_op_iter i;
6214 gphi *phi = si.phi ();
6215 tree res = gimple_phi_result (phi);
6217 if (virtual_operand_p (res))
6218 continue;
6220 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6222 tree arg = USE_FROM_PTR (arg_p);
6223 if (TREE_CODE (arg) == SSA_NAME)
6224 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6227 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6231 /* Do an RPO walk over the function computing SSA name liveness
6232 on-the-fly and deciding on assert expressions to insert. */
6234 static void
6235 find_assert_locations (void)
6237 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6238 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6239 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6240 int rpo_cnt, i;
6242 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6243 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6244 for (i = 0; i < rpo_cnt; ++i)
6245 bb_rpo[rpo[i]] = i;
6247 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6248 the order we compute liveness and insert asserts we otherwise
6249 fail to insert asserts into the loop latch. */
6250 loop_p loop;
6251 FOR_EACH_LOOP (loop, 0)
6253 i = loop->latch->index;
6254 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6255 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6256 !gsi_end_p (gsi); gsi_next (&gsi))
6258 gphi *phi = gsi.phi ();
6259 if (virtual_operand_p (gimple_phi_result (phi)))
6260 continue;
6261 tree arg = gimple_phi_arg_def (phi, j);
6262 if (TREE_CODE (arg) == SSA_NAME)
6264 if (live[i] == NULL)
6266 live[i] = sbitmap_alloc (num_ssa_names);
6267 bitmap_clear (live[i]);
6269 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6274 for (i = rpo_cnt - 1; i >= 0; --i)
6276 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6277 edge e;
6278 edge_iterator ei;
6280 if (!live[rpo[i]])
6282 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6283 bitmap_clear (live[rpo[i]]);
6286 /* Process BB and update the live information with uses in
6287 this block. */
6288 find_assert_locations_1 (bb, live[rpo[i]]);
6290 /* Merge liveness into the predecessor blocks and free it. */
6291 if (!bitmap_empty_p (live[rpo[i]]))
6293 int pred_rpo = i;
6294 FOR_EACH_EDGE (e, ei, bb->preds)
6296 int pred = e->src->index;
6297 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6298 continue;
6300 if (!live[pred])
6302 live[pred] = sbitmap_alloc (num_ssa_names);
6303 bitmap_clear (live[pred]);
6305 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6307 if (bb_rpo[pred] < pred_rpo)
6308 pred_rpo = bb_rpo[pred];
6311 /* Record the RPO number of the last visited block that needs
6312 live information from this block. */
6313 last_rpo[rpo[i]] = pred_rpo;
6315 else
6317 sbitmap_free (live[rpo[i]]);
6318 live[rpo[i]] = NULL;
6321 /* We can free all successors live bitmaps if all their
6322 predecessors have been visited already. */
6323 FOR_EACH_EDGE (e, ei, bb->succs)
6324 if (last_rpo[e->dest->index] == i
6325 && live[e->dest->index])
6327 sbitmap_free (live[e->dest->index]);
6328 live[e->dest->index] = NULL;
6332 XDELETEVEC (rpo);
6333 XDELETEVEC (bb_rpo);
6334 XDELETEVEC (last_rpo);
6335 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6336 if (live[i])
6337 sbitmap_free (live[i]);
6338 XDELETEVEC (live);
6341 /* Create an ASSERT_EXPR for NAME and insert it in the location
6342 indicated by LOC. Return true if we made any edge insertions. */
6344 static bool
6345 process_assert_insertions_for (tree name, assert_locus *loc)
6347 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6348 gimple *stmt;
6349 tree cond;
6350 gimple *assert_stmt;
6351 edge_iterator ei;
6352 edge e;
6354 /* If we have X <=> X do not insert an assert expr for that. */
6355 if (loc->expr == loc->val)
6356 return false;
6358 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6359 assert_stmt = build_assert_expr_for (cond, name);
6360 if (loc->e)
6362 /* We have been asked to insert the assertion on an edge. This
6363 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6364 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6365 || (gimple_code (gsi_stmt (loc->si))
6366 == GIMPLE_SWITCH));
6368 gsi_insert_on_edge (loc->e, assert_stmt);
6369 return true;
6372 /* Otherwise, we can insert right after LOC->SI iff the
6373 statement must not be the last statement in the block. */
6374 stmt = gsi_stmt (loc->si);
6375 if (!stmt_ends_bb_p (stmt))
6377 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6378 return false;
6381 /* If STMT must be the last statement in BB, we can only insert new
6382 assertions on the non-abnormal edge out of BB. Note that since
6383 STMT is not control flow, there may only be one non-abnormal edge
6384 out of BB. */
6385 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6386 if (!(e->flags & EDGE_ABNORMAL))
6388 gsi_insert_on_edge (e, assert_stmt);
6389 return true;
6392 gcc_unreachable ();
6396 /* Process all the insertions registered for every name N_i registered
6397 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6398 found in ASSERTS_FOR[i]. */
6400 static void
6401 process_assert_insertions (void)
6403 unsigned i;
6404 bitmap_iterator bi;
6405 bool update_edges_p = false;
6406 int num_asserts = 0;
6408 if (dump_file && (dump_flags & TDF_DETAILS))
6409 dump_all_asserts (dump_file);
6411 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6413 assert_locus *loc = asserts_for[i];
6414 gcc_assert (loc);
6416 while (loc)
6418 assert_locus *next = loc->next;
6419 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6420 free (loc);
6421 loc = next;
6422 num_asserts++;
6426 if (update_edges_p)
6427 gsi_commit_edge_inserts ();
6429 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6430 num_asserts);
6434 /* Traverse the flowgraph looking for conditional jumps to insert range
6435 expressions. These range expressions are meant to provide information
6436 to optimizations that need to reason in terms of value ranges. They
6437 will not be expanded into RTL. For instance, given:
6439 x = ...
6440 y = ...
6441 if (x < y)
6442 y = x - 2;
6443 else
6444 x = y + 3;
6446 this pass will transform the code into:
6448 x = ...
6449 y = ...
6450 if (x < y)
6452 x = ASSERT_EXPR <x, x < y>
6453 y = x - 2
6455 else
6457 y = ASSERT_EXPR <y, x >= y>
6458 x = y + 3
6461 The idea is that once copy and constant propagation have run, other
6462 optimizations will be able to determine what ranges of values can 'x'
6463 take in different paths of the code, simply by checking the reaching
6464 definition of 'x'. */
6466 static void
6467 insert_range_assertions (void)
6469 need_assert_for = BITMAP_ALLOC (NULL);
6470 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6472 calculate_dominance_info (CDI_DOMINATORS);
6474 find_assert_locations ();
6475 if (!bitmap_empty_p (need_assert_for))
6477 process_assert_insertions ();
6478 update_ssa (TODO_update_ssa_no_phi);
6481 if (dump_file && (dump_flags & TDF_DETAILS))
6483 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6484 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6487 free (asserts_for);
6488 BITMAP_FREE (need_assert_for);
6491 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6492 and "struct" hacks. If VRP can determine that the
6493 array subscript is a constant, check if it is outside valid
6494 range. If the array subscript is a RANGE, warn if it is
6495 non-overlapping with valid range.
6496 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6498 static void
6499 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6501 value_range *vr = NULL;
6502 tree low_sub, up_sub;
6503 tree low_bound, up_bound, up_bound_p1;
6505 if (TREE_NO_WARNING (ref))
6506 return;
6508 low_sub = up_sub = TREE_OPERAND (ref, 1);
6509 up_bound = array_ref_up_bound (ref);
6511 /* Can not check flexible arrays. */
6512 if (!up_bound
6513 || TREE_CODE (up_bound) != INTEGER_CST)
6514 return;
6516 /* Accesses to trailing arrays via pointers may access storage
6517 beyond the types array bounds. */
6518 if (warn_array_bounds < 2
6519 && array_at_struct_end_p (ref))
6520 return;
6522 low_bound = array_ref_low_bound (ref);
6523 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6524 build_int_cst (TREE_TYPE (up_bound), 1));
6526 /* Empty array. */
6527 if (tree_int_cst_equal (low_bound, up_bound_p1))
6529 warning_at (location, OPT_Warray_bounds,
6530 "array subscript is above array bounds");
6531 TREE_NO_WARNING (ref) = 1;
6534 if (TREE_CODE (low_sub) == SSA_NAME)
6536 vr = get_value_range (low_sub);
6537 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6539 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6540 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6544 if (vr && vr->type == VR_ANTI_RANGE)
6546 if (TREE_CODE (up_sub) == INTEGER_CST
6547 && (ignore_off_by_one
6548 ? tree_int_cst_lt (up_bound, up_sub)
6549 : tree_int_cst_le (up_bound, up_sub))
6550 && TREE_CODE (low_sub) == INTEGER_CST
6551 && tree_int_cst_le (low_sub, low_bound))
6553 warning_at (location, OPT_Warray_bounds,
6554 "array subscript is outside array bounds");
6555 TREE_NO_WARNING (ref) = 1;
6558 else if (TREE_CODE (up_sub) == INTEGER_CST
6559 && (ignore_off_by_one
6560 ? !tree_int_cst_le (up_sub, up_bound_p1)
6561 : !tree_int_cst_le (up_sub, up_bound)))
6563 if (dump_file && (dump_flags & TDF_DETAILS))
6565 fprintf (dump_file, "Array bound warning for ");
6566 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6567 fprintf (dump_file, "\n");
6569 warning_at (location, OPT_Warray_bounds,
6570 "array subscript is above array bounds");
6571 TREE_NO_WARNING (ref) = 1;
6573 else if (TREE_CODE (low_sub) == INTEGER_CST
6574 && tree_int_cst_lt (low_sub, low_bound))
6576 if (dump_file && (dump_flags & TDF_DETAILS))
6578 fprintf (dump_file, "Array bound warning for ");
6579 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6580 fprintf (dump_file, "\n");
6582 warning_at (location, OPT_Warray_bounds,
6583 "array subscript is below array bounds");
6584 TREE_NO_WARNING (ref) = 1;
6588 /* Searches if the expr T, located at LOCATION computes
6589 address of an ARRAY_REF, and call check_array_ref on it. */
6591 static void
6592 search_for_addr_array (tree t, location_t location)
6594 /* Check each ARRAY_REFs in the reference chain. */
6597 if (TREE_CODE (t) == ARRAY_REF)
6598 check_array_ref (location, t, true /*ignore_off_by_one*/);
6600 t = TREE_OPERAND (t, 0);
6602 while (handled_component_p (t));
6604 if (TREE_CODE (t) == MEM_REF
6605 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6606 && !TREE_NO_WARNING (t))
6608 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6609 tree low_bound, up_bound, el_sz;
6610 offset_int idx;
6611 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6612 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6613 || !TYPE_DOMAIN (TREE_TYPE (tem)))
6614 return;
6616 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6617 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6618 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6619 if (!low_bound
6620 || TREE_CODE (low_bound) != INTEGER_CST
6621 || !up_bound
6622 || TREE_CODE (up_bound) != INTEGER_CST
6623 || !el_sz
6624 || TREE_CODE (el_sz) != INTEGER_CST)
6625 return;
6627 idx = mem_ref_offset (t);
6628 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6629 if (idx < 0)
6631 if (dump_file && (dump_flags & TDF_DETAILS))
6633 fprintf (dump_file, "Array bound warning for ");
6634 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6635 fprintf (dump_file, "\n");
6637 warning_at (location, OPT_Warray_bounds,
6638 "array subscript is below array bounds");
6639 TREE_NO_WARNING (t) = 1;
6641 else if (idx > (wi::to_offset (up_bound)
6642 - wi::to_offset (low_bound) + 1))
6644 if (dump_file && (dump_flags & TDF_DETAILS))
6646 fprintf (dump_file, "Array bound warning for ");
6647 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6648 fprintf (dump_file, "\n");
6650 warning_at (location, OPT_Warray_bounds,
6651 "array subscript is above array bounds");
6652 TREE_NO_WARNING (t) = 1;
6657 /* walk_tree() callback that checks if *TP is
6658 an ARRAY_REF inside an ADDR_EXPR (in which an array
6659 subscript one outside the valid range is allowed). Call
6660 check_array_ref for each ARRAY_REF found. The location is
6661 passed in DATA. */
6663 static tree
6664 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6666 tree t = *tp;
6667 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6668 location_t location;
6670 if (EXPR_HAS_LOCATION (t))
6671 location = EXPR_LOCATION (t);
6672 else
6674 location_t *locp = (location_t *) wi->info;
6675 location = *locp;
6678 *walk_subtree = TRUE;
6680 if (TREE_CODE (t) == ARRAY_REF)
6681 check_array_ref (location, t, false /*ignore_off_by_one*/);
6683 else if (TREE_CODE (t) == ADDR_EXPR)
6685 search_for_addr_array (t, location);
6686 *walk_subtree = FALSE;
6689 return NULL_TREE;
6692 /* Walk over all statements of all reachable BBs and call check_array_bounds
6693 on them. */
6695 static void
6696 check_all_array_refs (void)
6698 basic_block bb;
6699 gimple_stmt_iterator si;
6701 FOR_EACH_BB_FN (bb, cfun)
6703 edge_iterator ei;
6704 edge e;
6705 bool executable = false;
6707 /* Skip blocks that were found to be unreachable. */
6708 FOR_EACH_EDGE (e, ei, bb->preds)
6709 executable |= !!(e->flags & EDGE_EXECUTABLE);
6710 if (!executable)
6711 continue;
6713 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6715 gimple *stmt = gsi_stmt (si);
6716 struct walk_stmt_info wi;
6717 if (!gimple_has_location (stmt)
6718 || is_gimple_debug (stmt))
6719 continue;
6721 memset (&wi, 0, sizeof (wi));
6723 location_t loc = gimple_location (stmt);
6724 wi.info = &loc;
6726 walk_gimple_op (gsi_stmt (si),
6727 check_array_bounds,
6728 &wi);
6733 /* Return true if all imm uses of VAR are either in STMT, or
6734 feed (optionally through a chain of single imm uses) GIMPLE_COND
6735 in basic block COND_BB. */
6737 static bool
6738 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6740 use_operand_p use_p, use2_p;
6741 imm_use_iterator iter;
6743 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6744 if (USE_STMT (use_p) != stmt)
6746 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6747 if (is_gimple_debug (use_stmt))
6748 continue;
6749 while (is_gimple_assign (use_stmt)
6750 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6751 && single_imm_use (gimple_assign_lhs (use_stmt),
6752 &use2_p, &use_stmt2))
6753 use_stmt = use_stmt2;
6754 if (gimple_code (use_stmt) != GIMPLE_COND
6755 || gimple_bb (use_stmt) != cond_bb)
6756 return false;
6758 return true;
6761 /* Handle
6762 _4 = x_3 & 31;
6763 if (_4 != 0)
6764 goto <bb 6>;
6765 else
6766 goto <bb 7>;
6767 <bb 6>:
6768 __builtin_unreachable ();
6769 <bb 7>:
6770 x_5 = ASSERT_EXPR <x_3, ...>;
6771 If x_3 has no other immediate uses (checked by caller),
6772 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6773 from the non-zero bitmask. */
6775 static void
6776 maybe_set_nonzero_bits (basic_block bb, tree var)
6778 edge e = single_pred_edge (bb);
6779 basic_block cond_bb = e->src;
6780 gimple *stmt = last_stmt (cond_bb);
6781 tree cst;
6783 if (stmt == NULL
6784 || gimple_code (stmt) != GIMPLE_COND
6785 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6786 ? EQ_EXPR : NE_EXPR)
6787 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6788 || !integer_zerop (gimple_cond_rhs (stmt)))
6789 return;
6791 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6792 if (!is_gimple_assign (stmt)
6793 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6794 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6795 return;
6796 if (gimple_assign_rhs1 (stmt) != var)
6798 gimple *stmt2;
6800 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6801 return;
6802 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6803 if (!gimple_assign_cast_p (stmt2)
6804 || gimple_assign_rhs1 (stmt2) != var
6805 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6806 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6807 != TYPE_PRECISION (TREE_TYPE (var))))
6808 return;
6810 cst = gimple_assign_rhs2 (stmt);
6811 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var), cst));
6814 /* Convert range assertion expressions into the implied copies and
6815 copy propagate away the copies. Doing the trivial copy propagation
6816 here avoids the need to run the full copy propagation pass after
6817 VRP.
6819 FIXME, this will eventually lead to copy propagation removing the
6820 names that had useful range information attached to them. For
6821 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6822 then N_i will have the range [3, +INF].
6824 However, by converting the assertion into the implied copy
6825 operation N_i = N_j, we will then copy-propagate N_j into the uses
6826 of N_i and lose the range information. We may want to hold on to
6827 ASSERT_EXPRs a little while longer as the ranges could be used in
6828 things like jump threading.
6830 The problem with keeping ASSERT_EXPRs around is that passes after
6831 VRP need to handle them appropriately.
6833 Another approach would be to make the range information a first
6834 class property of the SSA_NAME so that it can be queried from
6835 any pass. This is made somewhat more complex by the need for
6836 multiple ranges to be associated with one SSA_NAME. */
6838 static void
6839 remove_range_assertions (void)
6841 basic_block bb;
6842 gimple_stmt_iterator si;
6843 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
6844 a basic block preceeded by GIMPLE_COND branching to it and
6845 __builtin_trap, -1 if not yet checked, 0 otherwise. */
6846 int is_unreachable;
6848 /* Note that the BSI iterator bump happens at the bottom of the
6849 loop and no bump is necessary if we're removing the statement
6850 referenced by the current BSI. */
6851 FOR_EACH_BB_FN (bb, cfun)
6852 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
6854 gimple *stmt = gsi_stmt (si);
6855 gimple *use_stmt;
6857 if (is_gimple_assign (stmt)
6858 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
6860 tree lhs = gimple_assign_lhs (stmt);
6861 tree rhs = gimple_assign_rhs1 (stmt);
6862 tree var;
6863 use_operand_p use_p;
6864 imm_use_iterator iter;
6866 var = ASSERT_EXPR_VAR (rhs);
6867 gcc_assert (TREE_CODE (var) == SSA_NAME);
6869 if (!POINTER_TYPE_P (TREE_TYPE (lhs))
6870 && SSA_NAME_RANGE_INFO (lhs))
6872 if (is_unreachable == -1)
6874 is_unreachable = 0;
6875 if (single_pred_p (bb)
6876 && assert_unreachable_fallthru_edge_p
6877 (single_pred_edge (bb)))
6878 is_unreachable = 1;
6880 /* Handle
6881 if (x_7 >= 10 && x_7 < 20)
6882 __builtin_unreachable ();
6883 x_8 = ASSERT_EXPR <x_7, ...>;
6884 if the only uses of x_7 are in the ASSERT_EXPR and
6885 in the condition. In that case, we can copy the
6886 range info from x_8 computed in this pass also
6887 for x_7. */
6888 if (is_unreachable
6889 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
6890 single_pred (bb)))
6892 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
6893 SSA_NAME_RANGE_INFO (lhs)->get_min (),
6894 SSA_NAME_RANGE_INFO (lhs)->get_max ());
6895 maybe_set_nonzero_bits (bb, var);
6899 /* Propagate the RHS into every use of the LHS. */
6900 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
6901 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
6902 SET_USE (use_p, var);
6904 /* And finally, remove the copy, it is not needed. */
6905 gsi_remove (&si, true);
6906 release_defs (stmt);
6908 else
6910 if (!is_gimple_debug (gsi_stmt (si)))
6911 is_unreachable = 0;
6912 gsi_next (&si);
6918 /* Return true if STMT is interesting for VRP. */
6920 static bool
6921 stmt_interesting_for_vrp (gimple *stmt)
6923 if (gimple_code (stmt) == GIMPLE_PHI)
6925 tree res = gimple_phi_result (stmt);
6926 return (!virtual_operand_p (res)
6927 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
6928 || POINTER_TYPE_P (TREE_TYPE (res))));
6930 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
6932 tree lhs = gimple_get_lhs (stmt);
6934 /* In general, assignments with virtual operands are not useful
6935 for deriving ranges, with the obvious exception of calls to
6936 builtin functions. */
6937 if (lhs && TREE_CODE (lhs) == SSA_NAME
6938 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6939 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6940 && (is_gimple_call (stmt)
6941 || !gimple_vuse (stmt)))
6942 return true;
6943 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
6944 switch (gimple_call_internal_fn (stmt))
6946 case IFN_ADD_OVERFLOW:
6947 case IFN_SUB_OVERFLOW:
6948 case IFN_MUL_OVERFLOW:
6949 /* These internal calls return _Complex integer type,
6950 but are interesting to VRP nevertheless. */
6951 if (lhs && TREE_CODE (lhs) == SSA_NAME)
6952 return true;
6953 break;
6954 default:
6955 break;
6958 else if (gimple_code (stmt) == GIMPLE_COND
6959 || gimple_code (stmt) == GIMPLE_SWITCH)
6960 return true;
6962 return false;
6966 /* Initialize local data structures for VRP. */
6968 static void
6969 vrp_initialize (void)
6971 basic_block bb;
6973 values_propagated = false;
6974 num_vr_values = num_ssa_names;
6975 vr_value = XCNEWVEC (value_range *, num_vr_values);
6976 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
6977 bitmap_obstack_initialize (&vrp_equiv_obstack);
6979 FOR_EACH_BB_FN (bb, cfun)
6981 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6982 gsi_next (&si))
6984 gphi *phi = si.phi ();
6985 if (!stmt_interesting_for_vrp (phi))
6987 tree lhs = PHI_RESULT (phi);
6988 set_value_range_to_varying (get_value_range (lhs));
6989 prop_set_simulate_again (phi, false);
6991 else
6992 prop_set_simulate_again (phi, true);
6995 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
6996 gsi_next (&si))
6998 gimple *stmt = gsi_stmt (si);
7000 /* If the statement is a control insn, then we do not
7001 want to avoid simulating the statement once. Failure
7002 to do so means that those edges will never get added. */
7003 if (stmt_ends_bb_p (stmt))
7004 prop_set_simulate_again (stmt, true);
7005 else if (!stmt_interesting_for_vrp (stmt))
7007 ssa_op_iter i;
7008 tree def;
7009 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
7010 set_value_range_to_varying (get_value_range (def));
7011 prop_set_simulate_again (stmt, false);
7013 else
7014 prop_set_simulate_again (stmt, true);
7019 /* Return the singleton value-range for NAME or NAME. */
7021 static inline tree
7022 vrp_valueize (tree name)
7024 if (TREE_CODE (name) == SSA_NAME)
7026 value_range *vr = get_value_range (name);
7027 if (vr->type == VR_RANGE
7028 && (vr->min == vr->max
7029 || operand_equal_p (vr->min, vr->max, 0)))
7030 return vr->min;
7032 return name;
7035 /* Return the singleton value-range for NAME if that is a constant
7036 but signal to not follow SSA edges. */
7038 static inline tree
7039 vrp_valueize_1 (tree name)
7041 if (TREE_CODE (name) == SSA_NAME)
7043 /* If the definition may be simulated again we cannot follow
7044 this SSA edge as the SSA propagator does not necessarily
7045 re-visit the use. */
7046 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7047 if (!gimple_nop_p (def_stmt)
7048 && prop_simulate_again_p (def_stmt))
7049 return NULL_TREE;
7050 value_range *vr = get_value_range (name);
7051 if (range_int_cst_singleton_p (vr))
7052 return vr->min;
7054 return name;
7057 /* Visit assignment STMT. If it produces an interesting range, record
7058 the SSA name in *OUTPUT_P. */
7060 static enum ssa_prop_result
7061 vrp_visit_assignment_or_call (gimple *stmt, tree *output_p)
7063 tree def, lhs;
7064 ssa_op_iter iter;
7065 enum gimple_code code = gimple_code (stmt);
7066 lhs = gimple_get_lhs (stmt);
7068 /* We only keep track of ranges in integral and pointer types. */
7069 if (TREE_CODE (lhs) == SSA_NAME
7070 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7071 /* It is valid to have NULL MIN/MAX values on a type. See
7072 build_range_type. */
7073 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7074 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7075 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7077 value_range new_vr = VR_INITIALIZER;
7079 /* Try folding the statement to a constant first. */
7080 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7081 vrp_valueize_1);
7082 if (tem && is_gimple_min_invariant (tem))
7083 set_value_range_to_value (&new_vr, tem, NULL);
7084 /* Then dispatch to value-range extracting functions. */
7085 else if (code == GIMPLE_CALL)
7086 extract_range_basic (&new_vr, stmt);
7087 else
7088 extract_range_from_assignment (&new_vr, as_a <gassign *> (stmt));
7090 if (update_value_range (lhs, &new_vr))
7092 *output_p = lhs;
7094 if (dump_file && (dump_flags & TDF_DETAILS))
7096 fprintf (dump_file, "Found new range for ");
7097 print_generic_expr (dump_file, lhs, 0);
7098 fprintf (dump_file, ": ");
7099 dump_value_range (dump_file, &new_vr);
7100 fprintf (dump_file, "\n");
7103 if (new_vr.type == VR_VARYING)
7104 return SSA_PROP_VARYING;
7106 return SSA_PROP_INTERESTING;
7109 return SSA_PROP_NOT_INTERESTING;
7111 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7112 switch (gimple_call_internal_fn (stmt))
7114 case IFN_ADD_OVERFLOW:
7115 case IFN_SUB_OVERFLOW:
7116 case IFN_MUL_OVERFLOW:
7117 /* These internal calls return _Complex integer type,
7118 which VRP does not track, but the immediate uses
7119 thereof might be interesting. */
7120 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7122 imm_use_iterator iter;
7123 use_operand_p use_p;
7124 enum ssa_prop_result res = SSA_PROP_VARYING;
7126 set_value_range_to_varying (get_value_range (lhs));
7128 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
7130 gimple *use_stmt = USE_STMT (use_p);
7131 if (!is_gimple_assign (use_stmt))
7132 continue;
7133 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
7134 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
7135 continue;
7136 tree rhs1 = gimple_assign_rhs1 (use_stmt);
7137 tree use_lhs = gimple_assign_lhs (use_stmt);
7138 if (TREE_CODE (rhs1) != rhs_code
7139 || TREE_OPERAND (rhs1, 0) != lhs
7140 || TREE_CODE (use_lhs) != SSA_NAME
7141 || !stmt_interesting_for_vrp (use_stmt)
7142 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
7143 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
7144 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
7145 continue;
7147 /* If there is a change in the value range for any of the
7148 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
7149 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
7150 or IMAGPART_EXPR immediate uses, but none of them have
7151 a change in their value ranges, return
7152 SSA_PROP_NOT_INTERESTING. If there are no
7153 {REAL,IMAG}PART_EXPR uses at all,
7154 return SSA_PROP_VARYING. */
7155 value_range new_vr = VR_INITIALIZER;
7156 extract_range_basic (&new_vr, use_stmt);
7157 value_range *old_vr = get_value_range (use_lhs);
7158 if (old_vr->type != new_vr.type
7159 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
7160 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
7161 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
7162 res = SSA_PROP_INTERESTING;
7163 else
7164 res = SSA_PROP_NOT_INTERESTING;
7165 BITMAP_FREE (new_vr.equiv);
7166 if (res == SSA_PROP_INTERESTING)
7168 *output_p = lhs;
7169 return res;
7173 return res;
7175 break;
7176 default:
7177 break;
7180 /* Every other statement produces no useful ranges. */
7181 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
7182 set_value_range_to_varying (get_value_range (def));
7184 return SSA_PROP_VARYING;
7187 /* Helper that gets the value range of the SSA_NAME with version I
7188 or a symbolic range containing the SSA_NAME only if the value range
7189 is varying or undefined. */
7191 static inline value_range
7192 get_vr_for_comparison (int i)
7194 value_range vr = *get_value_range (ssa_name (i));
7196 /* If name N_i does not have a valid range, use N_i as its own
7197 range. This allows us to compare against names that may
7198 have N_i in their ranges. */
7199 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7201 vr.type = VR_RANGE;
7202 vr.min = ssa_name (i);
7203 vr.max = ssa_name (i);
7206 return vr;
7209 /* Compare all the value ranges for names equivalent to VAR with VAL
7210 using comparison code COMP. Return the same value returned by
7211 compare_range_with_value, including the setting of
7212 *STRICT_OVERFLOW_P. */
7214 static tree
7215 compare_name_with_value (enum tree_code comp, tree var, tree val,
7216 bool *strict_overflow_p, bool use_equiv_p)
7218 bitmap_iterator bi;
7219 unsigned i;
7220 bitmap e;
7221 tree retval, t;
7222 int used_strict_overflow;
7223 bool sop;
7224 value_range equiv_vr;
7226 /* Get the set of equivalences for VAR. */
7227 e = get_value_range (var)->equiv;
7229 /* Start at -1. Set it to 0 if we do a comparison without relying
7230 on overflow, or 1 if all comparisons rely on overflow. */
7231 used_strict_overflow = -1;
7233 /* Compare vars' value range with val. */
7234 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7235 sop = false;
7236 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7237 if (retval)
7238 used_strict_overflow = sop ? 1 : 0;
7240 /* If the equiv set is empty we have done all work we need to do. */
7241 if (e == NULL)
7243 if (retval
7244 && used_strict_overflow > 0)
7245 *strict_overflow_p = true;
7246 return retval;
7249 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7251 if (! use_equiv_p
7252 && ! SSA_NAME_IS_DEFAULT_DEF (ssa_name (i))
7253 && prop_simulate_again_p (SSA_NAME_DEF_STMT (ssa_name (i))))
7254 continue;
7256 equiv_vr = get_vr_for_comparison (i);
7257 sop = false;
7258 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7259 if (t)
7261 /* If we get different answers from different members
7262 of the equivalence set this check must be in a dead
7263 code region. Folding it to a trap representation
7264 would be correct here. For now just return don't-know. */
7265 if (retval != NULL
7266 && t != retval)
7268 retval = NULL_TREE;
7269 break;
7271 retval = t;
7273 if (!sop)
7274 used_strict_overflow = 0;
7275 else if (used_strict_overflow < 0)
7276 used_strict_overflow = 1;
7280 if (retval
7281 && used_strict_overflow > 0)
7282 *strict_overflow_p = true;
7284 return retval;
7288 /* Given a comparison code COMP and names N1 and N2, compare all the
7289 ranges equivalent to N1 against all the ranges equivalent to N2
7290 to determine the value of N1 COMP N2. Return the same value
7291 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7292 whether we relied on an overflow infinity in the comparison. */
7295 static tree
7296 compare_names (enum tree_code comp, tree n1, tree n2,
7297 bool *strict_overflow_p)
7299 tree t, retval;
7300 bitmap e1, e2;
7301 bitmap_iterator bi1, bi2;
7302 unsigned i1, i2;
7303 int used_strict_overflow;
7304 static bitmap_obstack *s_obstack = NULL;
7305 static bitmap s_e1 = NULL, s_e2 = NULL;
7307 /* Compare the ranges of every name equivalent to N1 against the
7308 ranges of every name equivalent to N2. */
7309 e1 = get_value_range (n1)->equiv;
7310 e2 = get_value_range (n2)->equiv;
7312 /* Use the fake bitmaps if e1 or e2 are not available. */
7313 if (s_obstack == NULL)
7315 s_obstack = XNEW (bitmap_obstack);
7316 bitmap_obstack_initialize (s_obstack);
7317 s_e1 = BITMAP_ALLOC (s_obstack);
7318 s_e2 = BITMAP_ALLOC (s_obstack);
7320 if (e1 == NULL)
7321 e1 = s_e1;
7322 if (e2 == NULL)
7323 e2 = s_e2;
7325 /* Add N1 and N2 to their own set of equivalences to avoid
7326 duplicating the body of the loop just to check N1 and N2
7327 ranges. */
7328 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7329 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7331 /* If the equivalence sets have a common intersection, then the two
7332 names can be compared without checking their ranges. */
7333 if (bitmap_intersect_p (e1, e2))
7335 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7336 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7338 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7339 ? boolean_true_node
7340 : boolean_false_node;
7343 /* Start at -1. Set it to 0 if we do a comparison without relying
7344 on overflow, or 1 if all comparisons rely on overflow. */
7345 used_strict_overflow = -1;
7347 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7348 N2 to their own set of equivalences to avoid duplicating the body
7349 of the loop just to check N1 and N2 ranges. */
7350 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7352 value_range vr1 = get_vr_for_comparison (i1);
7354 t = retval = NULL_TREE;
7355 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7357 bool sop = false;
7359 value_range vr2 = get_vr_for_comparison (i2);
7361 t = compare_ranges (comp, &vr1, &vr2, &sop);
7362 if (t)
7364 /* If we get different answers from different members
7365 of the equivalence set this check must be in a dead
7366 code region. Folding it to a trap representation
7367 would be correct here. For now just return don't-know. */
7368 if (retval != NULL
7369 && t != retval)
7371 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7372 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7373 return NULL_TREE;
7375 retval = t;
7377 if (!sop)
7378 used_strict_overflow = 0;
7379 else if (used_strict_overflow < 0)
7380 used_strict_overflow = 1;
7384 if (retval)
7386 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7387 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7388 if (used_strict_overflow > 0)
7389 *strict_overflow_p = true;
7390 return retval;
7394 /* None of the equivalent ranges are useful in computing this
7395 comparison. */
7396 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7397 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7398 return NULL_TREE;
7401 /* Helper function for vrp_evaluate_conditional_warnv & other
7402 optimizers. */
7404 static tree
7405 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7406 tree op0, tree op1,
7407 bool * strict_overflow_p)
7409 value_range *vr0, *vr1;
7411 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7412 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7414 tree res = NULL_TREE;
7415 if (vr0 && vr1)
7416 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7417 if (!res && vr0)
7418 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7419 if (!res && vr1)
7420 res = (compare_range_with_value
7421 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7422 return res;
7425 /* Helper function for vrp_evaluate_conditional_warnv. */
7427 static tree
7428 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7429 tree op1, bool use_equiv_p,
7430 bool *strict_overflow_p, bool *only_ranges)
7432 tree ret;
7433 if (only_ranges)
7434 *only_ranges = true;
7436 /* We only deal with integral and pointer types. */
7437 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7438 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7439 return NULL_TREE;
7441 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7442 (code, op0, op1, strict_overflow_p)))
7443 return ret;
7444 if (only_ranges)
7445 *only_ranges = false;
7446 /* Do not use compare_names during propagation, it's quadratic. */
7447 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7448 && use_equiv_p)
7449 return compare_names (code, op0, op1, strict_overflow_p);
7450 else if (TREE_CODE (op0) == SSA_NAME)
7451 return compare_name_with_value (code, op0, op1,
7452 strict_overflow_p, use_equiv_p);
7453 else if (TREE_CODE (op1) == SSA_NAME)
7454 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7455 strict_overflow_p, use_equiv_p);
7456 return NULL_TREE;
7459 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7460 information. Return NULL if the conditional can not be evaluated.
7461 The ranges of all the names equivalent with the operands in COND
7462 will be used when trying to compute the value. If the result is
7463 based on undefined signed overflow, issue a warning if
7464 appropriate. */
7466 static tree
7467 vrp_evaluate_conditional (tree_code code, tree op0, tree op1, gimple *stmt)
7469 bool sop;
7470 tree ret;
7471 bool only_ranges;
7473 /* Some passes and foldings leak constants with overflow flag set
7474 into the IL. Avoid doing wrong things with these and bail out. */
7475 if ((TREE_CODE (op0) == INTEGER_CST
7476 && TREE_OVERFLOW (op0))
7477 || (TREE_CODE (op1) == INTEGER_CST
7478 && TREE_OVERFLOW (op1)))
7479 return NULL_TREE;
7481 sop = false;
7482 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7483 &only_ranges);
7485 if (ret && sop)
7487 enum warn_strict_overflow_code wc;
7488 const char* warnmsg;
7490 if (is_gimple_min_invariant (ret))
7492 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7493 warnmsg = G_("assuming signed overflow does not occur when "
7494 "simplifying conditional to constant");
7496 else
7498 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7499 warnmsg = G_("assuming signed overflow does not occur when "
7500 "simplifying conditional");
7503 if (issue_strict_overflow_warning (wc))
7505 location_t location;
7507 if (!gimple_has_location (stmt))
7508 location = input_location;
7509 else
7510 location = gimple_location (stmt);
7511 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7515 if (warn_type_limits
7516 && ret && only_ranges
7517 && TREE_CODE_CLASS (code) == tcc_comparison
7518 && TREE_CODE (op0) == SSA_NAME)
7520 /* If the comparison is being folded and the operand on the LHS
7521 is being compared against a constant value that is outside of
7522 the natural range of OP0's type, then the predicate will
7523 always fold regardless of the value of OP0. If -Wtype-limits
7524 was specified, emit a warning. */
7525 tree type = TREE_TYPE (op0);
7526 value_range *vr0 = get_value_range (op0);
7528 if (vr0->type == VR_RANGE
7529 && INTEGRAL_TYPE_P (type)
7530 && vrp_val_is_min (vr0->min)
7531 && vrp_val_is_max (vr0->max)
7532 && is_gimple_min_invariant (op1))
7534 location_t location;
7536 if (!gimple_has_location (stmt))
7537 location = input_location;
7538 else
7539 location = gimple_location (stmt);
7541 warning_at (location, OPT_Wtype_limits,
7542 integer_zerop (ret)
7543 ? G_("comparison always false "
7544 "due to limited range of data type")
7545 : G_("comparison always true "
7546 "due to limited range of data type"));
7550 return ret;
7554 /* Visit conditional statement STMT. If we can determine which edge
7555 will be taken out of STMT's basic block, record it in
7556 *TAKEN_EDGE_P and return SSA_PROP_INTERESTING. Otherwise, return
7557 SSA_PROP_VARYING. */
7559 static enum ssa_prop_result
7560 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7562 tree val;
7563 bool sop;
7565 *taken_edge_p = NULL;
7567 if (dump_file && (dump_flags & TDF_DETAILS))
7569 tree use;
7570 ssa_op_iter i;
7572 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7573 print_gimple_stmt (dump_file, stmt, 0, 0);
7574 fprintf (dump_file, "\nWith known ranges\n");
7576 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7578 fprintf (dump_file, "\t");
7579 print_generic_expr (dump_file, use, 0);
7580 fprintf (dump_file, ": ");
7581 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7584 fprintf (dump_file, "\n");
7587 /* Compute the value of the predicate COND by checking the known
7588 ranges of each of its operands.
7590 Note that we cannot evaluate all the equivalent ranges here
7591 because those ranges may not yet be final and with the current
7592 propagation strategy, we cannot determine when the value ranges
7593 of the names in the equivalence set have changed.
7595 For instance, given the following code fragment
7597 i_5 = PHI <8, i_13>
7599 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7600 if (i_14 == 1)
7603 Assume that on the first visit to i_14, i_5 has the temporary
7604 range [8, 8] because the second argument to the PHI function is
7605 not yet executable. We derive the range ~[0, 0] for i_14 and the
7606 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7607 the first time, since i_14 is equivalent to the range [8, 8], we
7608 determine that the predicate is always false.
7610 On the next round of propagation, i_13 is determined to be
7611 VARYING, which causes i_5 to drop down to VARYING. So, another
7612 visit to i_14 is scheduled. In this second visit, we compute the
7613 exact same range and equivalence set for i_14, namely ~[0, 0] and
7614 { i_5 }. But we did not have the previous range for i_5
7615 registered, so vrp_visit_assignment thinks that the range for
7616 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7617 is not visited again, which stops propagation from visiting
7618 statements in the THEN clause of that if().
7620 To properly fix this we would need to keep the previous range
7621 value for the names in the equivalence set. This way we would've
7622 discovered that from one visit to the other i_5 changed from
7623 range [8, 8] to VR_VARYING.
7625 However, fixing this apparent limitation may not be worth the
7626 additional checking. Testing on several code bases (GCC, DLV,
7627 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7628 4 more predicates folded in SPEC. */
7629 sop = false;
7631 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7632 gimple_cond_lhs (stmt),
7633 gimple_cond_rhs (stmt),
7634 false, &sop, NULL);
7635 if (val)
7637 if (!sop)
7638 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7639 else
7641 if (dump_file && (dump_flags & TDF_DETAILS))
7642 fprintf (dump_file,
7643 "\nIgnoring predicate evaluation because "
7644 "it assumes that signed overflow is undefined");
7645 val = NULL_TREE;
7649 if (dump_file && (dump_flags & TDF_DETAILS))
7651 fprintf (dump_file, "\nPredicate evaluates to: ");
7652 if (val == NULL_TREE)
7653 fprintf (dump_file, "DON'T KNOW\n");
7654 else
7655 print_generic_stmt (dump_file, val, 0);
7658 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
7661 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7662 that includes the value VAL. The search is restricted to the range
7663 [START_IDX, n - 1] where n is the size of VEC.
7665 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7666 returned.
7668 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7669 it is placed in IDX and false is returned.
7671 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7672 returned. */
7674 static bool
7675 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7677 size_t n = gimple_switch_num_labels (stmt);
7678 size_t low, high;
7680 /* Find case label for minimum of the value range or the next one.
7681 At each iteration we are searching in [low, high - 1]. */
7683 for (low = start_idx, high = n; high != low; )
7685 tree t;
7686 int cmp;
7687 /* Note that i != high, so we never ask for n. */
7688 size_t i = (high + low) / 2;
7689 t = gimple_switch_label (stmt, i);
7691 /* Cache the result of comparing CASE_LOW and val. */
7692 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7694 if (cmp == 0)
7696 /* Ranges cannot be empty. */
7697 *idx = i;
7698 return true;
7700 else if (cmp > 0)
7701 high = i;
7702 else
7704 low = i + 1;
7705 if (CASE_HIGH (t) != NULL
7706 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7708 *idx = i;
7709 return true;
7714 *idx = high;
7715 return false;
7718 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7719 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7720 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7721 then MAX_IDX < MIN_IDX.
7722 Returns true if the default label is not needed. */
7724 static bool
7725 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7726 size_t *max_idx)
7728 size_t i, j;
7729 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7730 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7732 if (i == j
7733 && min_take_default
7734 && max_take_default)
7736 /* Only the default case label reached.
7737 Return an empty range. */
7738 *min_idx = 1;
7739 *max_idx = 0;
7740 return false;
7742 else
7744 bool take_default = min_take_default || max_take_default;
7745 tree low, high;
7746 size_t k;
7748 if (max_take_default)
7749 j--;
7751 /* If the case label range is continuous, we do not need
7752 the default case label. Verify that. */
7753 high = CASE_LOW (gimple_switch_label (stmt, i));
7754 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7755 high = CASE_HIGH (gimple_switch_label (stmt, i));
7756 for (k = i + 1; k <= j; ++k)
7758 low = CASE_LOW (gimple_switch_label (stmt, k));
7759 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7761 take_default = true;
7762 break;
7764 high = low;
7765 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7766 high = CASE_HIGH (gimple_switch_label (stmt, k));
7769 *min_idx = i;
7770 *max_idx = j;
7771 return !take_default;
7775 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7776 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7777 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7778 Returns true if the default label is not needed. */
7780 static bool
7781 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7782 size_t *max_idx1, size_t *min_idx2,
7783 size_t *max_idx2)
7785 size_t i, j, k, l;
7786 unsigned int n = gimple_switch_num_labels (stmt);
7787 bool take_default;
7788 tree case_low, case_high;
7789 tree min = vr->min, max = vr->max;
7791 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7793 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7795 /* Set second range to emtpy. */
7796 *min_idx2 = 1;
7797 *max_idx2 = 0;
7799 if (vr->type == VR_RANGE)
7801 *min_idx1 = i;
7802 *max_idx1 = j;
7803 return !take_default;
7806 /* Set first range to all case labels. */
7807 *min_idx1 = 1;
7808 *max_idx1 = n - 1;
7810 if (i > j)
7811 return false;
7813 /* Make sure all the values of case labels [i , j] are contained in
7814 range [MIN, MAX]. */
7815 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7816 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7817 if (tree_int_cst_compare (case_low, min) < 0)
7818 i += 1;
7819 if (case_high != NULL_TREE
7820 && tree_int_cst_compare (max, case_high) < 0)
7821 j -= 1;
7823 if (i > j)
7824 return false;
7826 /* If the range spans case labels [i, j], the corresponding anti-range spans
7827 the labels [1, i - 1] and [j + 1, n - 1]. */
7828 k = j + 1;
7829 l = n - 1;
7830 if (k > l)
7832 k = 1;
7833 l = 0;
7836 j = i - 1;
7837 i = 1;
7838 if (i > j)
7840 i = k;
7841 j = l;
7842 k = 1;
7843 l = 0;
7846 *min_idx1 = i;
7847 *max_idx1 = j;
7848 *min_idx2 = k;
7849 *max_idx2 = l;
7850 return false;
7853 /* Visit switch statement STMT. If we can determine which edge
7854 will be taken out of STMT's basic block, record it in
7855 *TAKEN_EDGE_P and return SSA_PROP_INTERESTING. Otherwise, return
7856 SSA_PROP_VARYING. */
7858 static enum ssa_prop_result
7859 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7861 tree op, val;
7862 value_range *vr;
7863 size_t i = 0, j = 0, k, l;
7864 bool take_default;
7866 *taken_edge_p = NULL;
7867 op = gimple_switch_index (stmt);
7868 if (TREE_CODE (op) != SSA_NAME)
7869 return SSA_PROP_VARYING;
7871 vr = get_value_range (op);
7872 if (dump_file && (dump_flags & TDF_DETAILS))
7874 fprintf (dump_file, "\nVisiting switch expression with operand ");
7875 print_generic_expr (dump_file, op, 0);
7876 fprintf (dump_file, " with known range ");
7877 dump_value_range (dump_file, vr);
7878 fprintf (dump_file, "\n");
7881 if ((vr->type != VR_RANGE
7882 && vr->type != VR_ANTI_RANGE)
7883 || symbolic_range_p (vr))
7884 return SSA_PROP_VARYING;
7886 /* Find the single edge that is taken from the switch expression. */
7887 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
7889 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
7890 label */
7891 if (j < i)
7893 gcc_assert (take_default);
7894 val = gimple_switch_default_label (stmt);
7896 else
7898 /* Check if labels with index i to j and maybe the default label
7899 are all reaching the same label. */
7901 val = gimple_switch_label (stmt, i);
7902 if (take_default
7903 && CASE_LABEL (gimple_switch_default_label (stmt))
7904 != CASE_LABEL (val))
7906 if (dump_file && (dump_flags & TDF_DETAILS))
7907 fprintf (dump_file, " not a single destination for this "
7908 "range\n");
7909 return SSA_PROP_VARYING;
7911 for (++i; i <= j; ++i)
7913 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
7915 if (dump_file && (dump_flags & TDF_DETAILS))
7916 fprintf (dump_file, " not a single destination for this "
7917 "range\n");
7918 return SSA_PROP_VARYING;
7921 for (; k <= l; ++k)
7923 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
7925 if (dump_file && (dump_flags & TDF_DETAILS))
7926 fprintf (dump_file, " not a single destination for this "
7927 "range\n");
7928 return SSA_PROP_VARYING;
7933 *taken_edge_p = find_edge (gimple_bb (stmt),
7934 label_to_block (CASE_LABEL (val)));
7936 if (dump_file && (dump_flags & TDF_DETAILS))
7938 fprintf (dump_file, " will take edge to ");
7939 print_generic_stmt (dump_file, CASE_LABEL (val), 0);
7942 return SSA_PROP_INTERESTING;
7946 /* Evaluate statement STMT. If the statement produces a useful range,
7947 return SSA_PROP_INTERESTING and record the SSA name with the
7948 interesting range into *OUTPUT_P.
7950 If STMT is a conditional branch and we can determine its truth
7951 value, the taken edge is recorded in *TAKEN_EDGE_P.
7953 If STMT produces a varying value, return SSA_PROP_VARYING. */
7955 static enum ssa_prop_result
7956 vrp_visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
7958 tree def;
7959 ssa_op_iter iter;
7961 if (dump_file && (dump_flags & TDF_DETAILS))
7963 fprintf (dump_file, "\nVisiting statement:\n");
7964 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
7967 if (!stmt_interesting_for_vrp (stmt))
7968 gcc_assert (stmt_ends_bb_p (stmt));
7969 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7970 return vrp_visit_assignment_or_call (stmt, output_p);
7971 else if (gimple_code (stmt) == GIMPLE_COND)
7972 return vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
7973 else if (gimple_code (stmt) == GIMPLE_SWITCH)
7974 return vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
7976 /* All other statements produce nothing of interest for VRP, so mark
7977 their outputs varying and prevent further simulation. */
7978 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
7979 set_value_range_to_varying (get_value_range (def));
7981 return SSA_PROP_VARYING;
7984 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
7985 { VR1TYPE, VR0MIN, VR0MAX } and store the result
7986 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
7987 possible such range. The resulting range is not canonicalized. */
7989 static void
7990 union_ranges (enum value_range_type *vr0type,
7991 tree *vr0min, tree *vr0max,
7992 enum value_range_type vr1type,
7993 tree vr1min, tree vr1max)
7995 bool mineq = operand_equal_p (*vr0min, vr1min, 0);
7996 bool maxeq = operand_equal_p (*vr0max, vr1max, 0);
7998 /* [] is vr0, () is vr1 in the following classification comments. */
7999 if (mineq && maxeq)
8001 /* [( )] */
8002 if (*vr0type == vr1type)
8003 /* Nothing to do for equal ranges. */
8005 else if ((*vr0type == VR_RANGE
8006 && vr1type == VR_ANTI_RANGE)
8007 || (*vr0type == VR_ANTI_RANGE
8008 && vr1type == VR_RANGE))
8010 /* For anti-range with range union the result is varying. */
8011 goto give_up;
8013 else
8014 gcc_unreachable ();
8016 else if (operand_less_p (*vr0max, vr1min) == 1
8017 || operand_less_p (vr1max, *vr0min) == 1)
8019 /* [ ] ( ) or ( ) [ ]
8020 If the ranges have an empty intersection, result of the union
8021 operation is the anti-range or if both are anti-ranges
8022 it covers all. */
8023 if (*vr0type == VR_ANTI_RANGE
8024 && vr1type == VR_ANTI_RANGE)
8025 goto give_up;
8026 else if (*vr0type == VR_ANTI_RANGE
8027 && vr1type == VR_RANGE)
8029 else if (*vr0type == VR_RANGE
8030 && vr1type == VR_ANTI_RANGE)
8032 *vr0type = vr1type;
8033 *vr0min = vr1min;
8034 *vr0max = vr1max;
8036 else if (*vr0type == VR_RANGE
8037 && vr1type == VR_RANGE)
8039 /* The result is the convex hull of both ranges. */
8040 if (operand_less_p (*vr0max, vr1min) == 1)
8042 /* If the result can be an anti-range, create one. */
8043 if (TREE_CODE (*vr0max) == INTEGER_CST
8044 && TREE_CODE (vr1min) == INTEGER_CST
8045 && vrp_val_is_min (*vr0min)
8046 && vrp_val_is_max (vr1max))
8048 tree min = int_const_binop (PLUS_EXPR,
8049 *vr0max,
8050 build_int_cst (TREE_TYPE (*vr0max), 1));
8051 tree max = int_const_binop (MINUS_EXPR,
8052 vr1min,
8053 build_int_cst (TREE_TYPE (vr1min), 1));
8054 if (!operand_less_p (max, min))
8056 *vr0type = VR_ANTI_RANGE;
8057 *vr0min = min;
8058 *vr0max = max;
8060 else
8061 *vr0max = vr1max;
8063 else
8064 *vr0max = vr1max;
8066 else
8068 /* If the result can be an anti-range, create one. */
8069 if (TREE_CODE (vr1max) == INTEGER_CST
8070 && TREE_CODE (*vr0min) == INTEGER_CST
8071 && vrp_val_is_min (vr1min)
8072 && vrp_val_is_max (*vr0max))
8074 tree min = int_const_binop (PLUS_EXPR,
8075 vr1max,
8076 build_int_cst (TREE_TYPE (vr1max), 1));
8077 tree max = int_const_binop (MINUS_EXPR,
8078 *vr0min,
8079 build_int_cst (TREE_TYPE (*vr0min), 1));
8080 if (!operand_less_p (max, min))
8082 *vr0type = VR_ANTI_RANGE;
8083 *vr0min = min;
8084 *vr0max = max;
8086 else
8087 *vr0min = vr1min;
8089 else
8090 *vr0min = vr1min;
8093 else
8094 gcc_unreachable ();
8096 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8097 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8099 /* [ ( ) ] or [( ) ] or [ ( )] */
8100 if (*vr0type == VR_RANGE
8101 && vr1type == VR_RANGE)
8103 else if (*vr0type == VR_ANTI_RANGE
8104 && vr1type == VR_ANTI_RANGE)
8106 *vr0type = vr1type;
8107 *vr0min = vr1min;
8108 *vr0max = vr1max;
8110 else if (*vr0type == VR_ANTI_RANGE
8111 && vr1type == VR_RANGE)
8113 /* Arbitrarily choose the right or left gap. */
8114 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8115 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8116 build_int_cst (TREE_TYPE (vr1min), 1));
8117 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8118 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8119 build_int_cst (TREE_TYPE (vr1max), 1));
8120 else
8121 goto give_up;
8123 else if (*vr0type == VR_RANGE
8124 && vr1type == VR_ANTI_RANGE)
8125 /* The result covers everything. */
8126 goto give_up;
8127 else
8128 gcc_unreachable ();
8130 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8131 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8133 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8134 if (*vr0type == VR_RANGE
8135 && vr1type == VR_RANGE)
8137 *vr0type = vr1type;
8138 *vr0min = vr1min;
8139 *vr0max = vr1max;
8141 else if (*vr0type == VR_ANTI_RANGE
8142 && vr1type == VR_ANTI_RANGE)
8144 else if (*vr0type == VR_RANGE
8145 && vr1type == VR_ANTI_RANGE)
8147 *vr0type = VR_ANTI_RANGE;
8148 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8150 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8151 build_int_cst (TREE_TYPE (*vr0min), 1));
8152 *vr0min = vr1min;
8154 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8156 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8157 build_int_cst (TREE_TYPE (*vr0max), 1));
8158 *vr0max = vr1max;
8160 else
8161 goto give_up;
8163 else if (*vr0type == VR_ANTI_RANGE
8164 && vr1type == VR_RANGE)
8165 /* The result covers everything. */
8166 goto give_up;
8167 else
8168 gcc_unreachable ();
8170 else if ((operand_less_p (vr1min, *vr0max) == 1
8171 || operand_equal_p (vr1min, *vr0max, 0))
8172 && operand_less_p (*vr0min, vr1min) == 1
8173 && operand_less_p (*vr0max, vr1max) == 1)
8175 /* [ ( ] ) or [ ]( ) */
8176 if (*vr0type == VR_RANGE
8177 && vr1type == VR_RANGE)
8178 *vr0max = vr1max;
8179 else if (*vr0type == VR_ANTI_RANGE
8180 && vr1type == VR_ANTI_RANGE)
8181 *vr0min = vr1min;
8182 else if (*vr0type == VR_ANTI_RANGE
8183 && vr1type == VR_RANGE)
8185 if (TREE_CODE (vr1min) == INTEGER_CST)
8186 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8187 build_int_cst (TREE_TYPE (vr1min), 1));
8188 else
8189 goto give_up;
8191 else if (*vr0type == VR_RANGE
8192 && vr1type == VR_ANTI_RANGE)
8194 if (TREE_CODE (*vr0max) == INTEGER_CST)
8196 *vr0type = vr1type;
8197 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8198 build_int_cst (TREE_TYPE (*vr0max), 1));
8199 *vr0max = vr1max;
8201 else
8202 goto give_up;
8204 else
8205 gcc_unreachable ();
8207 else if ((operand_less_p (*vr0min, vr1max) == 1
8208 || operand_equal_p (*vr0min, vr1max, 0))
8209 && operand_less_p (vr1min, *vr0min) == 1
8210 && operand_less_p (vr1max, *vr0max) == 1)
8212 /* ( [ ) ] or ( )[ ] */
8213 if (*vr0type == VR_RANGE
8214 && vr1type == VR_RANGE)
8215 *vr0min = vr1min;
8216 else if (*vr0type == VR_ANTI_RANGE
8217 && vr1type == VR_ANTI_RANGE)
8218 *vr0max = vr1max;
8219 else if (*vr0type == VR_ANTI_RANGE
8220 && vr1type == VR_RANGE)
8222 if (TREE_CODE (vr1max) == INTEGER_CST)
8223 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8224 build_int_cst (TREE_TYPE (vr1max), 1));
8225 else
8226 goto give_up;
8228 else if (*vr0type == VR_RANGE
8229 && vr1type == VR_ANTI_RANGE)
8231 if (TREE_CODE (*vr0min) == INTEGER_CST)
8233 *vr0type = vr1type;
8234 *vr0min = vr1min;
8235 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8236 build_int_cst (TREE_TYPE (*vr0min), 1));
8238 else
8239 goto give_up;
8241 else
8242 gcc_unreachable ();
8244 else
8245 goto give_up;
8247 return;
8249 give_up:
8250 *vr0type = VR_VARYING;
8251 *vr0min = NULL_TREE;
8252 *vr0max = NULL_TREE;
8255 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8256 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8257 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8258 possible such range. The resulting range is not canonicalized. */
8260 static void
8261 intersect_ranges (enum value_range_type *vr0type,
8262 tree *vr0min, tree *vr0max,
8263 enum value_range_type vr1type,
8264 tree vr1min, tree vr1max)
8266 bool mineq = operand_equal_p (*vr0min, vr1min, 0);
8267 bool maxeq = operand_equal_p (*vr0max, vr1max, 0);
8269 /* [] is vr0, () is vr1 in the following classification comments. */
8270 if (mineq && maxeq)
8272 /* [( )] */
8273 if (*vr0type == vr1type)
8274 /* Nothing to do for equal ranges. */
8276 else if ((*vr0type == VR_RANGE
8277 && vr1type == VR_ANTI_RANGE)
8278 || (*vr0type == VR_ANTI_RANGE
8279 && vr1type == VR_RANGE))
8281 /* For anti-range with range intersection the result is empty. */
8282 *vr0type = VR_UNDEFINED;
8283 *vr0min = NULL_TREE;
8284 *vr0max = NULL_TREE;
8286 else
8287 gcc_unreachable ();
8289 else if (operand_less_p (*vr0max, vr1min) == 1
8290 || operand_less_p (vr1max, *vr0min) == 1)
8292 /* [ ] ( ) or ( ) [ ]
8293 If the ranges have an empty intersection, the result of the
8294 intersect operation is the range for intersecting an
8295 anti-range with a range or empty when intersecting two ranges. */
8296 if (*vr0type == VR_RANGE
8297 && vr1type == VR_ANTI_RANGE)
8299 else if (*vr0type == VR_ANTI_RANGE
8300 && vr1type == VR_RANGE)
8302 *vr0type = vr1type;
8303 *vr0min = vr1min;
8304 *vr0max = vr1max;
8306 else if (*vr0type == VR_RANGE
8307 && vr1type == VR_RANGE)
8309 *vr0type = VR_UNDEFINED;
8310 *vr0min = NULL_TREE;
8311 *vr0max = NULL_TREE;
8313 else if (*vr0type == VR_ANTI_RANGE
8314 && vr1type == VR_ANTI_RANGE)
8316 /* If the anti-ranges are adjacent to each other merge them. */
8317 if (TREE_CODE (*vr0max) == INTEGER_CST
8318 && TREE_CODE (vr1min) == INTEGER_CST
8319 && operand_less_p (*vr0max, vr1min) == 1
8320 && integer_onep (int_const_binop (MINUS_EXPR,
8321 vr1min, *vr0max)))
8322 *vr0max = vr1max;
8323 else if (TREE_CODE (vr1max) == INTEGER_CST
8324 && TREE_CODE (*vr0min) == INTEGER_CST
8325 && operand_less_p (vr1max, *vr0min) == 1
8326 && integer_onep (int_const_binop (MINUS_EXPR,
8327 *vr0min, vr1max)))
8328 *vr0min = vr1min;
8329 /* Else arbitrarily take VR0. */
8332 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8333 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8335 /* [ ( ) ] or [( ) ] or [ ( )] */
8336 if (*vr0type == VR_RANGE
8337 && vr1type == VR_RANGE)
8339 /* If both are ranges the result is the inner one. */
8340 *vr0type = vr1type;
8341 *vr0min = vr1min;
8342 *vr0max = vr1max;
8344 else if (*vr0type == VR_RANGE
8345 && vr1type == VR_ANTI_RANGE)
8347 /* Choose the right gap if the left one is empty. */
8348 if (mineq)
8350 if (TREE_CODE (vr1max) == INTEGER_CST)
8351 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8352 build_int_cst (TREE_TYPE (vr1max), 1));
8353 else
8354 *vr0min = vr1max;
8356 /* Choose the left gap if the right one is empty. */
8357 else if (maxeq)
8359 if (TREE_CODE (vr1min) == INTEGER_CST)
8360 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8361 build_int_cst (TREE_TYPE (vr1min), 1));
8362 else
8363 *vr0max = vr1min;
8365 /* Choose the anti-range if the range is effectively varying. */
8366 else if (vrp_val_is_min (*vr0min)
8367 && vrp_val_is_max (*vr0max))
8369 *vr0type = vr1type;
8370 *vr0min = vr1min;
8371 *vr0max = vr1max;
8373 /* Else choose the range. */
8375 else if (*vr0type == VR_ANTI_RANGE
8376 && vr1type == VR_ANTI_RANGE)
8377 /* If both are anti-ranges the result is the outer one. */
8379 else if (*vr0type == VR_ANTI_RANGE
8380 && vr1type == VR_RANGE)
8382 /* The intersection is empty. */
8383 *vr0type = VR_UNDEFINED;
8384 *vr0min = NULL_TREE;
8385 *vr0max = NULL_TREE;
8387 else
8388 gcc_unreachable ();
8390 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8391 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8393 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8394 if (*vr0type == VR_RANGE
8395 && vr1type == VR_RANGE)
8396 /* Choose the inner range. */
8398 else if (*vr0type == VR_ANTI_RANGE
8399 && vr1type == VR_RANGE)
8401 /* Choose the right gap if the left is empty. */
8402 if (mineq)
8404 *vr0type = VR_RANGE;
8405 if (TREE_CODE (*vr0max) == INTEGER_CST)
8406 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8407 build_int_cst (TREE_TYPE (*vr0max), 1));
8408 else
8409 *vr0min = *vr0max;
8410 *vr0max = vr1max;
8412 /* Choose the left gap if the right is empty. */
8413 else if (maxeq)
8415 *vr0type = VR_RANGE;
8416 if (TREE_CODE (*vr0min) == INTEGER_CST)
8417 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8418 build_int_cst (TREE_TYPE (*vr0min), 1));
8419 else
8420 *vr0max = *vr0min;
8421 *vr0min = vr1min;
8423 /* Choose the anti-range if the range is effectively varying. */
8424 else if (vrp_val_is_min (vr1min)
8425 && vrp_val_is_max (vr1max))
8427 /* Else choose the range. */
8428 else
8430 *vr0type = vr1type;
8431 *vr0min = vr1min;
8432 *vr0max = vr1max;
8435 else if (*vr0type == VR_ANTI_RANGE
8436 && vr1type == VR_ANTI_RANGE)
8438 /* If both are anti-ranges the result is the outer one. */
8439 *vr0type = vr1type;
8440 *vr0min = vr1min;
8441 *vr0max = vr1max;
8443 else if (vr1type == VR_ANTI_RANGE
8444 && *vr0type == VR_RANGE)
8446 /* The intersection is empty. */
8447 *vr0type = VR_UNDEFINED;
8448 *vr0min = NULL_TREE;
8449 *vr0max = NULL_TREE;
8451 else
8452 gcc_unreachable ();
8454 else if ((operand_less_p (vr1min, *vr0max) == 1
8455 || operand_equal_p (vr1min, *vr0max, 0))
8456 && operand_less_p (*vr0min, vr1min) == 1)
8458 /* [ ( ] ) or [ ]( ) */
8459 if (*vr0type == VR_ANTI_RANGE
8460 && vr1type == VR_ANTI_RANGE)
8461 *vr0max = vr1max;
8462 else if (*vr0type == VR_RANGE
8463 && vr1type == VR_RANGE)
8464 *vr0min = vr1min;
8465 else if (*vr0type == VR_RANGE
8466 && vr1type == VR_ANTI_RANGE)
8468 if (TREE_CODE (vr1min) == INTEGER_CST)
8469 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8470 build_int_cst (TREE_TYPE (vr1min), 1));
8471 else
8472 *vr0max = vr1min;
8474 else if (*vr0type == VR_ANTI_RANGE
8475 && vr1type == VR_RANGE)
8477 *vr0type = VR_RANGE;
8478 if (TREE_CODE (*vr0max) == INTEGER_CST)
8479 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8480 build_int_cst (TREE_TYPE (*vr0max), 1));
8481 else
8482 *vr0min = *vr0max;
8483 *vr0max = vr1max;
8485 else
8486 gcc_unreachable ();
8488 else if ((operand_less_p (*vr0min, vr1max) == 1
8489 || operand_equal_p (*vr0min, vr1max, 0))
8490 && operand_less_p (vr1min, *vr0min) == 1)
8492 /* ( [ ) ] or ( )[ ] */
8493 if (*vr0type == VR_ANTI_RANGE
8494 && vr1type == VR_ANTI_RANGE)
8495 *vr0min = vr1min;
8496 else if (*vr0type == VR_RANGE
8497 && vr1type == VR_RANGE)
8498 *vr0max = vr1max;
8499 else if (*vr0type == VR_RANGE
8500 && vr1type == VR_ANTI_RANGE)
8502 if (TREE_CODE (vr1max) == INTEGER_CST)
8503 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8504 build_int_cst (TREE_TYPE (vr1max), 1));
8505 else
8506 *vr0min = vr1max;
8508 else if (*vr0type == VR_ANTI_RANGE
8509 && vr1type == VR_RANGE)
8511 *vr0type = VR_RANGE;
8512 if (TREE_CODE (*vr0min) == INTEGER_CST)
8513 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8514 build_int_cst (TREE_TYPE (*vr0min), 1));
8515 else
8516 *vr0max = *vr0min;
8517 *vr0min = vr1min;
8519 else
8520 gcc_unreachable ();
8523 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8524 result for the intersection. That's always a conservative
8525 correct estimate. */
8527 return;
8531 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8532 in *VR0. This may not be the smallest possible such range. */
8534 static void
8535 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8537 value_range saved;
8539 /* If either range is VR_VARYING the other one wins. */
8540 if (vr1->type == VR_VARYING)
8541 return;
8542 if (vr0->type == VR_VARYING)
8544 copy_value_range (vr0, vr1);
8545 return;
8548 /* When either range is VR_UNDEFINED the resulting range is
8549 VR_UNDEFINED, too. */
8550 if (vr0->type == VR_UNDEFINED)
8551 return;
8552 if (vr1->type == VR_UNDEFINED)
8554 set_value_range_to_undefined (vr0);
8555 return;
8558 /* Save the original vr0 so we can return it as conservative intersection
8559 result when our worker turns things to varying. */
8560 saved = *vr0;
8561 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8562 vr1->type, vr1->min, vr1->max);
8563 /* Make sure to canonicalize the result though as the inversion of a
8564 VR_RANGE can still be a VR_RANGE. */
8565 set_and_canonicalize_value_range (vr0, vr0->type,
8566 vr0->min, vr0->max, vr0->equiv);
8567 /* If that failed, use the saved original VR0. */
8568 if (vr0->type == VR_VARYING)
8570 *vr0 = saved;
8571 return;
8573 /* If the result is VR_UNDEFINED there is no need to mess with
8574 the equivalencies. */
8575 if (vr0->type == VR_UNDEFINED)
8576 return;
8578 /* The resulting set of equivalences for range intersection is the union of
8579 the two sets. */
8580 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8581 bitmap_ior_into (vr0->equiv, vr1->equiv);
8582 else if (vr1->equiv && !vr0->equiv)
8583 bitmap_copy (vr0->equiv, vr1->equiv);
8586 static void
8587 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8589 if (dump_file && (dump_flags & TDF_DETAILS))
8591 fprintf (dump_file, "Intersecting\n ");
8592 dump_value_range (dump_file, vr0);
8593 fprintf (dump_file, "\nand\n ");
8594 dump_value_range (dump_file, vr1);
8595 fprintf (dump_file, "\n");
8597 vrp_intersect_ranges_1 (vr0, vr1);
8598 if (dump_file && (dump_flags & TDF_DETAILS))
8600 fprintf (dump_file, "to\n ");
8601 dump_value_range (dump_file, vr0);
8602 fprintf (dump_file, "\n");
8606 /* Meet operation for value ranges. Given two value ranges VR0 and
8607 VR1, store in VR0 a range that contains both VR0 and VR1. This
8608 may not be the smallest possible such range. */
8610 static void
8611 vrp_meet_1 (value_range *vr0, value_range *vr1)
8613 value_range saved;
8615 if (vr0->type == VR_UNDEFINED)
8617 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8618 return;
8621 if (vr1->type == VR_UNDEFINED)
8623 /* VR0 already has the resulting range. */
8624 return;
8627 if (vr0->type == VR_VARYING)
8629 /* Nothing to do. VR0 already has the resulting range. */
8630 return;
8633 if (vr1->type == VR_VARYING)
8635 set_value_range_to_varying (vr0);
8636 return;
8639 saved = *vr0;
8640 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8641 vr1->type, vr1->min, vr1->max);
8642 if (vr0->type == VR_VARYING)
8644 /* Failed to find an efficient meet. Before giving up and setting
8645 the result to VARYING, see if we can at least derive a useful
8646 anti-range. FIXME, all this nonsense about distinguishing
8647 anti-ranges from ranges is necessary because of the odd
8648 semantics of range_includes_zero_p and friends. */
8649 if (((saved.type == VR_RANGE
8650 && range_includes_zero_p (saved.min, saved.max) == 0)
8651 || (saved.type == VR_ANTI_RANGE
8652 && range_includes_zero_p (saved.min, saved.max) == 1))
8653 && ((vr1->type == VR_RANGE
8654 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8655 || (vr1->type == VR_ANTI_RANGE
8656 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8658 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8660 /* Since this meet operation did not result from the meeting of
8661 two equivalent names, VR0 cannot have any equivalences. */
8662 if (vr0->equiv)
8663 bitmap_clear (vr0->equiv);
8664 return;
8667 set_value_range_to_varying (vr0);
8668 return;
8670 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8671 vr0->equiv);
8672 if (vr0->type == VR_VARYING)
8673 return;
8675 /* The resulting set of equivalences is always the intersection of
8676 the two sets. */
8677 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8678 bitmap_and_into (vr0->equiv, vr1->equiv);
8679 else if (vr0->equiv && !vr1->equiv)
8680 bitmap_clear (vr0->equiv);
8683 static void
8684 vrp_meet (value_range *vr0, value_range *vr1)
8686 if (dump_file && (dump_flags & TDF_DETAILS))
8688 fprintf (dump_file, "Meeting\n ");
8689 dump_value_range (dump_file, vr0);
8690 fprintf (dump_file, "\nand\n ");
8691 dump_value_range (dump_file, vr1);
8692 fprintf (dump_file, "\n");
8694 vrp_meet_1 (vr0, vr1);
8695 if (dump_file && (dump_flags & TDF_DETAILS))
8697 fprintf (dump_file, "to\n ");
8698 dump_value_range (dump_file, vr0);
8699 fprintf (dump_file, "\n");
8704 /* Visit all arguments for PHI node PHI that flow through executable
8705 edges. If a valid value range can be derived from all the incoming
8706 value ranges, set a new range for the LHS of PHI. */
8708 static enum ssa_prop_result
8709 vrp_visit_phi_node (gphi *phi)
8711 size_t i;
8712 tree lhs = PHI_RESULT (phi);
8713 value_range *lhs_vr = get_value_range (lhs);
8714 value_range vr_result = VR_INITIALIZER;
8715 bool first = true;
8716 int edges, old_edges;
8717 struct loop *l;
8719 if (dump_file && (dump_flags & TDF_DETAILS))
8721 fprintf (dump_file, "\nVisiting PHI node: ");
8722 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8725 edges = 0;
8726 for (i = 0; i < gimple_phi_num_args (phi); i++)
8728 edge e = gimple_phi_arg_edge (phi, i);
8730 if (dump_file && (dump_flags & TDF_DETAILS))
8732 fprintf (dump_file,
8733 " Argument #%d (%d -> %d %sexecutable)\n",
8734 (int) i, e->src->index, e->dest->index,
8735 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8738 if (e->flags & EDGE_EXECUTABLE)
8740 tree arg = PHI_ARG_DEF (phi, i);
8741 value_range vr_arg;
8743 ++edges;
8745 if (TREE_CODE (arg) == SSA_NAME)
8747 vr_arg = *(get_value_range (arg));
8748 /* Do not allow equivalences or symbolic ranges to leak in from
8749 backedges. That creates invalid equivalencies.
8750 See PR53465 and PR54767. */
8751 if (e->flags & EDGE_DFS_BACK)
8753 if (vr_arg.type == VR_RANGE
8754 || vr_arg.type == VR_ANTI_RANGE)
8756 vr_arg.equiv = NULL;
8757 if (symbolic_range_p (&vr_arg))
8759 vr_arg.type = VR_VARYING;
8760 vr_arg.min = NULL_TREE;
8761 vr_arg.max = NULL_TREE;
8765 else
8767 /* If the non-backedge arguments range is VR_VARYING then
8768 we can still try recording a simple equivalence. */
8769 if (vr_arg.type == VR_VARYING)
8771 vr_arg.type = VR_RANGE;
8772 vr_arg.min = arg;
8773 vr_arg.max = arg;
8774 vr_arg.equiv = NULL;
8778 else
8780 if (TREE_OVERFLOW_P (arg))
8781 arg = drop_tree_overflow (arg);
8783 vr_arg.type = VR_RANGE;
8784 vr_arg.min = arg;
8785 vr_arg.max = arg;
8786 vr_arg.equiv = NULL;
8789 if (dump_file && (dump_flags & TDF_DETAILS))
8791 fprintf (dump_file, "\t");
8792 print_generic_expr (dump_file, arg, dump_flags);
8793 fprintf (dump_file, ": ");
8794 dump_value_range (dump_file, &vr_arg);
8795 fprintf (dump_file, "\n");
8798 if (first)
8799 copy_value_range (&vr_result, &vr_arg);
8800 else
8801 vrp_meet (&vr_result, &vr_arg);
8802 first = false;
8804 if (vr_result.type == VR_VARYING)
8805 break;
8809 if (vr_result.type == VR_VARYING)
8810 goto varying;
8811 else if (vr_result.type == VR_UNDEFINED)
8812 goto update_range;
8814 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
8815 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
8817 /* To prevent infinite iterations in the algorithm, derive ranges
8818 when the new value is slightly bigger or smaller than the
8819 previous one. We don't do this if we have seen a new executable
8820 edge; this helps us avoid an overflow infinity for conditionals
8821 which are not in a loop. If the old value-range was VR_UNDEFINED
8822 use the updated range and iterate one more time. */
8823 if (edges > 0
8824 && gimple_phi_num_args (phi) > 1
8825 && edges == old_edges
8826 && lhs_vr->type != VR_UNDEFINED)
8828 /* Compare old and new ranges, fall back to varying if the
8829 values are not comparable. */
8830 int cmp_min = compare_values (lhs_vr->min, vr_result.min);
8831 if (cmp_min == -2)
8832 goto varying;
8833 int cmp_max = compare_values (lhs_vr->max, vr_result.max);
8834 if (cmp_max == -2)
8835 goto varying;
8837 /* For non VR_RANGE or for pointers fall back to varying if
8838 the range changed. */
8839 if ((lhs_vr->type != VR_RANGE || vr_result.type != VR_RANGE
8840 || POINTER_TYPE_P (TREE_TYPE (lhs)))
8841 && (cmp_min != 0 || cmp_max != 0))
8842 goto varying;
8844 /* If the new minimum is larger than the previous one
8845 retain the old value. If the new minimum value is smaller
8846 than the previous one and not -INF go all the way to -INF + 1.
8847 In the first case, to avoid infinite bouncing between different
8848 minimums, and in the other case to avoid iterating millions of
8849 times to reach -INF. Going to -INF + 1 also lets the following
8850 iteration compute whether there will be any overflow, at the
8851 expense of one additional iteration. */
8852 if (cmp_min < 0)
8853 vr_result.min = lhs_vr->min;
8854 else if (cmp_min > 0
8855 && !vrp_val_is_min (vr_result.min))
8856 vr_result.min
8857 = int_const_binop (PLUS_EXPR,
8858 vrp_val_min (TREE_TYPE (vr_result.min)),
8859 build_int_cst (TREE_TYPE (vr_result.min), 1));
8861 /* Similarly for the maximum value. */
8862 if (cmp_max > 0)
8863 vr_result.max = lhs_vr->max;
8864 else if (cmp_max < 0
8865 && !vrp_val_is_max (vr_result.max))
8866 vr_result.max
8867 = int_const_binop (MINUS_EXPR,
8868 vrp_val_max (TREE_TYPE (vr_result.min)),
8869 build_int_cst (TREE_TYPE (vr_result.min), 1));
8871 /* If we dropped either bound to +-INF then if this is a loop
8872 PHI node SCEV may known more about its value-range. */
8873 if (cmp_min > 0 || cmp_min < 0
8874 || cmp_max < 0 || cmp_max > 0)
8875 goto scev_check;
8877 goto infinite_check;
8880 /* If the new range is different than the previous value, keep
8881 iterating. */
8882 update_range:
8883 if (update_value_range (lhs, &vr_result))
8885 if (dump_file && (dump_flags & TDF_DETAILS))
8887 fprintf (dump_file, "Found new range for ");
8888 print_generic_expr (dump_file, lhs, 0);
8889 fprintf (dump_file, ": ");
8890 dump_value_range (dump_file, &vr_result);
8891 fprintf (dump_file, "\n");
8894 if (vr_result.type == VR_VARYING)
8895 return SSA_PROP_VARYING;
8897 return SSA_PROP_INTERESTING;
8900 /* Nothing changed, don't add outgoing edges. */
8901 return SSA_PROP_NOT_INTERESTING;
8903 varying:
8904 set_value_range_to_varying (&vr_result);
8906 scev_check:
8907 /* If this is a loop PHI node SCEV may known more about its value-range.
8908 scev_check can be reached from two paths, one is a fall through from above
8909 "varying" label, the other is direct goto from code block which tries to
8910 avoid infinite simulation. */
8911 if ((l = loop_containing_stmt (phi))
8912 && l->header == gimple_bb (phi))
8913 adjust_range_with_scev (&vr_result, l, phi, lhs);
8915 infinite_check:
8916 /* If we will end up with a (-INF, +INF) range, set it to
8917 VARYING. Same if the previous max value was invalid for
8918 the type and we end up with vr_result.min > vr_result.max. */
8919 if ((vr_result.type == VR_RANGE || vr_result.type == VR_ANTI_RANGE)
8920 && !((vrp_val_is_max (vr_result.max) && vrp_val_is_min (vr_result.min))
8921 || compare_values (vr_result.min, vr_result.max) > 0))
8922 goto update_range;
8924 /* No match found. Set the LHS to VARYING. */
8925 set_value_range_to_varying (lhs_vr);
8926 return SSA_PROP_VARYING;
8929 /* Simplify boolean operations if the source is known
8930 to be already a boolean. */
8931 static bool
8932 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
8934 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
8935 tree lhs, op0, op1;
8936 bool need_conversion;
8938 /* We handle only !=/== case here. */
8939 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
8941 op0 = gimple_assign_rhs1 (stmt);
8942 if (!op_with_boolean_value_range_p (op0))
8943 return false;
8945 op1 = gimple_assign_rhs2 (stmt);
8946 if (!op_with_boolean_value_range_p (op1))
8947 return false;
8949 /* Reduce number of cases to handle to NE_EXPR. As there is no
8950 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
8951 if (rhs_code == EQ_EXPR)
8953 if (TREE_CODE (op1) == INTEGER_CST)
8954 op1 = int_const_binop (BIT_XOR_EXPR, op1,
8955 build_int_cst (TREE_TYPE (op1), 1));
8956 else
8957 return false;
8960 lhs = gimple_assign_lhs (stmt);
8961 need_conversion
8962 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
8964 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
8965 if (need_conversion
8966 && !TYPE_UNSIGNED (TREE_TYPE (op0))
8967 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
8968 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
8969 return false;
8971 /* For A != 0 we can substitute A itself. */
8972 if (integer_zerop (op1))
8973 gimple_assign_set_rhs_with_ops (gsi,
8974 need_conversion
8975 ? NOP_EXPR : TREE_CODE (op0), op0);
8976 /* For A != B we substitute A ^ B. Either with conversion. */
8977 else if (need_conversion)
8979 tree tem = make_ssa_name (TREE_TYPE (op0));
8980 gassign *newop
8981 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
8982 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
8983 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
8984 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
8985 set_range_info (tem, VR_RANGE,
8986 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
8987 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
8988 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
8990 /* Or without. */
8991 else
8992 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
8993 update_stmt (gsi_stmt (*gsi));
8995 return true;
8998 /* Simplify a division or modulo operator to a right shift or
8999 bitwise and if the first operand is unsigned or is greater
9000 than zero and the second operand is an exact power of two.
9001 For TRUNC_MOD_EXPR op0 % op1 with constant op1, optimize it
9002 into just op0 if op0's range is known to be a subset of
9003 [-op1 + 1, op1 - 1] for signed and [0, op1 - 1] for unsigned
9004 modulo. */
9006 static bool
9007 simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9009 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9010 tree val = NULL;
9011 tree op0 = gimple_assign_rhs1 (stmt);
9012 tree op1 = gimple_assign_rhs2 (stmt);
9013 value_range *vr = get_value_range (op0);
9015 if (rhs_code == TRUNC_MOD_EXPR
9016 && TREE_CODE (op1) == INTEGER_CST
9017 && tree_int_cst_sgn (op1) == 1
9018 && range_int_cst_p (vr)
9019 && tree_int_cst_lt (vr->max, op1))
9021 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9022 || tree_int_cst_sgn (vr->min) >= 0
9023 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1), op1),
9024 vr->min))
9026 /* If op0 already has the range op0 % op1 has,
9027 then TRUNC_MOD_EXPR won't change anything. */
9028 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
9029 gimple_assign_set_rhs_from_tree (&gsi, op0);
9030 update_stmt (stmt);
9031 return true;
9035 if (!integer_pow2p (op1))
9037 /* X % -Y can be only optimized into X % Y either if
9038 X is not INT_MIN, or Y is not -1. Fold it now, as after
9039 remove_range_assertions the range info might be not available
9040 anymore. */
9041 if (rhs_code == TRUNC_MOD_EXPR
9042 && fold_stmt (gsi, follow_single_use_edges))
9043 return true;
9044 return false;
9047 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9048 val = integer_one_node;
9049 else
9051 bool sop = false;
9053 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9055 if (val
9056 && sop
9057 && integer_onep (val)
9058 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9060 location_t location;
9062 if (!gimple_has_location (stmt))
9063 location = input_location;
9064 else
9065 location = gimple_location (stmt);
9066 warning_at (location, OPT_Wstrict_overflow,
9067 "assuming signed overflow does not occur when "
9068 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9072 if (val && integer_onep (val))
9074 tree t;
9076 if (rhs_code == TRUNC_DIV_EXPR)
9078 t = build_int_cst (integer_type_node, tree_log2 (op1));
9079 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9080 gimple_assign_set_rhs1 (stmt, op0);
9081 gimple_assign_set_rhs2 (stmt, t);
9083 else
9085 t = build_int_cst (TREE_TYPE (op1), 1);
9086 t = int_const_binop (MINUS_EXPR, op1, t);
9087 t = fold_convert (TREE_TYPE (op0), t);
9089 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9090 gimple_assign_set_rhs1 (stmt, op0);
9091 gimple_assign_set_rhs2 (stmt, t);
9094 update_stmt (stmt);
9095 return true;
9098 return false;
9101 /* Simplify a min or max if the ranges of the two operands are
9102 disjoint. Return true if we do simplify. */
9104 static bool
9105 simplify_min_or_max_using_ranges (gimple *stmt)
9107 tree op0 = gimple_assign_rhs1 (stmt);
9108 tree op1 = gimple_assign_rhs2 (stmt);
9109 bool sop = false;
9110 tree val;
9112 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9113 (LE_EXPR, op0, op1, &sop));
9114 if (!val)
9116 sop = false;
9117 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9118 (LT_EXPR, op0, op1, &sop));
9121 if (val)
9123 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9125 location_t location;
9127 if (!gimple_has_location (stmt))
9128 location = input_location;
9129 else
9130 location = gimple_location (stmt);
9131 warning_at (location, OPT_Wstrict_overflow,
9132 "assuming signed overflow does not occur when "
9133 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9136 /* VAL == TRUE -> OP0 < or <= op1
9137 VAL == FALSE -> OP0 > or >= op1. */
9138 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9139 == integer_zerop (val)) ? op0 : op1;
9140 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
9141 gimple_assign_set_rhs_from_tree (&gsi, res);
9142 update_stmt (stmt);
9143 return true;
9146 return false;
9149 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9150 ABS_EXPR. If the operand is <= 0, then simplify the
9151 ABS_EXPR into a NEGATE_EXPR. */
9153 static bool
9154 simplify_abs_using_ranges (gimple *stmt)
9156 tree op = gimple_assign_rhs1 (stmt);
9157 value_range *vr = get_value_range (op);
9159 if (vr)
9161 tree val = NULL;
9162 bool sop = false;
9164 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9165 if (!val)
9167 /* The range is neither <= 0 nor > 0. Now see if it is
9168 either < 0 or >= 0. */
9169 sop = false;
9170 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9171 &sop);
9174 if (val)
9176 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9178 location_t location;
9180 if (!gimple_has_location (stmt))
9181 location = input_location;
9182 else
9183 location = gimple_location (stmt);
9184 warning_at (location, OPT_Wstrict_overflow,
9185 "assuming signed overflow does not occur when "
9186 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9189 gimple_assign_set_rhs1 (stmt, op);
9190 if (integer_zerop (val))
9191 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9192 else
9193 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9194 update_stmt (stmt);
9195 return true;
9199 return false;
9202 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9203 If all the bits that are being cleared by & are already
9204 known to be zero from VR, or all the bits that are being
9205 set by | are already known to be one from VR, the bit
9206 operation is redundant. */
9208 static bool
9209 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9211 tree op0 = gimple_assign_rhs1 (stmt);
9212 tree op1 = gimple_assign_rhs2 (stmt);
9213 tree op = NULL_TREE;
9214 value_range vr0 = VR_INITIALIZER;
9215 value_range vr1 = VR_INITIALIZER;
9216 wide_int may_be_nonzero0, may_be_nonzero1;
9217 wide_int must_be_nonzero0, must_be_nonzero1;
9218 wide_int mask;
9220 if (TREE_CODE (op0) == SSA_NAME)
9221 vr0 = *(get_value_range (op0));
9222 else if (is_gimple_min_invariant (op0))
9223 set_value_range_to_value (&vr0, op0, NULL);
9224 else
9225 return false;
9227 if (TREE_CODE (op1) == SSA_NAME)
9228 vr1 = *(get_value_range (op1));
9229 else if (is_gimple_min_invariant (op1))
9230 set_value_range_to_value (&vr1, op1, NULL);
9231 else
9232 return false;
9234 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9235 &must_be_nonzero0))
9236 return false;
9237 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9238 &must_be_nonzero1))
9239 return false;
9241 switch (gimple_assign_rhs_code (stmt))
9243 case BIT_AND_EXPR:
9244 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9245 if (mask == 0)
9247 op = op0;
9248 break;
9250 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9251 if (mask == 0)
9253 op = op1;
9254 break;
9256 break;
9257 case BIT_IOR_EXPR:
9258 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9259 if (mask == 0)
9261 op = op1;
9262 break;
9264 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9265 if (mask == 0)
9267 op = op0;
9268 break;
9270 break;
9271 default:
9272 gcc_unreachable ();
9275 if (op == NULL_TREE)
9276 return false;
9278 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9279 update_stmt (gsi_stmt (*gsi));
9280 return true;
9283 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9284 a known value range VR.
9286 If there is one and only one value which will satisfy the
9287 conditional, then return that value. Else return NULL.
9289 If signed overflow must be undefined for the value to satisfy
9290 the conditional, then set *STRICT_OVERFLOW_P to true. */
9292 static tree
9293 test_for_singularity (enum tree_code cond_code, tree op0,
9294 tree op1, value_range *vr,
9295 bool *strict_overflow_p)
9297 tree min = NULL;
9298 tree max = NULL;
9300 /* Extract minimum/maximum values which satisfy the conditional as it was
9301 written. */
9302 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9304 /* This should not be negative infinity; there is no overflow
9305 here. */
9306 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9308 max = op1;
9309 if (cond_code == LT_EXPR && !is_overflow_infinity (max))
9311 tree one = build_int_cst (TREE_TYPE (op0), 1);
9312 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9313 if (EXPR_P (max))
9314 TREE_NO_WARNING (max) = 1;
9317 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9319 /* This should not be positive infinity; there is no overflow
9320 here. */
9321 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9323 min = op1;
9324 if (cond_code == GT_EXPR && !is_overflow_infinity (min))
9326 tree one = build_int_cst (TREE_TYPE (op0), 1);
9327 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9328 if (EXPR_P (min))
9329 TREE_NO_WARNING (min) = 1;
9333 /* Now refine the minimum and maximum values using any
9334 value range information we have for op0. */
9335 if (min && max)
9337 if (compare_values (vr->min, min) == 1)
9338 min = vr->min;
9339 if (compare_values (vr->max, max) == -1)
9340 max = vr->max;
9342 /* If the new min/max values have converged to a single value,
9343 then there is only one value which can satisfy the condition,
9344 return that value. */
9345 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9347 if ((cond_code == LE_EXPR || cond_code == LT_EXPR)
9348 && is_overflow_infinity (vr->max))
9349 *strict_overflow_p = true;
9350 if ((cond_code == GE_EXPR || cond_code == GT_EXPR)
9351 && is_overflow_infinity (vr->min))
9352 *strict_overflow_p = true;
9354 return min;
9357 return NULL;
9360 /* Return whether the value range *VR fits in an integer type specified
9361 by PRECISION and UNSIGNED_P. */
9363 static bool
9364 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9366 tree src_type;
9367 unsigned src_precision;
9368 widest_int tem;
9369 signop src_sgn;
9371 /* We can only handle integral and pointer types. */
9372 src_type = TREE_TYPE (vr->min);
9373 if (!INTEGRAL_TYPE_P (src_type)
9374 && !POINTER_TYPE_P (src_type))
9375 return false;
9377 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9378 and so is an identity transform. */
9379 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9380 src_sgn = TYPE_SIGN (src_type);
9381 if ((src_precision < dest_precision
9382 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9383 || (src_precision == dest_precision && src_sgn == dest_sgn))
9384 return true;
9386 /* Now we can only handle ranges with constant bounds. */
9387 if (vr->type != VR_RANGE
9388 || TREE_CODE (vr->min) != INTEGER_CST
9389 || TREE_CODE (vr->max) != INTEGER_CST)
9390 return false;
9392 /* For sign changes, the MSB of the wide_int has to be clear.
9393 An unsigned value with its MSB set cannot be represented by
9394 a signed wide_int, while a negative value cannot be represented
9395 by an unsigned wide_int. */
9396 if (src_sgn != dest_sgn
9397 && (wi::lts_p (vr->min, 0) || wi::lts_p (vr->max, 0)))
9398 return false;
9400 /* Then we can perform the conversion on both ends and compare
9401 the result for equality. */
9402 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9403 if (tem != wi::to_widest (vr->min))
9404 return false;
9405 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9406 if (tem != wi::to_widest (vr->max))
9407 return false;
9409 return true;
9412 /* Simplify a conditional using a relational operator to an equality
9413 test if the range information indicates only one value can satisfy
9414 the original conditional. */
9416 static bool
9417 simplify_cond_using_ranges (gcond *stmt)
9419 tree op0 = gimple_cond_lhs (stmt);
9420 tree op1 = gimple_cond_rhs (stmt);
9421 enum tree_code cond_code = gimple_cond_code (stmt);
9423 if (cond_code != NE_EXPR
9424 && cond_code != EQ_EXPR
9425 && TREE_CODE (op0) == SSA_NAME
9426 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9427 && is_gimple_min_invariant (op1))
9429 value_range *vr = get_value_range (op0);
9431 /* If we have range information for OP0, then we might be
9432 able to simplify this conditional. */
9433 if (vr->type == VR_RANGE)
9435 enum warn_strict_overflow_code wc = WARN_STRICT_OVERFLOW_COMPARISON;
9436 bool sop = false;
9437 tree new_tree = test_for_singularity (cond_code, op0, op1, vr, &sop);
9439 if (new_tree
9440 && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
9442 if (dump_file)
9444 fprintf (dump_file, "Simplified relational ");
9445 print_gimple_stmt (dump_file, stmt, 0, 0);
9446 fprintf (dump_file, " into ");
9449 gimple_cond_set_code (stmt, EQ_EXPR);
9450 gimple_cond_set_lhs (stmt, op0);
9451 gimple_cond_set_rhs (stmt, new_tree);
9453 update_stmt (stmt);
9455 if (dump_file)
9457 print_gimple_stmt (dump_file, stmt, 0, 0);
9458 fprintf (dump_file, "\n");
9461 if (sop && issue_strict_overflow_warning (wc))
9463 location_t location = input_location;
9464 if (gimple_has_location (stmt))
9465 location = gimple_location (stmt);
9467 warning_at (location, OPT_Wstrict_overflow,
9468 "assuming signed overflow does not occur when "
9469 "simplifying conditional");
9472 return true;
9475 /* Try again after inverting the condition. We only deal
9476 with integral types here, so no need to worry about
9477 issues with inverting FP comparisons. */
9478 sop = false;
9479 new_tree = test_for_singularity
9480 (invert_tree_comparison (cond_code, false),
9481 op0, op1, vr, &sop);
9483 if (new_tree
9484 && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
9486 if (dump_file)
9488 fprintf (dump_file, "Simplified relational ");
9489 print_gimple_stmt (dump_file, stmt, 0, 0);
9490 fprintf (dump_file, " into ");
9493 gimple_cond_set_code (stmt, NE_EXPR);
9494 gimple_cond_set_lhs (stmt, op0);
9495 gimple_cond_set_rhs (stmt, new_tree);
9497 update_stmt (stmt);
9499 if (dump_file)
9501 print_gimple_stmt (dump_file, stmt, 0, 0);
9502 fprintf (dump_file, "\n");
9505 if (sop && issue_strict_overflow_warning (wc))
9507 location_t location = input_location;
9508 if (gimple_has_location (stmt))
9509 location = gimple_location (stmt);
9511 warning_at (location, OPT_Wstrict_overflow,
9512 "assuming signed overflow does not occur when "
9513 "simplifying conditional");
9516 return true;
9521 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9522 see if OP0 was set by a type conversion where the source of
9523 the conversion is another SSA_NAME with a range that fits
9524 into the range of OP0's type.
9526 If so, the conversion is redundant as the earlier SSA_NAME can be
9527 used for the comparison directly if we just massage the constant in the
9528 comparison. */
9529 if (TREE_CODE (op0) == SSA_NAME
9530 && TREE_CODE (op1) == INTEGER_CST)
9532 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9533 tree innerop;
9535 if (!is_gimple_assign (def_stmt)
9536 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9537 return false;
9539 innerop = gimple_assign_rhs1 (def_stmt);
9541 if (TREE_CODE (innerop) == SSA_NAME
9542 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9543 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9544 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9546 value_range *vr = get_value_range (innerop);
9548 if (range_int_cst_p (vr)
9549 && range_fits_type_p (vr,
9550 TYPE_PRECISION (TREE_TYPE (op0)),
9551 TYPE_SIGN (TREE_TYPE (op0)))
9552 && int_fits_type_p (op1, TREE_TYPE (innerop))
9553 /* The range must not have overflowed, or if it did overflow
9554 we must not be wrapping/trapping overflow and optimizing
9555 with strict overflow semantics. */
9556 && ((!is_negative_overflow_infinity (vr->min)
9557 && !is_positive_overflow_infinity (vr->max))
9558 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (innerop))))
9560 /* If the range overflowed and the user has asked for warnings
9561 when strict overflow semantics were used to optimize code,
9562 issue an appropriate warning. */
9563 if (cond_code != EQ_EXPR && cond_code != NE_EXPR
9564 && (is_negative_overflow_infinity (vr->min)
9565 || is_positive_overflow_infinity (vr->max))
9566 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_CONDITIONAL))
9568 location_t location;
9570 if (!gimple_has_location (stmt))
9571 location = input_location;
9572 else
9573 location = gimple_location (stmt);
9574 warning_at (location, OPT_Wstrict_overflow,
9575 "assuming signed overflow does not occur when "
9576 "simplifying conditional");
9579 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9580 gimple_cond_set_lhs (stmt, innerop);
9581 gimple_cond_set_rhs (stmt, newconst);
9582 return true;
9587 return false;
9590 /* Simplify a switch statement using the value range of the switch
9591 argument. */
9593 static bool
9594 simplify_switch_using_ranges (gswitch *stmt)
9596 tree op = gimple_switch_index (stmt);
9597 value_range *vr = NULL;
9598 bool take_default;
9599 edge e;
9600 edge_iterator ei;
9601 size_t i = 0, j = 0, n, n2;
9602 tree vec2;
9603 switch_update su;
9604 size_t k = 1, l = 0;
9606 if (TREE_CODE (op) == SSA_NAME)
9608 vr = get_value_range (op);
9610 /* We can only handle integer ranges. */
9611 if ((vr->type != VR_RANGE
9612 && vr->type != VR_ANTI_RANGE)
9613 || symbolic_range_p (vr))
9614 return false;
9616 /* Find case label for min/max of the value range. */
9617 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9619 else if (TREE_CODE (op) == INTEGER_CST)
9621 take_default = !find_case_label_index (stmt, 1, op, &i);
9622 if (take_default)
9624 i = 1;
9625 j = 0;
9627 else
9629 j = i;
9632 else
9633 return false;
9635 n = gimple_switch_num_labels (stmt);
9637 /* We can truncate the case label ranges that partially overlap with OP's
9638 value range. */
9639 size_t min_idx = 1, max_idx = 0;
9640 if (vr != NULL)
9641 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9642 if (min_idx <= max_idx)
9644 tree min_label = gimple_switch_label (stmt, min_idx);
9645 tree max_label = gimple_switch_label (stmt, max_idx);
9647 /* Avoid changing the type of the case labels when truncating. */
9648 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9649 tree vr_min = fold_convert (case_label_type, vr->min);
9650 tree vr_max = fold_convert (case_label_type, vr->max);
9652 if (vr->type == VR_RANGE)
9654 /* If OP's value range is [2,8] and the low label range is
9655 0 ... 3, truncate the label's range to 2 .. 3. */
9656 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9657 && CASE_HIGH (min_label) != NULL_TREE
9658 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9659 CASE_LOW (min_label) = vr_min;
9661 /* If OP's value range is [2,8] and the high label range is
9662 7 ... 10, truncate the label's range to 7 .. 8. */
9663 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9664 && CASE_HIGH (max_label) != NULL_TREE
9665 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9666 CASE_HIGH (max_label) = vr_max;
9668 else if (vr->type == VR_ANTI_RANGE)
9670 tree one_cst = build_one_cst (case_label_type);
9672 if (min_label == max_label)
9674 /* If OP's value range is ~[7,8] and the label's range is
9675 7 ... 10, truncate the label's range to 9 ... 10. */
9676 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9677 && CASE_HIGH (min_label) != NULL_TREE
9678 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9679 CASE_LOW (min_label)
9680 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9682 /* If OP's value range is ~[7,8] and the label's range is
9683 5 ... 8, truncate the label's range to 5 ... 6. */
9684 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9685 && CASE_HIGH (min_label) != NULL_TREE
9686 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9687 CASE_HIGH (min_label)
9688 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9690 else
9692 /* If OP's value range is ~[2,8] and the low label range is
9693 0 ... 3, truncate the label's range to 0 ... 1. */
9694 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9695 && CASE_HIGH (min_label) != NULL_TREE
9696 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9697 CASE_HIGH (min_label)
9698 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9700 /* If OP's value range is ~[2,8] and the high label range is
9701 7 ... 10, truncate the label's range to 9 ... 10. */
9702 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9703 && CASE_HIGH (max_label) != NULL_TREE
9704 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9705 CASE_LOW (max_label)
9706 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9710 /* Canonicalize singleton case ranges. */
9711 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9712 CASE_HIGH (min_label) = NULL_TREE;
9713 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9714 CASE_HIGH (max_label) = NULL_TREE;
9717 /* We can also eliminate case labels that lie completely outside OP's value
9718 range. */
9720 /* Bail out if this is just all edges taken. */
9721 if (i == 1
9722 && j == n - 1
9723 && take_default)
9724 return false;
9726 /* Build a new vector of taken case labels. */
9727 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
9728 n2 = 0;
9730 /* Add the default edge, if necessary. */
9731 if (take_default)
9732 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
9734 for (; i <= j; ++i, ++n2)
9735 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
9737 for (; k <= l; ++k, ++n2)
9738 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
9740 /* Mark needed edges. */
9741 for (i = 0; i < n2; ++i)
9743 e = find_edge (gimple_bb (stmt),
9744 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
9745 e->aux = (void *)-1;
9748 /* Queue not needed edges for later removal. */
9749 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
9751 if (e->aux == (void *)-1)
9753 e->aux = NULL;
9754 continue;
9757 if (dump_file && (dump_flags & TDF_DETAILS))
9759 fprintf (dump_file, "removing unreachable case label\n");
9761 to_remove_edges.safe_push (e);
9762 e->flags &= ~EDGE_EXECUTABLE;
9765 /* And queue an update for the stmt. */
9766 su.stmt = stmt;
9767 su.vec = vec2;
9768 to_update_switch_stmts.safe_push (su);
9769 return false;
9772 /* Simplify an integral conversion from an SSA name in STMT. */
9774 static bool
9775 simplify_conversion_using_ranges (gimple *stmt)
9777 tree innerop, middleop, finaltype;
9778 gimple *def_stmt;
9779 signop inner_sgn, middle_sgn, final_sgn;
9780 unsigned inner_prec, middle_prec, final_prec;
9781 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
9783 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
9784 if (!INTEGRAL_TYPE_P (finaltype))
9785 return false;
9786 middleop = gimple_assign_rhs1 (stmt);
9787 def_stmt = SSA_NAME_DEF_STMT (middleop);
9788 if (!is_gimple_assign (def_stmt)
9789 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9790 return false;
9791 innerop = gimple_assign_rhs1 (def_stmt);
9792 if (TREE_CODE (innerop) != SSA_NAME
9793 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
9794 return false;
9796 /* Get the value-range of the inner operand. Use get_range_info in
9797 case innerop was created during substitute-and-fold. */
9798 wide_int imin, imax;
9799 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
9800 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
9801 return false;
9802 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
9803 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
9805 /* Simulate the conversion chain to check if the result is equal if
9806 the middle conversion is removed. */
9807 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
9808 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
9809 final_prec = TYPE_PRECISION (finaltype);
9811 /* If the first conversion is not injective, the second must not
9812 be widening. */
9813 if (wi::gtu_p (innermax - innermin,
9814 wi::mask <widest_int> (middle_prec, false))
9815 && middle_prec < final_prec)
9816 return false;
9817 /* We also want a medium value so that we can track the effect that
9818 narrowing conversions with sign change have. */
9819 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
9820 if (inner_sgn == UNSIGNED)
9821 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
9822 else
9823 innermed = 0;
9824 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
9825 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
9826 innermed = innermin;
9828 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
9829 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
9830 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
9831 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
9833 /* Require that the final conversion applied to both the original
9834 and the intermediate range produces the same result. */
9835 final_sgn = TYPE_SIGN (finaltype);
9836 if (wi::ext (middlemin, final_prec, final_sgn)
9837 != wi::ext (innermin, final_prec, final_sgn)
9838 || wi::ext (middlemed, final_prec, final_sgn)
9839 != wi::ext (innermed, final_prec, final_sgn)
9840 || wi::ext (middlemax, final_prec, final_sgn)
9841 != wi::ext (innermax, final_prec, final_sgn))
9842 return false;
9844 gimple_assign_set_rhs1 (stmt, innerop);
9845 update_stmt (stmt);
9846 return true;
9849 /* Simplify a conversion from integral SSA name to float in STMT. */
9851 static bool
9852 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
9853 gimple *stmt)
9855 tree rhs1 = gimple_assign_rhs1 (stmt);
9856 value_range *vr = get_value_range (rhs1);
9857 machine_mode fltmode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
9858 machine_mode mode;
9859 tree tem;
9860 gassign *conv;
9862 /* We can only handle constant ranges. */
9863 if (vr->type != VR_RANGE
9864 || TREE_CODE (vr->min) != INTEGER_CST
9865 || TREE_CODE (vr->max) != INTEGER_CST)
9866 return false;
9868 /* First check if we can use a signed type in place of an unsigned. */
9869 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
9870 && (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)), 0)
9871 != CODE_FOR_nothing)
9872 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
9873 mode = TYPE_MODE (TREE_TYPE (rhs1));
9874 /* If we can do the conversion in the current input mode do nothing. */
9875 else if (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)),
9876 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
9877 return false;
9878 /* Otherwise search for a mode we can use, starting from the narrowest
9879 integer mode available. */
9880 else
9882 mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
9885 /* If we cannot do a signed conversion to float from mode
9886 or if the value-range does not fit in the signed type
9887 try with a wider mode. */
9888 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
9889 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
9890 break;
9892 mode = GET_MODE_WIDER_MODE (mode);
9893 /* But do not widen the input. Instead leave that to the
9894 optabs expansion code. */
9895 if (GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
9896 return false;
9898 while (mode != VOIDmode);
9899 if (mode == VOIDmode)
9900 return false;
9903 /* It works, insert a truncation or sign-change before the
9904 float conversion. */
9905 tem = make_ssa_name (build_nonstandard_integer_type
9906 (GET_MODE_PRECISION (mode), 0));
9907 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
9908 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
9909 gimple_assign_set_rhs1 (stmt, tem);
9910 update_stmt (stmt);
9912 return true;
9915 /* Simplify an internal fn call using ranges if possible. */
9917 static bool
9918 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9920 enum tree_code subcode;
9921 bool is_ubsan = false;
9922 bool ovf = false;
9923 switch (gimple_call_internal_fn (stmt))
9925 case IFN_UBSAN_CHECK_ADD:
9926 subcode = PLUS_EXPR;
9927 is_ubsan = true;
9928 break;
9929 case IFN_UBSAN_CHECK_SUB:
9930 subcode = MINUS_EXPR;
9931 is_ubsan = true;
9932 break;
9933 case IFN_UBSAN_CHECK_MUL:
9934 subcode = MULT_EXPR;
9935 is_ubsan = true;
9936 break;
9937 case IFN_ADD_OVERFLOW:
9938 subcode = PLUS_EXPR;
9939 break;
9940 case IFN_SUB_OVERFLOW:
9941 subcode = MINUS_EXPR;
9942 break;
9943 case IFN_MUL_OVERFLOW:
9944 subcode = MULT_EXPR;
9945 break;
9946 default:
9947 return false;
9950 tree op0 = gimple_call_arg (stmt, 0);
9951 tree op1 = gimple_call_arg (stmt, 1);
9952 tree type;
9953 if (is_ubsan)
9954 type = TREE_TYPE (op0);
9955 else if (gimple_call_lhs (stmt) == NULL_TREE)
9956 return false;
9957 else
9958 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
9959 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
9960 || (is_ubsan && ovf))
9961 return false;
9963 gimple *g;
9964 location_t loc = gimple_location (stmt);
9965 if (is_ubsan)
9966 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
9967 else
9969 int prec = TYPE_PRECISION (type);
9970 tree utype = type;
9971 if (ovf
9972 || !useless_type_conversion_p (type, TREE_TYPE (op0))
9973 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
9974 utype = build_nonstandard_integer_type (prec, 1);
9975 if (TREE_CODE (op0) == INTEGER_CST)
9976 op0 = fold_convert (utype, op0);
9977 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
9979 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
9980 gimple_set_location (g, loc);
9981 gsi_insert_before (gsi, g, GSI_SAME_STMT);
9982 op0 = gimple_assign_lhs (g);
9984 if (TREE_CODE (op1) == INTEGER_CST)
9985 op1 = fold_convert (utype, op1);
9986 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
9988 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
9989 gimple_set_location (g, loc);
9990 gsi_insert_before (gsi, g, GSI_SAME_STMT);
9991 op1 = gimple_assign_lhs (g);
9993 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
9994 gimple_set_location (g, loc);
9995 gsi_insert_before (gsi, g, GSI_SAME_STMT);
9996 if (utype != type)
9998 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
9999 gimple_assign_lhs (g));
10000 gimple_set_location (g, loc);
10001 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10003 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10004 gimple_assign_lhs (g),
10005 build_int_cst (type, ovf));
10007 gimple_set_location (g, loc);
10008 gsi_replace (gsi, g, false);
10009 return true;
10012 /* Simplify STMT using ranges if possible. */
10014 static bool
10015 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10017 gimple *stmt = gsi_stmt (*gsi);
10018 if (is_gimple_assign (stmt))
10020 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10021 tree rhs1 = gimple_assign_rhs1 (stmt);
10023 switch (rhs_code)
10025 case EQ_EXPR:
10026 case NE_EXPR:
10027 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10028 if the RHS is zero or one, and the LHS are known to be boolean
10029 values. */
10030 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10031 return simplify_truth_ops_using_ranges (gsi, stmt);
10032 break;
10034 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10035 and BIT_AND_EXPR respectively if the first operand is greater
10036 than zero and the second operand is an exact power of two.
10037 Also optimize TRUNC_MOD_EXPR away if the second operand is
10038 constant and the first operand already has the right value
10039 range. */
10040 case TRUNC_DIV_EXPR:
10041 case TRUNC_MOD_EXPR:
10042 if (TREE_CODE (rhs1) == SSA_NAME
10043 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10044 return simplify_div_or_mod_using_ranges (gsi, stmt);
10045 break;
10047 /* Transform ABS (X) into X or -X as appropriate. */
10048 case ABS_EXPR:
10049 if (TREE_CODE (rhs1) == SSA_NAME
10050 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10051 return simplify_abs_using_ranges (stmt);
10052 break;
10054 case BIT_AND_EXPR:
10055 case BIT_IOR_EXPR:
10056 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10057 if all the bits being cleared are already cleared or
10058 all the bits being set are already set. */
10059 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10060 return simplify_bit_ops_using_ranges (gsi, stmt);
10061 break;
10063 CASE_CONVERT:
10064 if (TREE_CODE (rhs1) == SSA_NAME
10065 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10066 return simplify_conversion_using_ranges (stmt);
10067 break;
10069 case FLOAT_EXPR:
10070 if (TREE_CODE (rhs1) == SSA_NAME
10071 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10072 return simplify_float_conversion_using_ranges (gsi, stmt);
10073 break;
10075 case MIN_EXPR:
10076 case MAX_EXPR:
10077 return simplify_min_or_max_using_ranges (stmt);
10078 break;
10080 default:
10081 break;
10084 else if (gimple_code (stmt) == GIMPLE_COND)
10085 return simplify_cond_using_ranges (as_a <gcond *> (stmt));
10086 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10087 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10088 else if (is_gimple_call (stmt)
10089 && gimple_call_internal_p (stmt))
10090 return simplify_internal_call_using_ranges (gsi, stmt);
10092 return false;
10095 /* If the statement pointed by SI has a predicate whose value can be
10096 computed using the value range information computed by VRP, compute
10097 its value and return true. Otherwise, return false. */
10099 static bool
10100 fold_predicate_in (gimple_stmt_iterator *si)
10102 bool assignment_p = false;
10103 tree val;
10104 gimple *stmt = gsi_stmt (*si);
10106 if (is_gimple_assign (stmt)
10107 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10109 assignment_p = true;
10110 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10111 gimple_assign_rhs1 (stmt),
10112 gimple_assign_rhs2 (stmt),
10113 stmt);
10115 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10116 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10117 gimple_cond_lhs (cond_stmt),
10118 gimple_cond_rhs (cond_stmt),
10119 stmt);
10120 else
10121 return false;
10123 if (val)
10125 if (assignment_p)
10126 val = fold_convert (gimple_expr_type (stmt), val);
10128 if (dump_file)
10130 fprintf (dump_file, "Folding predicate ");
10131 print_gimple_expr (dump_file, stmt, 0, 0);
10132 fprintf (dump_file, " to ");
10133 print_generic_expr (dump_file, val, 0);
10134 fprintf (dump_file, "\n");
10137 if (is_gimple_assign (stmt))
10138 gimple_assign_set_rhs_from_tree (si, val);
10139 else
10141 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10142 gcond *cond_stmt = as_a <gcond *> (stmt);
10143 if (integer_zerop (val))
10144 gimple_cond_make_false (cond_stmt);
10145 else if (integer_onep (val))
10146 gimple_cond_make_true (cond_stmt);
10147 else
10148 gcc_unreachable ();
10151 return true;
10154 return false;
10157 /* Callback for substitute_and_fold folding the stmt at *SI. */
10159 static bool
10160 vrp_fold_stmt (gimple_stmt_iterator *si)
10162 if (fold_predicate_in (si))
10163 return true;
10165 return simplify_stmt_using_ranges (si);
10168 /* Unwindable const/copy equivalences. */
10169 const_and_copies *equiv_stack;
10171 /* A trivial wrapper so that we can present the generic jump threading
10172 code with a simple API for simplifying statements. STMT is the
10173 statement we want to simplify, WITHIN_STMT provides the location
10174 for any overflow warnings. */
10176 static tree
10177 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10178 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED)
10180 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10181 return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10182 gimple_cond_lhs (cond_stmt),
10183 gimple_cond_rhs (cond_stmt),
10184 within_stmt);
10186 /* We simplify a switch statement by trying to determine which case label
10187 will be taken. If we are successful then we return the corresponding
10188 CASE_LABEL_EXPR. */
10189 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10191 tree op = gimple_switch_index (switch_stmt);
10192 if (TREE_CODE (op) != SSA_NAME)
10193 return NULL_TREE;
10195 value_range *vr = get_value_range (op);
10196 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10197 || symbolic_range_p (vr))
10198 return NULL_TREE;
10200 if (vr->type == VR_RANGE)
10202 size_t i, j;
10203 /* Get the range of labels that contain a part of the operand's
10204 value range. */
10205 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10207 /* Is there only one such label? */
10208 if (i == j)
10210 tree label = gimple_switch_label (switch_stmt, i);
10212 /* The i'th label will be taken only if the value range of the
10213 operand is entirely within the bounds of this label. */
10214 if (CASE_HIGH (label) != NULL_TREE
10215 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10216 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10217 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10218 && tree_int_cst_equal (vr->min, vr->max)))
10219 return label;
10222 /* If there are no such labels then the default label will be
10223 taken. */
10224 if (i > j)
10225 return gimple_switch_label (switch_stmt, 0);
10228 if (vr->type == VR_ANTI_RANGE)
10230 unsigned n = gimple_switch_num_labels (switch_stmt);
10231 tree min_label = gimple_switch_label (switch_stmt, 1);
10232 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10234 /* The default label will be taken only if the anti-range of the
10235 operand is entirely outside the bounds of all the (non-default)
10236 case labels. */
10237 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10238 && (CASE_HIGH (max_label) != NULL_TREE
10239 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10240 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10241 return gimple_switch_label (switch_stmt, 0);
10244 return NULL_TREE;
10247 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10249 value_range new_vr = VR_INITIALIZER;
10250 tree lhs = gimple_assign_lhs (assign_stmt);
10252 if (TREE_CODE (lhs) == SSA_NAME
10253 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10254 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10256 extract_range_from_assignment (&new_vr, assign_stmt);
10257 if (range_int_cst_singleton_p (&new_vr))
10258 return new_vr.min;
10262 return NULL_TREE;
10265 /* Blocks which have more than one predecessor and more than
10266 one successor present jump threading opportunities, i.e.,
10267 when the block is reached from a specific predecessor, we
10268 may be able to determine which of the outgoing edges will
10269 be traversed. When this optimization applies, we are able
10270 to avoid conditionals at runtime and we may expose secondary
10271 optimization opportunities.
10273 This routine is effectively a driver for the generic jump
10274 threading code. It basically just presents the generic code
10275 with edges that may be suitable for jump threading.
10277 Unlike DOM, we do not iterate VRP if jump threading was successful.
10278 While iterating may expose new opportunities for VRP, it is expected
10279 those opportunities would be very limited and the compile time cost
10280 to expose those opportunities would be significant.
10282 As jump threading opportunities are discovered, they are registered
10283 for later realization. */
10285 static void
10286 identify_jump_threads (void)
10288 basic_block bb;
10289 gcond *dummy;
10290 int i;
10291 edge e;
10293 /* Ugh. When substituting values earlier in this pass we can
10294 wipe the dominance information. So rebuild the dominator
10295 information as we need it within the jump threading code. */
10296 calculate_dominance_info (CDI_DOMINATORS);
10298 /* We do not allow VRP information to be used for jump threading
10299 across a back edge in the CFG. Otherwise it becomes too
10300 difficult to avoid eliminating loop exit tests. Of course
10301 EDGE_DFS_BACK is not accurate at this time so we have to
10302 recompute it. */
10303 mark_dfs_back_edges ();
10305 /* Do not thread across edges we are about to remove. Just marking
10306 them as EDGE_IGNORE will do. */
10307 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10308 e->flags |= EDGE_IGNORE;
10310 /* Allocate our unwinder stack to unwind any temporary equivalences
10311 that might be recorded. */
10312 equiv_stack = new const_and_copies ();
10314 /* To avoid lots of silly node creation, we create a single
10315 conditional and just modify it in-place when attempting to
10316 thread jumps. */
10317 dummy = gimple_build_cond (EQ_EXPR,
10318 integer_zero_node, integer_zero_node,
10319 NULL, NULL);
10321 /* Walk through all the blocks finding those which present a
10322 potential jump threading opportunity. We could set this up
10323 as a dominator walker and record data during the walk, but
10324 I doubt it's worth the effort for the classes of jump
10325 threading opportunities we are trying to identify at this
10326 point in compilation. */
10327 FOR_EACH_BB_FN (bb, cfun)
10329 gimple *last;
10331 /* If the generic jump threading code does not find this block
10332 interesting, then there is nothing to do. */
10333 if (! potentially_threadable_block (bb))
10334 continue;
10336 last = last_stmt (bb);
10338 /* We're basically looking for a switch or any kind of conditional with
10339 integral or pointer type arguments. Note the type of the second
10340 argument will be the same as the first argument, so no need to
10341 check it explicitly.
10343 We also handle the case where there are no statements in the
10344 block. This come up with forwarder blocks that are not
10345 optimized away because they lead to a loop header. But we do
10346 want to thread through them as we can sometimes thread to the
10347 loop exit which is obviously profitable. */
10348 if (!last
10349 || gimple_code (last) == GIMPLE_SWITCH
10350 || (gimple_code (last) == GIMPLE_COND
10351 && TREE_CODE (gimple_cond_lhs (last)) == SSA_NAME
10352 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (last)))
10353 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (last))))
10354 && (TREE_CODE (gimple_cond_rhs (last)) == SSA_NAME
10355 || is_gimple_min_invariant (gimple_cond_rhs (last)))))
10357 edge_iterator ei;
10359 /* We've got a block with multiple predecessors and multiple
10360 successors which also ends in a suitable conditional or
10361 switch statement. For each predecessor, see if we can thread
10362 it to a specific successor. */
10363 FOR_EACH_EDGE (e, ei, bb->preds)
10365 /* Do not thread across edges marked to ignoreor abnormal
10366 edges in the CFG. */
10367 if (e->flags & (EDGE_IGNORE | EDGE_COMPLEX))
10368 continue;
10370 thread_across_edge (dummy, e, true, equiv_stack, NULL,
10371 simplify_stmt_for_jump_threading);
10376 /* Clear EDGE_IGNORE. */
10377 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10378 e->flags &= ~EDGE_IGNORE;
10380 /* We do not actually update the CFG or SSA graphs at this point as
10381 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10382 handle ASSERT_EXPRs gracefully. */
10385 /* We identified all the jump threading opportunities earlier, but could
10386 not transform the CFG at that time. This routine transforms the
10387 CFG and arranges for the dominator tree to be rebuilt if necessary.
10389 Note the SSA graph update will occur during the normal TODO
10390 processing by the pass manager. */
10391 static void
10392 finalize_jump_threads (void)
10394 thread_through_all_blocks (false);
10395 delete equiv_stack;
10399 /* Traverse all the blocks folding conditionals with known ranges. */
10401 static void
10402 vrp_finalize (bool warn_array_bounds_p)
10404 size_t i;
10406 values_propagated = true;
10408 if (dump_file)
10410 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10411 dump_all_value_ranges (dump_file);
10412 fprintf (dump_file, "\n");
10415 /* Set value range to non pointer SSA_NAMEs. */
10416 for (i = 0; i < num_vr_values; i++)
10417 if (vr_value[i])
10419 tree name = ssa_name (i);
10421 if (!name
10422 || POINTER_TYPE_P (TREE_TYPE (name))
10423 || (vr_value[i]->type == VR_VARYING)
10424 || (vr_value[i]->type == VR_UNDEFINED))
10425 continue;
10427 if ((TREE_CODE (vr_value[i]->min) == INTEGER_CST)
10428 && (TREE_CODE (vr_value[i]->max) == INTEGER_CST)
10429 && (vr_value[i]->type == VR_RANGE
10430 || vr_value[i]->type == VR_ANTI_RANGE))
10431 set_range_info (name, vr_value[i]->type, vr_value[i]->min,
10432 vr_value[i]->max);
10435 substitute_and_fold (op_with_constant_singleton_value_range,
10436 vrp_fold_stmt, false);
10438 if (warn_array_bounds && warn_array_bounds_p)
10439 check_all_array_refs ();
10441 /* We must identify jump threading opportunities before we release
10442 the datastructures built by VRP. */
10443 identify_jump_threads ();
10445 /* Free allocated memory. */
10446 free (vr_value);
10447 free (vr_phi_edge_counts);
10448 bitmap_obstack_release (&vrp_equiv_obstack);
10449 vrp_value_range_pool.release ();
10451 /* So that we can distinguish between VRP data being available
10452 and not available. */
10453 vr_value = NULL;
10454 vr_phi_edge_counts = NULL;
10458 /* Main entry point to VRP (Value Range Propagation). This pass is
10459 loosely based on J. R. C. Patterson, ``Accurate Static Branch
10460 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
10461 Programming Language Design and Implementation, pp. 67-78, 1995.
10462 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
10464 This is essentially an SSA-CCP pass modified to deal with ranges
10465 instead of constants.
10467 While propagating ranges, we may find that two or more SSA name
10468 have equivalent, though distinct ranges. For instance,
10470 1 x_9 = p_3->a;
10471 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
10472 3 if (p_4 == q_2)
10473 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
10474 5 endif
10475 6 if (q_2)
10477 In the code above, pointer p_5 has range [q_2, q_2], but from the
10478 code we can also determine that p_5 cannot be NULL and, if q_2 had
10479 a non-varying range, p_5's range should also be compatible with it.
10481 These equivalences are created by two expressions: ASSERT_EXPR and
10482 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
10483 result of another assertion, then we can use the fact that p_5 and
10484 p_4 are equivalent when evaluating p_5's range.
10486 Together with value ranges, we also propagate these equivalences
10487 between names so that we can take advantage of information from
10488 multiple ranges when doing final replacement. Note that this
10489 equivalency relation is transitive but not symmetric.
10491 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
10492 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
10493 in contexts where that assertion does not hold (e.g., in line 6).
10495 TODO, the main difference between this pass and Patterson's is that
10496 we do not propagate edge probabilities. We only compute whether
10497 edges can be taken or not. That is, instead of having a spectrum
10498 of jump probabilities between 0 and 1, we only deal with 0, 1 and
10499 DON'T KNOW. In the future, it may be worthwhile to propagate
10500 probabilities to aid branch prediction. */
10502 static unsigned int
10503 execute_vrp (bool warn_array_bounds_p)
10505 int i;
10506 edge e;
10507 switch_update *su;
10509 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
10510 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
10511 scev_initialize ();
10513 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
10514 Inserting assertions may split edges which will invalidate
10515 EDGE_DFS_BACK. */
10516 insert_range_assertions ();
10518 to_remove_edges.create (10);
10519 to_update_switch_stmts.create (5);
10520 threadedge_initialize_values ();
10522 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
10523 mark_dfs_back_edges ();
10525 vrp_initialize ();
10526 ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
10527 vrp_finalize (warn_array_bounds_p);
10529 free_numbers_of_iterations_estimates (cfun);
10531 /* ASSERT_EXPRs must be removed before finalizing jump threads
10532 as finalizing jump threads calls the CFG cleanup code which
10533 does not properly handle ASSERT_EXPRs. */
10534 remove_range_assertions ();
10536 /* If we exposed any new variables, go ahead and put them into
10537 SSA form now, before we handle jump threading. This simplifies
10538 interactions between rewriting of _DECL nodes into SSA form
10539 and rewriting SSA_NAME nodes into SSA form after block
10540 duplication and CFG manipulation. */
10541 update_ssa (TODO_update_ssa);
10543 finalize_jump_threads ();
10545 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
10546 CFG in a broken state and requires a cfg_cleanup run. */
10547 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10548 remove_edge (e);
10549 /* Update SWITCH_EXPR case label vector. */
10550 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
10552 size_t j;
10553 size_t n = TREE_VEC_LENGTH (su->vec);
10554 tree label;
10555 gimple_switch_set_num_labels (su->stmt, n);
10556 for (j = 0; j < n; j++)
10557 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
10558 /* As we may have replaced the default label with a regular one
10559 make sure to make it a real default label again. This ensures
10560 optimal expansion. */
10561 label = gimple_switch_label (su->stmt, 0);
10562 CASE_LOW (label) = NULL_TREE;
10563 CASE_HIGH (label) = NULL_TREE;
10566 if (to_remove_edges.length () > 0)
10568 free_dominance_info (CDI_DOMINATORS);
10569 loops_state_set (LOOPS_NEED_FIXUP);
10572 to_remove_edges.release ();
10573 to_update_switch_stmts.release ();
10574 threadedge_finalize_values ();
10576 scev_finalize ();
10577 loop_optimizer_finalize ();
10578 return 0;
10581 namespace {
10583 const pass_data pass_data_vrp =
10585 GIMPLE_PASS, /* type */
10586 "vrp", /* name */
10587 OPTGROUP_NONE, /* optinfo_flags */
10588 TV_TREE_VRP, /* tv_id */
10589 PROP_ssa, /* properties_required */
10590 0, /* properties_provided */
10591 0, /* properties_destroyed */
10592 0, /* todo_flags_start */
10593 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
10596 class pass_vrp : public gimple_opt_pass
10598 public:
10599 pass_vrp (gcc::context *ctxt)
10600 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
10603 /* opt_pass methods: */
10604 opt_pass * clone () { return new pass_vrp (m_ctxt); }
10605 void set_pass_param (unsigned int n, bool param)
10607 gcc_assert (n == 0);
10608 warn_array_bounds_p = param;
10610 virtual bool gate (function *) { return flag_tree_vrp != 0; }
10611 virtual unsigned int execute (function *)
10612 { return execute_vrp (warn_array_bounds_p); }
10614 private:
10615 bool warn_array_bounds_p;
10616 }; // class pass_vrp
10618 } // anon namespace
10620 gimple_opt_pass *
10621 make_pass_vrp (gcc::context *ctxt)
10623 return new pass_vrp (ctxt);